File: valdiag.py

package info (click to toggle)
sdcc 3.8.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 99,212 kB
  • sloc: ansic: 918,594; cpp: 69,526; makefile: 56,790; sh: 29,616; asm: 12,364; perl: 12,136; yacc: 7,179; lisp: 1,672; python: 812; lex: 773; awk: 495; sed: 89
file content (393 lines) | stat: -rw-r--r-- 11,784 bytes parent folder | download
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
#!/usr/bin/env python
#---------------------------------------------------------------------------
#  valdiag.py - Validate diagnostic messages from SDCC/GCC
#	  Written By -  Erik Petrich . epetrich@users.sourceforge.net (2003)
#
#   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, 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, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#   
#   In other words, you are welcome to use, share and improve this program.
#   You are forbidden to forbid anyone else to use, share and improve
#   what you give them.   Help stamp out software-hoarding!  
#---------------------------------------------------------------------------

from __future__ import print_function

import sys, string, os, re, subprocess
from subprocess import Popen, PIPE, STDOUT

macrodefs = {}
extramacrodefs = {}

gcc = {
    "CC":"gcc",
    "CCFLAGS":"-c -pedantic -Wall -DPORT_HOST=1",
    "CCDEF":"-D",
    "CCOUTPUT":"-o",
    "C89":"-std=c89",
    "C99":"-std=c99",
    "defined": {
        "__GNUC__":"1",
        "GCC":"1"
    },
    "ignoremsg": [
    ]
}

sdcc = {
    "CC":"../../bin/sdcc",
    "CCFLAGS":"-c -m{port}",
    "CCDEF":"-D",
    "CCOUTPUT":"-o",
    "CCINCLUDEDIR":"-I",
    "C89":"--std-sdcc89",
    "C99":"--std-sdcc99",
    "defined": {
        "SDCC":"1",
        "SDCC_{port}":"1",
        "__{port}":"1"
    },
    "ignoremsg": [
        "code not generated.*due to previous errors",
        "unreferenced function argument"
    ]
}

testmodes = {
    "host":{
        "compiler":gcc,
        "port":"host",
        "defined": {
            "PORT_HOST":"1"
        }
    },
    "mcs51":{
        "compiler":sdcc,
        "port":"mcs51",
        "extra-defines": {
            "__has_bit":"1",
            "__has_data":"1",
            "__has_xdata":"1",
            "__has_reentrant":"1"
        }
    },
    "mcs51-large":{
        "compiler":sdcc,
        "port":"mcs51",
        "flags":"--model-large",
        "defined": {
            "SDCC_MODEL_LARGE":"1"
        },
        "extra-defines" : {
            "__has_bit":"1",
            "__has_data":"1",
            "__has_xdata":"1",
            "__has_reentrant":"1"
        }
    },
    "mcs51-stack-auto":{
        "compiler":sdcc,
        "port":"mcs51",
        "flags":"--stack-auto",
        "defined": {
            "SDCC_STACK_AUTO":"1"
        },
        "extra-defines": {
            "__has_bit":"1",
            "__has_data":"1",
            "__has_xdata":"1",
            "__has_reentrant":"1"
        }
    },
    "ds390":{
        "compiler":sdcc,
        "port":"ds390",
        "extra-defines": {
            "__has_bit":"1",
            "__has_data":"1",
            "__has_xdata":"1",
            "__has_reentrant":"1"
        }
    },
    "z80":{
        "compiler":sdcc,
        "port":"z80"
    },
    "z180":{
        "compiler":sdcc,
        "port":"z180"
    },
    "r2k":{
        "compiler":sdcc,
        "port":"r2k"
    },
    "gbz80":{
        "compiler":sdcc,
        "port":"gbz80"
    },
    "tlcs90":{
        "compiler":sdcc,
        "port":"tlcs90"
    },
    "hc08":{
        "compiler":sdcc,
        "port":"hc08",
        "extra-defines": {
            "__has_data":"1",
            "__has_xdata":"1",
            "__has_reentrant":"1"
        }
    },
    "s08":{
        "compiler":sdcc,
        "port":"s08",
        "extra-defines": {
            "__has_data":"1",
            "__has_xdata":"1",
            "__has_reentrant":"1"
        }
    },
    "stm8":{
        "compiler":sdcc,
        "port":"stm8"
    },
    "pic14":{
        "compiler":sdcc,
        "port":"pic14"
    },
    "pic16":{
        "compiler":sdcc,
        "port":"pic16"
    }
}


