classgeneratorbase.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2019 Alexey Edelev <semlanik@gmail.com>, Tatyana Borisova <tanusshhka@mail.ru>
  5. *
  6. * This file is part of QtProtobuf project https://git.semlanik.org/semlanik/qtprotobuf
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of this
  9. * software and associated documentation files (the "Software"), to deal in the Software
  10. * without restriction, including without limitation the rights to use, copy, modify,
  11. * merge, publish, distribute, sublicense, and/or sell copies of the Software, and
  12. * to permit persons to whom the Software is furnished to do so, subject to the following
  13. * conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all copies
  16. * or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  19. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  20. * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  21. * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. #include "classgeneratorbase.h"
  26. #include "templates.h"
  27. #include "generatoroptions.h"
  28. #include <google/protobuf/descriptor.h>
  29. #include <google/protobuf/io/zero_copy_stream.h>
  30. #include <set>
  31. using namespace ::QtProtobuf::generator;
  32. using namespace ::google::protobuf;
  33. using namespace ::google::protobuf::io;
  34. using namespace ::google::protobuf::compiler;
  35. ClassGeneratorBase::ClassGeneratorBase(const std::string &fullClassName, const std::shared_ptr<::google::protobuf::io::Printer> &printer) :
  36. mPrinter(printer)
  37. {
  38. utils::split(fullClassName, mNamespaces, '.');
  39. assert(mNamespaces.size() > 0);
  40. mClassName = utils::upperCaseName(mNamespaces.back());
  41. mNamespaces.erase(mNamespaces.end() - 1);
  42. for (size_t i = 0; i < mNamespaces.size(); i++) {
  43. if (i > 0) {
  44. mNamespacesColonDelimited = mNamespacesColonDelimited.append("::");
  45. }
  46. mNamespacesColonDelimited = mNamespacesColonDelimited.append(mNamespaces[i]);
  47. }
  48. }
  49. ClassGeneratorBase::ClassGeneratorBase(const std::string &fullClassName, const std::shared_ptr<::google::protobuf::io::ZeroCopyOutputStream> &out) :
  50. ClassGeneratorBase(fullClassName, std::shared_ptr<::google::protobuf::io::Printer>(new ::google::protobuf::io::Printer(out.get(), '$')))
  51. {
  52. mOutput = out;
  53. }
  54. void ClassGeneratorBase::printDisclaimer()
  55. {
  56. mPrinter->Print(Templates::DisclaimerTemplate);
  57. }
  58. void ClassGeneratorBase::printPreamble()
  59. {
  60. mPrinter->Print(Templates::PreambleTemplate);
  61. }
  62. void ClassGeneratorBase::printNamespaces()
  63. {
  64. printNamespaces(mNamespaces);
  65. }
  66. void ClassGeneratorBase::printNamespaces(const std::vector<std::string> &namespaces)
  67. {
  68. for (auto ns: namespaces) {
  69. mPrinter->Print({{"namespace", ns}}, Templates::NamespaceTemplate);
  70. }
  71. }
  72. void ClassGeneratorBase::printClassDeclaration()
  73. {
  74. mPrinter->Print({{"classname", mClassName}}, Templates::ProtoClassDefinitionTemplate);
  75. }
  76. void ClassGeneratorBase::encloseClass()
  77. {
  78. mPrinter->Print(Templates::SemicolonBlockEnclosureTemplate);
  79. }
  80. void ClassGeneratorBase::encloseNamespaces(int count)
  81. {
  82. for (int i = 0; i < count; i++) {
  83. mPrinter->Print(Templates::SimpleBlockEnclosureTemplate);
  84. }
  85. }
  86. void ClassGeneratorBase::encloseNamespaces()
  87. {
  88. encloseNamespaces(mNamespaces.size());
  89. }
  90. void ClassGeneratorBase::printPublic()
  91. {
  92. mPrinter->Print(Templates::PublicBlockTemplate);
  93. }
  94. void ClassGeneratorBase::printPrivate()
  95. {
  96. mPrinter->Print(Templates::PrivateBlockTemplate);
  97. }
  98. void ClassGeneratorBase::printMetaTypeDeclaration()
  99. {
  100. mPrinter->Print({{"classname", mClassName}, {"namespaces", mNamespacesColonDelimited}},
  101. Templates::DeclareMetaTypeTemplate);
  102. mPrinter->Print({{"classname", mClassName}, {"namespaces", mNamespacesColonDelimited}},
  103. Templates::DeclareComplexListTypeTemplate);
  104. if (GeneratorOptions::instance().hasQml()) {
  105. mPrinter->Print({{"classname", mClassName}, {"namespaces", mNamespacesColonDelimited}},
  106. Templates::DeclareComplexQmlListTypeTemplate);
  107. }
  108. }
  109. bool ClassGeneratorBase::isLocalMessageEnum(const google::protobuf::Descriptor *message,
  110. const ::google::protobuf::FieldDescriptor *field)
  111. {
  112. assert(field->enum_type() != nullptr);
  113. for (int i = 0; i < message->enum_type_count(); i++) {
  114. const auto enumDescr = message->enum_type(i);
  115. if (enumDescr && enumDescr->full_name() == field->enum_type()->full_name()) {
  116. return true;
  117. }
  118. }
  119. return false;
  120. }
  121. std::string ClassGeneratorBase::getTypeName(const FieldDescriptor *field, const Descriptor *messageFor)
  122. {
  123. assert(field != nullptr);
  124. std::string typeName;
  125. std::string namespaceQtProtoDefinition("QtProtobuf::");
  126. std::string namespaceTypeName;
  127. std::vector<std::string> typeNamespace;
  128. if (field->type() == FieldDescriptor::TYPE_MESSAGE) {
  129. const Descriptor *msg = field->message_type();
  130. namespaceTypeName = getNamespacesList(msg, typeNamespace, mNamespacesColonDelimited);
  131. typeName = namespaceTypeName.append(utils::upperCaseName(msg->name()));
  132. if (field->is_map()) {
  133. return mClassName + "::" + utils::upperCaseName(msg->name());
  134. }
  135. if (field->is_repeated()) {
  136. return namespaceTypeName.append(Templates::ListSuffix);
  137. }
  138. } else if (field->type() == FieldDescriptor::TYPE_ENUM) {
  139. const EnumDescriptor *enumType = field->enum_type();
  140. namespaceTypeName = getNamespacesList(enumType, typeNamespace, mNamespacesColonDelimited);
  141. EnumVisibility visibility = getEnumVisibility(field, messageFor);
  142. if (visibility == LOCAL_ENUM) {
  143. if (field->is_repeated()) {
  144. typeName = typeName.append(mClassName + "::" + enumType->name());
  145. } else {
  146. //Note: For local enum classes it's impossible to use class name space in Q_PROPERTY
  147. //declaration. So please avoid addition of mClassName in line bellow
  148. typeName = typeName.append(enumType->name());
  149. }
  150. } else if (visibility == GLOBAL_ENUM) {
  151. namespaceTypeName = getNamespacesList(enumType, typeNamespace, "");
  152. typeName = namespaceTypeName.append(Templates::GlobalEnumClassNameTemplate)
  153. .append("::").append(enumType->name());
  154. } else {
  155. typeName = namespaceTypeName.append(enumType->name());
  156. }
  157. if (field->is_repeated()) {
  158. return typeName.append(Templates::ListSuffix);
  159. }
  160. } else {
  161. auto it = Templates::TypeReflection.find(field->type());
  162. if (it != std::end(Templates::TypeReflection)) {
  163. if (field->type() != FieldDescriptor::TYPE_STRING
  164. && field->type() != FieldDescriptor::TYPE_BYTES
  165. && field->type() != FieldDescriptor::TYPE_BOOL
  166. && field->type() != FieldDescriptor::TYPE_FLOAT
  167. && field->type() != FieldDescriptor::TYPE_DOUBLE) {
  168. typeName = typeName.append(namespaceQtProtoDefinition.append(it->second));
  169. } else {
  170. typeName = typeName.append(it->second);
  171. }
  172. if (field->is_repeated()) {
  173. if (field->type() == FieldDescriptor::TYPE_FLOAT
  174. || field->type() == FieldDescriptor::TYPE_DOUBLE) {
  175. typeName[0] = ::toupper(typeName[0]);
  176. typeName = namespaceQtProtoDefinition.append(typeName);
  177. }
  178. typeName.append("List");
  179. }
  180. }
  181. }
  182. return typeName;
  183. }
  184. template<typename T>
  185. std::string ClassGeneratorBase::getNamespacesList(const T *message, std::vector<std::string> &container, const std::string &localNamespace)
  186. {
  187. std::string result;
  188. utils::split(std::string(message->full_name()), container, '.');
  189. if (container.size() > 1) {
  190. //delete type name -> only namespace stays
  191. container.pop_back();
  192. for (size_t i = 0; i < container.size(); i++) {
  193. if (i > 0) {
  194. result = result.append("::");
  195. }
  196. result = result.append(container[i]);
  197. }
  198. }
  199. if (!container.empty()
  200. && localNamespace != result) {
  201. result = result.append("::");
  202. } else {
  203. result.clear();
  204. }
  205. return result;
  206. }
  207. ClassGeneratorBase::EnumVisibility ClassGeneratorBase::getEnumVisibility(const FieldDescriptor *field, const Descriptor *messageFor)
  208. {
  209. assert(field->enum_type() != nullptr);
  210. if (isLocalMessageEnum(messageFor, field)) {
  211. return LOCAL_ENUM;
  212. }
  213. const EnumDescriptor *enumType = field->enum_type();
  214. const FileDescriptor *enumFile = field->enum_type()->file();
  215. for (int i = 0; i < enumFile->message_type_count(); i++) {
  216. const Descriptor *msg = enumFile->message_type(i);
  217. for (int j = 0; j < msg->enum_type_count(); j++) {
  218. if (enumType->full_name() == msg->enum_type(j)->full_name()) {
  219. return NEIGHBOUR_ENUM;
  220. }
  221. }
  222. }
  223. return GLOBAL_ENUM;
  224. }
  225. void ClassGeneratorBase::getMethodParameters(const MethodDescriptor *method, std::map<std::string, std::string> &parameters)
  226. {
  227. std::string inputTypeName = method->input_type()->full_name();
  228. std::string outputTypeName = method->output_type()->full_name();
  229. std::string methodName = method->name();
  230. std::string methodNameUpper = method->name();
  231. methodNameUpper[0] = ::toupper(methodNameUpper[0]);
  232. utils::replace(inputTypeName, ".", "::");
  233. utils::replace(outputTypeName, ".", "::");
  234. parameters = {{"classname", mClassName},
  235. {"return_type", outputTypeName},
  236. {"method_name", methodName},
  237. {"method_name_upper", methodNameUpper},
  238. {"param_type", inputTypeName},
  239. {"param_name", "arg"},
  240. {"return_name", "ret"}
  241. };
  242. }
  243. bool ClassGeneratorBase::hasGlobalEnum(const std::list<const FileDescriptor *> &list)
  244. {
  245. for (auto file : list) {
  246. if (file->enum_type_count() <= 0) {
  247. return false;
  248. }
  249. }
  250. return true;
  251. }
  252. void ClassGeneratorBase::printField(const google::protobuf::Descriptor *message, const FieldDescriptor *field, const char *fieldTemplate)
  253. {
  254. assert(field != nullptr);
  255. std::map<std::string, std::string> propertyMap;
  256. if (producePropertyMap(message, field, propertyMap)) {
  257. mPrinter->Print(propertyMap, fieldTemplate);
  258. }
  259. }
  260. bool ClassGeneratorBase::producePropertyMap(const google::protobuf::Descriptor *message, const FieldDescriptor *field, PropertyMap &propertyMap)
  261. {
  262. assert(field != nullptr);
  263. std::string typeName = getTypeName(field, message);
  264. if (typeName.size() <= 0) {
  265. std::cerr << "Type "
  266. << field->type_name()
  267. << " is not supported by Qt Generator"
  268. " please look at https://doc.qt.io/qt-5/qtqml-typesystem-basictypes.html"
  269. " for details" << std::endl;
  270. return false;
  271. }
  272. std::string typeNameLower(typeName);
  273. utils::tolower(typeNameLower);
  274. std::string capProperty = field->name();
  275. capProperty[0] = static_cast<char>(::toupper(capProperty[0]));
  276. std::string typeNameNoList = typeName;
  277. if (field->is_repeated() && !field->is_map()) {
  278. if(field->type() == FieldDescriptor::TYPE_MESSAGE
  279. || field->type() == FieldDescriptor::TYPE_ENUM) {
  280. typeNameNoList.resize(typeNameNoList.size() - strlen(Templates::ListSuffix));
  281. } else {
  282. typeNameNoList.resize(typeNameNoList.size() - strlen("List"));
  283. }
  284. }
  285. std::string fieldName = utils::lowerCaseName(field->name());
  286. fieldName = qualifiedName(fieldName);
  287. propertyMap = {{"type", typeName},
  288. {"classname", utils::upperCaseName(message->name())},
  289. {"type_lower", typeNameLower},
  290. {"property_name", fieldName},
  291. {"property_name_cap", capProperty},
  292. {"type_nolist", typeNameNoList}
  293. };
  294. return true;
  295. }
  296. bool ClassGeneratorBase::isComplexType(const FieldDescriptor *field)
  297. {
  298. assert(field != nullptr);
  299. return field->type() == FieldDescriptor::TYPE_MESSAGE
  300. || field->type() == FieldDescriptor::TYPE_STRING
  301. || field->type() == FieldDescriptor::TYPE_BYTES;
  302. }
  303. std::string ClassGeneratorBase::qualifiedName(const std::string &name)
  304. {
  305. std::string fieldName(name);
  306. const std::vector<std::string> &searchExeptions = Templates::ListOfQmlExeptions;
  307. auto searchResult = std::find(searchExeptions.begin(), searchExeptions.end(), fieldName);
  308. if (searchResult != searchExeptions.end()) {
  309. return fieldName.append(Templates::ProtoSufix);
  310. }
  311. return fieldName;
  312. }
  313. void ClassGeneratorBase::printInclude(const google::protobuf::Descriptor *message, const FieldDescriptor *field, std::set<std::string> &existingIncludes)
  314. {
  315. assert(field != nullptr);
  316. std::string newInclude;
  317. const char *includeTemplate;
  318. switch (field->type()) {
  319. case FieldDescriptor::TYPE_MESSAGE:
  320. if ( field->is_map() ) {
  321. newInclude = "QMap";
  322. assert(field->message_type() != nullptr);
  323. assert(field->message_type()->field_count() == 2);
  324. printInclude(message, field->message_type()->field(0), existingIncludes);
  325. printInclude(message, field->message_type()->field(1), existingIncludes);
  326. includeTemplate = Templates::ExternalIncludeTemplate;
  327. } else {
  328. std::string typeName = field->message_type()->name();
  329. utils::tolower(typeName);
  330. newInclude = typeName;
  331. includeTemplate = Templates::InternalIncludeTemplate;
  332. }
  333. break;
  334. case FieldDescriptor::TYPE_BYTES:
  335. newInclude = "QByteArray";
  336. includeTemplate = Templates::ExternalIncludeTemplate;
  337. break;
  338. case FieldDescriptor::TYPE_STRING:
  339. newInclude = "QString";
  340. includeTemplate = Templates::ExternalIncludeTemplate;
  341. break;
  342. case FieldDescriptor::TYPE_ENUM: {
  343. EnumVisibility enumVisibily = getEnumVisibility(field, message);
  344. if (enumVisibily == GLOBAL_ENUM) {
  345. includeTemplate = Templates::GlobalEnumIncludeTemplate;
  346. } else if (enumVisibily == NEIGHBOUR_ENUM) {
  347. includeTemplate = Templates::InternalIncludeTemplate;
  348. std::string fullEnumName = field->enum_type()->full_name();
  349. std::vector<std::string> fullEnumNameParts;
  350. utils::split(fullEnumName, fullEnumNameParts, '.');
  351. std::string enumTypeOwner = fullEnumNameParts.at(fullEnumNameParts.size() - 2);
  352. utils::tolower(enumTypeOwner);
  353. newInclude = enumTypeOwner;
  354. } else {
  355. return;
  356. }
  357. }
  358. break;
  359. default:
  360. return;
  361. }
  362. if (existingIncludes.find(newInclude) == std::end(existingIncludes)) {
  363. mPrinter->Print({{"include", newInclude}}, includeTemplate);
  364. existingIncludes.insert(newInclude);
  365. }
  366. }