pluto_auto.py 3.06 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/python3

import argparse
import sys
import re
import tempfile
import os

class PlutoVariables:

    def __init__(self, prefix):
        self.prefix = prefix
        self.by_name = dict()

    def add(self, name, pluto, index):
        self.by_name[name] = (int(pluto), int(index))
        pass

    def codegen(self, expr):
20
        m = re.match('([^=]+)=(AND|OR)\{(.*),(.*)\}', expr)
21
22
        if m:
            lh = m.group(1)
23
24
25
26
27
28
29
30
31
32
33
            op = m.group(2)
            regexp = m.group(3).replace('*', '.*')
            expr = m.group(4)
            rh = []
            for k,v in sorted(self.by_name.items()):
                rh_m = re.match(regexp, k)
                if rh_m:
                    matches = (k,)+rh_m.groups()
                    rh.append(expr.format(*matches, pluto=v[0]))
                    pass
                pass
34
35
36
            if len(rh) == 0:
                return("%s=0" % (lh))
            elif op == 'AND':
37
38
39
                return("%s=%s" % (lh, '*'.join(rh)))
            elif op == 'OR':
                return("%s=%s" % (lh, '+'.join(rh)))
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
        raise Exception('Invalid expression', expr)

class SPS:

    def __init__(self, path):
        self.data = open(path, encoding='utf-16').read()
        self.gm = PlutoVariables('GM')
        self.parse()

    def parse(self):
        for l in self.data.split('\n'):
            # Collect variables
            m = re.match('! GM([0-9]+)[.]([0-9]+)=(\S+)', l)
            if m:
                self.gm.add(m.group(3), m.group(1), m.group(2))
                pass
            pass
        pass

    def expand(self):
        result = []
        for l in self.data.split('\n'):
            result.append(l)
            m = re.match(';\s*AUTO:\s*(.*)', l)
            if m:
                code = self.gm.codegen(m.group(1))
                if code != result[-2]:
                    result[-2] = code
                    pass
                pass
            pass
        return '\n'.join(result)
        

if __name__ == '__main__':
    optParser = argparse.ArgumentParser()
    optParser.add_argument("sps", nargs='+',
                           help="Pluto master programs")
    optParser.add_argument("--write",
                           action="store_true", default=False, 
                           help="Rewrite source file if needed")
    options = optParser.parse_args(sys.argv[1:])
    for f in options.sps:
        sps = SPS(f)
        orig = sps.data
        expanded = sps.expand()
        if orig != expanded:
            if options.write:
                f1 = tempfile.NamedTemporaryFile(dir=os.path.dirname(f),
                                                 delete=False)
                print(f1.name)
                f1.write(expanded.replace('\n', '\r\n').encode('utf-16'))
                f1.close()
                os.rename(f1.name, f)
                pass
            else:
                for w, (l1, l2) in enumerate(zip(orig.split('\n'),
                    expanded.split('\n'))):
                    if (l1!=l2):
                        print("%d '%s'" % (w, l1))
                        print("%d '%s'" % (w, l2))