Index: bindings/python/clang/cindex.py =================================================================== --- bindings/python/clang/cindex.py +++ bindings/python/clang/cindex.py @@ -44,6 +44,7 @@ Most object information is exposed using properties, when the underlying API call is efficient. """ +from __future__ import print_function # TODO # ==== Index: docs/conf.py =================================================================== --- docs/conf.py +++ docs/conf.py @@ -11,6 +11,7 @@ # All configuration values have a default; values that are commented out # serve to show the default. +from __future__ import print_function import sys, os from datetime import date @@ -233,14 +234,14 @@ header = f.readline().rstrip('\n') if len(header) != len(title): - print >>sys.stderr, ( + print(( "error: invalid header in %r (does not match title)" % ( - file_subpath,)) + file_subpath,)), file=sys.stderr) if ' - ' not in title: - print >>sys.stderr, ( + print(( ("error: invalid title in %r " "(expected ' - ')") % ( - file_subpath,)) + file_subpath,)), file=sys.stderr) # Split the name out of the title. name,description = title.split(' - ', 1) Index: docs/tools/dump_ast_matchers.py =================================================================== --- docs/tools/dump_ast_matchers.py +++ docs/tools/dump_ast_matchers.py @@ -41,8 +41,8 @@ url = 'https://clang.llvm.org/doxygen/classclang_1_1%s.html' % name if url not in doxygen_probes: try: - print 'Probing %s...' % url - urllib2.urlopen(url) + print('Probing %s...' % url) + urlib2.urlopen(url) doxygen_probes[url] = True except: doxygen_probes[url] = False @@ -307,14 +307,14 @@ if not result_types: if not comment: # Only overloads don't have their own doxygen comments; ignore those. - print 'Ignoring "%s"' % name + print('Ignoring "%s"' % name) else: - print 'Cannot determine result type for "%s"' % name + print('Cannot determine result type for "%s"' % name) else: for result_type in result_types: add_matcher(result_type, name, args, comment) else: - print '*** Unparsable: "' + declaration + '" ***' + print('*** Unparsable: "' + declaration + '" ***') def sort_table(matcher_type, matcher_map): """Returns the sorted html table for the given row map.""" Index: tools/clang-format/clang-format-diff.py =================================================================== --- tools/clang-format/clang-format-diff.py +++ tools/clang-format/clang-format-diff.py @@ -21,6 +21,7 @@ svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i """ +from __future__ import print_function import argparse import difflib Index: tools/scan-build-py/libscanbuild/arguments.py =================================================================== --- tools/scan-build-py/libscanbuild/arguments.py +++ tools/scan-build-py/libscanbuild/arguments.py @@ -12,6 +12,7 @@ It also implements basic validation methods, related to the command. Validations are mostly calling specific help methods, or mangling values. """ +from __future__ import print_function import os import sys Index: tools/scan-view/share/ScanView.py =================================================================== --- tools/scan-view/share/ScanView.py +++ tools/scan-view/share/ScanView.py @@ -1,5 +1,6 @@ import BaseHTTPServer import SimpleHTTPServer +from __future__ import print_function import os import sys import urllib, urlparse @@ -101,20 +102,20 @@ result = None try: if self.server.options.debug: - print >>sys.stderr, "%s: SERVER: submitting bug."%(sys.argv[0],) + print("%s: SERVER: submitting bug."%(sys.argv[0],), file=sys.stderr) self.status = self.reporter.fileReport(self.report, self.parameters) self.success = True time.sleep(3) if self.server.options.debug: - print >>sys.stderr, "%s: SERVER: submission complete."%(sys.argv[0],) + print("%s: SERVER: submission complete."%(sys.argv[0],), file=sys.stderr) except Reporter.ReportFailure as e: self.status = e.value except Exception as e: s = StringIO() import traceback - print >>s,'Unhandled Exception
'
+            print('Unhandled Exception
', file=s)
             traceback.print_exc(e,file=s)
-            print >>s,'
' + print('
', file=s) self.status = s.getvalue() class ScanViewServer(BaseHTTPServer.HTTPServer): @@ -160,16 +161,16 @@ def halt(self): self.halted = True if self.options.debug: - print >>sys.stderr, "%s: SERVER: halting." % (sys.argv[0],) + print("%s: SERVER: halting." % (sys.argv[0],), file=sys.stderr) def serve_forever(self): while not self.halted: if self.options.debug > 1: - print >>sys.stderr, "%s: SERVER: waiting..." % (sys.argv[0],) + print("%s: SERVER: waiting..." % (sys.argv[0],), file=sys.stderr) try: self.handle_request() except OSError as e: - print 'OSError',e.errno + print('OSError',e.errno) def finish_request(self, request, client_address): if self.options.autoReload: @@ -182,7 +183,7 @@ info = sys.exc_info() if info and isinstance(info[1], socket.error): if self.options.debug > 1: - print >>sys.stderr, "%s: SERVER: ignored socket error." % (sys.argv[0],) + print("%s: SERVER: ignored socket error." % (sys.argv[0],), file=sys.stderr) return BaseHTTPServer.HTTPServer.handle_error(self, request, client_address) @@ -269,7 +270,7 @@ def handle_exception(self, exc): import traceback s = StringIO() - print >>s, "INTERNAL ERROR\n" + print("INTERNAL ERROR\n", file=s) traceback.print_exc(exc, s) f = self.send_string(s.getvalue(), 'text/plain') if f: @@ -415,8 +416,8 @@ import startfile if self.server.options.debug: - print >>sys.stderr, '%s: SERVER: opening "%s"'%(sys.argv[0], - file) + print('%s: SERVER: opening "%s"'%(sys.argv[0], + file), file=sys.stderr) status = startfile.open(file) if status: @@ -695,8 +696,8 @@ path = posixpath.join(self.server.root, relpath) if self.server.options.debug > 1: - print >>sys.stderr, '%s: SERVER: sending path "%s"'%(sys.argv[0], - path) + print('%s: SERVER: sending path "%s"'%(sys.argv[0], + path), file=sys.stderr) return self.send_path(path) def send_404(self): Index: utils/ABITest/ABITestGen.py =================================================================== --- utils/ABITest/ABITestGen.py +++ utils/ABITest/ABITestGen.py @@ -1,5 +1,6 @@ #!/usr/bin/env python +from __future__ import print_function from pprint import pprint import random, atexit, time from random import randrange @@ -28,42 +29,42 @@ if info: for f in (self.output,self.outputHeader,self.outputTests,self.outputDriver): if f: - print >>f,info + print(info, file=f) if self.writeBody: - print >>self.output, '#include \n' + print('#include \n', file=self.output) if self.outputTests: - print >>self.outputTests, '#include ' - print >>self.outputTests, '#include ' - print >>self.outputTests, '#include \n' + print('#include ', file=self.outputTests) + print('#include ', file=self.outputTests) + print('#include \n', file=self.outputTests) if headerName: for f in (self.output,self.outputTests,self.outputDriver): if f is not None: - print >>f, '#include "%s"\n'%(headerName,) + print('#include "%s"\n'%(headerName,), file=f) if self.outputDriver: - print >>self.outputDriver, '#include ' - print >>self.outputDriver, '#include \n' - print >>self.outputDriver, 'int main(int argc, char **argv) {' - print >>self.outputDriver, ' int index = -1;' - print >>self.outputDriver, ' if (argc > 1) index = atoi(argv[1]);' + print('#include ', file=self.outputDriver) + print('#include \n', file=self.outputDriver) + print('int main(int argc, char **argv) {', file=self.outputDriver) + print(' int index = -1;', file=self.outputDriver) + print(' if (argc > 1) index = atoi(argv[1]);', file=self.outputDriver) def finish(self): if self.layoutTests: - print >>self.output, 'int main(int argc, char **argv) {' - print >>self.output, ' int index = -1;' - print >>self.output, ' if (argc > 1) index = atoi(argv[1]);' + print('int main(int argc, char **argv) {', file=self.output) + print(' int index = -1;', file=self.output) + print(' if (argc > 1) index = atoi(argv[1]);', file=self.output) for i,f in self.layoutTests: - print >>self.output, ' if (index == -1 || index == %d)' % i - print >>self.output, ' %s();' % f - print >>self.output, ' return 0;' - print >>self.output, '}' + print(' if (index == -1 || index == %d)' % i, file=self.output) + print(' %s();' % f, file=self.output) + print(' return 0;', file=self.output) + print('}', file=self.output) if self.outputDriver: - print >>self.outputDriver, ' printf("DONE\\n");' - print >>self.outputDriver, ' return 0;' - print >>self.outputDriver, '}' + print(' printf("DONE\\n");', file=self.outputDriver) + print(' return 0;', file=self.outputDriver) + print('}', file=self.outputDriver) def addDeclaration(self, decl): if decl in self.declarations: @@ -71,11 +72,11 @@ self.declarations.add(decl) if self.outputHeader: - print >>self.outputHeader, decl + print(decl, file=self.outputHeader) else: - print >>self.output, decl + print(decl, file=self.output) if self.outputTests: - print >>self.outputTests, decl + print(decl, file=self.outputTests) return True def getTypeName(self, T): @@ -91,12 +92,12 @@ tyNameClean = tyName.replace(' ','_').replace('*','star') fnName = 'test_%s' % tyNameClean - print >>self.output,'void %s(void) {' % fnName + print('void %s(void) {' % fnName, file=self.output) self.printSizeOfType(' %s'%fnName, tyName, ty, self.output) self.printAlignOfType(' %s'%fnName, tyName, ty, self.output) self.printOffsetsOfType(' %s'%fnName, tyName, ty, self.output) - print >>self.output,'}' - print >>self.output + print('}', file=self.output) + print(file=self.output) self.layoutTests.append((i,fnName)) @@ -115,71 +116,71 @@ fnName = 'fn%d'%(FT.index,) if self.outputHeader: - print >>self.outputHeader,'%s %s(%s);'%(retvalTypeName, fnName, args) + print('%s %s(%s);'%(retvalTypeName, fnName, args), file=self.outputHeader) elif self.outputTests: - print >>self.outputTests,'%s %s(%s);'%(retvalTypeName, fnName, args) + print('%s %s(%s);'%(retvalTypeName, fnName, args), file=self.outputTests) - print >>self.output,'%s %s(%s)'%(retvalTypeName, fnName, args), + print('%s %s(%s)'%(retvalTypeName, fnName, args), end=' ', file=self.output) if self.writeBody: - print >>self.output, '{' + print('{', file=self.output) for i,t in enumerate(FT.argTypes): self.printValueOfType(' %s'%fnName, 'arg%d'%i, t) if retvalName is not None: - print >>self.output, ' return %s;'%(retvalName,) - print >>self.output, '}' + print(' return %s;'%(retvalName,), file=self.output) + print('}', file=self.output) else: - print >>self.output, '{}' - print >>self.output + print('{}', file=self.output) + print(file=self.output) if self.outputDriver: - print >>self.outputDriver, ' if (index == -1 || index == %d) {' % i - print >>self.outputDriver, ' extern void test_%s(void);' % fnName - print >>self.outputDriver, ' test_%s();' % fnName - print >>self.outputDriver, ' }' + print(' if (index == -1 || index == %d) {' % i, file=self.outputDriver) + print(' extern void test_%s(void);' % fnName, file=self.outputDriver) + print(' test_%s();' % fnName, file=self.outputDriver) + print(' }', file=self.outputDriver) if self.outputTests: if self.outputHeader: - print >>self.outputHeader, 'void test_%s(void);'%(fnName,) + print('void test_%s(void);'%(fnName,), file=self.outputHeader) if retvalName is None: retvalTests = None else: retvalTests = self.getTestValuesArray(FT.returnType) tests = [self.getTestValuesArray(ty) for ty in FT.argTypes] - print >>self.outputTests, 'void test_%s(void) {'%(fnName,) + print('void test_%s(void) {'%(fnName,), file=self.outputTests) if retvalTests is not None: - print >>self.outputTests, ' printf("%s: testing return.\\n");'%(fnName,) - print >>self.outputTests, ' for (int i=0; i<%d; ++i) {'%(retvalTests[1],) + print(' printf("%s: testing return.\\n");'%(fnName,), file=self.outputTests) + print(' for (int i=0; i<%d; ++i) {'%(retvalTests[1],), file=self.outputTests) args = ', '.join(['%s[%d]'%(t,randrange(l)) for t,l in tests]) - print >>self.outputTests, ' %s RV;'%(retvalTypeName,) - print >>self.outputTests, ' %s = %s[i];'%(retvalName, retvalTests[0]) - print >>self.outputTests, ' RV = %s(%s);'%(fnName, args) + print(' %s RV;'%(retvalTypeName,), file=self.outputTests) + print(' %s = %s[i];'%(retvalName, retvalTests[0]), file=self.outputTests) + print(' RV = %s(%s);'%(fnName, args), file=self.outputTests) self.printValueOfType(' %s_RV'%fnName, 'RV', FT.returnType, output=self.outputTests, indent=4) self.checkTypeValues('RV', '%s[i]' % retvalTests[0], FT.returnType, output=self.outputTests, indent=4) - print >>self.outputTests, ' }' + print(' }', file=self.outputTests) if tests: - print >>self.outputTests, ' printf("%s: testing arguments.\\n");'%(fnName,) + print(' printf("%s: testing arguments.\\n");'%(fnName,), file=self.outputTests) for i,(array,length) in enumerate(tests): for j in range(length): args = ['%s[%d]'%(t,randrange(l)) for t,l in tests] args[i] = '%s[%d]'%(array,j) - print >>self.outputTests, ' %s(%s);'%(fnName, ', '.join(args),) - print >>self.outputTests, '}' + print(' %s(%s);'%(fnName, ', '.join(args),), file=self.outputTests) + print('}', file=self.outputTests) def getTestReturnValue(self, type): typeName = self.getTypeName(type) info = self.testReturnValues.get(typeName) if info is None: name = '%s_retval'%(typeName.replace(' ','_').replace('*','star'),) - print >>self.output, '%s %s;'%(typeName,name) + print('%s %s;'%(typeName,name), file=self.output) if self.outputHeader: - print >>self.outputHeader, 'extern %s %s;'%(typeName,name) + print('extern %s %s;'%(typeName,name), file=self.outputHeader) elif self.outputTests: - print >>self.outputTests, 'extern %s %s;'%(typeName,name) + print('extern %s %s;'%(typeName,name), file=self.outputTests) info = self.testReturnValues[typeName] = name return info @@ -188,12 +189,12 @@ info = self.testValues.get(typeName) if info is None: name = '%s_values'%(typeName.replace(' ','_').replace('*','star'),) - print >>self.outputTests, 'static %s %s[] = {'%(typeName,name) + print('static %s %s[] = {'%(typeName,name), file=self.outputTests) length = 0 for item in self.getTestValues(type): - print >>self.outputTests, '\t%s,'%(item,) + print('\t%s,'%(item,), file=self.outputTests) length += 1 - print >>self.outputTests,'};' + print('};', file=self.outputTests) info = self.testValues[typeName] = (name,length) return info @@ -253,16 +254,16 @@ raise NotImplementedError('Cannot make tests values of type: "%s"'%(t,)) def printSizeOfType(self, prefix, name, t, output=None, indent=2): - print >>output, '%*sprintf("%s: sizeof(%s) = %%ld\\n", (long)sizeof(%s));'%(indent, '', prefix, name, name) + print('%*sprintf("%s: sizeof(%s) = %%ld\\n", (long)sizeof(%s));'%(indent, '', prefix, name, name), file=output) def printAlignOfType(self, prefix, name, t, output=None, indent=2): - print >>output, '%*sprintf("%s: __alignof__(%s) = %%ld\\n", (long)__alignof__(%s));'%(indent, '', prefix, name, name) + print('%*sprintf("%s: __alignof__(%s) = %%ld\\n", (long)__alignof__(%s));'%(indent, '', prefix, name, name), file=output) def printOffsetsOfType(self, prefix, name, t, output=None, indent=2): if isinstance(t, RecordType): for i,f in enumerate(t.fields): if f.isBitField(): continue fname = 'field%d' % i - print >>output, '%*sprintf("%s: __builtin_offsetof(%s, %s) = %%ld\\n", (long)__builtin_offsetof(%s, %s));'%(indent, '', prefix, name, fname, name, fname) + print('%*sprintf("%s: __builtin_offsetof(%s, %s) = %%ld\\n", (long)__builtin_offsetof(%s, %s));'%(indent, '', prefix, name, fname, name, fname), file=output) def printValueOfType(self, prefix, name, t, output=None, indent=2): if output is None: @@ -286,13 +287,13 @@ code = 'Lf' else: code = 'p' - print >>output, '%*sprintf("%s: %s = %%%s\\n", %s);'%( - indent, '', prefix, name, code, value_expr) + print('%*sprintf("%s: %s = %%%s\\n", %s);'%( + indent, '', prefix, name, code, value_expr), file=output) elif isinstance(t, EnumType): - print >>output, '%*sprintf("%s: %s = %%d\\n", %s);'%(indent, '', prefix, name, name) + print('%*sprintf("%s: %s = %%d\\n", %s);'%(indent, '', prefix, name, name), file=output) elif isinstance(t, RecordType): if not t.fields: - print >>output, '%*sprintf("%s: %s (empty)\\n");'%(indent, '', prefix, name) + print('%*sprintf("%s: %s (empty)\\n");'%(indent, '', prefix, name), file=output) for i,f in enumerate(t.fields): if f.isPaddingBitField(): continue @@ -317,9 +318,9 @@ if output is None: output = self.output if isinstance(t, BuiltinType): - print >>output, '%*sassert(%s == %s);' % (indent, '', nameLHS, nameRHS) + print('%*sassert(%s == %s);' % (indent, '', nameLHS, nameRHS), file=output) elif isinstance(t, EnumType): - print >>output, '%*sassert(%s == %s);' % (indent, '', nameLHS, nameRHS) + print('%*sassert(%s == %s);' % (indent, '', nameLHS, nameRHS), file=output) elif isinstance(t, RecordType): for i,f in enumerate(t.fields): if f.isPaddingBitField(): @@ -644,7 +645,7 @@ FT = ftg.get(N) except RuntimeError as e: if e.args[0]=='maximum recursion depth exceeded': - print >>sys.stderr,'WARNING: Skipped %d, recursion limit exceeded (bad arguments?)'%(N,) + print('WARNING: Skipped %d, recursion limit exceeded (bad arguments?)'%(N,), file=sys.stderr) return raise if opts.testLayout: Index: utils/ABITest/Enumeration.py =================================================================== --- utils/ABITest/Enumeration.py +++ utils/ABITest/Enumeration.py @@ -1,5 +1,6 @@ """Utilities for enumeration of finite and countably infinite sets. """ +from __future__ import print_function ### # Countable iteration @@ -233,18 +234,18 @@ for i in range(min(W*H,40)): x,y = getNthPairBounded(i,W,H) x2,y2 = getNthPairBounded(i,W,H,useDivmod=True) - print i,(x,y),(x2,y2) + print(i,(x,y),(x2,y2)) a[y][x] = '%2d'%i b[y2][x2] = '%2d'%i - print '-- a --' + print('-- a --') for ln in a[::-1]: if ''.join(ln).strip(): - print ' '.join(ln) - print '-- b --' + print(' '.join(ln)) + print('-- b --') for ln in b[::-1]: if ''.join(ln).strip(): - print ' '.join(ln) + print(' '.join(ln)) def testPairsVB(): bounds = [2,2,4,aleph0,5,aleph0] @@ -252,13 +253,13 @@ b = [[' ' for x in range(15)] for y in range(15)] for i in range(min(sum(bounds),40)): x,y = getNthPairVariableBounds(i, bounds) - print i,(x,y) + print(i,(x,y)) a[y][x] = '%2d'%i - print '-- a --' + print('-- a --') for ln in a[::-1]: if ''.join(ln).strip(): - print ' '.join(ln) + print(' '.join(ln)) ### Index: utils/ABITest/TypeGen.py =================================================================== --- utils/ABITest/TypeGen.py +++ utils/ABITest/TypeGen.py @@ -1,4 +1,5 @@ """Flexible enumeration of C types.""" +from __future__ import print_function from Enumeration import * @@ -461,7 +462,7 @@ atg.addGenerator( btg ) atg.addGenerator( RecordTypeGenerator(fields0, False, 4) ) atg.addGenerator( etg ) - print 'Cardinality:',atg.cardinality + print('Cardinality:',atg.cardinality) for i in range(100): if i == atg.cardinality: try: @@ -469,7 +470,7 @@ raise RuntimeError("Cardinality was wrong") except AssertionError: break - print '%4d: %s'%(i, atg.get(i)) + print('%4d: %s'%(i, atg.get(i))) if __name__ == '__main__': test() Index: utils/CIndex/completion_logger_server.py =================================================================== --- utils/CIndex/completion_logger_server.py +++ utils/CIndex/completion_logger_server.py @@ -1,4 +1,5 @@ #!/usr/bin/env python +from __future__ import print_function import sys from socket import * from time import strftime @@ -6,7 +7,7 @@ def main(): if len(sys.argv) < 4: - print "completion_logger_server.py " + print("completion_logger_server.py ") exit(1) host = sys.argv[1] @@ -18,7 +19,7 @@ UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.bind(addr) - print "Listing on {0}:{1} and logging to '{2}'".format(host, port, sys.argv[3]) + print("Listing on {0}:{1} and logging to '{2}'".format(host, port, sys.argv[3])) # Open the logging file. f = open(sys.argv[3], "a") Index: utils/TestUtils/deep-stack.py =================================================================== --- utils/TestUtils/deep-stack.py +++ utils/TestUtils/deep-stack.py @@ -1,22 +1,23 @@ #!/usr/bin/env python +from __future__ import print_function def pcall(f, N): if N == 0: - print >>f, ' f(0)' + print(' f(0)', file=f) return - print >>f, ' f(' + print(' f(', file=f) pcall(f, N - 1) - print >>f, ' )' + print(' )', file=f) def main(): f = open('t.c','w') - print >>f, 'int f(int n) { return n; }' - print >>f, 'int t() {' - print >>f, ' return' + print('int f(int n) { return n; }', file=f) + print('int t() {', file=f) + print(' return', file=f) pcall(f, 10000) - print >>f, ' ;' - print >>f, '}' + print(' ;', file=f) + print('}', file=f) if __name__ == "__main__": import sys Index: utils/analyzer/CmpRuns.py =================================================================== --- utils/analyzer/CmpRuns.py +++ utils/analyzer/CmpRuns.py @@ -25,6 +25,7 @@ diff = compareResults(resultsA, resultsB) """ +from __future__ import print_function from collections import defaultdict @@ -318,7 +319,7 @@ statsB = deriveStats(resultsB) keys = sorted(statsA.keys()) for key in keys: - print key + print(key) for kkey in statsA[key]: valA = float(statsA[key][kkey]) valB = float(statsB[key][kkey]) @@ -331,7 +332,7 @@ report = Colors.GREEN + report + Colors.CLEAR elif ratio > 0.2: report = Colors.RED + report + Colors.CLEAR - print "\t %s %s" % (kkey, report) + print("\t %s %s" % (kkey, report)) def dumpScanBuildResultsDiff(dirA, dirB, opts, deleteEmpty=True, Stdout=sys.stdout): Index: utils/analyzer/SATestAdd.py =================================================================== --- utils/analyzer/SATestAdd.py +++ utils/analyzer/SATestAdd.py @@ -42,6 +42,7 @@ diff -ur CachedSource PatchedSource \ > changes_for_analyzer.patch """ +from __future__ import print_function import SATestBuild import os @@ -66,7 +67,7 @@ CurDir = os.path.abspath(os.curdir) Dir = SATestBuild.getProjectDir(ID) if not os.path.exists(Dir): - print "Error: Project directory is missing: %s" % Dir + print("Error: Project directory is missing: %s" % Dir) sys.exit(-1) # Build the project. @@ -78,30 +79,30 @@ if os.path.exists(ProjectMapPath): FileMode = "r+b" else: - print "Warning: Creating the Project Map file!!" + print("Warning: Creating the Project Map file!!") FileMode = "w+b" with open(ProjectMapPath, FileMode) as PMapFile: if (isExistingProject(PMapFile, ID)): - print >> sys.stdout, 'Warning: Project with ID \'', ID, \ - '\' already exists.' - print >> sys.stdout, "Reference output has been regenerated." + print('Warning: Project with ID \'', ID, \ + '\' already exists.', file=sys.stdout) + print("Reference output has been regenerated.", file=sys.stdout) else: PMapWriter = csv.writer(PMapFile) PMapWriter.writerow((ID, int(BuildMode))) - print "The project map is updated: ", ProjectMapPath + print("The project map is updated: ", ProjectMapPath) # TODO: Add an option not to build. # TODO: Set the path to the Repository directory. if __name__ == '__main__': if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'): - print >> sys.stderr, 'Add a new project for testing to the analyzer'\ + print('Add a new project for testing to the analyzer'\ '\nUsage: ', sys.argv[0],\ 'project_ID \n' \ 'mode: 0 for single file project, ' \ '1 for scan_build, ' \ - '2 for single file c++11 project' + '2 for single file c++11 project', file=sys.stderr) sys.exit(-1) BuildMode = 1 Index: utils/analyzer/SATestBuild.py =================================================================== --- utils/analyzer/SATestBuild.py +++ utils/analyzer/SATestBuild.py @@ -119,7 +119,7 @@ else: Clang = SATestUtils.which("clang", os.environ['PATH']) if not Clang: - print "Error: cannot find 'clang' in PATH" + print("Error: cannot find 'clang' in PATH") sys.exit(1) # Number of jobs. @@ -567,8 +567,8 @@ NewList.remove(os.path.join(NewDir, LogFolderName)) if len(RefList) != len(NewList): - print "Mismatch in number of results folders: %s vs %s" % ( - RefList, NewList) + print("Mismatch in number of results folders: %s vs %s" % ( + RefList, NewList)) sys.exit(1) # There might be more then one folder underneath - one per each scan-build @@ -715,11 +715,11 @@ """ for I in iterateOverProjects(PMapFile): if len(I) != 2: - print "Error: Rows in the ProjectMapFile should have 2 entries." + print("Error: Rows in the ProjectMapFile should have 2 entries.") raise Exception() if I[1] not in ('0', '1', '2'): - print "Error: Second entry in the ProjectMapFile should be 0" \ - " (single file), 1 (project), or 2(single file c++11)." + print("Error: Second entry in the ProjectMapFile should be 0" \ + " (single file), 1 (project), or 2(single file c++11).") raise Exception() def singleThreadedTestAll(Args, ProjectsToTest): @@ -802,5 +802,5 @@ TestsPassed = testAll(Args) if not TestsPassed: - print "ERROR: Tests failed." + print("ERROR: Tests failed.") sys.exit(42) Index: utils/analyzer/SATestUpdateDiffs.py =================================================================== --- utils/analyzer/SATestUpdateDiffs.py +++ utils/analyzer/SATestUpdateDiffs.py @@ -3,6 +3,7 @@ """ Update reference results for static analyzer. """ +from __future__ import print_function import SATestBuild @@ -15,7 +16,7 @@ def runCmd(Command, **kwargs): if Verbose: - print "Executing %s" % Command + print("Executing %s" % Command) check_call(Command, shell=True, **kwargs) @@ -30,8 +31,8 @@ SATestBuild.getSBOutputDirName(IsReferenceBuild=False)) if not os.path.exists(CreatedResultsPath): - print >> sys.stderr, "New results not found, was SATestBuild.py "\ - "previously run?" + print("New results not found, was SATestBuild.py "\ + "previously run?", file=sys.stderr) sys.exit(1) BuildLogPath = SATestBuild.getBuildLogPath(RefResultsPath) @@ -62,9 +63,9 @@ def main(argv): if len(argv) == 2 and argv[1] in ('-h', '--help'): - print >> sys.stderr, "Update static analyzer reference results based "\ + print("Update static analyzer reference results based "\ "\non the previous run of SATestBuild.py.\n"\ - "\nN.B.: Assumes that SATestBuild.py was just run" + "\nN.B.: Assumes that SATestBuild.py was just run", file=sys.stderr) sys.exit(1) with SATestBuild.projectFileHandler() as f: Index: utils/analyzer/SumTimerInfo.py =================================================================== --- utils/analyzer/SumTimerInfo.py +++ utils/analyzer/SumTimerInfo.py @@ -6,13 +6,14 @@ Statistics are enabled by passing '-internal-stats' option to scan-build (or '-analyzer-stats' to the analyzer). """ +from __future__ import print_function import sys if __name__ == '__main__': if len(sys.argv) < 2: - print >> sys.stderr, 'Usage: ', sys.argv[0],\ - 'scan_build_output_file' + print('Usage: ', sys.argv[0],\ + 'scan_build_output_file', file=sys.stderr) sys.exit(-1) f = open(sys.argv[1], 'r') @@ -65,15 +66,15 @@ s = line.split() TotalTime = TotalTime + float(s[6]) - print "TU Count %d" % (Count) - print "Time %f" % (Time) - print "Warnings %d" % (Warnings) - print "Functions Analyzed %d" % (FunctionsAnalyzed) - print "Reachable Blocks %d" % (ReachableBlocks) - print "Reached Max Steps %d" % (ReachedMaxSteps) - print "Number of Steps %d" % (NumSteps) - print "Number of Inlined calls %d (bifurcated %d)" % ( - NumInlinedCallSites, NumBifurcatedCallSites) - print "MaxTime %f" % (MaxTime) - print "TotalTime %f" % (TotalTime) - print "Max CFG Size %d" % (MaxCFGSize) + print("TU Count %d" % (Count)) + print("Time %f" % (Time)) + print("Warnings %d" % (Warnings)) + print("Functions Analyzed %d" % (FunctionsAnalyzed)) + print("Reachable Blocks %d" % (ReachableBlocks)) + print("Reached Max Steps %d" % (ReachedMaxSteps)) + print("Number of Steps %d" % (NumSteps)) + print("Number of Inlined calls %d (bifurcated %d)" % ( + NumInlinedCallSites, NumBifurcatedCallSites)) + print("MaxTime %f" % (MaxTime)) + print("TotalTime %f" % (TotalTime)) + print("Max CFG Size %d" % (MaxCFGSize)) Index: utils/check_cfc/setup.py =================================================================== --- utils/check_cfc/setup.py +++ utils/check_cfc/setup.py @@ -1,6 +1,7 @@ """For use on Windows. Run with: python.exe setup.py py2exe """ +from __future__ import print_function from distutils.core import setup try: import py2exe @@ -8,10 +9,10 @@ import platform import sys if platform.system() == 'Windows': - print "Could not find py2exe. Please install then run setup.py py2exe." + print("Could not find py2exe. Please install then run setup.py py2exe.") raise else: - print "setup.py only required on Windows." + print("setup.py only required on Windows.") sys.exit(1) setup( Index: utils/clangdiag.py =================================================================== --- utils/clangdiag.py +++ utils/clangdiag.py @@ -9,6 +9,7 @@ # (lldb) command script import /path/to/clandiag.py #---------------------------------------------------------------------- +from __future__ import print_function import lldb import argparse import commands @@ -189,4 +190,4 @@ # Add any commands contained in this module to LLDB debugger.HandleCommand( 'command script add -f clangdiag.the_diag_command clangdiag') - print 'The "clangdiag" command has been installed, type "help clangdiag" or "clangdiag --help" for detailed help.' + print('The "clangdiag" command has been installed, type "help clangdiag" or "clangdiag --help" for detailed help.') Index: utils/modfuzz.py =================================================================== --- utils/modfuzz.py +++ utils/modfuzz.py @@ -4,6 +4,7 @@ # 1) Update the 'decls' list below with your fuzzing configuration. # 2) Run with the clang binary as the command-line argument. +from __future__ import print_function import random import subprocess import sys @@ -97,7 +98,7 @@ if not model.fails(): return except KeyboardInterrupt: - print + print() return True sys.stdout.write('\nReducing:\n') Index: utils/token-delta.py =================================================================== --- utils/token-delta.py +++ utils/token-delta.py @@ -1,5 +1,6 @@ #!/usr/bin/env python +from __future__ import print_function import os import re import subprocess @@ -165,7 +166,7 @@ byFile = self.writeFiles(changes, self.tempFiles) if self.log: - print >>sys.stderr, 'TEST - ', + print('TEST - ', end=' ', file=sys.stderr) if self.log > 1: for i,(file,_) in enumerate(self.tokenLists): indices = byFile[i] @@ -184,8 +185,8 @@ sys.stderr.write(str(byFile[i][-1])) sys.stderr.write('] ') else: - print >>sys.stderr, ', '.join(['%s:%d tokens' % (file, len(byFile[i])) - for i,(file,_) in enumerate(self.tokenLists)]), + print(', '.join(['%s:%d tokens' % (file, len(byFile[i])) + for i,(file,_) in enumerate(self.tokenLists)]), end=' ', file=sys.stderr) p = subprocess.Popen([self.testProgram] + self.tempFiles) res = p.wait() == 0 @@ -194,10 +195,10 @@ self.writeFiles(changes, self.targetFiles) if self.log: - print >>sys.stderr, '=> %s' % res + print('=> %s' % res, file=sys.stderr) else: if res: - print '\nSUCCESS (%d tokens)' % len(changes) + print('\nSUCCESS (%d tokens)' % len(changes)) else: sys.stderr.write('.') @@ -209,7 +210,7 @@ for j in range(len(tokens))]) self.writeFiles(res, self.targetFiles) if not self.log: - print >>sys.stderr + print(file=sys.stderr) return res def tokenBasedMultiDelta(program, files, log): @@ -218,15 +219,15 @@ for file in files] numTokens = sum([len(tokens) for _,tokens in tokenLists]) - print "Delta on %s with %d tokens." % (', '.join(files), numTokens) + print("Delta on %s with %d tokens." % (', '.join(files), numTokens)) tbmd = TMBDDelta(program, tokenLists, log) res = tbmd.run() - print "Finished %s with %d tokens (in %d tests)." % (', '.join(tbmd.targetFiles), + print("Finished %s with %d tokens (in %d tests)." % (', '.join(tbmd.targetFiles), len(res), - tbmd.numTests) + tbmd.numTests)) def main(): from optparse import OptionParser, OptionGroup @@ -247,5 +248,5 @@ try: main() except KeyboardInterrupt: - print >>sys.stderr,'Interrupted.' + print('Interrupted.', file=sys.stderr) os._exit(1) # Avoid freeing our giant cache.