Browse Source

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
Serge Guelton 6 years ago
parent
commit
4f672fc63a

+ 1 - 0
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
 Most object information is exposed using properties, when the underlying API
 call is efficient.
 call is efficient.
 """
 """
+from __future__ import print_function
 
 
 # TODO
 # TODO
 # ====
 # ====

+ 5 - 4
docs/conf.py

@@ -11,6 +11,7 @@
 # All configuration values have a default; values that are commented out
 # All configuration values have a default; values that are commented out
 # serve to show the default.
 # serve to show the default.
 
 
+from __future__ import print_function
 import sys, os
 import sys, os
 from datetime import date
 from datetime import date
 
 
@@ -233,14 +234,14 @@ for name in os.listdir(command_guide_path):
         header = f.readline().rstrip('\n')
         header = f.readline().rstrip('\n')
 
 
         if len(header) != len(title):
         if len(header) != len(title):
-            print >>sys.stderr, (
+            print((
                 "error: invalid header in %r (does not match title)" % (
                 "error: invalid header in %r (does not match title)" % (
-                    file_subpath,))
+                    file_subpath,)), file=sys.stderr)
         if ' - ' not in title:
         if ' - ' not in title:
-            print >>sys.stderr, (
+            print((
                 ("error: invalid title in %r "
                 ("error: invalid title in %r "
                  "(expected '<name> - <description>')") % (
                  "(expected '<name> - <description>')") % (
-                    file_subpath,))
+                    file_subpath,)), file=sys.stderr)
 
 
         # Split the name out of the title.
         # Split the name out of the title.
         name,description = title.split(' - ', 1)
         name,description = title.split(' - ', 1)

+ 4 - 4
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
     url = 'https://clang.llvm.org/doxygen/classclang_1_1%s.html' % name
     if url not in doxygen_probes:
     if url not in doxygen_probes:
       try:
       try:
-        print 'Probing %s...' % url
+        print('Probing %s...' % url)
         urllib2.urlopen(url)
         urllib2.urlopen(url)
         doxygen_probes[url] = True
         doxygen_probes[url] = True
       except:
       except:
@@ -307,14 +307,14 @@ def act_on_decl(declaration, comment, allowed_types):
       if not result_types:
       if not result_types:
         if not comment:
         if not comment:
           # Only overloads don't have their own doxygen comments; ignore those.
           # Only overloads don't have their own doxygen comments; ignore those.
-          print 'Ignoring "%s"' % name
+          print('Ignoring "%s"' % name)
         else:
         else:
-          print 'Cannot determine result type for "%s"' % name
+          print('Cannot determine result type for "%s"' % name)
       else:
       else:
         for result_type in result_types:
         for result_type in result_types:
           add_matcher(result_type, name, args, comment)
           add_matcher(result_type, name, args, comment)
     else:
     else:
-      print '*** Unparsable: "' + declaration + '" ***'
+      print('*** Unparsable: "' + declaration + '" ***')
 
 
 def sort_table(matcher_type, matcher_map):
 def sort_table(matcher_type, matcher_map):
   """Returns the sorted html table for the given row map."""
   """Returns the sorted html table for the given row map."""

+ 1 - 0
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
   svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i
 
 
 """
 """
+from __future__ import print_function
 
 
 import argparse
 import argparse
 import difflib
 import difflib

+ 1 - 0
tools/scan-build-py/libscanbuild/arguments.py

@@ -12,6 +12,7 @@ earlier.)
 It also implements basic validation methods, related to the command.
 It also implements basic validation methods, related to the command.
 Validations are mostly calling specific help methods, or mangling values.
 Validations are mostly calling specific help methods, or mangling values.
 """
 """
+from __future__ import print_function
 
 
 import os
 import os
 import sys
 import sys

+ 7 - 5
tools/scan-view/bin/scan-view

@@ -1,5 +1,7 @@
 #!/usr/bin/env python
 #!/usr/bin/env python
 
 
+from __future__ import print_function
+
 """The clang static analyzer results viewer.
 """The clang static analyzer results viewer.
 """
 """
 
 
@@ -52,10 +54,10 @@ def start_browser(port, options):
             sys.stderr.flush()
             sys.stderr.flush()
         time.sleep(kSleepTimeout)
         time.sleep(kSleepTimeout)
     else:
     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:
     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)
     webbrowser.open(url)
 
 
 
 
