classgeneratorbase.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. #include "generatorcommon.h"
  32. using namespace ::QtProtobuf::generator;
  33. using namespace ::google::protobuf;
  34. using namespace ::google::protobuf::io;
  35. using namespace ::google::protobuf::compiler;
  36. ClassGeneratorBase::ClassGeneratorBase(const std::string &fullClassName, const std::shared_ptr<::google::protobuf::io::Printer> &printer) :
  37. mPrinter(printer)
  38. {
  39. mNamespaces = utils::split(fullClassName, '.');
  40. assert(mNamespaces.size() > 0);
  41. mClassName = utils::upperCaseName(mNamespaces.back());
  42. mNamespaces.erase(mNamespaces.end() - 1);
  43. for (size_t i = 0; i < mNamespaces.size(); i++) {
  44. if (i > 0) {
  45. mNamespacesColonDelimited = mNamespacesColonDelimited.append("::");
  46. }
  47. mNamespacesColonDelimited = mNamespacesColonDelimited.append(mNamespaces[i]);
  48. }
  49. }
  50. ClassGeneratorBase::ClassGeneratorBase(const std::string &fullClassName, const std::shared_ptr<::google::protobuf::io::ZeroCopyOutputStream> &out) :
  51. ClassGeneratorBase(fullClassName, std::shared_ptr<::google::protobuf::io::Printer>(new ::google::protobuf::io::Printer(out.get(), '$')))
  52. {
  53. mOutput = out;
  54. }
  55. void ClassGeneratorBase::printDisclaimer()
  56. {
  57. mPrinter->Print(Templates::DisclaimerTemplate);
  58. }
  59. void ClassGeneratorBase::printPreamble()
  60. {
  61. mPrinter->Print(Templates::PreambleTemplate);
  62. }
  63. void ClassGeneratorBase::printNamespaces()
  64. {
  65. printNamespaces(mNamespaces);
  66. }
  67. void ClassGeneratorBase::printNamespaces(const std::vector<std::string> &namespaces)
  68. {
  69. for (auto ns: namespaces) {
  70. mPrinter->Print({{"namespace", ns}}, Templates::NamespaceTemplate);
  71. }
  72. }
  73. void ClassGeneratorBase::printClassDeclaration()
  74. {
  75. mPrinter->Print({{"classname", mClassName}}, Templates::ProtoClassDefinitionTemplate);
  76. }
  77. void ClassGeneratorBase::encloseClass()
  78. {
  79. mPrinter->Print(Templates::SemicolonBlockEnclosureTemplate);
  80. }
  81. void ClassGeneratorBase::encloseNamespaces(int count)
  82. {
  83. for (int i = 0; i < count; i++) {
  84. mPrinter->Print(Templates::SimpleBlockEnclosureTemplate);
  85. }
  86. }
  87. void ClassGeneratorBase::encloseNamespaces()
  88. {
  89. encloseNamespaces(mNamespaces.size());
  90. }
  91. void ClassGeneratorBase::printPublicBlock()
  92. {
  93. mPrinter->Print(Templates::PublicBlockTemplate);
  94. }
  95. void ClassGeneratorBase::printPrivateBlock()
  96. {
  97. mPrinter->Print(Templates::PrivateBlockTemplate);
  98. }
  99. void ClassGeneratorBase::printSignalsBlock()
  100. {
  101. mPrinter->Print(Templates::SignalsBlockTemplate);
  102. }
  103. bool ClassGeneratorBase::isLocalMessageEnum(const google::protobuf::Descriptor *message,
  104. const ::google::protobuf::FieldDescriptor *field)
  105. {
  106. if (message == nullptr) {
  107. return false;
  108. }
  109. assert(field->enum_type() != nullptr);
  110. for (int i = 0; i < message->enum_type_count(); i++) {
  111. const auto enumDescr = message->enum_type(i);
  112. if (enumDescr && enumDescr->full_name() == field->enum_type()->full_name()) {
  113. return true;
  114. }
  115. }
  116. return false;
  117. }
  118. std::string ClassGeneratorBase::getTypeName(const FieldDescriptor *field, const Descriptor *messageFor)
  119. {
  120. assert(field != nullptr);
  121. std::string typeName;
  122. std::string namespaceQtProtoDefinition("QtProtobuf::");
  123. std::string namespaceTypeName;
  124. std::vector<std::string> typeNamespace;
  125. if (field->type() == FieldDescriptor::TYPE_MESSAGE) {
  126. const Descriptor *msg = field->message_type();
  127. namespaceTypeName = getNamespacesList(msg, typeNamespace, mNamespacesColonDelimited);
  128. typeName = namespaceTypeName.append(utils::upperCaseName(msg->name()));
  129. if (field->is_map()) {
  130. return mClassName + "::" + utils::upperCaseName(msg->name());
  131. }
  132. if (field->is_repeated()) {
  133. return namespaceTypeName.append(Templates::ListSuffix);
  134. }
  135. } else if (field->type() == FieldDescriptor::TYPE_ENUM) {
  136. const EnumDescriptor *enumType = field->enum_type();
  137. namespaceTypeName = getNamespacesList(enumType, typeNamespace, mNamespacesColonDelimited);
  138. EnumVisibility visibility = getEnumVisibility(field, messageFor);
  139. if (visibility == LOCAL_ENUM) {
  140. if (field->is_repeated()) {
  141. typeName = typeName.append(mClassName + "::" + enumType->name());
  142. } else {
  143. //Note: For local enum classes it's impossible to use class name space in Q_PROPERTY
  144. //declaration. So please avoid addition of mClassName in line bellow
  145. typeName = typeName.append(enumType->name());
  146. }
  147. } else if (visibility == GLOBAL_ENUM) {
  148. namespaceTypeName = getNamespacesList(enumType, typeNamespace, "");
  149. typeName = namespaceTypeName.append(enumType->name() + Templates::EnumClassSuffix)
  150. .append("::").append(enumType->name());
  151. } else {
  152. typeName = namespaceTypeName.append(enumType->name());
  153. }
  154. if (field->is_repeated()) {
  155. return typeName.append(Templates::ListSuffix);
  156. }
  157. } else {
  158. auto it = Templates::TypeReflection.find(field->type());
  159. if (it != std::end(Templates::TypeReflection)) {
  160. if (field->type() != FieldDescriptor::TYPE_STRING
  161. && field->type() != FieldDescriptor::TYPE_BYTES
  162. && field->type() != FieldDescriptor::TYPE_BOOL
  163. && field->type() != FieldDescriptor::TYPE_FLOAT
  164. && field->type() != FieldDescriptor::TYPE_DOUBLE) {
  165. typeName = typeName.append(namespaceQtProtoDefinition.append(it->second));
  166. } else {
  167. typeName = typeName.append(it->second);
  168. }
  169. if (field->is_repeated()) {
  170. if (field->type() == FieldDescriptor::TYPE_FLOAT
  171. || field->type() == FieldDescriptor::TYPE_DOUBLE) {
  172. typeName[0] = static_cast<char>(::toupper(typeName[0]));
  173. typeName = namespaceQtProtoDefinition.append(typeName);
  174. }
  175. typeName.append("List");
  176. }
  177. }
  178. }
  179. return typeName;
  180. }
  181. std::string ClassGeneratorBase::getQmlAliasTypeName(const ::google::protobuf::FieldDescriptor *field, const ::google::protobuf::Descriptor *messageFor)
  182. {
  183. if (!field->is_repeated() && !field->is_map()) {
  184. switch (field->type()) {
  185. case FieldDescriptor::TYPE_INT32:
  186. case FieldDescriptor::TYPE_SFIXED32:
  187. return "int";
  188. case FieldDescriptor::TYPE_FIXED32:
  189. return "unsigned int";
  190. default:
  191. break;//Do nothing
  192. }
  193. }
  194. return getTypeName(field, messageFor);
  195. }
  196. template<typename T>
  197. std::string ClassGeneratorBase::getNamespacesList(const T *message, std::vector<std::string> &container, const std::string &localNamespace)
  198. {
  199. std::string result;
  200. container = utils::split(std::string(message->full_name()), '.');
  201. if (container.size() > 1) {
  202. //delete type name -> only namespace stays
  203. container.pop_back();
  204. for (size_t i = 0; i < container.size(); i++) {
  205. if (i > 0) {
  206. result = result.append("::");
  207. }
  208. result = result.append(container[i]);
  209. }
  210. }
  211. if (!container.empty()
  212. && localNamespace != result) {
  213. result = result.append("::");
  214. } else {
  215. result.clear();
  216. }
  217. return result;
  218. }
  219. ClassGeneratorBase::EnumVisibility ClassGeneratorBase::getEnumVisibility(const FieldDescriptor *field, const Descriptor *messageFor)
  220. {
  221. assert(field->enum_type() != nullptr);
  222. if (isLocalMessageEnum(messageFor, field)) {
  223. return LOCAL_ENUM;
  224. }
  225. const EnumDescriptor *enumType = field->enum_type();
  226. const FileDescriptor *enumFile = field->enum_type()->file();
  227. for (int i = 0; i < enumFile->message_type_count(); i++) {
  228. const Descriptor *msg = enumFile->message_type(i);
  229. for (int j = 0; j < msg->enum_type_count(); j++) {
  230. if (enumType->full_name() == msg->enum_type(j)->full_name()) {
  231. return NEIGHBOUR_ENUM;
  232. }
  233. }
  234. }
  235. return GLOBAL_ENUM;
  236. }
  237. void ClassGeneratorBase::getMethodParameters(const MethodDescriptor *method, std::map<std::string, std::string> &parameters)
  238. {
  239. std::string inputTypeName = method->input_type()->full_name();
  240. std::string outputTypeName = method->output_type()->full_name();
  241. std::string methodName = method->name();
  242. std::string methodNameUpper = method->name();
  243. methodNameUpper[0] = static_cast<char>(::toupper(methodNameUpper[0]));
  244. utils::replace(inputTypeName, ".", "::");
  245. utils::replace(outputTypeName, ".", "::");
  246. parameters = {{"classname", mClassName},
  247. {"return_type", outputTypeName},
  248. {"method_name", methodName},
  249. {"method_name_upper", methodNameUpper},
  250. {"param_type", inputTypeName},
  251. {"param_name", "arg"},
  252. {"return_name", "ret"}
  253. };
  254. }
  255. bool ClassGeneratorBase::hasGlobalEnum(const std::list<const FileDescriptor *> &list)
  256. {
  257. for (auto file : list) {
  258. if (file->enum_type_count() <= 0) {
  259. return false;
  260. }
  261. }
  262. return true;
  263. }
  264. void ClassGeneratorBase::printField(const google::protobuf::Descriptor *message, const FieldDescriptor *field, const char *fieldTemplate)
  265. {
  266. assert(field != nullptr);
  267. std::map<std::string, std::string> propertyMap;
  268. if (producePropertyMap(message, field, propertyMap)) {
  269. mPrinter->Print(propertyMap, fieldTemplate);
  270. }
  271. }
  272. bool ClassGeneratorBase::producePropertyMap(const google::protobuf::Descriptor *message, const FieldDescriptor *field, PropertyMap &propertyMap)
  273. {
  274. assert(field != nullptr);
  275. std::string scriptable = "true";
  276. std::string typeName = getTypeName(field, message);
  277. std::string qmlAliasTypeName = getQmlAliasTypeName(field, message);
  278. std::string getterType = typeName;
  279. if (typeName.size() <= 0) {
  280. std::cerr << "Type "
  281. << field->type_name()
  282. << " is not supported by Qt Generator"
  283. " please look at https://doc.qt.io/qt-5/qtqml-typesystem-basictypes.html"
  284. " for details" << std::endl;
  285. return false;
  286. }
  287. std::string typeNameNoList = typeName;
  288. if (field->is_repeated() && !field->is_map()) {
  289. if(field->type() == FieldDescriptor::TYPE_MESSAGE
  290. || field->type() == FieldDescriptor::TYPE_ENUM) {
  291. typeNameNoList.resize(typeNameNoList.size() - strlen(Templates::ListSuffix));
  292. } else {
  293. typeNameNoList.resize(typeNameNoList.size() - strlen("List"));
  294. }
  295. }
  296. if (!field->is_map() && !field->is_repeated() && (field->type() == FieldDescriptor::TYPE_INT64
  297. || field->type() == FieldDescriptor::TYPE_SINT64
  298. || field->type() == FieldDescriptor::TYPE_FIXED64
  299. || field->type() == FieldDescriptor::TYPE_SFIXED64)) {
  300. scriptable = "false";
  301. }
  302. if (field->type() == FieldDescriptor::TYPE_INT32
  303. || field->type() == FieldDescriptor::TYPE_FIXED32
  304. || field->type() == FieldDescriptor::TYPE_SFIXED32
  305. || field->type() == FieldDescriptor::TYPE_INT64
  306. || field->type() == FieldDescriptor::TYPE_FIXED64
  307. || field->type() == FieldDescriptor::TYPE_SFIXED64) {
  308. getterType = "const " + getterType;
  309. }
  310. std::string fieldName = utils::lowerCaseName(field->camelcase_name());
  311. fieldName = qualifiedName(fieldName);
  312. std::string capProperty = fieldName;
  313. capProperty[0] = static_cast<char>(::toupper(capProperty[0]));
  314. propertyMap = {{"type", typeName},
  315. {"classname", utils::upperCaseName(message->name())},
  316. {"property_name", fieldName},
  317. {"property_name_cap", capProperty},
  318. {"type_nolist", typeNameNoList},
  319. {"qml_alias_type", qmlAliasTypeName},
  320. {"scriptable", scriptable},
  321. {"getter_type", getterType}
  322. };
  323. return true;
  324. }
  325. bool ClassGeneratorBase::isComplexType(const FieldDescriptor *field)
  326. {
  327. assert(field != nullptr);
  328. return field->type() == FieldDescriptor::TYPE_MESSAGE
  329. || field->type() == FieldDescriptor::TYPE_STRING
  330. || field->type() == FieldDescriptor::TYPE_BYTES;
  331. }
  332. std::string ClassGeneratorBase::qualifiedName(const std::string &name)
  333. {
  334. std::string fieldName(name);
  335. const std::vector<std::string> &searchExeptions = Templates::ListOfQmlExeptions;
  336. auto searchResult = std::find(searchExeptions.begin(), searchExeptions.end(), fieldName);
  337. if (searchResult != searchExeptions.end()) {
  338. return fieldName.append(Templates::ProtoSufix);
  339. }
  340. return fieldName;
  341. }
  342. void ClassGeneratorBase::printInclude(const google::protobuf::Descriptor *message, const FieldDescriptor *field, std::set<std::string> &existingIncludes)
  343. {
  344. assert(field != nullptr);
  345. std::string newInclude;
  346. const char *includeTemplate;
  347. switch (field->type()) {
  348. case FieldDescriptor::TYPE_MESSAGE:
  349. if ( field->is_map() ) {
  350. newInclude = "QMap";
  351. assert(field->message_type() != nullptr);
  352. assert(field->message_type()->field_count() == 2);
  353. printInclude(message, field->message_type()->field(0), existingIncludes);
  354. printInclude(message, field->message_type()->field(1), existingIncludes);
  355. includeTemplate = Templates::ExternalIncludeTemplate;
  356. } else {
  357. std::string outFileBasename = "";
  358. std::string fieldPackage = field->message_type()->file()->package();
  359. if (fieldPackage != message->file()->package()) {
  360. std::vector<std::string> packages = utils::split(fieldPackage, '.');
  361. for (auto package : packages) {
  362. outFileBasename += package + "/";
  363. }
  364. }
  365. std::string typeName = field->message_type()->name();
  366. utils::tolower(typeName);
  367. newInclude = outFileBasename + typeName;
  368. includeTemplate = Templates::InternalIncludeTemplate;
  369. }
  370. break;
  371. case FieldDescriptor::TYPE_BYTES:
  372. newInclude = "QByteArray";
  373. includeTemplate = Templates::ExternalIncludeTemplate;
  374. break;
  375. case FieldDescriptor::TYPE_STRING:
  376. newInclude = "QString";
  377. includeTemplate = Templates::ExternalIncludeTemplate;
  378. break;
  379. case FieldDescriptor::TYPE_ENUM: {
  380. EnumVisibility enumVisibily = getEnumVisibility(field, message);
  381. if (enumVisibily == GLOBAL_ENUM) {
  382. includeTemplate = Templates::GlobalEnumIncludeTemplate;
  383. } else if (enumVisibily == NEIGHBOUR_ENUM) {
  384. includeTemplate = Templates::InternalIncludeTemplate;
  385. std::string fullEnumName = field->enum_type()->full_name();
  386. std::vector<std::string> fullEnumNameParts = utils::split(fullEnumName, '.');
  387. std::string enumTypeOwner = fullEnumNameParts.at(fullEnumNameParts.size() - 2);
  388. utils::tolower(enumTypeOwner);
  389. newInclude = enumTypeOwner;
  390. } else {
  391. return;
  392. }
  393. }
  394. break;
  395. default:
  396. return;
  397. }
  398. if (existingIncludes.find(newInclude) == std::end(existingIncludes)) {
  399. mPrinter->Print({{"include", newInclude}}, includeTemplate);
  400. existingIncludes.insert(newInclude);
  401. }
  402. }