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