@@ -69,9 +71,9 @@ def run(port, options, root):
 
 
     import ScanView
     import ScanView
     try:
     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),
         httpd = ScanView.create_server((options.host, port),
                                        options, root)
                                        options, root)
         httpd.serve_forever()
         httpd.serve_forever()

+ 16 - 15
tools/scan-view/share/ScanView.py

@@ -1,3 +1,4 @@
+from __future__ import print_function
 try:
 try:
     from http.server import HTTPServer, SimpleHTTPRequestHandler
     from http.server import HTTPServer, SimpleHTTPRequestHandler
 except ImportError:
 except ImportError:
@@ -102,20 +103,20 @@ class ReporterThread(threading.Thread):
         result = None
         result = None
         try:
         try:
             if self.server.options.debug:
             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.status = self.reporter.fileReport(self.report, self.parameters)
             self.success = True
             self.success = True
             time.sleep(3)
             time.sleep(3)
             if self.server.options.debug:
             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:
         except Reporter.ReportFailure as e:
             self.status = e.value
             self.status = e.value
         except Exception as e:
         except Exception as e:
             s = StringIO.StringIO()
             s = StringIO.StringIO()
             import traceback
             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()
             self.status = s.getvalue()
 
 
 class ScanViewServer(HTTPServer):
 class ScanViewServer(HTTPServer):
@@ -161,16 +162,16 @@ class ScanViewServer(HTTPServer):
     def halt(self):
     def halt(self):
         self.halted = True
         self.halted = True
         if self.options.debug:
         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):
     def serve_forever(self):
         while not self.halted:
         while not self.halted:
             if self.options.debug > 1:
             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:
             try:
                 self.handle_request()
                 self.handle_request()
             except OSError as e:
             except OSError as e:
-                print 'OSError',e.errno
+                print('OSError',e.errno)
 
 
     def finish_request(self, request, client_address):
     def finish_request(self, request, client_address):
         if self.options.autoReload:
         if self.options.autoReload:
@@ -183,7 +184,7 @@ class ScanViewServer(HTTPServer):
         info = sys.exc_info()
         info = sys.exc_info()
         if info and isinstance(info[1], socket.error):
         if info and isinstance(info[1], socket.error):
             if self.options.debug > 1:
             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
             return
         HTTPServer.handle_error(self, request, client_address)
         HTTPServer.handle_error(self, request, client_address)
 
 
@@ -270,8 +271,8 @@ class ScanViewRequestHandler(SimpleHTTPRequestHandler):
     def handle_exception(self, exc):
     def handle_exception(self, exc):
         import traceback
         import traceback
         s = StringIO.StringIO()
         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')
         f = self.send_string(s.getvalue(), 'text/plain')
         if f:
         if f:
             self.copyfile(f, self.wfile)
             self.copyfile(f, self.wfile)
@@ -416,8 +417,8 @@ Submit</h3>
 
 
         import startfile
         import startfile
         if self.server.options.debug:
         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)
         status = startfile.open(file)
         if status:
         if status:
@@ -696,8 +697,8 @@ File Bug</h3>
         path = posixpath.join(self.server.root, relpath)
         path = posixpath.join(self.server.root, relpath)
 
 
         if self.server.options.debug > 1:
         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)
         return self.send_path(path)
 
 
     def send_404(self):
     def send_404(self):

+ 67 - 66
utils/ABITest/ABITestGen.py

@@ -1,5 +1,6 @@
 #!/usr/bin/env python
 #!/usr/bin/env python
 
 
+from __future__ import print_function
 from pprint import pprint
 from pprint import pprint
 import random, atexit, time
 import random, atexit, time
 from random import randrange
 from random import randrange
@@ -28,42 +29,42 @@ class TypePrinter(object):
         if info:
         if info:
             for f in (self.output,self.outputHeader,self.outputTests,self.outputDriver):
             for f in (self.output,self.outputHeader,self.outputTests,self.outputDriver):
                 if f:
                 if f:
-                    print >>f,info
+                    print(info, file=f)
 
 
         if self.writeBody:
         if self.writeBody:
-            print >>self.output, '#include <stdio.h>\n'
+            print('#include <stdio.h>\n', file=self.output)
             if self.outputTests:
             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:
         if headerName:
             for f in (self.output,self.outputTests,self.outputDriver):
             for f in (self.output,self.outputTests,self.outputDriver):
                 if f is not None:
                 if f is not None:
