-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomp.py
104 lines (94 loc) · 2.6 KB
/
comp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# Nicholas Prado
# a virtual machine, largely adhering to Deitel's Simpletron spec
import cpu
import ram
#from sys import argv # assuming you tell me which files you want loaded from HD
def testRam( usb ) :
' unit test for ram module '
print "Set addr 4 as -30\nPrint first five vals in reverse order\nDump ram to core.txt\n"
for uu in range( 5, 0, -1 ) :
print usb.getFrom( uu )
core = open( "core.txt", 'w' )
usb.coreDump( core )
core.close( )
def testCpu( mem ) :
cmd = cpu.Cpu( 0, mem )
cmd.run( )
# I wonder how I would test fetch and execute besides running?
# I have indirectly tested them but getting the cpu's inernal state
# isn't something I want to complicate with. Oh well it works anyway.
core = open( "core.txt", 'w' )
mem.coreDump( core )
core.close( )
def invalid( input ) :
bad_input = True
word_lim = 9999
lower_lim = -1 * word_lim
try:
val = int( input, 10 )
except ValueError:
return bad_input
if val < lower_lim :
return bad_input
elif val > word_lim :
return bad_input
else :
return not bad_input
def exit( input ) :
return input == "##"
def deitel_version( ) :
print ' *** Welcome to Simpletron! ***\n\
*** Please enter your program one instruction ***\n\
*** (or data word) at a time into the input ***\n\
*** text field. I will display the location ***\n\
*** number and a question mark (?). You then ***\n\
*** type the word for that location. Enter the ***\n\
*** hash twice to stop entering your program. ***'
ssd = ram.Ram( )
addr = 0
while True :
unknown = raw_input( str( addr ) + "_?_" )
if exit( unknown ) :
print "Stopping input. Running Simpletron ..."
break
elif invalid( unknown ) :
print "\tinvalid, use {-9999 - 9999}"
continue
val = int( unknown )
ssd.setAt( addr, val )
addr += 1
cmd = cpu.Cpu( 0, ssd, not verbose )
cmd.run( )
def run( file ) :
ssd = ram.Ram( )
cmd = cpu.Cpu( 0, ssd, verbose )
ssd.loader( file )
#testRam( ssd )
#testCpu( ssd )
cmd.run( )
verbose = False # I've changed testCompiler to alter this
#run( argv[ 1 ] ) # uncomment here & line 7 to test cpu explicitly
#deitel_version() # type instructions by hand
'''
Bad examples of using exec( ):
>>>
>>> for name in sys.argv[1:]:
>>> exec "%s=1" % name
>>> def func(s, **kw):
>>> for var, val in kw.items():
>>> exec "s.%s=val" % var # invalid!
>>> execfile("handler.py")
>>> handle()
Good examples:
>>>
>>> d = {}
>>> for name in sys.argv[1:]:
>>> d[name] = 1
>>> def func(s, **kw):
>>> for var, val in kw.items():
>>> setattr(s, var, val)
>>> d={}
>>> execfile("handle.py", d, d)
>>> handle = d['handle']
>>> handle()
'''