gen_header.py 1.9 KB
Newer Older
J
jiakai 已提交
1 2 3 4
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
J
jiakai 已提交
5 6 7
import sys

MAGIC = 'midout_trace v0\n'
J
jiakai 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

class MidoutHeaderGen:
    _tag_names = None
    _region_names = None

    def __init__(self):
        self._tag_names = set()
        self._region_names = set()

    def add_item(self, name: str):
        prefix = 'midout::Region<midout::tags::'
        assert name.startswith(prefix), 'bad name: {}'.format(name)
        comma = name.find(',', len(prefix))
        self._tag_names.add(name[len(prefix):comma])
        self._region_names.add(name)

    def write(self, fout):
J
jiakai 已提交
25 26
        print('#define MIDOUT_GENERATED \\', file=fout)
        print('namespace midout { namespace tags { \\', file=fout)
J
jiakai 已提交
27
        for i in sorted(self._tag_names):
J
jiakai 已提交
28 29
            print('class {}; \\'.format(i), file=fout)
        print('} \\', file=fout)
J
jiakai 已提交
30 31 32

        for i in self._region_names:
            i = i.replace('midout::', '')
J
jiakai 已提交
33 34
            print('template<> \\', file=fout)
            print('struct {} {{ static constexpr bool enable = true; }}; \\'.
J
jiakai 已提交
35 36 37 38 39 40 41 42 43
                  format(i), file=fout)

        print('}', file=fout)


def main():
    parser = argparse.ArgumentParser(
        description='generate header file from midout traces',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
J
jiakai 已提交
44 45
    parser.add_argument('-o', '--output',
                        help='output header file; default to stdout')
J
jiakai 已提交
46 47 48 49 50
    parser.add_argument('inputs', nargs='+', help='input trace files')
    args = parser.parse_args()
    gen = MidoutHeaderGen()
    for i in args.inputs:
        with open(i) as fin:
J
jiakai 已提交
51
            assert fin.read(len(MAGIC)) == MAGIC, 'bad trace file'
J
jiakai 已提交
52 53 54
            for line in fin:
                gen.add_item(line.strip())

J
jiakai 已提交
55 56 57 58 59
    if not args.output:
        gen.write(sys.stdout)
    else:
        with open(args.output, 'w') as fout:
            gen.write(fout)
J
jiakai 已提交
60 61 62

if __name__ == '__main__':
    main()