File: vpu_tutor.py

package info (click to toggle)
apoo 2.2-2
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd, squeeze, wheezy
  • size: 560 kB
  • ctags: 425
  • sloc: python: 3,092; perl: 100; makefile: 56; sh: 4
file content (289 lines) | stat: -rw-r--r-- 11,053 bytes parent folder | download | duplicates (4)
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# -*- coding: UTF-8 -*-
"""
The core of an exercise tester in the spirit of the Ganesh project

Copyright (C) 1998-2003 Rogério Reis & Nelma Moreira {rvr,nam}@ncc.up.pt

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.   

@author: Rogério Reis & Nelma Moreira {rvr,nam}@ncc.up.pt
"""

from constants import *
from vpu import Vpu, ReadProgram, CantRead, isNumber, isRegName
import constants, vpu
# constants need to be imported twice because of -v option...
import sys, stat, posix, string

__version =  "$Id: vpu_tutor.py,v 1.29 2006-11-13 11:11:59 rvr Exp $"

class Vpu_Tutor(Vpu):
    def doIt(self):
        try:
            input = open(self.tutorFile,'r')
        except IOError:
            CantRead(self.tutorFile)
        self.ggrade = 0
        last, loaded, run = 'ready',0,0
        tutor = []
        # remove commands and create a tutor command list
        while 1:
            line = input.readline()
            if not line: break
            if len(line) == 1: continue
            line = string.split(line)
            if line:
                if line[0][0] == '#':
                    continue
                flag = 1
                for i in range(len(line)):
                    if line[i][0] != '#' and flag:
                        continue
                    else:
                        flag = 0
                        del(line[i])
            tutor.append(line)
        # now lets parse and execute the tutor file
        for line in tutor:
            if not line:
                continue
            if line[0] == 'load':
                if last != 'ready':
                    sys.stderr.write("error: load out of order\n")
                    sys.exit(1)
                last = 'load'
                run = 0
            elif line[0] == 'initial':
                if last != 'ready' or not loaded:
                    sys.stderr.write("error: initial out of order\n")
                    sys.exit(1)
                last = line[0]
                run = 0
                labelReq1 = {}
                labelReq2 = {}
                for arg in line[1:]:
                    if ':' in arg:
                        a = string.split(arg,':')
                        labelReq1[a[0]] = ParseValuesM(a[1])
                    elif ';' in arg:
                        a = string.split(arg,';')
                        labelReq2[a[0]] = int(a[1])
                    else:
                        sys.stderr.write("error: bad arguments for initial\n")
                        sys.exit(1)
            elif line[0] == 'init':
                if last == 'load':
                    sys.stdout.write("error: Not testing the initial set of values\n")
                    sys.exit(1)
                elif not loaded:
                    sys.stdout.write("error: program not loaded\n")
                    sys.exit(1)
                else:
                    self.load(program)
                    for arg in line[1:]:
                        foo = string.split(arg,':')
                        if isRegName(foo[0]):
                            bar = int(foo[0][1:])
                            self.reg[bar] = int(foo[1])
                        else:
                            self.VerifyLabelM(foo[0])
                            Values = ParseValuesM(foo[1])
                            # lets verify if the values fit
                            # in the originally allocated space
                            if len(Values) > self.labelms[foo[0]]:
                                self.reserveMemory(foo[0],len(Values))
                            add = self.labelm[foo[0]]
                            for i in Values:
                                self.RAM[add] = i
                                add = add + 1
                last = line[0]
                run = 0
            elif line[0] == 'exec':
                if not loaded:
                    sys.stdout.write("error: program not loaded\n")
                    sys.exit(1)
                else:
                    if len(line) == 1:
                        target = ""
                    else:
                        target = line[1]
                    run = 1
                    last = line[0]
            elif line[0] == 'final' or line[0] == '+final':
                last = line[0]
                if not run:
                    sys.stdout.write("error: need to run the program before testing the results\n")
                    sys.exit(1)
                RegVal = {}
                LabelReq1 = {}
                for arg in line[1:]:
                    foo = string.split(arg,':')
                    if isRegName(foo[0]):
                        RegVal[int(foo[0][1:])] = int(foo[1])
                    else:
                        LabelReq1[foo[0]] = ParseValuesM(foo[1])
            elif line[0] == 'end':
                if self.NoErrorsp():
                    sys.stdout.write("%d OK\n"%self.ggrade)
                else:
                    sys.stdout.write("%d %s"%(self.ggrade,self.ErrMessage))
                sys.exit(0)
            elif line[0] == 'value':
                grade = int(line[1])
                if not last in ['load','initial','exec','final','+final']:
                    sys.stderr.write("error: value out of order\n")
                    sys.exit(1)
                elif last == 'load':
                    program = ReadProgram(self.programFile)
                    try:
                        self.load(program)
                    except vpuError, obj:
                        self.respond(obj.message,obj.line)
                    loaded = 1
                    self.ggrade = self.ggrade + grade
                    last = 'ready'
                elif last == 'initial':
                    for l in labelReq1.keys():
                        self.VerifyLabel1(l,labelReq1[l])
                    for l in labelReq2.keys():
                        self.VerifyLabel2(l,labelReq2[l])
                    self.ggrade = self.ggrade + grade
                elif last == 'exec':
                    if target == "":
                        try:
                            self.run()
                        except EndOfProgram:
                            self.ggrade = self.ggrade + grade
                        except ArithmeticError:
                            self.respond(sys.exc_type)
                        except vpuError, obj:
                            self.respond(obj.message)
                        except: # this should NEVER happen!
                            print sys.exc_type, sys.exc_value 
                elif last == 'final':
                    for r in RegVal.keys():
                        self.VerifyReg(r,RegVal[r])
                    for r in LabelReq1.keys():
                        self.VerifyLabel1(r,LabelReq1[r])
                    self.ggrade = self.ggrade + grade
                elif last == '+final':
                    nErrors = 0
                    for r in RegVal.keys():
                        nErrors = nErrors + self.VerifyReg(r,RegVal[r],True)
                    for r in LabelReq1.keys():
                        nErrors = nErrors + self.VerifyLabel1(r,LabelReq1[r],True)
                    if not nErrors:
                        self.ggrade = self.ggrade + grade

    def VerifyReg(self, r, value, NotVital=False):
        if self.reg[r] != value:
            if NotVital:
                self.SetErrMsg("Register R%d does not have the right value\n"%r)
                return 1
            else:
                sys.stdout.write("%d Register R%d does not have the right value\n"%(self.ggrade,r))
                sys.exit(0)
        else:
            return 0
        
    def VerifyLabelM(self,label):
        if not label in self.labelm.keys():
            sys.stdout.write("%d Label %s not created\n"%(self.ggrade,label))
            sys.exit(0)
                    
    def VerifyLabel1(self, label, values, NotVital=False):
        self.VerifyLabelM(label)
        add = self.labelm[label]
        for v in values:
            try: Wrong = self.RAM[add] != v
            except IndexError:
                Wrong = True
            if Wrong:
                if NotVital:
                    self.SetErrMsg("Label %s does not have the right value\n"%label)
                    return 1
                else:
                    sys.stdout.write("%d Label %s does not have the right value\n"%(self.ggrade,label))
                    sys.exit(0)
            add = add + 1
        return 0
    
    def VerifyLabel2(self, label, size):
        self.VerifyLabelM(label)
        if self.labelms[label] != size:
            sys.stdout.write("%d Label %s does not have the right size assigned\n"%(self.ggrade,label))
            sys.exit(0)

    def NoErrorsp(self):
        try:
            foo = self.ErrMessage
        except AttributeError:
            return True
        return False
    
    def SetErrMsg(self,msg):
        try:
            foo = self.ErrMessage
        except AttributeError:
            self.ErrMessage = msg

    def respond(self,message,line=0):
        if line != 0:
            sys.stdout.write("%d %s in line %d\n"%(self.ggrade,message,line))
            sys.exit(0)
        else:
            sys.stdout.write("%d %s\n"%(self.ggrade,message))
            sys.exit(0)
            
