@@ -58,20 +58,22 @@ def visit_def(node):
5858
5959class Commands :
6060
61- def __init__ (self ):
61+ def __init__ (self , show_speed : bool = False ):
6262 self ._syntax = {
63- "1" : self .__add ,
64- "2" : self .__sub ,
65- "3" : self .__sta ,
66- "4" : self .__sft ,
67- "5" : self .__lda ,
68- "6" : self .__bra ,
69- "7" : self .__brz ,
70- "8" : self .__brp ,
71- "901" : self .__inp ,
72- "902" : self .__out ,
73- "0" : self .__hlt
63+ "1" : { "cmd" : self .__add , "cycles" : 3 } ,
64+ "2" : { "cmd" : self .__sub , "cycles" : 3 } ,
65+ "3" : { "cmd" : self .__sta , "cycles" : 1 } ,
66+ "4" : { "cmd" : self .__sft , "cycles" : 0 } ,
67+ "5" : { "cmd" : self .__lda , "cycles" : 2 } ,
68+ "6" : { "cmd" : self .__bra , "cycles" : 2 } ,
69+ "7" : { "cmd" : self .__brz , "cycles" : 2 } ,
70+ "8" : { "cmd" : self .__brp , "cycles" : 2 } ,
71+ "901" : { "cmd" : self .__inp , "cycles" : 1 } ,
72+ "902" : { "cmd" : self .__out , "cycles" : 1 } ,
73+ "0" : { "cmd" : self .__hlt , "cycles" : 0 }
7474 }
75+ self ._show_speed = show_speed
76+ self ._total_clock = 0
7577
7678 def parse (self , ** kwargs ):
7779 try :
@@ -85,7 +87,8 @@ def parse(self, **kwargs):
8587 if self ._arg == "9" :
8688 self ._arg = kwargs ['arg' ]
8789 try :
88- return self ._syntax [self ._arg ]
90+ self ._total_clock += self ._syntax [self ._arg ]["cycles" ]
91+ return self ._syntax [self ._arg ]["cmd" ]
8992 except :
9093 print (f"[ERROR] Invalid instruction at line { self ._line } ." )
9194 return
@@ -99,6 +102,8 @@ def __add(self, acc, storage) -> int:
99102 def __sub (self , acc , storage ) -> int :
100103 sub = int (storage ._spaces [self ._val ])
101104 acc .value -= sub
105+ if acc .value < 0 :
106+ acc .value = 0
102107
103108 @storage
104109 def __sta (self , acc , storage ):
@@ -147,6 +152,7 @@ def __sft(self, acc, storage):
147152
148153 @inputs
149154 def __inp (self , acc , storage , input : int = 0 ):
155+ storage ._expected_inputs += 1
150156 try :
151157 int (input )
152158 if input > 999 :
@@ -162,5 +168,7 @@ def __out(self, acc, storage):
162168
163169 @halt
164170 def __hlt (self , acc , storage ):
171+ if self ._show_speed :
172+ print (self ._total_clock )
165173 sys .exit (0 )
166174 return False
0 commit comments