-                    print >>f, '#include "%s"\n'%(headerName,)
+                    print('#include "%s"\n'%(headerName,), file=f)
         
         
         if self.outputDriver:
         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):
     def finish(self):
         if self.layoutTests:
         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:
             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:
         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):
     def addDeclaration(self, decl):
         if decl in self.declarations:
         if decl in self.declarations:
@@ -71,11 +72,11 @@ class TypePrinter(object):
 
 
         self.declarations.add(decl)
         self.declarations.add(decl)
         if self.outputHeader:
         if self.outputHeader:
-            print >>self.outputHeader, decl
+            print(decl, file=self.outputHeader)
         else:
         else:
-            print >>self.output, decl
+            print(decl, file=self.output)
             if self.outputTests:
             if self.outputTests:
-                print >>self.outputTests, decl
+                print(decl, file=self.outputTests)
         return True
         return True
 
 
     def getTypeName(self, T):
     def getTypeName(self, T):
@@ -91,12 +92,12 @@ class TypePrinter(object):
         tyNameClean = tyName.replace(' ','_').replace('*','star')
         tyNameClean = tyName.replace(' ','_').replace('*','star')
         fnName = 'test_%s' % tyNameClean
         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.printSizeOfType('    %s'%fnName, tyName, ty, self.output)
         self.printAlignOfType('    %s'%fnName, tyName, ty, self.output)
         self.printAlignOfType('    %s'%fnName, tyName, ty, self.output)
         self.printOffsetsOfType('    %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))
         self.layoutTests.append((i,fnName))
         
         
@@ -115,71 +116,71 @@ class TypePrinter(object):
 
 
         fnName = 'fn%d'%(FT.index,)
         fnName = 'fn%d'%(FT.index,)
         if self.outputHeader:
         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:
         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:
         if self.writeBody:
-            print >>self.output, '{'
+            print('{', file=self.output)
             
             
             for i,t in enumerate(FT.argTypes):
             for i,t in enumerate(FT.argTypes):
                 self.printValueOfType('    %s'%fnName, 'arg%d'%i, t)
                 self.printValueOfType('    %s'%fnName, 'arg%d'%i, t)
 
 
             if retvalName is not None:
             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:
         else:
-            print >>self.output, '{}'
-        print >>self.output
+            print('{}', file=self.output)
+        print(file=self.output)
 
 
         if self.outputDriver:
         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.outputTests:
             if self.outputHeader:
             if self.outputHeader:
-                print >>self.outputHeader, 'void test_%s(void);'%(fnName,)
+                print('void test_%s(void);'%(fnName,), file=self.outputHeader)
 
 
             if retvalName is None:
             if retvalName is None:
                 retvalTests = None
                 retvalTests = None
             else:
             else:
                 retvalTests = self.getTestValuesArray(FT.returnType)
                 retvalTests = self.getTestValuesArray(FT.returnType)
             tests = map(self.getTestValuesArray, FT.argTypes)
             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:
             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])
                 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.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)
                 self.checkTypeValues('RV', '%s[i]' % retvalTests[0], FT.returnType, output=self.outputTests, indent=4)
-                print >>self.outputTests, '  }'
+                print('  }', file=self.outputTests)
             
             
             if tests:
             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 i,(array,length) in enumerate(tests):
                 for j in range(length):
                 for j in range(length):
                     args = ['%s[%d]'%(t,randrange(l)) for t,l in tests]
                     args = ['%s[%d]'%(t,randrange(l)) for t,l in tests]
                     args[i] = '%s[%d]'%(array,j)
                     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):
     def getTestReturnValue(self, type):
         typeName = self.getTypeName(type)        
         typeName = self.getTypeName(type)        
         info = self.testReturnValues.get(typeName)
         info = self.testReturnValues.get(typeName)
         if info is None:
         if info is None:
             name = '%s_retval'%(typeName.replace(' ','_').replace('*','star'),)
             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:
             if self.outputHeader:
-                print >>self.outputHeader, 'extern %s %s;'%(typeName,name)
+                print('extern %s %s;'%(typeName,name), file=self.outputHeader)
             elif self.outputTests:                
             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
             info = self.testReturnValues[typeName] = name
         return info
         return info
 
 