def evalQualifier(expr):
    global macrodefs
    tokens = re.split("([^0-9A-Za-z_])", expr)
    for tokenindex in range(len(tokens)):
        token = tokens[tokenindex]
        if token in macrodefs:
            tokens[tokenindex] = macrodefs[token]
        elif token == "defined":
            tokens[tokenindex] = ""
            if tokens[tokenindex+2] in macrodefs:
                tokens[tokenindex+2] = "1"
            else:
                tokens[tokenindex+2] = "0"
        elif len(token)>0:
            if token[0]=="_" or token[0] in string.ascii_letters:
                tokens[tokenindex] = "0"
    #expr = string.join(tokens,"")
    expr = "".join(tokens)
    expr = expr.replace("&&"," and ");
    expr = expr.replace("||"," or ");
    expr = expr.replace("!"," not ");
    return eval(expr)

def expandPyExpr(expr):
    tokens = re.split("({|})", expr)
    for tokenindex in range(1,len(tokens)):
        if tokens[tokenindex-1]=="{":
            tokens[tokenindex]=eval(tokens[tokenindex])
            tokens[tokenindex-1]=""
            tokens[tokenindex+1]=""
    expandedExpr = "".join(tokens)
    return expandedExpr

def addDefines(deflist, isExtra):
    for define in list(deflist.keys()):
        expandeddef = expandPyExpr(define)
        macrodefs[expandeddef] = expandPyExpr(deflist[define])
        if isExtra:
            extramacrodefs[expandeddef] = macrodefs[expandeddef]

def parseInputfile(inputfilename):
    inputfile = open(inputfilename, "r")
    testcases = {}
    testname = ""
    linenumber = 1

    # Find the test cases and tests in this file
    for line in inputfile.readlines():

        # See if a new testcase is being defined
        p = line.find("TEST")
        if p>=0:
            testname = line[p:].split()[0]
            if testname not in testcases:
                testcases[testname] = {}

        # See if a new test is being defined
        for testtype in ["ERROR", "WARNING", "IGNORE"]:
            p = line.find(testtype);
            if p>=0:
                # Found a test definition
                qualifier = line[p+len(testtype):].strip()
                p = qualifier.find("*/")
                if p>=0:
                    qualifier = qualifier[:p].strip()
                if len(qualifier)==0:
                    qualifier="1"
                qualifier = evalQualifier(qualifier)
                if qualifier:
                    if not linenumber in testcases[testname]:
                        testcases[testname][linenumber]=[]
                    testcases[testname][linenumber].append(testtype)

        linenumber = linenumber + 1

    inputfile.close()
    return testcases

def parseResults(output):
    results = {}
    for line in output:
        print(line, end=' ')

        if line.count("SIGSEG"):
            results[0] = ["FAULT", line.strip()]
            continue

        # look for something of the form:
        #   filename:line:message
        msg = line.split(":",2)
        if len(msg)<3: continue
        if msg[0]!=inputfilename: continue
        if len(msg[1])==0: continue
        if not msg[1][0] in string.digits: continue

        # it's in the right form; parse it
        linenumber = int(msg[1])
        msgtype = "UNKNOWN"
        uppermsg = msg[2].upper()
        if uppermsg.count("ERROR"):
            msgtype = "ERROR"
        if uppermsg.count("WARNING"):
            msgtype = "WARNING"
        msgtext = msg[2].strip()
        ignore = 0
        for ignoreExpr in ignoreExprList:
           if re.search(ignoreExpr,msgtext)!=None:
               ignore = 1
        if not ignore:
            results[linenumber]=[msgtype,msg[2].strip()]
    return results

def showUsage():
    print("Usage: test testmode cfile [objectfile]")
    print("Choices for testmode are:")
    for testmodename in list(testmodes.keys()):
        print("   %s" % testmodename)
    sys.exit(1)

