1 /* 2 * Copyright 2019 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include "enum_gen.h" 18 19 #include <iostream> 20 21 #include "util.h" 22 EnumGen(EnumDef e)23EnumGen::EnumGen(EnumDef e) : e_(std::move(e)) {} 24 GenDefinition(std::ostream & stream)25void EnumGen::GenDefinition(std::ostream& stream) { 26 stream << "enum class "; 27 stream << e_.name_; 28 stream << " : " << util::GetTypeForSize(e_.size_); 29 stream << " {"; 30 for (const auto& pair : e_.constants_) { 31 stream << pair.second << " = 0x" << std::hex << pair.first << std::dec << ","; 32 } 33 stream << "};\n"; 34 } 35 GenDefinitionPybind11(std::ostream & stream)36void EnumGen::GenDefinitionPybind11(std::ostream& stream) { 37 stream << "py::enum_<" << e_.name_ << ">(m, \"" << e_.name_ << "\")"; 38 for (const auto& pair : e_.constants_) { 39 stream << ".value(\"" << pair.second << "\", " << e_.name_ << "::" << pair.second << ")"; 40 } 41 stream << ";\n"; 42 } 43 GenLogging(std::ostream & stream)44void EnumGen::GenLogging(std::ostream& stream) { 45 // Print out the switch statement that converts all the constants to strings. 46 stream << "inline std::string " << e_.name_ << "Text(const " << e_.name_ << "& param) {"; 47 stream << "std::stringstream builder;"; 48 stream << "switch (param) {"; 49 for (const auto& pair : e_.constants_) { 50 stream << "case " << e_.name_ << "::" << pair.second << ":"; 51 stream << " builder << \"" << pair.second << "\"; break;"; 52 } 53 stream << "default:"; 54 stream << " builder << \"Unknown " << e_.name_ << "\";"; 55 stream << "}"; 56 stream << "builder << \"(\" << std::hex << \"0x\" << std::setfill('0')"; 57 stream << "<< std::setw(" << (e_.size_ > 0 ? e_.size_ : 0) << "/4)"; 58 stream << "<< static_cast<uint64_t>(param) << \")\";"; 59 stream << "return builder.str();"; 60 stream << "}\n\n"; 61 } 62