@@ -188,12 +189,12 @@ class TypePrinter(object):
         info = self.testValues.get(typeName)
         info = self.testValues.get(typeName)
         if info is None:
         if info is None:
             name = '%s_values'%(typeName.replace(' ','_').replace('*','star'),)
             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
             length = 0
             for item in self.getTestValues(type):
             for item in self.getTestValues(type):
-                print >>self.outputTests, '\t%s,'%(item,)
+                print('\t%s,'%(item,), file=self.outputTests)
                 length += 1
                 length += 1
-            print >>self.outputTests,'};'
+            print('};', file=self.outputTests)
             info = self.testValues[typeName] = (name,length)
             info = self.testValues[typeName] = (name,length)
         return info
         return info
 
 
@@ -253,16 +254,16 @@ class TypePrinter(object):
             raise NotImplementedError('Cannot make tests values of type: "%s"'%(t,))
             raise NotImplementedError('Cannot make tests values of type: "%s"'%(t,))
 
 
     def printSizeOfType(self, prefix, name, t, output=None, indent=2):
     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):
     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):
     def printOffsetsOfType(self, prefix, name, t, output=None, indent=2):
         if isinstance(t, RecordType):
         if isinstance(t, RecordType):
             for i,f in enumerate(t.fields):
             for i,f in enumerate(t.fields):
                 if f.isBitField():
                 if f.isBitField():
                     continue
                     continue
                 fname = 'field%d' % i
                 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):
     def printValueOfType(self, prefix, name, t, output=None, indent=2):
         if output is None:
         if output is None:
@@ -286,13 +287,13 @@ class TypePrinter(object):
                 code = 'Lf'
                 code = 'Lf'
             else:
             else:
                 code = 'p'
                 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):
         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):
         elif isinstance(t, RecordType):
             if not t.fields:
             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):
             for i,f in enumerate(t.fields):
                 if f.isPaddingBitField():
                 if f.isPaddingBitField():
                     continue
                     continue
@@ -317,9 +318,9 @@ class TypePrinter(object):
         if output is None:
         if output is None:
             output = self.output
             output = self.output
         if isinstance(t, BuiltinType):
         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):
         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):
         elif isinstance(t, RecordType):
             for i,f in enumerate(t.fields):
             for i,f in enumerate(t.fields):
                 if f.isPaddingBitField():
                 if f.isPaddingBitField():
@@ -644,7 +645,7 @@ def main():
             FT = ftg.get(N)
             FT = ftg.get(N)
         except RuntimeError as e:
         except RuntimeError as e:
             if e.args[0]=='maximum recursion depth exceeded':
             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
                 return
             raise
             raise
         if opts.testLayout:
         if opts.testLayout:

+ 9 - 8
utils/ABITest/Enumeration.py

@@ -1,5 +1,6 @@
 """Utilities for enumeration of finite and countably infinite sets.
 """Utilities for enumeration of finite and countably infinite sets.
 """
 """
+from __future__ import print_function
 ###
 ###
 # Countable iteration
 # Countable iteration
 
 
@@ -234,18 +235,18 @@ def testPairs():
     for i in range(min(W*H,40)):
     for i in range(min(W*H,40)):
         x,y = getNthPairBounded(i,W,H)
         x,y = getNthPairBounded(i,W,H)
         x2,y2 = getNthPairBounded(i,W,H,useDivmod=True)
         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
         a[y][x] = '%2d'%i
         b[y2][x2] = '%2d'%i
         b[y2][x2] = '%2d'%i
 
 
-    print '-- a --'
+    print('-- a --')
     for ln in a[::-1]:
     for ln in a[::-1]:
         if ''.join(ln).strip():
         if ''.join(ln).strip():
-            print '  '.join(ln)
-    print '-- b --'
+            print('  '.join(ln))
+    print('-- b --')
     for ln in b[::-1]:
     for ln in b[::-1]:
         if ''.join(ln).strip():
         if ''.join(ln).strip():
-            print '  '.join(ln)
+            print('  '.join(ln))
 
 
 def testPairsVB():
 def testPairsVB():
     bounds = [2,2,4,aleph0,5,aleph0]
     bounds = [2,2,4,aleph0,5,aleph0]
