Acsor wrote
I'm on my way to implement the lexer/parser layer of the VM language, and am wondering whether such instructions as
push constant -1
push local -1
that is those involving the -1 constant, are allowed. My prejudiced answer is that they are not, but I couldn't find a paragraph or any affirmative excerpt that says it. Is there such a reference, or way of knowing whether -1 is formally included in the VM language syntax?
Normally, the segments are parts of the memory where some data is stored. For example the local segment contains the local variables (the ones defined in the body of a method). The segment is defined by its starting address and the number after the segment is the so called offset to the specific variable.
For example, if the local segment starts at address 541 then the first variable would be local 0 and will have address 541+0, the second local variable would be local 1 with address 541+1 and so on. local -1 would mean to access memory that is before the segment. That should never happen in a well written compiler and is not allowed here.
The constant segment is different though. It is a pseudo-segment, as it does not denote any memory. Therefore push constant -1 isn't so strange. It would mean to just push the value -1 on the stack. That said, I think this is still disallowed in the Hack VM. I imagine the reasons are things like easier implementation and better consistency in the rules.
Note, that I'm not 100% sure about that, as I haven't checked this parts of the book recently. But I searched the provided .vm files and I didn't find any mentions of "constant -". I'm pretty sure that there would've been a test like that if it was part of the specification.