[07/Static] Implements static push/pop memory segment

This commit is contained in:
Nemo 2020-06-02 17:28:20 +05:30
parent 67b4e2653e
commit 4e49913808
4 changed files with 103 additions and 0 deletions

View File

@ -0,0 +1,73 @@
@111 // push constant 111
D=A
@SP
A=M
M=D
@SP
M=M+1 // end push constant 111 (L0)
@333 // push constant 333
D=A
@SP
A=M
M=D
@SP
M=M+1 // end push constant 333 (L1)
@888 // push constant 888
D=A
@SP
A=M
M=D
@SP
M=M+1 // end push constant 888 (L2)
@SP //pop static 8
AM=M-1
D=M
@StaticTest.8
M=D // end pop static 8 (L3)
@SP //pop static 3
AM=M-1
D=M
@StaticTest.3
M=D // end pop static 3 (L4)
@SP //pop static 1
AM=M-1
D=M
@StaticTest.1
M=D // end pop static 1 (L5)
@StaticTest.3
D=M
@SP
A=M
M=D
@SP
M=M+1 // end push static 3 (L6)
@StaticTest.1
D=M
@SP
A=M
M=D
@SP
M=M+1 // end push static 1 (L7)
@SP // ==== sub ====
A=M-1
D=M
A=A-1
M=M-D
@SP
M=M-1 // end sub (L8)
@StaticTest.8
D=M
@SP
A=M
M=D
@SP
M=M+1 // end push static 8 (L9)
@SP // ==== add ====
A=M-1
D=M
A=A-1
M=D+M
@SP
M=M-1 // end add (L10)
@72
0;JMP

View File

@ -0,0 +1,2 @@
|RAM[256]|
| 1110 |

View File

@ -9,6 +9,10 @@ class CodeWriter {
$this->file = fopen($outputFile, "w");
}
function setInputFileName($inputFileName) {
$this->vm = basename($inputFileName, ".vm");
}
function nextSourceLine() {
$this->sourceLine += 1;
}
@ -185,6 +189,14 @@ class CodeWriter {
]);
break;
case 'static':
$symbol = $this->resolveStatic($index);
$this->write([
$symbol,
"D=M"
]);
break;
case 'pointer':
$register = $this->resolvePointer($index);
$this->write([
@ -239,6 +251,10 @@ class CodeWriter {
]);
}
private function resolveStatic(Int $index) {
return "@{$this->vm}.$index";
}
private function writePop(String $segment, Int $index) {
switch ($segment) {
// The address is given by LCL+INDEX
@ -263,6 +279,17 @@ class CodeWriter {
]);
break;
case 'static':
$symbol = $this->resolveStatic($index);
$this->write([
"@SP //pop $segment $index",
"AM=M-1",
"D=M",
$symbol,
"M=D // end pop $segment $index (L{$this->sourceLine})"
]);
break;
case 'pointer':
// pointer points to a 2 register segment holding [this, that]
$register = $this->resolvePointer($index);

View File

@ -24,6 +24,7 @@ class VMTranslator {
function translate() {
foreach ($this->files as $file) {
$parser = new Parser($file);
$this->writer->setInputFileName($file);
foreach ($parser->commands() as $command) {
$commandType = CommandType::fromName($command);