@@ -253,13 +254,13 @@ def testPairsVB():
     b = [['  ' for x in range(15)] for y in range(15)]
     b = [['  ' for x in range(15)] for y in range(15)]
     for i in range(min(sum(bounds),40)):
     for i in range(min(sum(bounds),40)):
         x,y = getNthPairVariableBounds(i, bounds)
         x,y = getNthPairVariableBounds(i, bounds)
-        print i,(x,y)
+        print(i,(x,y))
         a[y][x] = '%2d'%i
         a[y][x] = '%2d'%i
 
 
-    print '-- a --'
+    print('-- a --')
     for ln in a[::-1]:
     for ln in a[::-1]:
         if ''.join(ln).strip():
         if ''.join(ln).strip():
-            print '  '.join(ln)
+            print('  '.join(ln))
 
 
 ###
 ###
 
 

+ 3 - 2
utils/ABITest/TypeGen.py

@@ -1,4 +1,5 @@
 """Flexible enumeration of C types."""
 """Flexible enumeration of C types."""
+from __future__ import print_function
 
 
 from Enumeration import *
 from Enumeration import *
 
 
@@ -462,7 +463,7 @@ def test():
     atg.addGenerator( btg )
     atg.addGenerator( btg )
     atg.addGenerator( RecordTypeGenerator(fields0, False, 4) )
     atg.addGenerator( RecordTypeGenerator(fields0, False, 4) )
     atg.addGenerator( etg )
     atg.addGenerator( etg )
-    print 'Cardinality:',atg.cardinality
+    print('Cardinality:',atg.cardinality)
     for i in range(100):
     for i in range(100):
         if i == atg.cardinality:
         if i == atg.cardinality:
             try:
             try:
@@ -470,7 +471,7 @@ def test():
                 raise RuntimeError("Cardinality was wrong")
                 raise RuntimeError("Cardinality was wrong")
             except AssertionError:
             except AssertionError:
                 break
                 break
-        print '%4d: %s'%(i, atg.get(i))
+        print('%4d: %s'%(i, atg.get(i)))
 
 
 if __name__ == '__main__':
 if __name__ == '__main__':
     test()
     test()

+ 3 - 2
utils/CIndex/completion_logger_server.py

@@ -1,4 +1,5 @@
 #!/usr/bin/env python
 #!/usr/bin/env python
+from __future__ import print_function
 import sys
 import sys
 from socket import *
 from socket import *
 from time import strftime
 from time import strftime
@@ -6,7 +7,7 @@ import datetime
 
 
 def main():
 def main():
   if len(sys.argv) < 4:
   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)
     exit(1)
 
 
   host = sys.argv[1]
   host = sys.argv[1]
@@ -18,7 +19,7 @@ def main():
   UDPSock = socket(AF_INET,SOCK_DGRAM)
   UDPSock = socket(AF_INET,SOCK_DGRAM)
   UDPSock.bind(addr)
   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.
   # Open the logging file.
   f = open(sys.argv[3], "a")
   f = open(sys.argv[3], "a")

+ 9 - 8
utils/TestUtils/deep-stack.py

@@ -1,22 +1,23 @@
 #!/usr/bin/env python
 #!/usr/bin/env python
 
 
+from __future__ import print_function
 def pcall(f, N):
 def pcall(f, N):
     if N == 0:
     if N == 0:
-        print >>f, '    f(0)'
+        print('    f(0)', file=f)
         return
         return
 
 
-    print >>f, '    f('
+    print('    f(', file=f)
     pcall(f, N - 1)
     pcall(f, N - 1)
-    print >>f, '     )'
+    print('     )', file=f)
 
 
 def main():
 def main():
     f = open('t.c','w')
     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)
     pcall(f, 10000)
-    print >>f, '  ;'
-    print >>f, '}'
+    print('  ;', file=f)
+    print('}', file=f)
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
     import sys
     import sys

+ 3 - 2
utils/analyzer/CmpRuns.py

@@ -25,6 +25,7 @@ Usage:
     diff = compareResults(resultsA, resultsB)
     diff = compareResults(resultsA, resultsB)
 
 
 """
 """
+from __future__ import print_function
 
 
 from collections import defaultdict
 from collections import defaultdict
 
 
@@ -318,7 +319,7 @@ def compareStats(resultsA, resultsB):
     statsB = deriveStats(resultsB)
     statsB = deriveStats(resultsB)
     keys = sorted(statsA.keys())
     keys = sorted(statsA.keys())
     for key in keys:
     for key in keys:
