Recursive Descent Parsing

Hi! i am making my first interpreter of my own language, i am having a problem with
the function getValue() I want provide the template argument at runtime, depending on the source code parsed.

And is my approach even correct? any comments will be highly appreciated.

Grammar: Variable
1
2
3
4
5
6
7
/*
 * <type>    :== "int" | "float" | "char" | "uint"
 * <name>     :== [<letter> | <underscore>]...
 * <value>   :== <number> | [<character>]...
 *
 * <variable> :== <type> <name> "=" <value> [";"] "\n"
*/


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
class Parser {
    std::istream& is_;
    std::streampos currentLine_;

public:
    Parser( std::istream& is ) : is_(is) { }
    void getVariable(); // TODO
    std::string getType();
    std::string getVariableName();
    template <typename T> T getValue( ?? );       // ?????????
};

std::string Parser::getType()
{
    static const char* const TYPES [] = {
        "int", "float", "char", "uint"
    }

    std::string ret;
    is_ >> ret;

    bool b = std::find( std::begin(TYPES),
                        std::end(TYPES),
                        ret ) != std::end(TYPES);

    if( !b ) {
        throw InvalidType;
    }

    return ret;
}

std::string Parser::getVariableName()
{
    std::string ret;
    is_ >> ret;

    bool b = std::all_of( ret.begin(), ret.end(),
                          [](char c)
                          {
                            return std::isalpha(c) || c == '_';
                          });

    if( !b ) {
        throw InvalidVariableName;
    }

    return ret;
}

int main() { }
Last edited on
getValue() will likely need to be the recursive descent parser that your title suggests. It's a deep subject and worthy of a few test programs so you can see how it works.

I think you'll struggle to provide the template argument at runtime because the expression will need to be parsed before you know the resulting type and templates need to be elaborated at compile time.

its a big subject to get a proper answer here, but http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm and http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/ should provide some deeper info.

the second link is a c# article, but it should translate to c++ easily.
thanks, i will check those articles out
Topic archived. No new replies allowed.