From be69ac321da25bdd29034ce7bc12eb034d5d699b Mon Sep 17 00:00:00 2001 From: Nemo Date: Mon, 1 Jun 2020 23:05:03 +0530 Subject: [PATCH] Reduce stack manipulation (use M instead of A) --- .../StackArithmetic/SimpleAdd/SimpleAdd.asm | 20 ++------ vm/VMTranslator.php | 49 +++++++++++-------- 2 files changed, 33 insertions(+), 36 deletions(-) diff --git a/projects/07/StackArithmetic/SimpleAdd/SimpleAdd.asm b/projects/07/StackArithmetic/SimpleAdd/SimpleAdd.asm index 094f2cb..9307c85 100644 --- a/projects/07/StackArithmetic/SimpleAdd/SimpleAdd.asm +++ b/projects/07/StackArithmetic/SimpleAdd/SimpleAdd.asm @@ -4,10 +4,8 @@ D=A @SP A=M M=D -A=A+1 -D=A @SP -M=D +M=M+1 // end push constant 7 // push constant 8 @8 @@ -15,25 +13,17 @@ D=A @SP A=M M=D -A=A+1 -D=A @SP -M=D +M=M+1 // end push constant 8 // ==== add ==== // pop starts @SP -A=M -A=A-1 +A=M-1 D=M // pop ends // inner add starts A=A-1 -D=D+M -// inner add ends -M=D -A=A+1 -D=A +M=D+M @SP -M=D -// ==== add ==== +M=M-1 diff --git a/vm/VMTranslator.php b/vm/VMTranslator.php index 0c7d170..8781a4a 100644 --- a/vm/VMTranslator.php +++ b/vm/VMTranslator.php @@ -68,50 +68,63 @@ class Parser { class CodeWriter { function __construct($outputFile) { + $this->ic = 0; $this->file = fopen($outputFile, "w"); } + function __destruct() { + fclose($this->file); + } + function writeArithmetic(String $command ) { // Read top of stack to D $this->write([ "// ==== $command ====", "// pop starts", "@SP", - "A=M", - "A=A-1", + "A=M-1", "D=M", "// pop ends", + "// inner $command starts", + 'A=A-1', ]); switch ($command) { case 'add': // But add it to previous D this time $this->write([ - "// inner add starts", - "A=A-1", - "D=D+M", - "// inner add ends", + "M=D+M" ]); 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: # code... break; } $this->write([ - // And then write the result back to M - "M=D", - // Now we write our current A to SP - "A=A+1", - "D=A", - "@SP", - "M=D", - "// ==== $command ====" + '@SP', + 'M=M-1' ]); } private function write(Array $lines) { foreach ($lines as $line) { + if (substr($line, 0, 2) !== "//") { + $this->ic += 1; + } fwrite($this->file, "$line\n"); } } @@ -131,10 +144,8 @@ class CodeWriter { // Write D to SP "M=D", // Bump Stack Pointer - "A=A+1", - "D=A", "@SP", - "M=D", + "M=M+1", "// end push $segment $index" ]); break; @@ -159,10 +170,6 @@ class CodeWriter { break; } } - - function close() { - throw new \Exception("Not yet Implemented"); - } }