How do I implement arrays in the interpreter?
I have managed to write several interpreters including
- Tokenizing
- Analysis including more complex expressions such as
((x+y)*z)/2
- Building bytecode from syntax trees
- Actual Bytecode Execution
What I failed: Implementation dictionaries/lists/arrays
.
I am always stuck with getting multiple values into one variable.
My value structure (used for all passed values including variables) looks like this:
class Value
{
public:
ValueType type;
int integerValue;
string stringValue;
}
Works fine with integers and strings, but how can I implement arrays?
(From now on, array
I mean arrays in my experimental language, not C ++)
-
How can I fit the concept of an array into the Value class above? Is it possible?
-
How do I make arrays that can be passed around in the same way that you could pass integers and strings in my language using the class above?
Accessing array elements or memory allocation won't be a problem, I just don't know how to store them.
a source to share
I think you need an extra layer of abstraction here.
Your "variable" should model the binding of some internal "named" object in the language you are building. The "object" should model the view.
Thus, a variable can contain anything, it is a "variant". A certain kind of object can contain an array of other objects.
Prompt:
class Object {
public:
enum etype { cInt, cString, cArray, cDictionary };
virtual etype type() const = 0;
virtual ~Object(){} // don't forget virtual destructor
// maybe some reference counter functions?...
};
class Variable {
public:
string name;
Object* value;
};
class Array : public Object {
std::map<size_t, Object*> objects_; //or smart pointers...
public:
virtual etype type() const { return cArray; }
Object* get( size_t i ) const { return objects_[i]; }
void put( size_t i, Object* o ) { objects_[i] = o; }
};
class Int : public Object {
public:
virtual etype type() const { return cInt; }
int value_;
};
a source to share