def ParseValuesM(str):
    l1 = string.split(str,',')
    list = []
    for i in l1:
        list.append(int(i))
    return list

def readable(path):
    try:
        mode = posix.stat(path)[stat.ST_MODE]
    except OSError:               # File doesn't exist
        sys.stderr.write("%s not found\n"%path)
        sys.exit(1)
    if not stat.S_ISREG(mode):    # or it's not readable
        sys.stderr.write("%s not readable\n"%path)
        sys.exit(1)
    
# just to use inside pdb
def test(a,b):
    vPu = Vpu_Tutor()
    vPu.tutorFile = a
    vPu.programFile = b
    vPu.doIt()

if __name__ == '__main__':
    if (len(sys.argv) == 2 and sys.argv[1] == "-v"):
            sys.stderr.write("%s\n"%__version)
            sys.stderr.write("%s\n"%vpu.__version)
            sys.stderr.write("%s\n"%constants.__version)
            sys.exit(0)
    elif (len(sys.argv) != 3):
        sys.stderr.write("Usage: apoo-tutor tutor-file apoo-program\n")
        sys.exit(1)
    for i in [sys.argv[1],sys.argv[2]]:
        readable(i)
    vpu = Vpu_Tutor()
    vpu.tutorFile = sys.argv[1]
    vpu.programFile = sys.argv[2]
    vpu.doIt()