I'm creating a programming language from scratch in C, and I'd prefer not to use third-party code for 开发者_JAVA百科variable handling.
Firstly, what's the best way to represent array assignments, like apples_in_crate[5] = 170
, in bytecode form?
Obviously, apples = 170
could be represented as:
PUSHSCALAR ("apples")
PUSHREAL (170)
ASSIGNSCALAR
but things get a lot more complicated when it comes to arrays. Any suggestions?
Secondly, how would you represent crate[5].apples = 170
(a record) in bytecode?
Any help would be appreciated.
Clarification: I'm writing an interpreter, so the size of an array is not known at "compile-time" or parse-time. For example, the following (abstract) code would be quite valid:
// Note: NUMBER_OF_CRATES is not known at compile-/parse-time,
// it could even be a dynamic expression.
array apples_in_crate[NUMBER_OF_CRATES]
for crate = 1 to NUMBER_OF_CRATES
apples_in_crate[crate] = randint (101) + 100
end for
That depends entirely on your bytecode. How static are your structures? If everything is done at compile-time (kind of like in C and C++), you know the size of each element in apples_in_create, so you can first push apples_in_create, then add 5 * sizeof(elements) to that value, then assign 170 to that address.
Same goes for your second example: Push crate, add 5 * sizeof(Crate), add offset_of(apples), assign value.
Now if you want things to be more flexible (say, if you want to allow for things like reflection), you'll have to have your system be more aware of your data types at run-time. But without more information about what your bytecode is supposed to be like, it's hard to give you more advice.
As an example, Here's how it is represented in the Java Virtual Machine.
精彩评论