summaryrefslogtreecommitdiff
path: root/src/expand/concat.cpp
blob: bd741e2f5f74fbcf3669272795a0c036a53b6c59 (plain)
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
/*
 * MRustC - Rust Compiler
 * - By John Hodge (Mutabah/thePowersGang)
 *
 * expand/concat.cpp
 * - concat! handler
 */
#include <synext.hpp>
#include "../parse/common.hpp"
#include "../parse/parseerror.hpp"
#include "../parse/tokentree.hpp"
#include "../parse/ttstream.hpp"
#include "../parse/lex.hpp" // For Codepoint
#include <ast/expr.hpp>

class CConcatExpander:
    public ExpandProcMacro
{
    ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const TokenTree& tt, AST::Module& mod) override
    {
        Token   tok;

        auto lex = TTStream(sp, tt);

        ::std::string   rv;
        do {
            if( LOOK_AHEAD(lex) == TOK_EOF ) {
                GET_TOK(tok, lex);
                break ;
            }

            auto v = Parse_Expr0(lex);
            DEBUG("concat - v=" << *v);
            Expand_BareExpr(crate, mod,  v);
            DEBUG("concat[pe] - v=" << *v);
            if( auto* vp = dynamic_cast<AST::ExprNode_String*>(v.get()) )
            {
                rv += vp->m_value;
            }
            else if( auto* vp = dynamic_cast<AST::ExprNode_Integer*>(v.get()) )
            {
                if( vp->m_datatype == CORETYPE_CHAR ) {
                    rv += Codepoint { static_cast<uint32_t>(vp->m_value) };
                }
                else {
                    rv += FMT(vp->m_value);
                }
            }
            else if( auto* vp = dynamic_cast<AST::ExprNode_Float*>(v.get()) )
            {
                rv += FMT(vp->m_value);
            }
            else if( auto* vp = dynamic_cast<AST::ExprNode_Bool*>(v.get()) )
            {
                rv += (vp->m_value ? "true" : "false");
            }
            else
            {
                ERROR(sp, E0000, "Unexpected expression type in concat! argument");
            }
        } while( GET_TOK(tok, lex) == TOK_COMMA );
        if( tok.type() != TOK_EOF )
            throw ParseError::Unexpected(lex, tok, {TOK_COMMA, TOK_EOF});

        return box$( TTStreamO(sp, TokenTree(Token(TOK_STRING, mv$(rv)))) );
    }
};

STATIC_MACRO("concat", CConcatExpander);