-        print key
+        print(key)
         for kkey in statsA[key]:
         for kkey in statsA[key]:
             valA = float(statsA[key][kkey])
             valA = float(statsA[key][kkey])
             valB = float(statsB[key][kkey])
             valB = float(statsB[key][kkey])
@@ -331,7 +332,7 @@ def compareStats(resultsA, resultsB):
                         report = Colors.GREEN + report + Colors.CLEAR
                         report = Colors.GREEN + report + Colors.CLEAR
                     elif ratio > 0.2:
                     elif ratio > 0.2:
                         report = Colors.RED + report + Colors.CLEAR
                         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,
 def dumpScanBuildResultsDiff(dirA, dirB, opts, deleteEmpty=True,
                              Stdout=sys.stdout):
                              Stdout=sys.stdout):

+ 9 - 8
utils/analyzer/SATestAdd.py

@@ -42,6 +42,7 @@ the Repository Directory.
                                           diff -ur CachedSource PatchedSource \
                                           diff -ur CachedSource PatchedSource \
                                               > changes_for_analyzer.patch
                                               > changes_for_analyzer.patch
 """
 """
+from __future__ import print_function
 import SATestBuild
 import SATestBuild
 
 
 import os
 import os
@@ -66,7 +67,7 @@ def addNewProject(ID, BuildMode):
     CurDir = os.path.abspath(os.curdir)
     CurDir = os.path.abspath(os.curdir)
     Dir = SATestBuild.getProjectDir(ID)
     Dir = SATestBuild.getProjectDir(ID)
     if not os.path.exists(Dir):
     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)
         sys.exit(-1)
 
 
     # Build the project.
     # Build the project.
@@ -78,30 +79,30 @@ def addNewProject(ID, BuildMode):
     if os.path.exists(ProjectMapPath):
     if os.path.exists(ProjectMapPath):
         FileMode = "r+b"
         FileMode = "r+b"
     else:
     else:
-        print "Warning: Creating the Project Map file!!"
+        print("Warning: Creating the Project Map file!!")
         FileMode = "w+b"
         FileMode = "w+b"
 
 
     with open(ProjectMapPath, FileMode) as PMapFile:
     with open(ProjectMapPath, FileMode) as PMapFile:
         if (isExistingProject(PMapFile, ID)):
         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:
         else:
             PMapWriter = csv.writer(PMapFile)
             PMapWriter = csv.writer(PMapFile)
             PMapWriter.writerow((ID, int(BuildMode)))
             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: Add an option not to build.
 # TODO: Set the path to the Repository directory.
 # TODO: Set the path to the Repository directory.
 if __name__ == '__main__':
 if __name__ == '__main__':
     if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'):
     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],\
                              '\nUsage: ', sys.argv[0],\
                              'project_ID <mode>\n' \
                              'project_ID <mode>\n' \
                              'mode: 0 for single file project, ' \
                              'mode: 0 for single file project, ' \
                              '1 for scan_build, ' \
                              '1 for scan_build, ' \
-                             '2 for single file c++11 project'
+                             '2 for single file c++11 project', file=sys.stderr)
         sys.exit(-1)
         sys.exit(-1)
 
 
     BuildMode = 1
     BuildMode = 1

+ 7 - 7
utils/analyzer/SATestBuild.py

@@ -122,7 +122,7 @@ if 'CC' in os.environ:
 else:
 else:
     Clang = SATestUtils.which("clang", os.environ['PATH'])
     Clang = SATestUtils.which("clang", os.environ['PATH'])
 if not Clang:
 if not Clang:
-    print "Error: cannot find 'clang' in PATH"
+    print("Error: cannot find 'clang' in PATH")
     sys.exit(1)
     sys.exit(1)
 
 
 # Number of jobs.
 # Number of jobs.
@@ -570,8 +570,8 @@ def runCmpResults(Dir, Strictness=0):
     NewList.remove(os.path.join(NewDir, LogFolderName))
     NewList.remove(os.path.join(NewDir, LogFolderName))
 
 
     if len(RefList) != len(NewList):
     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)
         sys.exit(1)
 
 
     # There might be more then one folder underneath - one per each scan-build
     # 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):
     for I in iterateOverProjects(PMapFile):
         if len(I) != 2:
         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()
             raise Exception()
         if I[1] not in ('0', '1', '2'):
         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()
             raise Exception()
 
 
 def singleThreadedTestAll(Args, ProjectsToTest):
 def singleThreadedTestAll(Args, ProjectsToTest):
