From 71589f030886dfbe895bc2d8d03b0dc75b84b323 Mon Sep 17 00:00:00 2001 From: Denis Tereshkin Date: Wed, 22 Dec 2021 17:41:07 +0700 Subject: [PATCH] vmcompiler: prefix labels with current function name --- src/Nand2Tetris/VM.hs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/Nand2Tetris/VM.hs b/src/Nand2Tetris/VM.hs index 5ff2591..89fc2aa 100644 --- a/src/Nand2Tetris/VM.hs +++ b/src/Nand2Tetris/VM.hs @@ -22,6 +22,7 @@ module Nand2Tetris.VM import Control.Monad.State.Strict (State, evalState, forM, gets, modify') import Data.Functor (($>)) +import Data.Maybe (fromMaybe) import qualified Data.Text as T import Nand2Tetris.Error (Error) import Nand2Tetris.Hack (HackInstruction (A, C), @@ -290,16 +291,20 @@ compileInstruction instr = do compileInstruction' (VMArithmetic ACAnd) = return $ binopSequence SDAndM compileInstruction' (VMArithmetic ACOr) = return $ binopSequence SDOrM compileInstruction' (VMArithmetic ACNot) = return $ unopSequence (SNot RegM) - compileInstruction' (VMBranching (BLabel label)) = return [ALabel label] - compileInstruction' (VMBranching (BGoto label)) = - return [ Code (A (Label label)), + compileInstruction' (VMBranching (BLabel label)) = do + fname <- fromMaybe "_Global" <$> gets ceCurrentFunction + return [ALabel $ fname <> "$" <> label] + compileInstruction' (VMBranching (BGoto label)) = do + fname <- fromMaybe "_Global" <$> gets ceCurrentFunction + return [ Code (A (Label $ fname <> "$" <> label)), Code (C [] S0 Jmp) ] - compileInstruction' (VMBranching (BIfGoto label)) = + compileInstruction' (VMBranching (BIfGoto label)) = do + fname <- fromMaybe "_Global" <$> gets ceCurrentFunction return [ Code (A (Label "SP")), Code (C [RegA, RegM] (SRegMinus1 RegM) JNone), Code (C [RegD] (SReg RegM) JNone), - Code (A (Label label)), + Code (A (Label $ fname <> "$" <> label)), Code (C [] (SReg RegD) JNe) ] compileInstruction' (VMFunction (FFunction name nvars)) = do