summaryrefslogtreecommitdiff
path: root/rules/compat/map-variants.py
blob: a495e61cdf6d6de6e35c09ac01529bf05797caec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#!/usr/bin/env python3

import argparse
import re
import sys


class Layout(object):
    PATTERN = re.compile(r"(?P<layout>[^(]+)\((?P<variant>[^)]+)\)")

    def __init__(self, layout, variant=None):
        if match := self.PATTERN.match(layout):
            assert variant is None
            # parse a layout(variant) string
            layout = match.group("layout")
            variant = match.group("variant")
        self.layout = layout
        self.variant = variant

    def __str__(self):
        if self.variant:
            return "{}({})".format(self.layout, self.variant)
        else:
            return "{}".format(self.layout)


def read_file(path):
    """Returns a list of two-layout tuples [(layout1, layout2), ...]"""

    layouts = []
    for line in open(path):
        # Remove optional comment
        line = line.split("//")[0]
        # Split on whitespaces
        groups = tuple(line.split())
        length = len(groups)
        if length == 2:
            l1 = Layout(groups[0])
            l2 = Layout(groups[1])
        elif length == 4:
            l1 = Layout(groups[0], groups[1])
            l2 = Layout(groups[2], groups[3])
        else:
            raise ValueError(f"Invalid line: {line}")
        layouts.append((l1, l2))
    return layouts


# ml_s
def write_fixed_layout(dest, mappings, write_header):
    if write_header:
        dest.write("! model		layout				=	symbols\n")
    for l1, l2 in mappings:
        if l1.variant:
            raise ValueError(f"Unexpected variant: {l1}")
        dest.write("  *		{}			=	pc+{}\n".format(l1, l2))


# mln_s
def write_layout_n(dest, mappings, number, write_header):
    if write_header:
        dest.write("! model		layout[{}]	=	symbols\n".format(number))

    # symbols is one of
    #   +layout(variant):2 ... where the map-to-layout has a proper variant
    #   +layout%(v[2]):2 ... where the map-to-layout does not have a variant
    # and where the number is 1, we have a base and drop the suffix, i.e.
    # the above becomes
    #   pc+layout(variant)
    #   pc+layout%(v[1])

    base = "pc" if number == 1 else ""
    suffix = "" if number == 1 else ":{}".format(number)

    for l1, l2 in mappings:
        if l1.variant:
            raise ValueError(f"Unexpected variant: {l1}")
        second_layout = (
            str(l2) if l2.variant else "{}%(v[{}])".format(l2.layout, number)
        )
        dest.write(
            "  *		{}		=	{}+{}{}\n".format(
                l1, base, second_layout, suffix
            )
        )


# mlv_s
def write_fixed_layout_variant(dest, mappings, write_header):
    if write_header:
        dest.write("! model		layout		variant		=	symbols\n")
    for l1, l2 in mappings:
        if not l1.variant:
            raise ValueError(f"Expected variant: {l1}")
        dest.write(
            "  *		{}		{}		=	pc+{}\n".format(
                l1.layout, l1.variant, l2
            )
        )


# mlnvn_s
def write_layout_n_variant_n(dest, mappings, number, write_header):
    if write_header:
        dest.write(
            "! model		layout[{}]	variant[{}]	=	symbols\n".format(
                number, number
            )
        )

    # symbols is
    #   +layout(variant):2
    # and where the number is 1, we have a base and drop the suffix, i.e.
    # the above becomes
    #   pc+layout(variant)
    # This part is only executed for the variantMappings.lst

    base = "pc" if number == 1 else ""
    suffix = "" if number == 1 else ":{}".format(number)

    for l1, l2 in mappings:
        if not l1.variant:
            raise ValueError(f"Expected variant: {l1}")
        second_layout = (
            str(l2) if l2.variant else "{}%(v[{}])".format(l2.layout, number)
        )
        dest.write(
            "  *		{}		{}	=	{}+{}{}\n".format(
                l1.layout, l1.variant, base, second_layout, suffix
            )
        )


def map_variant(dest, files, want="mls", number=None):
    if number == 0:
        number = None

    for idx, f in enumerate(files):
        write_header = idx == 0

        mappings = read_file(f)
        if want == "mls":
            if number is None:
                write_fixed_layout(dest, mappings, write_header)
            else:
                write_layout_n(dest, mappings, number, write_header)
        elif want == "mlvs":
            if number is None:
                write_fixed_layout_variant(dest, mappings, write_header)
            else:
                write_layout_n_variant_n(dest, mappings, number, write_header)
        else:
            raise NotImplementedError()


if __name__ == "__main__":
    parser = argparse.ArgumentParser("variant mapping script")
    parser.add_argument("--want", type=str, choices=["mls", "mlvs"])
    parser.add_argument("--number", type=int, default=None)

    parser.add_argument("dest", type=str)
    parser.add_argument("files", nargs="+", type=str)
    ns = parser.parse_args()

    dest = None
    if ns.dest == "-":
        dest = sys.stdout

    with dest or open(ns.dest, "w") as fd:
        map_variant(fd, ns.files, ns.want, ns.number)