Debian Codegraph @

tensilelite/Tensile/EmbeddedData.py

raw symbols SCIP
1 ################################################################################
2 #
3 # Copyright (C) 2022 Advanced Micro Devices, Inc. All rights reserved.
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 # copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 # SOFTWARE.
22 #
23 ################################################################################
24
25 from .Common import CHeader
26
27 import itertools
28 import os
29
30 class Namespace:
31 def __init__(self, parent, name=None):
32 self.parent = parent
33 self.name = name
34
35 def __enter__(self):
36 if self.name is None:
37 self.parent.write("namespace {")
38 else:
39 self.parent.write("namespace {} {{".format(self.name))
40 self.parent.indent()
41 return self
42
43 def __exit__(self, *args, **kwargs):
44 self.parent.dedent()
45 if self.name is None:
46 self.parent.write("} // anonymous namespace")
47 else:
48 self.parent.write("}} // namespace {}".format(self.name))
49
50 class Indent:
51 def __init__(self, parent):
52 self.parent = parent
53
54 def __enter__(self):
55 return self
56
57 def __exit__(self, *args, **kwargs):
58 self.parent.dedent()
59
60 class EmbeddedDataFile:
61 def __init__(self, filename, file=None, indent_spaces=4):
62 self.filename = filename
63
64 self._indent_spaces = indent_spaces
65 self._indent_levels = [0]
66 self._open_blocks = []
67
68 self.file = file
69 if self.file is None:
70 self.file = open(filename, 'w')
71
72 self.write_header()
73
74 def __enter__(self):
75 self.file.__enter__()
76 return self
77
78 def __exit__(self, *args, **kwargs):
79 while len(self._open_blocks) > 0:
80 b = self._open_blocks.pop()
81 b.__exit__(*args, **kwargs)
82
83 self.write_footer()
84
85 self.file.__exit__(*args, **kwargs)
86
87 def namespace(self, name=None):
88 ns = Namespace(self, name).__enter__()
89 self._open_blocks.append(ns)
90
91 def end_namespace(self, name=None):
92 ns = self._open_blocks.pop()
93 if not isinstance(ns, Namespace):
94 raise RuntimeError("Mismatched block types: expected Namespace, found {}".format(ns.__class__))
95 if name != ns.name:
96 raise RuntimeError("Mismatched namespace open/close: expected {}, found {}".format(name, ns.name))
97
98 ns.__exit__(None, None, None)
99
100 def write_header(self):
101 self.write(CHeader)
102
103 self.write(self.includes)
104
105 self.namespace("Tensile")
106
107 @property
108 def include_guard(self):
109 return "#pragma once"
110
111 @property
112 def includes(self):
113 return """
114 #include <Tensile/EmbeddedData.hpp>
115
116 #include <Tensile/Contractions.hpp>
117 #include <Tensile/Tensile.hpp>
118 """
119
120 def get_lines(self, item):
121 if isinstance(item, str):
122 return item.split('\n')
123
124 if hasattr(item, '__iter__'):
125 return item
126
127 return str(item).split('\n')
128
129 def format(self, item):
130 out_lines = []
131 for line in self.get_lines(item):
132 out_lines.append(self.apply_indent(line))
133
134 return '\n'.join(out_lines) + '\n'
135
136 @property
137 def indent_level(self):
138 if len(self._indent_levels) == 0:
139 return 0
140
141 return self._indent_levels[-1]
142
143 def apply_indent(self, line=None):
144 if line is None:
145 return ' ' * self.indent_level
146
147 line = line.strip()
148
149 if line.startswith('#'):
150 return line
151
152 return (' ' * self.indent_level) + line
153
154 def indent(self, spaces=None):
155 if spaces is None:
156 spaces = self._indent_spaces
157 self._indent_levels.append(spaces + self.indent_level)
158 return Indent(self)
159
160 def dedent(self):
161 self._indent_levels.pop()
162
163 def write(self, *items):
164 for item in items:
165 self.file.write(self.format(item))
166
167 def comment(self, text):
168 self.write(['// ' + line for line in text.split('\n')])
169
170 def write_footer(self):
171 self.write('')
172
173 def embed_data(self, assocType, data, nullTerminated=False, comment=None, key=None):
174 if nullTerminated:
175 empty = False
176 data = itertools.chain(data, [0])
177 else:
178 empty = len(data) == 0
179 data = iter(data)
180
181 with Namespace(self):
182 if comment is not None:
183 self.comment(comment)
184 if empty:
185 if key is None:
186 self.write("EmbedData<{0}> TENSILE_EMBED_SYMBOL_NAME{{}};".format(assocType))
187 else:
188 self.write('EmbedData<{0}> TENSILE_EMBED_SYMBOL_NAME("{1}", {{}});'.format(assocType, key))
189 return
190
191 hex_format = '{:#04x}'
192
193 if key is None:
194 self.write("EmbedData<{0}> TENSILE_EMBED_SYMBOL_NAME({{".format(assocType))
195 else:
196 self.write('EmbedData<{0}> TENSILE_EMBED_SYMBOL_NAME("{1}", {{'.format(assocType, key))
197 with self.indent():
198 line = hex_format.format(next(data))
199 for byteIdx, byte in enumerate(data):
200 if byteIdx % 16 == 15:
201 self.write(line + ",")
202 line = hex_format.format(byte)
203 else:
204 line += ', ' + hex_format.format(byte)
205
206 self.write(line + '});')
207
208 def embed_file(self, assocType, filename, nullTerminated=False, key=None):
209 with open(filename, 'rb') as f:
210 byteArray = bytearray(f.read())
211 self.embed_data(assocType, byteArray, nullTerminated, os.path.basename(filename), key)