@@ -806,5 +806,5 @@ if __name__ == '__main__':
 
 
     TestsPassed = testAll(Args)
     TestsPassed = testAll(Args)
     if not TestsPassed:
     if not TestsPassed:
-        print "ERROR: Tests failed."
+        print("ERROR: Tests failed.")
         sys.exit(42)
         sys.exit(42)

+ 6 - 5
utils/analyzer/SATestUpdateDiffs.py

@@ -3,6 +3,7 @@
 """
 """
 Update reference results for static analyzer.
 Update reference results for static analyzer.
 """
 """
+from __future__ import print_function
 
 
 import SATestBuild
 import SATestBuild
 
 
@@ -15,7 +16,7 @@ Verbose = 0
 
 
 def runCmd(Command, **kwargs):
 def runCmd(Command, **kwargs):
     if Verbose:
     if Verbose:
-        print "Executing %s" % Command
+        print("Executing %s" % Command)
     check_call(Command, shell=True, **kwargs)
     check_call(Command, shell=True, **kwargs)
 
 
 
 
@@ -30,8 +31,8 @@ def updateReferenceResults(ProjName, ProjBuildMode):
         SATestBuild.getSBOutputDirName(IsReferenceBuild=False))
         SATestBuild.getSBOutputDirName(IsReferenceBuild=False))
 
 
     if not os.path.exists(CreatedResultsPath):
     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)
         sys.exit(1)
 
 
     BuildLogPath = SATestBuild.getBuildLogPath(RefResultsPath)
     BuildLogPath = SATestBuild.getBuildLogPath(RefResultsPath)
@@ -62,9 +63,9 @@ def updateReferenceResults(ProjName, ProjBuildMode):
 
 
 def main(argv):
 def main(argv):
     if len(argv) == 2 and argv[1] in ('-h', '--help'):
     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"\
                              "\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)
         sys.exit(1)
 
 
     with SATestBuild.projectFileHandler() as f:
     with SATestBuild.projectFileHandler() as f:

+ 15 - 14
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
 Statistics are enabled by passing '-internal-stats' option to scan-build
 (or '-analyzer-stats' to the analyzer).
 (or '-analyzer-stats' to the analyzer).
 """
 """
+from __future__ import print_function
 
 
 import sys
 import sys
 
 
 if __name__ == '__main__':
 if __name__ == '__main__':
     if len(sys.argv) < 2:
     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)
         sys.exit(-1)
 
 
     f = open(sys.argv[1], 'r')
     f = open(sys.argv[1], 'r')
@@ -65,15 +66,15 @@ if __name__ == '__main__':
             s = line.split()
             s = line.split()
             TotalTime = TotalTime + float(s[6])
             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))

+ 3 - 2
utils/check_cfc/setup.py

@@ -1,6 +1,7 @@
 """For use on Windows. Run with:
 """For use on Windows. Run with:
     python.exe setup.py py2exe
     python.exe setup.py py2exe
     """
     """
+from __future__ import print_function
 from distutils.core import setup
 from distutils.core import setup
 try:
 try:
     import py2exe
     import py2exe
@@ -8,10 +9,10 @@ except ImportError:
     import platform
     import platform
     import sys
     import sys
     if platform.system() == 'Windows':
     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
         raise
     else:
     else:
