Re: Qi Symbols mapping to AST enum

Henri Menke <[email protected]> Thu, 29 Nov 2018 13:36:32 +1300
Newsgroups gmane.comp.parsers.spirit.general
Message-ID <[email protected]>

On 29/11/18 12:35 PM, Michael Powell wrote:
> Hello,
> 
> I've got a qi::symbols capturing some built-in types. At the moment, I
> gather, they are mapped to std::string. However, I would rather map
> them to an AST level enum.
> 
> For instance,
> 
> struct builtin_type_t : qi::symbols<char, std::string> {
>     builtin_type_t() {
>         this->add("double", "double")
>             ("float", "float")
>             // ...
>             ;
>     }
> } builtin_type;
> 
> Instead,
> 
> namespace ast {
>     enum type_t { type_double, type_float /* , ... */ };
> }
> 
> struct builtin_type_t : qi::symbols<char, ast::type_t> {
>     builtin_type_t() {
>         this->add("double", ast::type_double)
>             ("float", ast::type_float)
>             // ...
>             ;
>     }
> } builtin_type;

Yes, this is entirely possible.  Below is a minimal example.  Just an
aside, you shouldn't name types with `_t` in the end because those are
names reserved for POSIX, see
https://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html

#include <boost/spirit/include/qi.hpp>
#include <iostream>

namespace qi = boost::spirit::qi;

namespace ast {
enum type_t { type_double, type_float /* , ... */ };
}

struct builtin_type_t : qi::symbols<char, ast::type_t> {
    builtin_type_t() {
        this->add
            ("double", ast::type_double)
            ("float", ast::type_float)
            // ...
            ;
    }
} builtin_type;

int main() {
    std::string input = "float";
    std::string::iterator iter = input.begin();
    std::string::iterator end = input.end();

    ast::type_t result;
    bool r = parse(iter, end, builtin_type, result);
    if (!r || iter != end) {
        std::cerr << "Parsing failed at: " << std::string(iter, end)
                  << "\n";
        return 1;
    }

    switch (result) {
    case ast::type_double:
        std::cout << "double\n";
        break;
    case ast::type_float:
        std::cout << "float\n";
        break;
    default:
        std::cerr << "Error: Unknown type!\n";
    }
}

> 
> I assume this is possible? Am I missing something about that?
> 
> Thanks!
> 
> Michael Powell
> 
> 
> _______________________________________________
> Spirit-general mailing list
> [email protected]
> https://lists.sourceforge.net/lists/listinfo/spirit-general
>