Reduce stack manipulation (use M instead of A)

This commit is contained in:
Nemo 2020-06-01 23:05:03 +05:30
parent b186ee7df1
commit be69ac321d
2 changed files with 33 additions and 36 deletions

View File

@ -4,10 +4,8 @@ D=A
@SP @SP
A=M A=M
M=D M=D
A=A+1
D=A
@SP @SP
M=D M=M+1
// end push constant 7 // end push constant 7
// push constant 8 // push constant 8
@8 @8
@ -15,25 +13,17 @@ D=A
@SP @SP
A=M A=M
M=D M=D
A=A+1
D=A
@SP @SP
M=D M=M+1
// end push constant 8 // end push constant 8
// ==== add ==== // ==== add ====
// pop starts // pop starts
@SP @SP
A=M A=M-1
A=A-1
D=M D=M
// pop ends // pop ends
// inner add starts // inner add starts
A=A-1 A=A-1
D=D+M M=D+M
// inner add ends
M=D
A=A+1
D=A
@SP @SP
M=D M=M-1
// ==== add ====

View File

@ -68,50 +68,63 @@ class Parser {
class CodeWriter { class CodeWriter {
function __construct($outputFile) { function __construct($outputFile) {
$this->ic = 0;
$this->file = fopen($outputFile, "w"); $this->file = fopen($outputFile, "w");
} }
function __destruct() {
fclose($this->file);
}
function writeArithmetic(String $command ) { function writeArithmetic(String $command ) {
// Read top of stack to D // Read top of stack to D
$this->write([ $this->write([
"// ==== $command ====", "// ==== $command ====",
"// pop starts", "// pop starts",
"@SP", "@SP",
"A=M", "A=M-1",
"A=A-1",
"D=M", "D=M",
"// pop ends", "// pop ends",
"// inner $command starts",
'A=A-1',
]); ]);
switch ($command) { switch ($command) {
case 'add': case 'add':
// But add it to previous D this time // But add it to previous D this time
$this->write([ $this->write([
"// inner add starts", "M=D+M"
"A=A-1",
"D=D+M",
"// inner add ends",
]); ]);
break; break;
case 'eq':
$jumpPointer = $this->ic+5;
$this->write([
'D=M-D', // ic
'M=0', // set M=0, in case they aren't equal
"@{jumpPointer}",
'D;JEQ', //ic+2
'M=0', //ic+3
'M=M-1', //ic+4
// set M=-1 (TRUE), in case they are equal
// *SP=-1 = true
]);
default: default:
# code... # code...
break; break;
} }
$this->write([ $this->write([
// And then write the result back to M '@SP',
"M=D", 'M=M-1'
// Now we write our current A to SP
"A=A+1",
"D=A",
"@SP",
"M=D",
"// ==== $command ===="
]); ]);
} }
private function write(Array $lines) { private function write(Array $lines) {
foreach ($lines as $line) { foreach ($lines as $line) {
if (substr($line, 0, 2) !== "//") {
$this->ic += 1;
}
fwrite($this->file, "$line\n"); fwrite($this->file, "$line\n");
} }
} }
@ -131,10 +144,8 @@ class CodeWriter {
// Write D to SP // Write D to SP
"M=D", "M=D",
// Bump Stack Pointer // Bump Stack Pointer
"A=A+1",
"D=A",
"@SP", "@SP",
"M=D", "M=M+1",
"// end push $segment $index" "// end push $segment $index"
]); ]);
break; break;
@ -159,10 +170,6 @@ class CodeWriter {
break; break;
} }
} }
function close() {
throw new \Exception("Not yet Implemented");
}
} }