# Start here
if len(sys.argv)<3:
    showUsage()

testmodename = sys.argv[1]
if not testmodename in testmodes:
    print("Unknown test mode '%s'" % testmodename)
    showUsage()

testmode = testmodes[testmodename]
compilermode = testmode["compiler"]
port = expandPyExpr(testmode["port"])
cc = expandPyExpr(compilermode["CC"])
ccflags = expandPyExpr(compilermode["CCFLAGS"])
if "flags" in testmode:
    ccflags = " ".join([ccflags,expandPyExpr(testmode["flags"])])
if len(sys.argv)>=4:
    if "CCOUTPUT" in compilermode:
        ccflags = " ".join([ccflags,expandPyExpr(compilermode["CCOUTPUT"]),sys.argv[3]])
if len(sys.argv)>=5:
    if "CCINCLUDEDIR" in compilermode:
        ccflags = " ".join([ccflags,expandPyExpr(compilermode["CCINCLUDEDIR"]),sys.argv[4]])
if "defined" in compilermode:
    addDefines(compilermode["defined"], False)
if "defined" in testmode:
    addDefines(testmode["defined"], False)
if "extra-defines" in compilermode:
    addDefines(compilermode["extra-defines"], True)
if "extra-defines" in testmode:
    addDefines(testmode["extra-defines"], True)
if "ignoremsg" in compilermode:
    ignoreExprList = compilermode["ignoremsg"]
else:
    ignoreExprList = []

inputfilename = sys.argv[2]
inputfilenameshort = os.path.basename(inputfilename)

try:
    testcases = parseInputfile(inputfilename)
except IOError:
    print("Unable to read file '%s'" % inputfilename)
    sys.exit(1)

casecount = len(list(testcases.keys()))
testcount = 0
failurecount = 0

print("--- Running: %s " % inputfilenameshort)
for testname in list(testcases.keys()):
    if testname.find("DISABLED")>=0:
      continue
    ccdef = compilermode["CCDEF"]+testname
    for extradef in list(extramacrodefs.keys()):
        ccdef = ccdef + " " + compilermode["CCDEF"] + extradef + "=" + extramacrodefs[extradef]
    if testname[-3:] == "C89":
        ccstd = compilermode["C89"]
    elif testname[-3:] == "C99":
        ccstd = compilermode["C99"]
    else:
        ccstd = ""
    cmd = " ".join([cc,ccflags,ccstd,ccdef,inputfilename])
    print()
    print(cmd)
    spawn = Popen(args=cmd.split(), bufsize=-1, stdout = PIPE, stderr = STDOUT, close_fds=True)
    (stdoutdata,stderrdata) = spawn.communicate()
    if not isinstance(stdoutdata, str): # python 3 returns bytes so
      stdoutdata = str(stdoutdata,"utf-8") # convert to str type first
    output = stdoutdata.splitlines(True)

    results = parseResults(output)

    if len(testcases[testname])==0:
        testcount = testcount + 1 #implicit test for no errors

    # Go through the tests of this case and make sure
    # the compiler gave a diagnostic
    for checkline in list(testcases[testname].keys()):
        testcount = testcount + 1
        if checkline in results:
            if "IGNORE" in testcases[testname][checkline]:
                testcount = testcount - 1  #this isn't really a test
            del results[checkline]
        else:
            for wanted in testcases[testname][checkline]:
                if not wanted=="IGNORE":
                    print("--- FAIL: expected %s" % wanted, end=' ')
                    print("at %s:%d" % (inputfilename, checkline))
                    failurecount = failurecount + 1

    # Output any unexpected diagnostics    
    for checkline in list(results.keys()):
        print('--- FAIL: unexpected message "%s" ' % results[checkline][1], end=' ')
        print("at %s:%d" % (inputfilename, checkline))
        failurecount = failurecount + 1

print()
print("--- Summary: %d/%d/%d: " % (failurecount, testcount, casecount), end=' ')
print("%d failed of %d tests in %d cases." % (failurecount, testcount, casecount))