1#!/usr/bin/env python 2 3import os 4from distutils.sysconfig import parse_makefile 5import sys 6import logging 7sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) 8from cmakegen import Mistakes, stripsplit, AUTODIRS, SKIPDIRS 9from collections import defaultdict 10 11PKGS = 'sys vec mat dm ksp snes ts tao'.split() 12LANGS = dict(c='C', cxx='CXX', cu='CU', F='F', F90='F90') 13 14class debuglogger(object): 15 def __init__(self, log): 16 self._log = log 17 18 def write(self, string): 19 self._log.debug(string) 20 21class Petsc(object): 22 def __init__(self, petsc_dir=None, petsc_arch=None, verbose=False): 23 if petsc_dir is None: 24 petsc_dir = os.environ.get('PETSC_DIR') 25 if petsc_dir is None: 26 try: 27 petsc_dir = parse_makefile(os.path.join('lib','petsc','conf', 'petscvariables')).get('PETSC_DIR') 28 finally: 29 if petsc_dir is None: 30 raise RuntimeError('Could not determine PETSC_DIR, please set in environment') 31 if petsc_arch is None: 32 petsc_arch = os.environ.get('PETSC_ARCH') 33 if petsc_arch is None: 34 try: 35 petsc_arch = parse_makefile(os.path.join(petsc_dir, 'lib','petsc','conf', 'petscvariables')).get('PETSC_ARCH') 36 finally: 37 if petsc_arch is None: 38 raise RuntimeError('Could not determine PETSC_ARCH, please set in environment') 39 self.petsc_dir = petsc_dir 40 self.petsc_arch = petsc_arch 41 self.read_conf() 42 try: 43 logging.basicConfig(filename=self.arch_path('lib','petsc','conf', 'gmake.log'), level=logging.DEBUG) 44 except IOError: 45 # Disable logging if path is not writeable (e.g., prefix install) 46 logging.basicConfig(filename='/dev/null', level=logging.DEBUG) 47 self.log = logging.getLogger('gmakegen') 48 self.mistakes = Mistakes(debuglogger(self.log), verbose=verbose) 49 self.gendeps = [] 50 51 def arch_path(self, *args): 52 return os.path.join(self.petsc_dir, self.petsc_arch, *args) 53 54 def read_conf(self): 55 self.conf = dict() 56 for line in open(self.arch_path('include', 'petscconf.h')): 57 if line.startswith('#define '): 58 define = line[len('#define '):] 59 space = define.find(' ') 60 key = define[:space] 61 val = define[space+1:] 62 self.conf[key] = val 63 self.conf.update(parse_makefile(self.arch_path('lib','petsc','conf', 'petscvariables'))) 64 self.have_fortran = int(self.conf.get('PETSC_HAVE_FORTRAN', '0')) 65 66 def inconf(self, key, val): 67 if key in ['package', 'function', 'define']: 68 return self.conf.get(val) 69 elif key == 'precision': 70 return val == self.conf['PETSC_PRECISION'] 71 elif key == 'scalar': 72 return val == self.conf['PETSC_SCALAR'] 73 elif key == 'language': 74 return val == self.conf['PETSC_LANGUAGE'] 75 raise RuntimeError('Unknown conf check: %s %s' % (key, val)) 76 77 def relpath(self, root, src): 78 return os.path.relpath(os.path.join(root, src), self.petsc_dir) 79 80 def get_sources(self, makevars): 81 """Return dict {lang: list_of_source_files}""" 82 source = dict() 83 for lang, sourcelang in LANGS.items(): 84 source[lang] = [f for f in makevars.get('SOURCE'+sourcelang,'').split() if f.endswith(lang)] 85 return source 86 87 def gen_pkg(self, pkg): 88 pkgsrcs = dict() 89 for lang in LANGS: 90 pkgsrcs[lang] = [] 91 for root, dirs, files in os.walk(os.path.join(self.petsc_dir, 'src', pkg)): 92 dirs.sort() 93 files.sort() 94 makefile = os.path.join(root,'makefile') 95 if not os.path.exists(makefile): 96 dirs[:] = [] 97 continue 98 mklines = open(makefile) 99 conditions = set(tuple(stripsplit(line)) for line in mklines if line.startswith('#requires')) 100 mklines.close() 101 if not all(self.inconf(key, val) for key, val in conditions): 102 dirs[:] = [] 103 continue 104 makevars = parse_makefile(makefile) 105 mdirs = makevars.get('DIRS','').split() # Directories specified in the makefile 106 self.mistakes.compareDirLists(root, mdirs, dirs) # diagnostic output to find unused directories 107 candidates = set(mdirs).union(AUTODIRS).difference(SKIPDIRS) 108 dirs[:] = list(candidates.intersection(dirs)) 109 allsource = [] 110 def mkrel(src): 111 return self.relpath(root, src) 112 source = self.get_sources(makevars) 113 for lang, s in source.items(): 114 pkgsrcs[lang] += [mkrel(t) for t in s] 115 allsource += s 116 self.mistakes.compareSourceLists(root, allsource, files) # Diagnostic output about unused source files 117 self.gendeps.append(self.relpath(root, 'makefile')) 118 return pkgsrcs 119 120 def gen_gnumake(self, fd): 121 def write(stem, srcs): 122 for lang in LANGS: 123 fd.write('%(stem)s.%(lang)s := %(srcs)s\n' % dict(stem=stem, lang=lang, srcs=' '.join(srcs[lang]))) 124 for pkg in PKGS: 125 srcs = self.gen_pkg(pkg) 126 write('srcs-' + pkg, srcs) 127 return self.gendeps 128 129 def gen_ninja(self, fd): 130 libobjs = [] 131 for pkg in PKGS: 132 srcs = self.gen_pkg(pkg) 133 for lang in LANGS: 134 for src in srcs[lang]: 135 obj = '$objdir/%s.o' % src 136 fd.write('build %(obj)s : %(lang)s_COMPILE %(src)s\n' % dict(obj=obj, lang=lang.upper(), src=os.path.join(self.petsc_dir,src))) 137 libobjs.append(obj) 138 fd.write('\n') 139 fd.write('build $libdir/libpetsc.so : %s_LINK_SHARED %s\n\n' % ('CF'[self.have_fortran], ' '.join(libobjs))) 140 fd.write('build petsc : phony || $libdir/libpetsc.so\n\n') 141 142 def summary(self): 143 self.mistakes.summary() 144 145def WriteGnuMake(petsc): 146 arch_files = petsc.arch_path('lib','petsc','conf', 'files') 147 fd = open(arch_files, 'w') 148 gendeps = petsc.gen_gnumake(fd) 149 fd.write('\n') 150 fd.write('# Dependency to regenerate this file\n') 151 fd.write('%s : %s %s\n' % (os.path.relpath(arch_files, petsc.petsc_dir), 152 os.path.relpath(__file__, os.path.realpath(petsc.petsc_dir)), 153 ' '.join(gendeps))) 154 fd.write('\n') 155 fd.write('# Dummy dependencies in case makefiles are removed\n') 156 fd.write(''.join([dep + ':\n' for dep in gendeps])) 157 fd.close() 158 159def WriteNinja(petsc): 160 conf = dict() 161 parse_makefile(os.path.join(petsc.petsc_dir, 'lib', 'petsc','conf', 'variables'), conf) 162 parse_makefile(petsc.arch_path('lib','petsc','conf', 'petscvariables'), conf) 163 build_ninja = petsc.arch_path('build.ninja') 164 fd = open(build_ninja, 'w') 165 fd.write('objdir = obj-ninja\n') 166 fd.write('libdir = lib\n') 167 fd.write('c_compile = %(PCC)s\n' % conf) 168 fd.write('c_flags = %(PETSC_CC_INCLUDES)s %(PCC_FLAGS)s %(CCPPFLAGS)s\n' % conf) 169 fd.write('c_link = %(PCC_LINKER)s\n' % conf) 170 fd.write('c_link_flags = %(PCC_LINKER_FLAGS)s\n' % conf) 171 if petsc.have_fortran: 172 fd.write('f_compile = %(FC)s\n' % conf) 173 fd.write('f_flags = %(PETSC_FC_INCLUDES)s %(FC_FLAGS)s %(FCPPFLAGS)s\n' % conf) 174 fd.write('f_link = %(FC_LINKER)s\n' % conf) 175 fd.write('f_link_flags = %(FC_LINKER_FLAGS)s\n' % conf) 176 fd.write('petsc_external_lib = %(PETSC_EXTERNAL_LIB_BASIC)s\n' % conf) 177 fd.write('python = %(PYTHON)s\n' % conf) 178 fd.write('\n') 179 fd.write('rule C_COMPILE\n' 180 ' command = $c_compile -MMD -MF $out.d $c_flags -c $in -o $out\n' 181 ' description = CC $out\n' 182 ' depfile = $out.d\n' 183 # ' deps = gcc\n') # 'gcc' is default, 'msvc' only recognized by newer versions of ninja 184 '\n') 185 fd.write('rule C_LINK_SHARED\n' 186 ' command = $c_link $c_link_flags -shared -o $out $in $petsc_external_lib\n' 187 ' description = CLINK_SHARED $out\n' 188 '\n') 189 if petsc.have_fortran: 190 fd.write('rule F_COMPILE\n' 191 ' command = $f_compile -MMD -MF $out.d $f_flags -c $in -o $out\n' 192 ' description = FC $out\n' 193 ' depfile = $out.d\n' 194 '\n') 195 fd.write('rule F_LINK_SHARED\n' 196 ' command = $f_link $f_link_flags -shared -o $out $in $petsc_external_lib\n' 197 ' description = FLINK_SHARED $out\n' 198 '\n') 199 fd.write('rule GEN_NINJA\n' 200 ' command = $python $in --output=ninja\n' 201 ' generator = 1\n' 202 '\n') 203 petsc.gen_ninja(fd) 204 fd.write('\n') 205 fd.write('build %s : GEN_NINJA | %s %s %s %s\n' % (build_ninja, 206 os.path.abspath(__file__), 207 os.path.join(petsc.petsc_dir, 'lib','petsc','conf', 'variables'), 208 petsc.arch_path('lib','petsc','conf', 'petscvariables'), 209 ' '.join(os.path.join(petsc.petsc_dir, dep) for dep in petsc.gendeps))) 210 211def main(petsc_dir=None, petsc_arch=None, output=None, verbose=False): 212 if output is None: 213 output = 'gnumake' 214 writer = dict(gnumake=WriteGnuMake, ninja=WriteNinja) 215 petsc = Petsc(petsc_dir=petsc_dir, petsc_arch=petsc_arch, verbose=verbose) 216 writer[output](petsc) 217 petsc.summary() 218 219if __name__ == '__main__': 220 import optparse 221 parser = optparse.OptionParser() 222 parser.add_option('--verbose', help='Show mismatches between makefiles and the filesystem', action='store_true', default=False) 223 parser.add_option('--petsc-arch', help='Set PETSC_ARCH different from environment', default=os.environ.get('PETSC_ARCH')) 224 parser.add_option('--output', help='Location to write output file', default=None) 225 opts, extra_args = parser.parse_args() 226 if extra_args: 227 import sys 228 sys.stderr.write('Unknown arguments: %s\n' % ' '.join(extra_args)) 229 exit(1) 230 main(petsc_arch=opts.petsc_arch, output=opts.output, verbose=opts.verbose) 231