From b69e7bfacd629ee4c25ffb873a80f49518deb43c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonathan=20M=C3=BCller?= Date: Tue, 31 Oct 2017 18:28:18 +0100 Subject: [PATCH] Add enum_to_string example --- example/CMakeLists.txt | 1 + example/enum_to_string.cpp | 61 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 example/enum_to_string.cpp diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt index 928bdfb..a831176 100644 --- a/example/CMakeLists.txt +++ b/example/CMakeLists.txt @@ -9,3 +9,4 @@ endfunction() _cppast_example(ast_printer) _cppast_example(documentation_generator) +_cppast_example(enum_to_string) diff --git a/example/enum_to_string.cpp b/example/enum_to_string.cpp new file mode 100644 index 0000000..ec1428a --- /dev/null +++ b/example/enum_to_string.cpp @@ -0,0 +1,61 @@ +// Copyright (C) 2017 Jonathan Müller +// This file is subject to the license terms in the LICENSE file +// found in the top-level directory of this distribution. + +/// \file +/// Generates enum `to_string()` code. + +#include + +#include // cpp_enum +#include // visit() + +#include "example_parser.hpp" + +void generate_to_string(const cppast::cpp_file& file) +{ + cppast::visit(file, + [](const cppast::cpp_entity& e) { + // only visit enums that have the attribute set + return (e.kind() == cppast::cpp_entity_kind::enum_t + && cppast::has_attribute(e, "generate::to_string")) + // or all namespaces + || e.kind() == cppast::cpp_entity_kind::namespace_t; + }, + [](const cppast::cpp_entity& e, const cppast::visitor_info& info) { + if (e.kind() == cppast::cpp_entity_kind::enum_t && !info.is_old_entity()) + { + // a new enum, generate to string function + auto& enum_ = static_cast(e); + + // write function header + std::cout << "const char* to_string(const " << enum_.name() << "& e) {\n"; + + // generate switch + std::cout << " switch (e) {\n"; + for (const auto& enumerator : enum_) + { + std::cout << " case " << enum_.name() << "::" << enumerator.name() + << ":\n"; + std::cout << " return \"" << enumerator.name() << "\";\n"; + } + std::cout << " }\n"; + + std::cout << "}\n\n"; + } + else if (e.kind() == cppast::cpp_entity_kind::namespace_t) + { + if (info.event == cppast::visitor_info::container_entity_enter) + // open namespace + std::cout << "namespace " << e.name() << " {\n\n"; + else // if (info.event == cppast::visitor_info::container_entity_exit) + // close namespace + std::cout << "}\n"; + } + }); +} + +int main(int argc, char* argv[]) +{ + return example_main(argc, argv, {}, &generate_to_string); +}