This repository contains a proof of concept of a gcc plugin enabling automatic code generation for bidirectional conversion of enums into strings. The idea comes from the deriving Enum attribute used in Haskell. The API is inspired by the magic_enum repository, which seems to be quite complicated and also has some small limitations. It was also a small sanity test of cooperation with Copilot. Anyways reflection in C++26 will probably support printing enums as a basic usecase, so it is left as a cool experimental feature.
make clean build test
As it is just a proof of concept it does not support all the possible edge cases.
There are some small issues with namespaces and the possible solution may require more advanced handling.
Do not use #pragma deriving in the templated class context. It keeps a seperate type of enum for each template specialization. Thus leading to a lot of redundancy. Apart from that it makes things unnecessarily complex which is counterproductive.
template <typename T> class spdlog {
public:
enum level_enum : T {
trace,
debug,
info,
warn,
err,
critical,
off,
n_levels
};
// Don't do it, this will not work...
// #pragma deriving level_enum Enum
};
Instead do:
class spdlog_base {
public:
enum level_enum : int {
trace,
debug,
info,
warn,
err,
critical,
off,
n_levels
}
#pragma deriving level_enum Enum
}
template <typename T>
class spdlog {
using level_enum = spdlog_base::level_enum;
};
template <typename T>
class spdlog : public spdlog_base {
};
For simplicity constexpr is not supported. From my research it seems to be a quite complicated endeavour to hack gcc to process the autogenerated code in the right order. In Haskell there are no header files, so maybe modules are a better solution for it.
It is also not supported as it would require per file configuration in multithreaded setup.
- https://gcc.gnu.org/onlinedocs/gccint/Plugins.html
- https://www.codingwiththomas.com/blog/accessing-gccs-abstract-syntax-tree-with-a-gcc-plugin
- https://github.com/gcc-mirror/gcc/blob/e3431c6fd4691d5a0c48ee78869e5f9a79f217c3/gcc/testsuite/g%2B%2B.dg/plugin/attribute_plugin.cc#L68
- https://gcc.gnu.org/onlinedocs/gccint/Types.html
- https://jongy.github.io/2020/04/25/gcc-assert-introspect.html
- https://learnxbyexample.com/haskell/enums/