summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSerge Guelton <sguelton@quarkslab.com>2018-12-18 08:36:33 +0000
committerSerge Guelton <sguelton@quarkslab.com>2018-12-18 08:36:33 +0000
commit4f672fc63af4f838531fa8b85152024c037ccea3 (patch)
tree5c6b4ebdcc16a64425627d6caaa4bf3bff622f65
parent69150282888f67763b847e6d1c2709f4c272abaa (diff)
Portable Python script across Python version
Using from __future__ import print_function it is possible to have a compatible behavior of `print(...)` across Python version. Differential Revision: https://reviews.llvm.org/D55213 git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@349454 91177308-0d34-0410-b5e6-96231b3b80d8
-rw-r--r--bindings/python/clang/cindex.py1
-rw-r--r--docs/conf.py9
-rwxr-xr-xdocs/tools/dump_ast_matchers.py8
-rwxr-xr-xtools/clang-format/clang-format-diff.py1
-rw-r--r--tools/scan-build-py/libscanbuild/arguments.py1
-rwxr-xr-xtools/scan-view/bin/scan-view12
-rw-r--r--tools/scan-view/share/ScanView.py31
-rwxr-xr-xutils/ABITest/ABITestGen.py133
-rw-r--r--utils/ABITest/Enumeration.py17
-rw-r--r--utils/ABITest/TypeGen.py5
-rwxr-xr-xutils/CIndex/completion_logger_server.py5
-rwxr-xr-xutils/TestUtils/deep-stack.py17
-rwxr-xr-xutils/analyzer/CmpRuns.py5
-rwxr-xr-xutils/analyzer/SATestAdd.py17
-rwxr-xr-xutils/analyzer/SATestBuild.py14
-rwxr-xr-xutils/analyzer/SATestUpdateDiffs.py11
-rw-r--r--utils/analyzer/SumTimerInfo.py29
-rw-r--r--utils/check_cfc/setup.py5
-rwxr-xr-xutils/clangdiag.py3
-rw-r--r--utils/modfuzz.py3
-rwxr-xr-xutils/token-delta.py21
21 files changed, 184 insertions, 164 deletions
diff --git a/bindings/python/clang/cindex.py b/bindings/python/clang/cindex.py
index 72e8fdb8a8..5dbe809af9 100644
--- a/bindings/python/clang/cindex.py
+++ b/bindings/python/clang/cindex.py
@@ -44,6 +44,7 @@ The major indexing objects are:
Most object information is exposed using properties, when the underlying API
call is efficient.
"""
+from __future__ import print_function
# TODO
# ====
diff --git a/docs/conf.py b/docs/conf.py
index dc69f8a848..a18ce3a304 100644
--- a/docs/conf.py
+++ b/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 @@ for name in os.listdir(command_guide_path):
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 '<name> - <description>')") % (
- file_subpath,))
+ file_subpath,)), file=sys.stderr)
# Split the name out of the title.
name,description = title.split(' - ', 1)
diff --git a/docs/tools/dump_ast_matchers.py b/docs/tools/dump_ast_matchers.py
index 2c0cbafa8a..cae27b20a9 100755
--- a/docs/tools/dump_ast_matchers.py
+++ b/docs/tools/dump_ast_matchers.py
@@ -41,7 +41,7 @@ def esc(text):
url = 'https://clang.llvm.org/doxygen/classclang_1_1%s.html' % name
if url not in doxygen_probes:
try:
- print 'Probing %s...' % url
+ print('Probing %s...' % url)
urllib2.urlopen(url)
doxygen_probes[url] = True
except:
@@ -307,14 +307,14 @@ def act_on_decl(declaration, comment, allowed_types):
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."""
diff --git a/tools/clang-format/clang-format-diff.py b/tools/clang-format/clang-format-diff.py
index ce4c1d6e0a..1721d8a430 100755
--- a/tools/clang-format/clang-format-diff.py
+++ b/tools/clang-format/clang-format-diff.py
@@ -21,6 +21,7 @@ Example usage for git/svn users:
svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i
"""
+from __future__ import print_function
import argparse
import difflib
diff --git a/tools/scan-build-py/libscanbuild/arguments.py b/tools/scan-build-py/libscanbuild/arguments.py
index a5d0c6bda6..73a7f24e67 100644
--- a/tools/scan-build-py/libscanbuild/arguments.py
+++ b/tools/scan-build-py/libscanbuild/arguments.py
@@ -12,6 +12,7 @@ earlier.)
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
diff --git a/tools/scan-view/bin/scan-view b/tools/scan-view/bin/scan-view
index 6e384ec217..e3abb1c834 100755
--- a/tools/scan-view/bin/scan-view
+++ b/tools/scan-view/bin/scan-view
@@ -1,5 +1,7 @@
#!/usr/bin/env python
+from __future__ import print_function
+
"""The clang static analyzer results viewer.
"""
@@ -52,10 +54,10 @@ def start_browser(port, options):
sys.stderr.flush()
time.sleep(kSleepTimeout)
else:
- print >> sys.stderr, 'WARNING: Unable to detect that server started.'
+ print('WARNING: Unable to detect that server started.', file=sys.stderr)
if options.debug:
- print >> sys.stderr, '%s: Starting webbrowser...' % sys.argv[0]
+ print('%s: Starting webbrowser...' % sys.argv[0], file=sys.stderr)
webbrowser.open(url)
@@ -69,9 +71,9 @@ def run(port, options, root):
import ScanView
try:
- print 'Starting scan-view at: http://%s:%d' % (options.host,
- port)
- print ' Use Ctrl-C to exit.'
+ print('Starting scan-view at: http://%s:%d' % (options.host,
+ port))
+ print(' Use Ctrl-C to exit.')
httpd = ScanView.create_server((options.host, port),
options, root)
httpd.serve_forever()
diff --git a/tools/scan-view/share/ScanView.py b/tools/scan-view/share/ScanView.py
index b465c971db..b1ce8c3d3a 100644
--- a/tools/scan-view/share/ScanView.py
+++ b/tools/scan-view/share/ScanView.py
@@ -1,3 +1,4 @@
+from __future__ import print_function
try:
from http.server import HTTPServer, SimpleHTTPRequestHandler
except ImportError:
@@ -102,20 +103,20 @@ class ReporterThread(threading.Thread):
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.StringIO()
import traceback
- print >>s,'<b>Unhandled Exception</b><br><pre>'
- traceback.print_exc(e,file=s)
- print >>s,'</pre>'
+ print('<b>Unhandled Exception</b><br><pre>', file=s)
+ traceback.print_exc(file=s)
+ print('</pre>', file=s)
self.status = s.getvalue()
class ScanViewServer(HTTPServer):
@@ -161,16 +162,16 @@ class ScanViewServer(HTTPServer):
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:
@@ -183,7 +184,7 @@ class ScanViewServer(HTTPServer):
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
HTTPServer.handle_error(self, request, client_address)
@@ -270,8 +271,8 @@ class ScanViewRequestHandler(SimpleHTTPRequestHandler):
def handle_exception(self, exc):
import traceback
s = StringIO.StringIO()
- print >>s, "INTERNAL ERROR\n"
- traceback.print_exc(exc, s)
+ print("INTERNAL ERROR\n", file=s)
+ traceback.print_exc(file=s)
f = self.send_string(s.getvalue(), 'text/plain')
if f:
self.copyfile(f, self.wfile)
@@ -416,8 +417,8 @@ Submit</h3>
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:
@@ -696,8 +697,8 @@ File Bug</h3>
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):
diff --git a/utils/ABITest/ABITestGen.py b/utils/ABITest/ABITestGen.py
index 0e588f056c..d42e08e123 100755
--- a/utils/ABITest/ABITestGen.py
+++ b/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 @@ class TypePrinter(object):
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 <stdio.h>\n'
+ print('#include <stdio.h>\n', file=self.output)
if self.outputTests:
- print >>self.outputTests, '#include <stdio.h>'
- print >>self.outputTests, '#include <string.h>'
- print >>self.outputTests, '#include <assert.h>\n'
+ print('#include <stdio.h>', file=self.outputTests)
+ print('#include <string.h>', file=self.outputTests)
+ print('#include <assert.h>\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 <stdio.h>'
- print >>self.outputDriver, '#include <stdlib.h>\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 <stdio.h>', file=self.outputDriver)
+ print('#include <stdlib.h>\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 @@ class TypePrinter(object):
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 @@ class TypePrinter(object):
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 @@ class TypePrinter(object):
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 = map(self.getTestValuesArray, 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 @@ class TypePrinter(object):
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 @@ class TypePrinter(object):
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 @@ class TypePrinter(object):
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 @@ class TypePrinter(object):
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 @@ def main():
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:
diff --git a/utils/ABITest/Enumeration.py b/utils/ABITest/Enumeration.py
index 29a81b4f13..76067243d1 100644
--- a/utils/ABITest/Enumeration.py
+++ b/utils/ABITest/Enumeration.py
@@ -1,5 +1,6 @@
"""Utilities for enumeration of finite and countably infinite sets.
"""
+from __future__ import print_function
###
# Countable iteration
@@ -234,18 +235,18 @@ def testPairs():
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]
@@ -253,13 +254,13 @@ def testPairsVB():
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))
###
diff --git a/utils/ABITest/TypeGen.py b/utils/ABITest/TypeGen.py
index f8a4d07e11..608089429a 100644
--- a/utils/ABITest/TypeGen.py
+++ b/utils/ABITest/TypeGen.py
@@ -1,4 +1,5 @@
"""Flexible enumeration of C types."""
+from __future__ import print_function
from Enumeration import *
@@ -462,7 +463,7 @@ def test():
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:
@@ -470,7 +471,7 @@ def test():
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()
diff --git a/utils/CIndex/completion_logger_server.py b/utils/CIndex/completion_logger_server.py
index 0652b1f4a8..818d10d73b 100755
--- a/utils/CIndex/completion_logger_server.py
+++ b/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 @@ import datetime
def main():
if len(sys.argv) < 4:
- print "completion_logger_server.py <listen address> <listen port> <log file>"
+ print("completion_logger_server.py <listen address> <listen port> <log file>")
exit(1)
host = sys.argv[1]
@@ -18,7 +19,7 @@ def main():
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")
diff --git a/utils/TestUtils/deep-stack.py b/utils/TestUtils/deep-stack.py
index 1750a5fca0..8636efabec 100755
--- a/utils/TestUtils/deep-stack.py
+++ b/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
diff --git a/utils/analyzer/CmpRuns.py b/utils/analyzer/CmpRuns.py
index 43d1fe83b9..14be963296 100755
--- a/utils/analyzer/CmpRuns.py
+++ b/utils/analyzer/CmpRuns.py
@@ -25,6 +25,7 @@ Usage:
diff = compareResults(resultsA, resultsB)
"""
+from __future__ import print_function
from collections import defaultdict
@@ -318,7 +319,7 @@ def compareStats(resultsA, resultsB):
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 @@ def compareStats(resultsA, resultsB):
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):
diff --git a/utils/analyzer/SATestAdd.py b/utils/analyzer/SATestAdd.py
index 041b24409f..377897e143 100755
--- a/utils/analyzer/SATestAdd.py
+++ b/utils/analyzer/SATestAdd.py
@@ -42,6 +42,7 @@ the Repository Directory.
diff -ur CachedSource PatchedSource \
> changes_for_analyzer.patch
"""
+from __future__ import print_function
import SATestBuild
import os
@@ -66,7 +67,7 @@ def addNewProject(ID, BuildMode):
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 @@ def addNewProject(ID, BuildMode):
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 <mode>\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
diff --git a/utils/analyzer/SATestBuild.py b/utils/analyzer/SATestBuild.py
index ef0ab195f1..70c425d38e 100755
--- a/utils/analyzer/SATestBuild.py
+++ b/utils/analyzer/SATestBuild.py
@@ -122,7 +122,7 @@ if 'CC' in os.environ:
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.
@@ -570,8 +570,8 @@ def runCmpResults(Dir, Strictness=0):
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
@@ -719,11 +719,11 @@ def validateProjectFile(PMapFile):
"""
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):
@@ -806,5 +806,5 @@ if __name__ == '__main__':
TestsPassed = testAll(Args)
if not TestsPassed:
- print "ERROR: Tests failed."
+ print("ERROR: Tests failed.")
sys.exit(42)
diff --git a/utils/analyzer/SATestUpdateDiffs.py b/utils/analyzer/SATestUpdateDiffs.py
index 3f1aafa690..64e6ca43db 100755
--- a/utils/analyzer/SATestUpdateDiffs.py
+++ b/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 @@ Verbose = 0
def runCmd(Command, **kwargs):
if Verbose:
- print "Executing %s" % Command
+ print("Executing %s" % Command)
check_call(Command, shell=True, **kwargs)
@@ -30,8 +31,8 @@ def updateReferenceResults(ProjName, ProjBuildMode):
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 updateReferenceResults(ProjName, ProjBuildMode):
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:
diff --git a/utils/analyzer/SumTimerInfo.py b/utils/analyzer/SumTimerInfo.py
index 50e1cb854f..b3219b00c7 100644
--- a/utils/analyzer/SumTimerInfo.py
+++ b/utils/analyzer/SumTimerInfo.py
@@ -6,13 +6,14 @@ Script to Summarize statistics in the scan-build output.
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 @@ if __name__ == '__main__':
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))
diff --git a/utils/check_cfc/setup.py b/utils/check_cfc/setup.py
index b5fc473639..6005f6f411 100644
--- a/utils/check_cfc/setup.py
+++ b/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 @@ except ImportError:
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(
diff --git a/utils/clangdiag.py b/utils/clangdiag.py
index 9a80e2696d..d449194e28 100755
--- a/utils/clangdiag.py
+++ b/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 @@ def __lldb_init_module(debugger, dict):
# 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.')
diff --git a/utils/modfuzz.py b/utils/modfuzz.py
index 948603338c..4dc25e8469 100644
--- a/utils/modfuzz.py
+++ b/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 @@ def generate():
if not model.fails():
return
except KeyboardInterrupt:
- print
+ print()
return True
sys.stdout.write('\nReducing:\n')
diff --git a/utils/token-delta.py b/utils/token-delta.py
index 5efb65cb2f..9fc5646bb7 100755
--- a/utils/token-delta.py
+++ b/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 @@ class TMBDDelta(DeltaAlgorithm):
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 @@ class TMBDDelta(DeltaAlgorithm):
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 @@ class TMBDDelta(DeltaAlgorithm):
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 @@ class TMBDDelta(DeltaAlgorithm):
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 @@ def tokenBasedMultiDelta(program, files, log):
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 @@ if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
- print >>sys.stderr,'Interrupted.'
+ print('Interrupted.', file=sys.stderr)
os._exit(1) # Avoid freeing our giant cache.