-        print "setup.py only required on Windows."
+        print("setup.py only required on Windows.")
         sys.exit(1)
         sys.exit(1)
 
 
 setup(
 setup(

+ 2 - 1
utils/clangdiag.py

@@ -9,6 +9,7 @@
 #   (lldb) command script import /path/to/clandiag.py
 #   (lldb) command script import /path/to/clandiag.py
 #----------------------------------------------------------------------
 #----------------------------------------------------------------------
 
 
+from __future__ import print_function
 import lldb
 import lldb
 import argparse
 import argparse
 import commands
 import commands
@@ -189,4 +190,4 @@ def __lldb_init_module(debugger, dict):
     # Add any commands contained in this module to LLDB
     # Add any commands contained in this module to LLDB
     debugger.HandleCommand(
     debugger.HandleCommand(
         'command script add -f clangdiag.the_diag_command clangdiag')
         '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.')

+ 2 - 1
utils/modfuzz.py

@@ -4,6 +4,7 @@
 #  1) Update the 'decls' list below with your fuzzing configuration.
 #  1) Update the 'decls' list below with your fuzzing configuration.
 #  2) Run with the clang binary as the command-line argument.
 #  2) Run with the clang binary as the command-line argument.
 
 
+from __future__ import print_function
 import random
 import random
 import subprocess
 import subprocess
 import sys
 import sys
@@ -97,7 +98,7 @@ def generate():
     if not model.fails():
     if not model.fails():
       return
       return
   except KeyboardInterrupt:
   except KeyboardInterrupt:
-    print
+    print()
     return True
     return True
 
 
   sys.stdout.write('\nReducing:\n')
   sys.stdout.write('\nReducing:\n')

+ 11 - 10
utils/token-delta.py

@@ -1,5 +1,6 @@
 #!/usr/bin/env python
 #!/usr/bin/env python
 
 
+from __future__ import print_function
 import os
 import os
 import re
 import re
 import subprocess
 import subprocess
@@ -165,7 +166,7 @@ class TMBDDelta(DeltaAlgorithm):
         byFile = self.writeFiles(changes, self.tempFiles)
         byFile = self.writeFiles(changes, self.tempFiles)
 
 
         if self.log:
         if self.log:
-            print >>sys.stderr, 'TEST - ',
+            print('TEST - ', end=' ', file=sys.stderr)
             if self.log > 1:
             if self.log > 1:
                 for i,(file,_) in enumerate(self.tokenLists):
                 for i,(file,_) in enumerate(self.tokenLists):
                     indices = byFile[i]
                     indices = byFile[i]
@@ -184,8 +185,8 @@ class TMBDDelta(DeltaAlgorithm):
                         sys.stderr.write(str(byFile[i][-1]))
                         sys.stderr.write(str(byFile[i][-1]))
                     sys.stderr.write('] ')
                     sys.stderr.write('] ')
             else:
             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)
         p = subprocess.Popen([self.testProgram] + self.tempFiles)
         res = p.wait() == 0
         res = p.wait() == 0
@@ -194,10 +195,10 @@ class TMBDDelta(DeltaAlgorithm):
             self.writeFiles(changes, self.targetFiles)
             self.writeFiles(changes, self.targetFiles)
 
 
         if self.log:
         if self.log:
-            print >>sys.stderr, '=> %s' % res
+            print('=> %s' % res, file=sys.stderr)
         else:
         else:
             if res:
             if res:
-                print '\nSUCCESS (%d tokens)' % len(changes)
+                print('\nSUCCESS (%d tokens)' % len(changes))
             else:                
             else:                
                 sys.stderr.write('.')
                 sys.stderr.write('.')
 
 
@@ -209,7 +210,7 @@ class TMBDDelta(DeltaAlgorithm):
                                           for j in range(len(tokens))])
                                           for j in range(len(tokens))])
         self.writeFiles(res, self.targetFiles)
         self.writeFiles(res, self.targetFiles)
         if not self.log:
         if not self.log:
-            print >>sys.stderr
+            print(file=sys.stderr)
         return res
         return res
 
 
 def tokenBasedMultiDelta(program, files, log):            
 def tokenBasedMultiDelta(program, files, log):            
@@ -218,15 +219,15 @@ def tokenBasedMultiDelta(program, files, log):
                   for file in files]
                   for file in files]
 
 
     numTokens = sum([len(tokens) for _,tokens in tokenLists])
     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)
     tbmd = TMBDDelta(program, tokenLists, log)
 
 
     res = tbmd.run()
     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),
                                                          len(res),
-                                                         tbmd.numTests)
+                                                         tbmd.numTests))
         
         
 def main():
 def main():
     from optparse import OptionParser, OptionGroup
     from optparse import OptionParser, OptionGroup
@@ -247,5 +248,5 @@ if __name__ == '__main__':
     try:
     try:
         main()
         main()
     except KeyboardInterrupt:
     except KeyboardInterrupt:
-        print >>sys.stderr,'Interrupted.'
+        print('Interrupted.', file=sys.stderr)
         os._exit(1) # Avoid freeing our giant cache.
         os._exit(1) # Avoid freeing our giant cache.