Question

I'm trying to create a simple dynamic language interpreter in C++. I'd like to be able to declare dynamically typed arrays, but I'm not sure how to store them in some object in C++.

In Ruby/Python I can store anything I want, but what's an efficient way of doing this in C++?

(Also, if someone has a link to a simple open source lexer/parser/interpreter for dynamic languages like Ruby, I'd appreciate a link).

Was it helpful?

Solution

You will have to roll some custom solution based on your language's semantics. For example, you can use boost::any to store any object, but you won't be able to perform, for example, name lookups. A knowledge of some assembler is useful here because you're basically emulating that. What most people do is something like

struct Object {
    boost::any cppobject;
    std::unordered_map<std::string, std::function<void(boost::any&, std::vector<boost::any>&)> funcs;
};

std::vector<Object> stuff;

When, in your hypothetical language, you have something like

stuff[0].hi();

Then you can convert it into something like

std::vector<boost::any> args;
// fill args
stuff.at(0).funcs["hi"](stuff.at(0).cppobject, args);
// now args holds the result

It's quite possible to optimize this scheme further, but not to generalize it further, as it's already maximally general.

OTHER TIPS

The way dynamic languages store universal objects is via pointers, you can do the same thing in C++. Store a pointer to a generic "object" that you define in your C++ classes, that's an efficient way of doing it.

An alternative to using unions or dynamically allocating objects of a common base type (and downcasting them as appropriate via dynamic_cast or an equivalent construct) is boost::variant, which allows you to write code such as:

typedef boost::variant<int, float, char, std::string> LangType;
std::vector<LangType> langObjects;

If your design allows for such an implementation, this has the advantage of being compile-time safe and avoiding any penalty imposed by use of the heap, virtual functions and polymorphic downcasts.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top