Newer
Older
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
from __future__ import annotations
from argparse import ArgumentParser
from types import ModuleType
from typing import Generic, TypeVar, Callable, Any, Sequence
from abc import ABC
from dataclasses import dataclass, fields, field
from enum import Enum, auto
from os import path
from importlib import util as iutil
class SfgConfigException(Exception): ... # noqa: E701
Option_T = TypeVar("Option_T")
class Option(Generic[Option_T]):
"""Option descriptor.
This descriptor is used to model configuration options.
It maintains a default value for the option that is used when no value
was specified by the user.
In configuration options, the value `None` stands for `unset`.
It can therefore not be used to set an option to the meaning "not any", or "empty"
- for these, special values need to be used.
"""
def __init__(
self,
default: Option_T | None = None,
validator: Callable[[Any, Option_T | None], Option_T | None] | None = None,
) -> None:
self._default = default
self._validator = validator
self._name: str
self._lookup: str
def validate(self, validator: Callable[[Any, Any], Any] | None):
self._validator = validator
return validator
@property
def default(self) -> Option_T | None:
return self._default
def get(self, obj) -> Option_T | None:
val = getattr(obj, self._lookup, None)
if val is None:
return self._default
else:
return val
def __set_name__(self, owner, name: str):
self._name = name
self._lookup = f"_{name}"
def __get__(self, obj, objtype=None) -> Option_T | None:
if obj is None:
return None
return getattr(obj, self._lookup, None)
def __set__(self, obj, value: Option_T | None):
if self._validator is not None:
value = self._validator(obj, value)
setattr(obj, self._lookup, value)
def __delete__(self, obj):
delattr(obj, self._lookup)
class ConfigBase(ABC):
def get_option(self, name: str) -> Any:
"""Get the value set for the specified option, or the option's default value if none has been set."""
descr: Option = type(self).__dict__[name]
return descr.get(self)
def override(self, other: ConfigBase):
for f in fields(self): # type: ignore
fvalue = getattr(self, f.name)
if isinstance(fvalue, ConfigBase): # type: ignore
fvalue.override(getattr(other, f.name))
else:
new_val = getattr(other, f.name)
if new_val is not None:
setattr(self, f.name, new_val)
@dataclass
class FileExtensions(ConfigBase):
"""Option category containing output file extensions."""
header: Option[str] = Option("hpp")
"""File extension for generated header file."""
impl: Option[str] = Option()
"""File extension for generated implementation file."""
@header.validate
@impl.validate
def _validate_extension(self, ext: str | None) -> str | None:
if ext is not None and ext[0] == ".":
return ext[1:]
return ext
class OutputMode(Enum):
"""Output mode of the source file generator."""
STANDALONE = auto()
"""Generate a header/implementation file pair (e.g. ``.hpp/.cpp``) where the implementation file will
be compiled to a standalone object."""
INLINE = auto()
"""Generate a header/inline implementation file pair (e.g. ``.hpp/.ipp``) where all implementations
are inlined by including the implementation file at the end of the header file."""
HEADER_ONLY = auto()
"""Generate only a header file.
At the moment, header-only mode does not support generation of kernels and requires that all functions
and methods are marked `inline`.
"""
@dataclass
class CodeStyle(ConfigBase):
"""Options affecting the code style used by the source file generator."""
indent_width: Option[int] = Option(2)
"""The number of spaces successively nested blocks should be indented with"""
# TODO possible future options:
# - newline before opening {
# - trailing return types
def indent(self, s: str):
from textwrap import indent
prefix = " " * self.get_option("indent_width")
return indent(s, prefix)
@dataclass
class ClangFormatOptions(ConfigBase):
"""Options affecting the invocation of ``clang-format`` for automatic code formatting."""
code_style: Option[str] = Option("file")
"""Code style to be used by clang-format. Passed verbatim to `--style` argument of the clang-format CLI.
Similar to clang-format itself, the default value is `file`, such that a `.clang-format` file found in the build
tree will automatically be used.
"""
force: Option[bool] = Option(False)
"""If set to ``True``, abort code generation if ``clang-format`` binary cannot be found."""
skip: Option[bool] = Option(False)
"""If set to ``True``, skip formatting using ``clang-format``."""
binary: Option[str] = Option("clang-format")
"""Path to the clang-format executable"""
@force.validate
def _validate_force(self, val: bool) -> bool:
if val and self.skip:
raise SfgConfigException(
"Cannot set both `clang_format.force` and `clang_format.skip` at the same time"
)
return val
@skip.validate
def _validate_skip(self, val: bool) -> bool:
if val and self.force:
raise SfgConfigException(
"Cannot set both `clang_format.force` and `clang_format.skip` at the same time"
)
return val
class _GlobalNamespace: ... # noqa: E701
GLOBAL_NAMESPACE = _GlobalNamespace()
"""Indicates the C++ global namespace."""
@dataclass
class SfgConfig(ConfigBase):
"""Configuration options for the `SourceFileGenerator`."""
extensions: FileExtensions = field(default_factory=FileExtensions)
"""File extensions of the generated files
Options in this category:
.. autosummary::
FileExtensions.header
FileExtensions.impl
"""
output_mode: Option[OutputMode] = Option(OutputMode.STANDALONE)
"""The generator's output mode; defines which files to generate, and the set of legal file extensions.
Possible parameters:
.. autosummary::
OutputMode.STANDALONE
OutputMode.INLINE
OutputMode.HEADER_ONLY
"""
outer_namespace: Option[str | _GlobalNamespace] = Option(GLOBAL_NAMESPACE)
"""The outermost namespace in the generated file. May be a valid C++ nested namespace qualifier
(like ``a::b::c``) or `GLOBAL_NAMESPACE` if no outer namespace should be generated.
.. autosummary::
GLOBAL_NAMESPACE
"""
codestyle: CodeStyle = field(default_factory=CodeStyle)
"""Options affecting the code style emitted by pystencils-sfg.
Options in this category:
.. autosummary::
CodeStyle.indent_width
"""
clang_format: ClangFormatOptions = field(default_factory=ClangFormatOptions)
"""Options governing the code style used by the code generator
Options in this category:
.. autosummary::
ClangFormatOptions.code_style
ClangFormatOptions.force
ClangFormatOptions.skip
ClangFormatOptions.binary
"""
output_directory: Option[str] = Option(".")
"""Directory to which the generated files should be written."""
class CommandLineParameters:
@staticmethod
def add_args_to_parser(parser: ArgumentParser):
config_group = parser.add_argument_group("Configuration")
config_group.add_argument(
"--sfg-output-dir", type=str, default=None, dest="output_directory"
)
config_group.add_argument(
"--sfg-file-extensions",
type=str,
default=None,
dest="file_extensions",
help="Comma-separated list of file extensions",
)
config_group.add_argument(
"--sfg-output-mode",
type=str,
default=None,
choices=("standalone", "inline", "header-only"),
dest="output_mode",
)
config_group.add_argument(
"--sfg-config-module", type=str, default=None, dest="config_module_path"
)
return parser
def __init__(self, args) -> None:
self._cl_config_module_path: str | None = args.config_module_path
if args.output_mode is not None:
match args.output_mode.lower():
case "standalone":
output_mode = OutputMode.STANDALONE
case "inline":
output_mode = OutputMode.INLINE
case "header-only":
output_mode = OutputMode.HEADER_ONLY
case _:
assert False, "invalid output mode"
else:
output_mode = None
self._cl_output_mode = output_mode
self._cl_output_dir: str | None = args.output_directory
if args.file_extensions is not None:
file_extentions = list(args.file_extensions.split(","))
h_ext, impl_ext = self._get_file_extensions(file_extentions)
self._cl_header_ext = h_ext
self._cl_impl_ext = impl_ext
else:
self._cl_header_ext = None
self._cl_impl_ext = None
self._config_module: ModuleType | None
if self._cl_config_module_path is not None:
self._config_module = self._import_config_module(
self._cl_config_module_path
)
else:
self._config_module = None
@property
def configuration_module(self) -> ModuleType | None:
return self._config_module
def get_config(self) -> SfgConfig:
cfg = SfgConfig()
if self._config_module is not None and hasattr(
self._config_module, "configure_sfg"
):
self._config_module.configure_sfg(cfg)
if self._cl_output_mode is not None:
cfg.output_mode = self._cl_output_mode
if self._cl_header_ext is not None:
cfg.extensions.header = self._cl_header_ext
if self._cl_impl_ext is not None:
cfg.extensions.impl = self._cl_impl_ext
if self._cl_output_dir is not None:
cfg.output_directory = self._cl_output_dir
return cfg
def find_conflicts(self, cfg: SfgConfig):
for name, mine, theirs in (
("output_mode", self._cl_output_mode, cfg.output_mode),
("extensions.header", self._cl_header_ext, cfg.extensions.header),
("extensions.impl", self._cl_impl_ext, cfg.extensions.impl),
("output_directory", self._cl_output_dir, cfg.output_directory),
):
if mine is not None and theirs is not None and mine != theirs:
raise SfgConfigException(
f"Conflicting values given for option {name} on command line and inside generator script.\n"
f" Value on command-line: {name}",
f" Value in script: {name}",
)
def get_project_info(self) -> Any:
if self._config_module is not None and hasattr(
self._config_module, "project_info"
):
return self._config_module.project_info()
else:
return None
def _get_file_extensions(self, extensions: Sequence[str]):
h_ext = None
src_ext = None
extensions = tuple(ext.strip() for ext in extensions)
extensions = tuple((ext[1:] if ext[0] == "." else ext) for ext in extensions)
HEADER_FILE_EXTENSIONS = {"h", "hpp", "hxx", "h++", "cuh"}
IMPL_FILE_EXTENSIONS = {"c", "cpp", "cxx", "c++", "cu", ".impl.h", "ipp"}
for ext in extensions:
if ext in HEADER_FILE_EXTENSIONS:
if h_ext is not None:
raise SfgConfigException(
"Multiple header file extensions specified."
)
h_ext = ext
elif ext in IMPL_FILE_EXTENSIONS:
if src_ext is not None:
raise SfgConfigException(
"Multiple source file extensions specified."
)
src_ext = ext
else:
raise SfgConfigException(
f"Invalid file extension: Don't know what to do with '.{ext}'"
)
return h_ext, src_ext
def _import_config_module(self, module_path: str) -> ModuleType:
cfg_modulename = path.splitext(path.split(module_path)[1])[0]
cfg_spec = iutil.spec_from_file_location(cfg_modulename, module_path)
if cfg_spec is None:
raise SfgConfigException(
f"Unable to import configuration module {module_path}",
)
config_module = iutil.module_from_spec(cfg_spec)
cfg_spec.loader.exec_module(config_module) # type: ignore
return config_module