cmQtAutoMocUic.cxx 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmQtAutoMocUic.h"
  4. #include "cmAlgorithms.h"
  5. #include "cmCryptoHash.h"
  6. #include "cmGeneratedFileStream.h"
  7. #include "cmMakefile.h"
  8. #include "cmQtAutoGen.h"
  9. #include "cmStringAlgorithms.h"
  10. #include "cmSystemTools.h"
  11. #include "cm_memory.hxx"
  12. #include "cmake.h"
  13. #include "cmsys/FStream.hxx"
  14. #include <algorithm>
  15. #include <set>
  16. #include <utility>
  17. #if defined(__APPLE__)
  18. # include <unistd.h>
  19. #endif
  20. static constexpr std::size_t MocUnderscoreLength = 4; // Length of "moc_"
  21. static constexpr std::size_t UiUnderscoreLength = 3; // Length of "ui_"
  22. cmQtAutoMocUic::IncludeKeyT::IncludeKeyT(std::string const& key,
  23. std::size_t basePrefixLength)
  24. : Key(key)
  25. , Dir(SubDirPrefix(key))
  26. , Base(cmSystemTools::GetFilenameWithoutLastExtension(key))
  27. {
  28. if (basePrefixLength != 0) {
  29. Base = Base.substr(basePrefixLength);
  30. }
  31. }
  32. void cmQtAutoMocUic::ParseCacheT::FileT::Clear()
  33. {
  34. Moc.Macro.clear();
  35. Moc.Include.Underscore.clear();
  36. Moc.Include.Dot.clear();
  37. Moc.Depends.clear();
  38. Uic.Include.clear();
  39. Uic.Depends.clear();
  40. }
  41. cmQtAutoMocUic::ParseCacheT::FileHandleT cmQtAutoMocUic::ParseCacheT::Get(
  42. std::string const& fileName) const
  43. {
  44. auto it = Map_.find(fileName);
  45. if (it != Map_.end()) {
  46. return it->second;
  47. }
  48. return FileHandleT();
  49. }
  50. cmQtAutoMocUic::ParseCacheT::GetOrInsertT
  51. cmQtAutoMocUic::ParseCacheT::GetOrInsert(std::string const& fileName)
  52. {
  53. // Find existing entry
  54. {
  55. auto it = Map_.find(fileName);
  56. if (it != Map_.end()) {
  57. return GetOrInsertT{ it->second, false };
  58. }
  59. }
  60. // Insert new entry
  61. return GetOrInsertT{
  62. Map_.emplace(fileName, std::make_shared<FileT>()).first->second, true
  63. };
  64. }
  65. cmQtAutoMocUic::ParseCacheT::ParseCacheT() = default;
  66. cmQtAutoMocUic::ParseCacheT::~ParseCacheT() = default;
  67. void cmQtAutoMocUic::ParseCacheT::Clear()
  68. {
  69. Map_.clear();
  70. }
  71. bool cmQtAutoMocUic::ParseCacheT::ReadFromFile(std::string const& fileName)
  72. {
  73. cmsys::ifstream fin(fileName.c_str());
  74. if (!fin) {
  75. return false;
  76. }
  77. FileHandleT fileHandle;
  78. std::string line;
  79. while (std::getline(fin, line)) {
  80. // Check if this an empty or a comment line
  81. if (line.empty() || line.front() == '#') {
  82. continue;
  83. }
  84. // Drop carriage return character at the end
  85. if (line.back() == '\r') {
  86. line.pop_back();
  87. if (line.empty()) {
  88. continue;
  89. }
  90. }
  91. // Check if this a file name line
  92. if (line.front() != ' ') {
  93. fileHandle = GetOrInsert(line).first;
  94. continue;
  95. }
  96. // Bad line or bad file handle
  97. if (!fileHandle || (line.size() < 6)) {
  98. continue;
  99. }
  100. constexpr std::size_t offset = 5;
  101. if (cmHasLiteralPrefix(line, " mmc:")) {
  102. fileHandle->Moc.Macro = line.substr(offset);
  103. continue;
  104. }
  105. if (cmHasLiteralPrefix(line, " miu:")) {
  106. fileHandle->Moc.Include.Underscore.emplace_back(line.substr(offset),
  107. MocUnderscoreLength);
  108. continue;
  109. }
  110. if (cmHasLiteralPrefix(line, " mid:")) {
  111. fileHandle->Moc.Include.Dot.emplace_back(line.substr(offset), 0);
  112. continue;
  113. }
  114. if (cmHasLiteralPrefix(line, " mdp:")) {
  115. fileHandle->Moc.Depends.emplace_back(line.substr(offset));
  116. continue;
  117. }
  118. if (cmHasLiteralPrefix(line, " uic:")) {
  119. fileHandle->Uic.Include.emplace_back(line.substr(offset),
  120. UiUnderscoreLength);
  121. continue;
  122. }
  123. if (cmHasLiteralPrefix(line, " udp:")) {
  124. fileHandle->Uic.Depends.emplace_back(line.substr(offset));
  125. continue;
  126. }
  127. }
  128. return true;
  129. }
  130. bool cmQtAutoMocUic::ParseCacheT::WriteToFile(std::string const& fileName)
  131. {
  132. cmGeneratedFileStream ofs(fileName);
  133. if (!ofs) {
  134. return false;
  135. }
  136. ofs << "# Generated by CMake. Changes will be overwritten." << std::endl;
  137. for (auto const& pair : Map_) {
  138. ofs << pair.first << std::endl;
  139. FileT const& file = *pair.second;
  140. if (!file.Moc.Macro.empty()) {
  141. ofs << " mmc:" << file.Moc.Macro << std::endl;
  142. }
  143. for (IncludeKeyT const& item : file.Moc.Include.Underscore) {
  144. ofs << " miu:" << item.Key << std::endl;
  145. }
  146. for (IncludeKeyT const& item : file.Moc.Include.Dot) {
  147. ofs << " mid:" << item.Key << std::endl;
  148. }
  149. for (std::string const& item : file.Moc.Depends) {
  150. ofs << " mdp:" << item << std::endl;
  151. }
  152. for (IncludeKeyT const& item : file.Uic.Include) {
  153. ofs << " uic:" << item.Key << std::endl;
  154. }
  155. for (std::string const& item : file.Uic.Depends) {
  156. ofs << " udp:" << item << std::endl;
  157. }
  158. }
  159. return ofs.Close();
  160. }
  161. cmQtAutoMocUic::BaseSettingsT::BaseSettingsT() = default;
  162. cmQtAutoMocUic::BaseSettingsT::~BaseSettingsT() = default;
  163. cmQtAutoMocUic::MocSettingsT::MocSettingsT()
  164. {
  165. RegExpInclude.compile(
  166. "(^|\n)[ \t]*#[ \t]*include[ \t]+"
  167. "[\"<](([^ \">]+/)?moc_[^ \">/]+\\.cpp|[^ \">]+\\.moc)[\">]");
  168. }
  169. cmQtAutoMocUic::MocSettingsT::~MocSettingsT() = default;
  170. bool cmQtAutoMocUic::MocSettingsT::skipped(std::string const& fileName) const
  171. {
  172. return (!Enabled || (SkipList.find(fileName) != SkipList.end()));
  173. }
  174. std::string cmQtAutoMocUic::MocSettingsT::MacrosString() const
  175. {
  176. std::string res;
  177. const auto itB = MacroFilters.cbegin();
  178. const auto itE = MacroFilters.cend();
  179. const auto itL = itE - 1;
  180. auto itC = itB;
  181. for (; itC != itE; ++itC) {
  182. // Separator
  183. if (itC != itB) {
  184. if (itC != itL) {
  185. res += ", ";
  186. } else {
  187. res += " or ";
  188. }
  189. }
  190. // Key
  191. res += itC->Key;
  192. }
  193. return res;
  194. }
  195. cmQtAutoMocUic::UicSettingsT::UicSettingsT()
  196. {
  197. RegExpInclude.compile("(^|\n)[ \t]*#[ \t]*include[ \t]+"
  198. "[\"<](([^ \">]+/)?ui_[^ \">/]+\\.h)[\">]");
  199. }
  200. cmQtAutoMocUic::UicSettingsT::~UicSettingsT() = default;
  201. bool cmQtAutoMocUic::UicSettingsT::skipped(std::string const& fileName) const
  202. {
  203. return (!Enabled || (SkipList.find(fileName) != SkipList.end()));
  204. }
  205. void cmQtAutoMocUic::JobT::LogError(GenT genType,
  206. cm::string_view message) const
  207. {
  208. Gen()->AbortError();
  209. Gen()->Log().Error(genType, message);
  210. }
  211. void cmQtAutoMocUic::JobT::LogCommandError(
  212. GenT genType, cm::string_view message,
  213. std::vector<std::string> const& command, std::string const& output) const
  214. {
  215. Gen()->AbortError();
  216. Gen()->Log().ErrorCommand(genType, message, command, output);
  217. }
  218. bool cmQtAutoMocUic::JobT::RunProcess(GenT genType,
  219. cmWorkerPool::ProcessResultT& result,
  220. std::vector<std::string> const& command,
  221. std::string* infoMessage)
  222. {
  223. // Log command
  224. if (Log().Verbose()) {
  225. cm::string_view info;
  226. if (infoMessage != nullptr) {
  227. info = *infoMessage;
  228. }
  229. Log().Info(genType,
  230. cmStrCat(info,
  231. info.empty() || cmHasSuffix(info, '\n') ? "" : "\n",
  232. QuotedCommand(command), '\n'));
  233. }
  234. // Run command
  235. return cmWorkerPool::JobT::RunProcess(result, command,
  236. BaseConst().AutogenBuildDir);
  237. }
  238. void cmQtAutoMocUic::JobMocPredefsT::Process()
  239. {
  240. // (Re)generate moc_predefs.h on demand
  241. std::unique_ptr<std::string> reason;
  242. if (Log().Verbose()) {
  243. reason = cm::make_unique<std::string>();
  244. }
  245. if (!Update(reason.get())) {
  246. return;
  247. }
  248. std::string const& predefsFileAbs = MocConst().PredefsFileAbs;
  249. {
  250. cmWorkerPool::ProcessResultT result;
  251. {
  252. // Compose command
  253. std::vector<std::string> cmd = MocConst().PredefsCmd;
  254. // Add definitions
  255. cmAppend(cmd, MocConst().OptionsDefinitions);
  256. // Add includes
  257. cmAppend(cmd, MocConst().OptionsIncludes);
  258. // Execute command
  259. if (!RunProcess(GenT::MOC, result, cmd, reason.get())) {
  260. LogCommandError(GenT::MOC,
  261. cmStrCat("The content generation command for ",
  262. MessagePath(predefsFileAbs), " failed.\n",
  263. result.ErrorMessage),
  264. cmd, result.StdOut);
  265. return;
  266. }
  267. }
  268. // (Re)write predefs file only on demand
  269. if (cmQtAutoGenerator::FileDiffers(predefsFileAbs, result.StdOut)) {
  270. if (!cmQtAutoGenerator::FileWrite(predefsFileAbs, result.StdOut)) {
  271. LogError(
  272. GenT::MOC,
  273. cmStrCat("Writing ", MessagePath(predefsFileAbs), " failed."));
  274. return;
  275. }
  276. } else {
  277. // Touch to update the time stamp
  278. if (Log().Verbose()) {
  279. Log().Info(GenT::MOC, "Touching " + MessagePath(predefsFileAbs));
  280. }
  281. if (!cmSystemTools::Touch(predefsFileAbs, false)) {
  282. LogError(
  283. GenT::MOC,
  284. cmStrCat("Touching ", MessagePath(predefsFileAbs), " failed."));
  285. return;
  286. }
  287. }
  288. }
  289. // Read file time afterwards
  290. if (!MocEval().PredefsTime.Load(predefsFileAbs)) {
  291. LogError(GenT::MOC,
  292. cmStrCat("Reading the file time of ", MessagePath(predefsFileAbs),
  293. " failed."));
  294. return;
  295. }
  296. }
  297. bool cmQtAutoMocUic::JobMocPredefsT::Update(std::string* reason) const
  298. {
  299. // Test if the file exists
  300. if (!MocEval().PredefsTime.Load(MocConst().PredefsFileAbs)) {
  301. if (reason != nullptr) {
  302. *reason = cmStrCat("Generating ", MessagePath(MocConst().PredefsFileAbs),
  303. ", because it doesn't exist.");
  304. }
  305. return true;
  306. }
  307. // Test if the settings changed
  308. if (MocConst().SettingsChanged) {
  309. if (reason != nullptr) {
  310. *reason = cmStrCat("Generating ", MessagePath(MocConst().PredefsFileAbs),
  311. ", because the moc settings changed.");
  312. }
  313. return true;
  314. }
  315. // Test if the executable is newer
  316. {
  317. std::string const& exec = MocConst().PredefsCmd.at(0);
  318. cmFileTime execTime;
  319. if (execTime.Load(exec)) {
  320. if (MocEval().PredefsTime.Older(execTime)) {
  321. if (reason != nullptr) {
  322. *reason =
  323. cmStrCat("Generating ", MessagePath(MocConst().PredefsFileAbs),
  324. " because it is older than ", MessagePath(exec), '.');
  325. }
  326. return true;
  327. }
  328. }
  329. }
  330. return false;
  331. }
  332. bool cmQtAutoMocUic::JobParseT::ReadFile()
  333. {
  334. // Clear old parse information
  335. FileHandle->ParseData->Clear();
  336. std::string const& fileName = FileHandle->FileName;
  337. // Write info
  338. if (Log().Verbose()) {
  339. Log().Info(GenT::GEN, cmStrCat("Parsing ", MessagePath(fileName)));
  340. }
  341. // Read file content
  342. {
  343. std::string error;
  344. if (!cmQtAutoGenerator::FileRead(Content, fileName, &error)) {
  345. LogError(
  346. GenT::GEN,
  347. cmStrCat("Could not read ", MessagePath(fileName), ".\n", error));
  348. return false;
  349. }
  350. }
  351. // Warn if empty
  352. if (Content.empty()) {
  353. Log().Warning(GenT::GEN, cmStrCat(MessagePath(fileName), " is empty."));
  354. return false;
  355. }
  356. return true;
  357. }
  358. void cmQtAutoMocUic::JobParseT::CreateKeys(std::vector<IncludeKeyT>& container,
  359. std::set<std::string> const& source,
  360. std::size_t basePrefixLength)
  361. {
  362. if (source.empty()) {
  363. return;
  364. }
  365. container.reserve(source.size());
  366. for (std::string const& src : source) {
  367. container.emplace_back(src, basePrefixLength);
  368. }
  369. }
  370. void cmQtAutoMocUic::JobParseT::MocMacro()
  371. {
  372. for (KeyExpT const& filter : MocConst().MacroFilters) {
  373. // Run a simple find string check
  374. if (Content.find(filter.Key) == std::string::npos) {
  375. continue;
  376. }
  377. // Run the expensive regular expression check loop
  378. cmsys::RegularExpressionMatch match;
  379. if (filter.Exp.find(Content.c_str(), match)) {
  380. // Keep detected macro name
  381. FileHandle->ParseData->Moc.Macro = filter.Key;
  382. return;
  383. }
  384. }
  385. }
  386. void cmQtAutoMocUic::JobParseT::MocDependecies()
  387. {
  388. if (MocConst().DependFilters.empty()) {
  389. return;
  390. }
  391. // Find dependency strings
  392. std::set<std::string> parseDepends;
  393. for (KeyExpT const& filter : MocConst().DependFilters) {
  394. // Run a simple find string check
  395. if (Content.find(filter.Key) == std::string::npos) {
  396. continue;
  397. }
  398. // Run the expensive regular expression check loop
  399. const char* contentChars = Content.c_str();
  400. cmsys::RegularExpressionMatch match;
  401. while (filter.Exp.find(contentChars, match)) {
  402. {
  403. std::string dep = match.match(1);
  404. if (!dep.empty()) {
  405. parseDepends.emplace(std::move(dep));
  406. }
  407. }
  408. contentChars += match.end();
  409. }
  410. }
  411. // Store dependency strings
  412. {
  413. auto& Depends = FileHandle->ParseData->Moc.Depends;
  414. Depends.reserve(parseDepends.size());
  415. for (std::string const& item : parseDepends) {
  416. Depends.emplace_back(item);
  417. // Replace end of line characters in filenames
  418. std::string& path = Depends.back();
  419. std::replace(path.begin(), path.end(), '\n', ' ');
  420. std::replace(path.begin(), path.end(), '\r', ' ');
  421. }
  422. }
  423. }
  424. void cmQtAutoMocUic::JobParseT::MocIncludes()
  425. {
  426. if (Content.find("moc") == std::string::npos) {
  427. return;
  428. }
  429. std::set<std::string> underscore;
  430. std::set<std::string> dot;
  431. {
  432. const char* contentChars = Content.c_str();
  433. cmsys::RegularExpression const& regExp = MocConst().RegExpInclude;
  434. cmsys::RegularExpressionMatch match;
  435. while (regExp.find(contentChars, match)) {
  436. std::string incString = match.match(2);
  437. std::string const incBase =
  438. cmSystemTools::GetFilenameWithoutLastExtension(incString);
  439. if (cmHasLiteralPrefix(incBase, "moc_")) {
  440. // moc_<BASE>.cpp
  441. // Remove the moc_ part from the base name
  442. underscore.emplace(std::move(incString));
  443. } else {
  444. // <BASE>.moc
  445. dot.emplace(std::move(incString));
  446. }
  447. // Forward content pointer
  448. contentChars += match.end();
  449. }
  450. }
  451. auto& Include = FileHandle->ParseData->Moc.Include;
  452. CreateKeys(Include.Underscore, underscore, MocUnderscoreLength);
  453. CreateKeys(Include.Dot, dot, 0);
  454. }
  455. void cmQtAutoMocUic::JobParseT::UicIncludes()
  456. {
  457. if (Content.find("ui_") == std::string::npos) {
  458. return;
  459. }
  460. std::set<std::string> includes;
  461. {
  462. const char* contentChars = Content.c_str();
  463. cmsys::RegularExpression const& regExp = UicConst().RegExpInclude;
  464. cmsys::RegularExpressionMatch match;
  465. while (regExp.find(contentChars, match)) {
  466. includes.emplace(match.match(2));
  467. // Forward content pointer
  468. contentChars += match.end();
  469. }
  470. }
  471. CreateKeys(FileHandle->ParseData->Uic.Include, includes, UiUnderscoreLength);
  472. }
  473. void cmQtAutoMocUic::JobParseHeaderT::Process()
  474. {
  475. if (!ReadFile()) {
  476. return;
  477. }
  478. // Moc parsing
  479. if (FileHandle->Moc) {
  480. MocMacro();
  481. MocDependecies();
  482. }
  483. // Uic parsing
  484. if (FileHandle->Uic) {
  485. UicIncludes();
  486. }
  487. }
  488. void cmQtAutoMocUic::JobParseSourceT::Process()
  489. {
  490. if (!ReadFile()) {
  491. return;
  492. }
  493. // Moc parsing
  494. if (FileHandle->Moc) {
  495. MocMacro();
  496. MocDependecies();
  497. MocIncludes();
  498. }
  499. // Uic parsing
  500. if (FileHandle->Uic) {
  501. UicIncludes();
  502. }
  503. }
  504. std::string cmQtAutoMocUic::JobEvalCacheT::MessageSearchLocations() const
  505. {
  506. std::string res;
  507. res.reserve(512);
  508. for (std::string const& path : SearchLocations) {
  509. res += " ";
  510. res += MessagePath(path);
  511. res += '\n';
  512. }
  513. return res;
  514. }
  515. void cmQtAutoMocUic::JobEvalCacheMocT::Process()
  516. {
  517. // Evaluate headers
  518. for (auto const& pair : BaseEval().Headers) {
  519. if (!EvalHeader(pair.second)) {
  520. return;
  521. }
  522. }
  523. // Evaluate sources
  524. for (auto const& pair : BaseEval().Sources) {
  525. if (!EvalSource(pair.second)) {
  526. return;
  527. }
  528. }
  529. }
  530. bool cmQtAutoMocUic::JobEvalCacheMocT::EvalHeader(SourceFileHandleT source)
  531. {
  532. SourceFileT const& sourceFile = *source;
  533. auto const& parseData = sourceFile.ParseData->Moc;
  534. if (!source->Moc) {
  535. return true;
  536. }
  537. if (!parseData.Macro.empty()) {
  538. // Create a new mapping
  539. MappingHandleT handle = std::make_shared<MappingT>();
  540. handle->SourceFile = std::move(source);
  541. // Absolute build path
  542. if (BaseConst().MultiConfig) {
  543. handle->OutputFile = Gen()->AbsoluteIncludePath(sourceFile.BuildPath);
  544. } else {
  545. handle->OutputFile = Gen()->AbsoluteBuildPath(sourceFile.BuildPath);
  546. }
  547. // Register mapping in headers map
  548. RegisterMapping(handle);
  549. }
  550. return true;
  551. }
  552. bool cmQtAutoMocUic::JobEvalCacheMocT::EvalSource(
  553. SourceFileHandleT const& source)
  554. {
  555. SourceFileT const& sourceFile = *source;
  556. auto const& parseData = sourceFile.ParseData->Moc;
  557. if (!sourceFile.Moc ||
  558. (parseData.Macro.empty() && parseData.Include.Underscore.empty() &&
  559. parseData.Include.Dot.empty())) {
  560. return true;
  561. }
  562. std::string const sourceDirPrefix = SubDirPrefix(sourceFile.FileName);
  563. std::string const sourceBase =
  564. cmSystemTools::GetFilenameWithoutLastExtension(sourceFile.FileName);
  565. // For relaxed mode check if the own "moc_" or ".moc" file is included
  566. bool const relaxedMode = MocConst().RelaxedMode;
  567. bool sourceIncludesMocUnderscore = false;
  568. bool sourceIncludesDotMoc = false;
  569. // Check if the sources own "moc_" or ".moc" file is included
  570. if (relaxedMode) {
  571. for (IncludeKeyT const& incKey : parseData.Include.Underscore) {
  572. if (incKey.Base == sourceBase) {
  573. sourceIncludesMocUnderscore = true;
  574. break;
  575. }
  576. }
  577. }
  578. for (IncludeKeyT const& incKey : parseData.Include.Dot) {
  579. if (incKey.Base == sourceBase) {
  580. sourceIncludesDotMoc = true;
  581. break;
  582. }
  583. }
  584. // Check if this source needs to be moc processed but doesn't.
  585. if (!sourceIncludesDotMoc && !parseData.Macro.empty() &&
  586. !(relaxedMode && sourceIncludesMocUnderscore)) {
  587. LogError(GenT::MOC,
  588. cmStrCat(MessagePath(sourceFile.FileName), "\ncontains a ",
  589. Quoted(parseData.Macro), " macro, but does not include ",
  590. MessagePath(sourceBase + ".moc"),
  591. "!\nConsider to\n - add #include \"", sourceBase,
  592. ".moc\"\n - enable SKIP_AUTOMOC for this file"));
  593. return false;
  594. }
  595. // Evaluate "moc_" includes
  596. for (IncludeKeyT const& incKey : parseData.Include.Underscore) {
  597. SourceFileHandleT headerHandle;
  598. {
  599. std::string const headerBase = cmStrCat(incKey.Dir, incKey.Base);
  600. if (!FindIncludedHeader(headerHandle, sourceDirPrefix, headerBase)) {
  601. LogError(GenT::MOC,
  602. cmStrCat(MessagePath(sourceFile.FileName),
  603. "\nincludes the moc file ", MessagePath(incKey.Key),
  604. ",\nbut a header ", MessageHeader(headerBase),
  605. "\ncould not be found "
  606. "in the following directories\n",
  607. MessageSearchLocations()));
  608. return false;
  609. }
  610. }
  611. // The include might be handled differently in relaxed mode
  612. if (relaxedMode && !sourceIncludesDotMoc && !parseData.Macro.empty() &&
  613. (incKey.Base == sourceBase)) {
  614. // The <BASE>.cpp file includes a Qt macro but does not include the
  615. // <BASE>.moc file. In this case, the moc_<BASE>.cpp should probably
  616. // be generated from <BASE>.cpp instead of <BASE>.h, because otherwise
  617. // it won't build. But warn, since this is not how it is supposed to be
  618. // used. This is for KDE4 compatibility.
  619. // Issue a warning
  620. Log().Warning(
  621. GenT::MOC,
  622. cmStrCat(MessagePath(sourceFile.FileName), "\ncontains a ",
  623. Quoted(parseData.Macro), " macro, but does not include ",
  624. MessagePath(sourceBase + ".moc"), ".\nInstead it includes ",
  625. MessagePath(incKey.Key), ".\nRunning moc on the source\n ",
  626. MessagePath(sourceFile.FileName), "!\nBetter include ",
  627. MessagePath(sourceBase + ".moc"),
  628. " for compatibility with regular mode.\n",
  629. "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n"));
  630. // Create mapping
  631. if (!RegisterIncluded(incKey.Key, source, source)) {
  632. return false;
  633. }
  634. continue;
  635. }
  636. // Check if header is skipped
  637. if (MocConst().skipped(headerHandle->FileName)) {
  638. continue;
  639. }
  640. // Create mapping
  641. if (!RegisterIncluded(incKey.Key, source, std::move(headerHandle))) {
  642. return false;
  643. }
  644. }
  645. // Evaluate ".moc" includes
  646. if (relaxedMode) {
  647. // Relaxed mode
  648. for (IncludeKeyT const& incKey : parseData.Include.Dot) {
  649. // Check if this is the sources own .moc file
  650. bool const ownMoc = (incKey.Base == sourceBase);
  651. if (ownMoc && !parseData.Macro.empty()) {
  652. // Create mapping for the regular use case
  653. if (!RegisterIncluded(incKey.Key, source, source)) {
  654. return false;
  655. }
  656. continue;
  657. }
  658. // Try to find a header instead but issue a warning.
  659. // This is for KDE4 compatibility.
  660. SourceFileHandleT headerHandle;
  661. {
  662. std::string const headerBase = cmStrCat(incKey.Dir, incKey.Base);
  663. if (!FindIncludedHeader(headerHandle, sourceDirPrefix, headerBase)) {
  664. LogError(
  665. GenT::MOC,
  666. cmStrCat(
  667. MessagePath(sourceFile.FileName), "\nincludes the moc file ",
  668. MessagePath(incKey.Key),
  669. ",\nwhich seems to be the moc file from a different source "
  670. "file.\nCMAKE_AUTOMOC_RELAXED_MODE:\nAlso a matching header ",
  671. MessageHeader(headerBase),
  672. "\ncould not be found in the following directories\n",
  673. MessageSearchLocations()));
  674. return false;
  675. }
  676. }
  677. // Check if header is skipped
  678. if (MocConst().skipped(headerHandle->FileName)) {
  679. continue;
  680. }
  681. // Issue a warning
  682. if (ownMoc && parseData.Macro.empty()) {
  683. Log().Warning(
  684. GenT::MOC,
  685. cmStrCat(MessagePath(sourceFile.FileName),
  686. "\nincludes the moc file ", MessagePath(incKey.Key),
  687. ", but does not contain a\n", MocConst().MacrosString(),
  688. " macro.\nRunning moc on the header\n ",
  689. MessagePath(headerHandle->FileName), "!\nBetter include ",
  690. MessagePath("moc_" + incKey.Base + ".cpp"),
  691. " for a compatibility with regular mode.\n",
  692. "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n"));
  693. } else {
  694. Log().Warning(
  695. GenT::MOC,
  696. cmStrCat(MessagePath(sourceFile.FileName),
  697. "\nincludes the moc file ", MessagePath(incKey.Key),
  698. " instead of ", MessagePath("moc_" + incKey.Base + ".cpp"),
  699. ".\nRunning moc on the header\n ",
  700. MessagePath(headerHandle->FileName), "!\nBetter include ",
  701. MessagePath("moc_" + incKey.Base + ".cpp"),
  702. " for compatibility with regular mode.\n",
  703. "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n"));
  704. }
  705. // Create mapping
  706. if (!RegisterIncluded(incKey.Key, source, std::move(headerHandle))) {
  707. return false;
  708. }
  709. }
  710. } else {
  711. // Strict mode
  712. for (IncludeKeyT const& incKey : parseData.Include.Dot) {
  713. // Check if this is the sources own .moc file
  714. bool const ownMoc = (incKey.Base == sourceBase);
  715. if (!ownMoc) {
  716. // Don't allow <BASE>.moc include other than own in regular mode
  717. LogError(GenT::MOC,
  718. cmStrCat(MessagePath(sourceFile.FileName),
  719. "\nincludes the moc file ", MessagePath(incKey.Key),
  720. ",\nwhich seems to be the moc file from a different "
  721. "source file.\nThis is not supported. Include ",
  722. MessagePath(sourceBase + ".moc"),
  723. " to run moc on this source file."));
  724. return false;
  725. }
  726. // Accept but issue a warning if moc isn't required
  727. if (parseData.Macro.empty()) {
  728. Log().Warning(GenT::MOC,
  729. cmStrCat(MessagePath(sourceFile.FileName),
  730. "\nincludes the moc file ",
  731. MessagePath(incKey.Key),
  732. ", but does not contain a ",
  733. MocConst().MacrosString(), " macro."));
  734. }
  735. // Create mapping
  736. if (!RegisterIncluded(incKey.Key, source, source)) {
  737. return false;
  738. }
  739. }
  740. }
  741. return true;
  742. }
  743. bool cmQtAutoMocUic::JobEvalCacheMocT::FindIncludedHeader(
  744. SourceFileHandleT& headerHandle, cm::string_view includerDir,
  745. cm::string_view includeBase)
  746. {
  747. // Clear search locations
  748. SearchLocations.clear();
  749. auto findHeader = [this,
  750. &headerHandle](std::string const& basePath) -> bool {
  751. bool found = false;
  752. std::string const baseCollapsed =
  753. this->Gen()->CollapseFullPathTS(cmStrCat(basePath, '.'));
  754. for (std::string const& ext : this->BaseConst().HeaderExtensions) {
  755. std::string const testPath = cmStrCat(baseCollapsed, ext);
  756. cmFileTime fileTime;
  757. if (!fileTime.Load(testPath)) {
  758. // File not found
  759. continue;
  760. }
  761. // Return a known file if it exists already
  762. {
  763. auto it = BaseEval().Headers.find(testPath);
  764. if (it != BaseEval().Headers.end()) {
  765. headerHandle = it->second;
  766. found = true;
  767. break;
  768. }
  769. }
  770. // Created and return discovered file entry
  771. {
  772. SourceFileHandleT& handle = MocEval().HeadersDiscovered[testPath];
  773. if (!handle) {
  774. handle = std::make_shared<SourceFileT>(testPath);
  775. handle->FileTime = fileTime;
  776. handle->IsHeader = true;
  777. handle->Moc = true;
  778. }
  779. headerHandle = handle;
  780. found = true;
  781. break;
  782. }
  783. }
  784. if (!found) {
  785. this->SearchLocations.emplace_back(
  786. cmQtAutoGen::ParentDir(baseCollapsed));
  787. }
  788. return found;
  789. };
  790. // Search in vicinity of the source
  791. if (findHeader(cmStrCat(includerDir, includeBase))) {
  792. return true;
  793. }
  794. // Search in include directories
  795. for (std::string const& path : MocConst().IncludePaths) {
  796. if (findHeader(cmStrCat(path, '/', includeBase))) {
  797. return true;
  798. }
  799. }
  800. // Return without success
  801. return false;
  802. }
  803. bool cmQtAutoMocUic::JobEvalCacheMocT::RegisterIncluded(
  804. std::string const& includeString, SourceFileHandleT includerFileHandle,
  805. SourceFileHandleT sourceFileHandle) const
  806. {
  807. // Check if this file is already included
  808. MappingHandleT& handle = MocEval().Includes[includeString];
  809. if (handle) {
  810. // Check if the output file would be generated from different source files
  811. if (handle->SourceFile != sourceFileHandle) {
  812. std::string files =
  813. cmStrCat(" ", MessagePath(includerFileHandle->FileName), '\n');
  814. for (auto const& item : handle->IncluderFiles) {
  815. files += cmStrCat(" ", MessagePath(item->FileName), '\n');
  816. }
  817. LogError(
  818. GenT::MOC,
  819. cmStrCat("The source files\n", files,
  820. "contain the same include string ",
  821. MessagePath(includeString),
  822. ", but\nthe moc file would be generated from different "
  823. "source files\n ",
  824. MessagePath(sourceFileHandle->FileName), " and\n ",
  825. MessagePath(handle->SourceFile->FileName),
  826. ".\nConsider to\n"
  827. " - not include the \"moc_<NAME>.cpp\" file\n"
  828. " - add a directory prefix to a \"<NAME>.moc\" include "
  829. "(e.g \"sub/<NAME>.moc\")\n"
  830. " - rename the source file(s)\n"));
  831. return false;
  832. }
  833. // The same mapping already exists. Just add to the includers list.
  834. handle->IncluderFiles.emplace_back(std::move(includerFileHandle));
  835. return true;
  836. }
  837. // Create a new mapping
  838. handle = std::make_shared<MappingT>();
  839. handle->IncludeString = includeString;
  840. handle->IncluderFiles.emplace_back(std::move(includerFileHandle));
  841. handle->SourceFile = std::move(sourceFileHandle);
  842. handle->OutputFile = Gen()->AbsoluteIncludePath(includeString);
  843. // Register mapping in sources/headers map
  844. RegisterMapping(handle);
  845. return true;
  846. }
  847. void cmQtAutoMocUic::JobEvalCacheMocT::RegisterMapping(
  848. MappingHandleT mappingHandle) const
  849. {
  850. auto& regMap = mappingHandle->SourceFile->IsHeader
  851. ? MocEval().HeaderMappings
  852. : MocEval().SourceMappings;
  853. // Check if source file already gets mapped
  854. auto& regHandle = regMap[mappingHandle->SourceFile->FileName];
  855. if (!regHandle) {
  856. // Yet unknown mapping
  857. regHandle = std::move(mappingHandle);
  858. } else {
  859. // Mappings with include string override those without
  860. if (!mappingHandle->IncludeString.empty()) {
  861. regHandle = std::move(mappingHandle);
  862. }
  863. }
  864. }
  865. std::string cmQtAutoMocUic::JobEvalCacheMocT::MessageHeader(
  866. cm::string_view headerBase) const
  867. {
  868. return MessagePath(cmStrCat(
  869. headerBase, ".{", cmJoin(this->BaseConst().HeaderExtensions, ","), '}'));
  870. }
  871. void cmQtAutoMocUic::JobEvalCacheUicT::Process()
  872. {
  873. // Prepare buffers
  874. SearchLocations.reserve((UicConst().SearchPaths.size() + 1) * 2);
  875. // Evaluate headers
  876. for (auto const& pair : BaseEval().Headers) {
  877. if (!EvalFile(pair.second)) {
  878. return;
  879. }
  880. }
  881. // Evaluate sources
  882. for (auto const& pair : BaseEval().Sources) {
  883. if (!EvalFile(pair.second)) {
  884. return;
  885. }
  886. }
  887. }
  888. bool cmQtAutoMocUic::JobEvalCacheUicT::EvalFile(
  889. SourceFileHandleT const& sourceFileHandle)
  890. {
  891. SourceFileT const& sourceFile = *sourceFileHandle;
  892. auto const& Include = sourceFile.ParseData->Uic.Include;
  893. if (!sourceFile.Uic || Include.empty()) {
  894. return true;
  895. }
  896. std::string const sourceDirPrefix = SubDirPrefix(sourceFile.FileName);
  897. for (IncludeKeyT const& incKey : Include) {
  898. // Find .ui file
  899. UiName = cmStrCat(incKey.Base, ".ui");
  900. if (!FindIncludedUi(sourceDirPrefix, incKey.Dir)) {
  901. LogError(GenT::UIC,
  902. cmStrCat(MessagePath(sourceFile.FileName),
  903. "\nincludes the uic file ", MessagePath(incKey.Key),
  904. ",\nbut the user interface file ", MessagePath(UiName),
  905. "\ncould not be found in the following directories\n",
  906. MessageSearchLocations()));
  907. return false;
  908. }
  909. // Check if the file is skipped
  910. if (UicConst().skipped(UiFileHandle->FileName)) {
  911. continue;
  912. }
  913. // Register mapping
  914. if (!RegisterMapping(incKey.Key, sourceFileHandle)) {
  915. return false;
  916. }
  917. }
  918. return true;
  919. }
  920. bool cmQtAutoMocUic::JobEvalCacheUicT::FindIncludedUi(
  921. cm::string_view sourceDirPrefix, cm::string_view includePrefix)
  922. {
  923. // Clear locations buffer
  924. SearchLocations.clear();
  925. auto findUi = [this](std::string const& testPath) -> bool {
  926. std::string const fullPath = this->Gen()->CollapseFullPathTS(testPath);
  927. cmFileTime fileTime;
  928. if (!fileTime.Load(fullPath)) {
  929. this->SearchLocations.emplace_back(cmQtAutoGen::ParentDir(fullPath));
  930. return false;
  931. }
  932. // .ui file found in files system!
  933. // Get or create .ui file handle
  934. SourceFileHandleT& handle = this->UicEval().UiFiles[fullPath];
  935. if (!handle) {
  936. // The file wasn't registered, yet
  937. handle = std::make_shared<SourceFileT>(fullPath);
  938. handle->FileTime = fileTime;
  939. }
  940. this->UiFileHandle = handle;
  941. return true;
  942. };
  943. // Vicinity of the source
  944. if (findUi(cmStrCat(sourceDirPrefix, UiName))) {
  945. return true;
  946. }
  947. if (!includePrefix.empty()) {
  948. if (findUi(cmStrCat(sourceDirPrefix, includePrefix, UiName))) {
  949. return true;
  950. }
  951. }
  952. // Additional AUTOUIC search paths
  953. auto const& searchPaths = UicConst().SearchPaths;
  954. if (!searchPaths.empty()) {
  955. for (std::string const& sPath : searchPaths) {
  956. if (findUi(cmStrCat(sPath, '/', UiName))) {
  957. return true;
  958. }
  959. }
  960. if (!includePrefix.empty()) {
  961. for (std::string const& sPath : searchPaths) {
  962. if (findUi(cmStrCat(sPath, '/', includePrefix, UiName))) {
  963. return true;
  964. }
  965. }
  966. }
  967. }
  968. return false;
  969. }
  970. bool cmQtAutoMocUic::JobEvalCacheUicT::RegisterMapping(
  971. std::string const& includeString, SourceFileHandleT includerFileHandle)
  972. {
  973. auto& Includes = Gen()->UicEval().Includes;
  974. auto it = Includes.find(includeString);
  975. if (it != Includes.end()) {
  976. MappingHandleT const& handle = it->second;
  977. if (handle->SourceFile != UiFileHandle) {
  978. // The output file already gets generated - from a different .ui file!
  979. std::string files =
  980. cmStrCat(" ", MessagePath(includerFileHandle->FileName), '\n');
  981. for (auto const& item : handle->IncluderFiles) {
  982. files += cmStrCat(" ", MessagePath(item->FileName), '\n');
  983. }
  984. LogError(
  985. GenT::UIC,
  986. cmStrCat(
  987. "The source files\n", files, "contain the same include string ",
  988. Quoted(includeString),
  989. ", but\nthe uic file would be generated from different "
  990. "user interface files\n ",
  991. MessagePath(UiFileHandle->FileName), " and\n ",
  992. MessagePath(handle->SourceFile->FileName),
  993. ".\nConsider to\n"
  994. " - add a directory prefix to a \"ui_<NAME>.h\" include "
  995. "(e.g \"sub/ui_<NAME>.h\")\n"
  996. " - rename the <NAME>.ui file(s) and adjust the \"ui_<NAME>.h\" "
  997. "include(s)\n"));
  998. return false;
  999. }
  1000. // Add includer file to existing mapping
  1001. handle->IncluderFiles.emplace_back(std::move(includerFileHandle));
  1002. } else {
  1003. // New mapping handle
  1004. MappingHandleT handle = std::make_shared<MappingT>();
  1005. handle->IncludeString = includeString;
  1006. handle->IncluderFiles.emplace_back(std::move(includerFileHandle));
  1007. handle->SourceFile = UiFileHandle;
  1008. handle->OutputFile = Gen()->AbsoluteIncludePath(includeString);
  1009. // Register mapping
  1010. Includes.emplace(includeString, std::move(handle));
  1011. }
  1012. return true;
  1013. }
  1014. void cmQtAutoMocUic::JobEvalCacheFinishT::Process()
  1015. {
  1016. // Add discovered header parse jobs
  1017. Gen()->CreateParseJobs<JobParseHeaderT>(MocEval().HeadersDiscovered);
  1018. // Add dependency probing jobs
  1019. {
  1020. // Add fence job to ensure all parsing has finished
  1021. Gen()->WorkerPool().EmplaceJob<JobFenceT>();
  1022. if (MocConst().Enabled) {
  1023. Gen()->WorkerPool().EmplaceJob<JobProbeDepsMocT>();
  1024. }
  1025. if (UicConst().Enabled) {
  1026. Gen()->WorkerPool().EmplaceJob<JobProbeDepsUicT>();
  1027. }
  1028. // Add probe finish job
  1029. Gen()->WorkerPool().EmplaceJob<JobProbeDepsFinishT>();
  1030. }
  1031. }
  1032. void cmQtAutoMocUic::JobProbeDepsMocT::Process()
  1033. {
  1034. // Create moc header jobs
  1035. for (auto const& pair : MocEval().HeaderMappings) {
  1036. // Register if this mapping is a candidate for mocs_compilation.cpp
  1037. bool const compFile = pair.second->IncludeString.empty();
  1038. if (compFile) {
  1039. MocEval().CompFiles.emplace_back(pair.second->SourceFile->BuildPath);
  1040. }
  1041. if (!Generate(pair.second, compFile)) {
  1042. return;
  1043. }
  1044. }
  1045. // Create moc source jobs
  1046. for (auto const& pair : MocEval().SourceMappings) {
  1047. if (!Generate(pair.second, false)) {
  1048. return;
  1049. }
  1050. }
  1051. }
  1052. bool cmQtAutoMocUic::JobProbeDepsMocT::Generate(MappingHandleT const& mapping,
  1053. bool compFile) const
  1054. {
  1055. std::unique_ptr<std::string> reason;
  1056. if (Log().Verbose()) {
  1057. reason = cm::make_unique<std::string>();
  1058. }
  1059. if (Probe(*mapping, reason.get())) {
  1060. // Register the parent directory for creation
  1061. MocEval().OutputDirs.emplace(cmQtAutoGen::ParentDir(mapping->OutputFile));
  1062. // Add moc job
  1063. Gen()->WorkerPool().EmplaceJob<JobCompileMocT>(mapping, std::move(reason));
  1064. // Check if a moc job for a mocs_compilation.cpp entry was generated
  1065. if (compFile) {
  1066. MocEval().CompUpdated = true;
  1067. }
  1068. }
  1069. return true;
  1070. }
  1071. bool cmQtAutoMocUic::JobProbeDepsMocT::Probe(MappingT const& mapping,
  1072. std::string* reason) const
  1073. {
  1074. std::string const& sourceFile = mapping.SourceFile->FileName;
  1075. std::string const& outputFile = mapping.OutputFile;
  1076. // Test if the output file exists
  1077. cmFileTime outputFileTime;
  1078. if (!outputFileTime.Load(outputFile)) {
  1079. if (reason != nullptr) {
  1080. *reason =
  1081. cmStrCat("Generating ", MessagePath(outputFile),
  1082. ", because it doesn't exist, from ", MessagePath(sourceFile));
  1083. }
  1084. return true;
  1085. }
  1086. // Test if any setting changed
  1087. if (MocConst().SettingsChanged) {
  1088. if (reason != nullptr) {
  1089. *reason = cmStrCat("Generating ", MessagePath(outputFile),
  1090. ", because the uic settings changed, from ",
  1091. MessagePath(sourceFile));
  1092. }
  1093. return true;
  1094. }
  1095. // Test if the source file is newer
  1096. if (outputFileTime.Older(mapping.SourceFile->FileTime)) {
  1097. if (reason != nullptr) {
  1098. *reason = cmStrCat("Generating ", MessagePath(outputFile),
  1099. ", because it's older than its source file, from ",
  1100. MessagePath(sourceFile));
  1101. }
  1102. return true;
  1103. }
  1104. // Test if the moc_predefs file is newer
  1105. if (!MocConst().PredefsFileAbs.empty()) {
  1106. if (outputFileTime.Older(MocEval().PredefsTime)) {
  1107. if (reason != nullptr) {
  1108. *reason = cmStrCat("Generating ", MessagePath(outputFile),
  1109. ", because it's older than ",
  1110. MessagePath(MocConst().PredefsFileAbs), ", from ",
  1111. MessagePath(sourceFile));
  1112. }
  1113. return true;
  1114. }
  1115. }
  1116. // Test if the moc executable is newer
  1117. if (outputFileTime.Older(MocConst().ExecutableTime)) {
  1118. if (reason != nullptr) {
  1119. *reason = cmStrCat("Generating ", MessagePath(outputFile),
  1120. ", because it's older than the moc executable, from ",
  1121. MessagePath(sourceFile));
  1122. }
  1123. return true;
  1124. }
  1125. // Test if a dependency file is newer
  1126. {
  1127. // Check dependency timestamps
  1128. std::string const sourceDir = SubDirPrefix(sourceFile);
  1129. for (std::string const& dep : mapping.SourceFile->ParseData->Moc.Depends) {
  1130. // Find dependency file
  1131. auto const depMatch = FindDependency(sourceDir, dep);
  1132. if (depMatch.first.empty()) {
  1133. Log().Warning(GenT::MOC,
  1134. cmStrCat(MessagePath(sourceFile), " depends on ",
  1135. MessagePath(dep),
  1136. " but the file does not exist."));
  1137. continue;
  1138. }
  1139. // Test if dependency file is older
  1140. if (outputFileTime.Older(depMatch.second)) {
  1141. if (reason != nullptr) {
  1142. *reason = cmStrCat("Generating ", MessagePath(outputFile),
  1143. ", because it's older than its dependency file ",
  1144. MessagePath(depMatch.first), ", from ",
  1145. MessagePath(sourceFile));
  1146. }
  1147. return true;
  1148. }
  1149. }
  1150. }
  1151. return false;
  1152. }
  1153. std::pair<std::string, cmFileTime>
  1154. cmQtAutoMocUic::JobProbeDepsMocT::FindDependency(
  1155. std::string const& sourceDir, std::string const& includeString) const
  1156. {
  1157. using ResPair = std::pair<std::string, cmFileTime>;
  1158. // Search in vicinity of the source
  1159. {
  1160. ResPair res{ sourceDir + includeString, {} };
  1161. if (res.second.Load(res.first)) {
  1162. return res;
  1163. }
  1164. }
  1165. // Search in include directories
  1166. for (std::string const& includePath : MocConst().IncludePaths) {
  1167. ResPair res{ cmStrCat(includePath, '/', includeString), {} };
  1168. if (res.second.Load(res.first)) {
  1169. return res;
  1170. }
  1171. }
  1172. // Return empty
  1173. return ResPair();
  1174. }
  1175. void cmQtAutoMocUic::JobProbeDepsUicT::Process()
  1176. {
  1177. for (auto const& pair : Gen()->UicEval().Includes) {
  1178. MappingHandleT const& mapping = pair.second;
  1179. std::unique_ptr<std::string> reason;
  1180. if (Log().Verbose()) {
  1181. reason = cm::make_unique<std::string>();
  1182. }
  1183. if (!Probe(*mapping, reason.get())) {
  1184. continue;
  1185. }
  1186. // Register the parent directory for creation
  1187. UicEval().OutputDirs.emplace(cmQtAutoGen::ParentDir(mapping->OutputFile));
  1188. // Add uic job
  1189. Gen()->WorkerPool().EmplaceJob<JobCompileUicT>(mapping, std::move(reason));
  1190. }
  1191. }
  1192. bool cmQtAutoMocUic::JobProbeDepsUicT::Probe(MappingT const& mapping,
  1193. std::string* reason) const
  1194. {
  1195. std::string const& sourceFile = mapping.SourceFile->FileName;
  1196. std::string const& outputFile = mapping.OutputFile;
  1197. // Test if the build file exists
  1198. cmFileTime outputFileTime;
  1199. if (!outputFileTime.Load(outputFile)) {
  1200. if (reason != nullptr) {
  1201. *reason =
  1202. cmStrCat("Generating ", MessagePath(outputFile),
  1203. ", because it doesn't exist, from ", MessagePath(sourceFile));
  1204. }
  1205. return true;
  1206. }
  1207. // Test if the uic settings changed
  1208. if (UicConst().SettingsChanged) {
  1209. if (reason != nullptr) {
  1210. *reason = cmStrCat("Generating ", MessagePath(outputFile),
  1211. ", because the uic settings changed, from ",
  1212. MessagePath(sourceFile));
  1213. }
  1214. return true;
  1215. }
  1216. // Test if the source file is newer
  1217. if (outputFileTime.Older(mapping.SourceFile->FileTime)) {
  1218. if (reason != nullptr) {
  1219. *reason = cmStrCat("Generating ", MessagePath(outputFile),
  1220. " because it's older than the source file ",
  1221. MessagePath(sourceFile));
  1222. }
  1223. return true;
  1224. }
  1225. // Test if the uic executable is newer
  1226. if (outputFileTime.Older(UicConst().ExecutableTime)) {
  1227. if (reason != nullptr) {
  1228. *reason = cmStrCat("Generating ", MessagePath(outputFile),
  1229. ", because it's older than the uic executable, from ",
  1230. MessagePath(sourceFile));
  1231. }
  1232. return true;
  1233. }
  1234. return false;
  1235. }
  1236. void cmQtAutoMocUic::JobProbeDepsFinishT::Process()
  1237. {
  1238. // Create output directories
  1239. {
  1240. using StringSet = std::unordered_set<std::string>;
  1241. auto createDirs = [this](GenT genType, StringSet const& dirSet) {
  1242. for (std::string const& dirName : dirSet) {
  1243. if (!cmSystemTools::MakeDirectory(dirName)) {
  1244. this->LogError(
  1245. genType,
  1246. cmStrCat("Creating directory ", MessagePath(dirName), " failed."));
  1247. return;
  1248. }
  1249. }
  1250. };
  1251. if (MocConst().Enabled && UicConst().Enabled) {
  1252. StringSet outputDirs = MocEval().OutputDirs;
  1253. outputDirs.insert(UicEval().OutputDirs.begin(),
  1254. UicEval().OutputDirs.end());
  1255. createDirs(GenT::GEN, outputDirs);
  1256. } else if (MocConst().Enabled) {
  1257. createDirs(GenT::MOC, MocEval().OutputDirs);
  1258. } else if (UicConst().Enabled) {
  1259. createDirs(GenT::UIC, UicEval().OutputDirs);
  1260. }
  1261. }
  1262. if (MocConst().Enabled) {
  1263. // Add mocs compilations job
  1264. Gen()->WorkerPool().EmplaceJob<JobMocsCompilationT>();
  1265. }
  1266. // Add finish job
  1267. Gen()->WorkerPool().EmplaceJob<JobFinishT>();
  1268. }
  1269. void cmQtAutoMocUic::JobCompileMocT::Process()
  1270. {
  1271. std::string const& sourceFile = Mapping->SourceFile->FileName;
  1272. std::string const& outputFile = Mapping->OutputFile;
  1273. // Compose moc command
  1274. std::vector<std::string> cmd;
  1275. {
  1276. // Reserve large enough
  1277. cmd.reserve(MocConst().OptionsDefinitions.size() +
  1278. MocConst().OptionsIncludes.size() +
  1279. MocConst().OptionsExtra.size() + 16);
  1280. cmd.push_back(MocConst().Executable);
  1281. // Add definitions
  1282. cmAppend(cmd, MocConst().OptionsDefinitions);
  1283. // Add includes
  1284. cmAppend(cmd, MocConst().OptionsIncludes);
  1285. // Add predefs include
  1286. if (!MocConst().PredefsFileAbs.empty()) {
  1287. cmd.emplace_back("--include");
  1288. cmd.push_back(MocConst().PredefsFileAbs);
  1289. }
  1290. // Add path prefix on demand
  1291. if (MocConst().PathPrefix && Mapping->SourceFile->IsHeader) {
  1292. for (std::string const& dir : MocConst().IncludePaths) {
  1293. cm::string_view prefix = sourceFile;
  1294. if (cmHasPrefix(prefix, dir)) {
  1295. prefix.remove_prefix(dir.size());
  1296. if (cmHasPrefix(prefix, '/')) {
  1297. prefix.remove_prefix(1);
  1298. auto slashPos = prefix.rfind('/');
  1299. if (slashPos != cm::string_view::npos) {
  1300. cmd.emplace_back("-p");
  1301. cmd.emplace_back(prefix.substr(0, slashPos));
  1302. } else {
  1303. cmd.emplace_back("-p");
  1304. cmd.emplace_back("./");
  1305. }
  1306. break;
  1307. }
  1308. }
  1309. }
  1310. }
  1311. // Add extra options
  1312. cmAppend(cmd, MocConst().OptionsExtra);
  1313. // Add output file
  1314. cmd.emplace_back("-o");
  1315. cmd.push_back(outputFile);
  1316. // Add source file
  1317. cmd.push_back(sourceFile);
  1318. }
  1319. // Execute moc command
  1320. cmWorkerPool::ProcessResultT result;
  1321. if (RunProcess(GenT::MOC, result, cmd, Reason.get())) {
  1322. // Moc command success. Print moc output.
  1323. if (!result.StdOut.empty()) {
  1324. Log().Info(GenT::MOC, result.StdOut);
  1325. }
  1326. } else {
  1327. // Moc command failed
  1328. std::string includers;
  1329. if (!Mapping->IncluderFiles.empty()) {
  1330. includers = "included by\n";
  1331. for (auto const& item : Mapping->IncluderFiles) {
  1332. includers += cmStrCat(" ", MessagePath(item->FileName), '\n');
  1333. }
  1334. }
  1335. LogCommandError(GenT::MOC,
  1336. cmStrCat("The moc process failed to compile\n ",
  1337. MessagePath(sourceFile), "\ninto\n ",
  1338. MessagePath(outputFile), '\n', includers,
  1339. result.ErrorMessage),
  1340. cmd, result.StdOut);
  1341. }
  1342. }
  1343. void cmQtAutoMocUic::JobCompileUicT::Process()
  1344. {
  1345. std::string const& sourceFile = Mapping->SourceFile->FileName;
  1346. std::string const& outputFile = Mapping->OutputFile;
  1347. // Compose uic command
  1348. std::vector<std::string> cmd;
  1349. cmd.push_back(UicConst().Executable);
  1350. {
  1351. std::vector<std::string> allOpts = UicConst().TargetOptions;
  1352. auto optionIt = UicConst().Options.find(sourceFile);
  1353. if (optionIt != UicConst().Options.end()) {
  1354. UicMergeOptions(allOpts, optionIt->second,
  1355. (BaseConst().QtVersionMajor == 5));
  1356. }
  1357. cmAppend(cmd, allOpts);
  1358. }
  1359. cmd.emplace_back("-o");
  1360. cmd.emplace_back(outputFile);
  1361. cmd.emplace_back(sourceFile);
  1362. cmWorkerPool::ProcessResultT result;
  1363. if (RunProcess(GenT::UIC, result, cmd, Reason.get())) {
  1364. // Uic command success
  1365. // Print uic output
  1366. if (!result.StdOut.empty()) {
  1367. Log().Info(GenT::UIC, result.StdOut);
  1368. }
  1369. } else {
  1370. // Uic command failed
  1371. std::string includers;
  1372. for (auto const& item : Mapping->IncluderFiles) {
  1373. includers += cmStrCat(" ", MessagePath(item->FileName), '\n');
  1374. }
  1375. LogCommandError(GenT::UIC,
  1376. cmStrCat("The uic process failed to compile\n ",
  1377. MessagePath(sourceFile), "\ninto\n ",
  1378. MessagePath(outputFile), "\nincluded by\n",
  1379. includers, result.ErrorMessage),
  1380. cmd, result.StdOut);
  1381. }
  1382. }
  1383. void cmQtAutoMocUic::JobMocsCompilationT::Process()
  1384. {
  1385. // Compose mocs compilation file content
  1386. std::string content =
  1387. "// This file is autogenerated. Changes will be overwritten.\n";
  1388. if (MocEval().CompFiles.empty()) {
  1389. // Placeholder content
  1390. content += "// No files found that require moc or the moc files are "
  1391. "included\n"
  1392. "enum some_compilers { need_more_than_nothing };\n";
  1393. } else {
  1394. // Valid content
  1395. const bool mc = BaseConst().MultiConfig;
  1396. cm::string_view const wrapFront = mc ? "#include <" : "#include \"";
  1397. cm::string_view const wrapBack = mc ? ">\n" : "\"\n";
  1398. content += cmWrap(wrapFront, MocEval().CompFiles, wrapBack, "");
  1399. }
  1400. std::string const& compAbs = MocConst().CompFileAbs;
  1401. if (cmQtAutoGenerator::FileDiffers(compAbs, content)) {
  1402. // Actually write mocs compilation file
  1403. if (Log().Verbose()) {
  1404. Log().Info(GenT::MOC,
  1405. "Generating MOC compilation " + MessagePath(compAbs));
  1406. }
  1407. if (!FileWrite(compAbs, content)) {
  1408. LogError(GenT::MOC,
  1409. cmStrCat("Writing MOC compilation ", MessagePath(compAbs),
  1410. " failed."));
  1411. }
  1412. } else if (MocEval().CompUpdated) {
  1413. // Only touch mocs compilation file
  1414. if (Log().Verbose()) {
  1415. Log().Info(GenT::MOC,
  1416. "Touching MOC compilation " + MessagePath(compAbs));
  1417. }
  1418. if (!cmSystemTools::Touch(compAbs, false)) {
  1419. LogError(GenT::MOC,
  1420. cmStrCat("Touching MOC compilation ", MessagePath(compAbs),
  1421. " failed."));
  1422. }
  1423. }
  1424. }
  1425. void cmQtAutoMocUic::JobFinishT::Process()
  1426. {
  1427. Gen()->AbortSuccess();
  1428. }
  1429. cmQtAutoMocUic::cmQtAutoMocUic() = default;
  1430. cmQtAutoMocUic::~cmQtAutoMocUic() = default;
  1431. bool cmQtAutoMocUic::Init(cmMakefile* makefile)
  1432. {
  1433. // Utility lambdas
  1434. auto InfoGet = [makefile](cm::string_view key) {
  1435. return makefile->GetSafeDefinition(std::string(key));
  1436. };
  1437. auto InfoGetBool = [makefile](cm::string_view key) {
  1438. return makefile->IsOn(std::string(key));
  1439. };
  1440. auto InfoGetList =
  1441. [makefile](cm::string_view key) -> std::vector<std::string> {
  1442. return cmExpandedList(makefile->GetSafeDefinition(std::string(key)));
  1443. };
  1444. auto InfoGetLists =
  1445. [makefile](cm::string_view key) -> std::vector<std::vector<std::string>> {
  1446. std::vector<std::vector<std::string>> lists;
  1447. {
  1448. std::string const value = makefile->GetSafeDefinition(std::string(key));
  1449. std::string::size_type pos = 0;
  1450. while (pos < value.size()) {
  1451. std::string::size_type next = value.find(ListSep, pos);
  1452. std::string::size_type length =
  1453. (next != std::string::npos) ? next - pos : value.size() - pos;
  1454. // Remove enclosing braces
  1455. if (length >= 2) {
  1456. std::string::const_iterator itBeg = value.begin() + (pos + 1);
  1457. std::string::const_iterator itEnd = itBeg + (length - 2);
  1458. lists.emplace_back(cmExpandedList(std::string(itBeg, itEnd)));
  1459. }
  1460. pos += length;
  1461. pos += ListSep.size();
  1462. }
  1463. }
  1464. return lists;
  1465. };
  1466. auto InfoGetConfig = [makefile, this](cm::string_view key) -> std::string {
  1467. if (const char* valueConf =
  1468. makefile->GetDefinition(cmStrCat(key, '_', InfoConfig()))) {
  1469. return std::string(valueConf);
  1470. }
  1471. return makefile->GetSafeDefinition(std::string(key));
  1472. };
  1473. auto InfoGetConfigList =
  1474. [&InfoGetConfig](cm::string_view key) -> std::vector<std::string> {
  1475. return cmExpandedList(InfoGetConfig(key));
  1476. };
  1477. auto LogInfoError = [this](cm::string_view msg) -> bool {
  1478. this->Log().Error(GenT::GEN,
  1479. cmStrCat("In ", Quoted(this->InfoFile()), ":\n", msg));
  1480. return false;
  1481. };
  1482. auto MatchSizes = [&LogInfoError](cm::string_view keyA, cm::string_view keyB,
  1483. std::size_t sizeA,
  1484. std::size_t sizeB) -> bool {
  1485. if (sizeA == sizeB) {
  1486. return true;
  1487. }
  1488. return LogInfoError(cmStrCat("Lists sizes mismatch ", keyA, '(', sizeA,
  1489. ") ", keyB, '(', sizeB, ')'));
  1490. };
  1491. // -- Read info file
  1492. if (!makefile->ReadListFile(InfoFile())) {
  1493. return LogInfoError("File processing failed");
  1494. }
  1495. // -- Meta
  1496. Logger_.RaiseVerbosity(InfoGet("AM_VERBOSITY"));
  1497. BaseConst_.MultiConfig = InfoGetBool("AM_MULTI_CONFIG");
  1498. {
  1499. unsigned long num = 1;
  1500. if (cmStrToULong(InfoGet("AM_PARALLEL"), &num)) {
  1501. num = std::max<unsigned long>(num, 1);
  1502. num = std::min<unsigned long>(num, ParallelMax);
  1503. }
  1504. WorkerPool_.SetThreadCount(static_cast<unsigned int>(num));
  1505. }
  1506. BaseConst_.HeaderExtensions =
  1507. makefile->GetCMakeInstance()->GetHeaderExtensions();
  1508. // - Files and directories
  1509. ProjectDirsRef().Source = InfoGet("AM_CMAKE_SOURCE_DIR");
  1510. ProjectDirsRef().Binary = InfoGet("AM_CMAKE_BINARY_DIR");
  1511. ProjectDirsRef().CurrentSource = InfoGet("AM_CMAKE_CURRENT_SOURCE_DIR");
  1512. ProjectDirsRef().CurrentBinary = InfoGet("AM_CMAKE_CURRENT_BINARY_DIR");
  1513. BaseConst_.AutogenBuildDir = InfoGet("AM_BUILD_DIR");
  1514. if (BaseConst_.AutogenBuildDir.empty()) {
  1515. return LogInfoError("Autogen build directory missing.");
  1516. }
  1517. BaseConst_.AutogenIncludeDir = InfoGetConfig("AM_INCLUDE_DIR");
  1518. if (BaseConst_.AutogenIncludeDir.empty()) {
  1519. return LogInfoError("Autogen include directory missing.");
  1520. }
  1521. BaseConst_.CMakeExecutable = InfoGetConfig("AM_CMAKE_EXECUTABLE");
  1522. if (BaseConst_.CMakeExecutable.empty()) {
  1523. return LogInfoError("CMake executable file name missing.");
  1524. }
  1525. if (!BaseConst_.CMakeExecutableTime.Load(BaseConst_.CMakeExecutable)) {
  1526. return LogInfoError(cmStrCat("The CMake executable ",
  1527. MessagePath(BaseConst_.CMakeExecutable),
  1528. " does not exist."));
  1529. }
  1530. BaseConst_.ParseCacheFile = InfoGetConfig("AM_PARSE_CACHE_FILE");
  1531. if (BaseConst_.ParseCacheFile.empty()) {
  1532. return LogInfoError("Parse cache file name missing.");
  1533. }
  1534. // - Settings file
  1535. SettingsFile_ = InfoGetConfig("AM_SETTINGS_FILE");
  1536. if (SettingsFile_.empty()) {
  1537. return LogInfoError("Settings file name missing.");
  1538. }
  1539. // - Qt environment
  1540. {
  1541. unsigned long qtv = BaseConst_.QtVersionMajor;
  1542. if (cmStrToULong(InfoGet("AM_QT_VERSION_MAJOR"), &qtv)) {
  1543. BaseConst_.QtVersionMajor = static_cast<unsigned int>(qtv);
  1544. }
  1545. }
  1546. // - Moc
  1547. MocConst_.Executable = InfoGet("AM_QT_MOC_EXECUTABLE");
  1548. if (!MocConst().Executable.empty()) {
  1549. MocConst_.Enabled = true;
  1550. // Load the executable file time
  1551. if (!MocConst_.ExecutableTime.Load(MocConst_.Executable)) {
  1552. return LogInfoError(cmStrCat("The moc executable ",
  1553. MessagePath(MocConst_.Executable),
  1554. " does not exist."));
  1555. }
  1556. for (std::string& sfl : InfoGetList("AM_MOC_SKIP")) {
  1557. MocConst_.SkipList.insert(std::move(sfl));
  1558. }
  1559. MocConst_.Definitions = InfoGetConfigList("AM_MOC_DEFINITIONS");
  1560. MocConst_.IncludePaths = InfoGetConfigList("AM_MOC_INCLUDES");
  1561. MocConst_.OptionsExtra = InfoGetList("AM_MOC_OPTIONS");
  1562. MocConst_.RelaxedMode = InfoGetBool("AM_MOC_RELAXED_MODE");
  1563. MocConst_.PathPrefix = InfoGetBool("AM_MOC_PATH_PREFIX");
  1564. for (std::string const& item : InfoGetList("AM_MOC_MACRO_NAMES")) {
  1565. MocConst_.MacroFilters.emplace_back(
  1566. item, ("[\n][ \t]*{?[ \t]*" + item).append("[^a-zA-Z0-9_]"));
  1567. }
  1568. {
  1569. auto addFilter = [this, &LogInfoError](std::string const& key,
  1570. std::string const& exp) -> bool {
  1571. auto filterErr = [&LogInfoError, &key,
  1572. &exp](cm::string_view err) -> bool {
  1573. return LogInfoError(cmStrCat("AUTOMOC_DEPEND_FILTERS: ", err, '\n',
  1574. " Key: ", Quoted(key), '\n',
  1575. " Exp: ", Quoted(exp), '\n'));
  1576. };
  1577. if (key.empty()) {
  1578. return filterErr("Key is empty");
  1579. }
  1580. if (exp.empty()) {
  1581. return filterErr("Regular expression is empty");
  1582. }
  1583. this->MocConst_.DependFilters.emplace_back(key, exp);
  1584. if (!this->MocConst_.DependFilters.back().Exp.is_valid()) {
  1585. return filterErr("Regular expression compiling failed");
  1586. }
  1587. return true;
  1588. };
  1589. // Insert default filter for Q_PLUGIN_METADATA
  1590. if (BaseConst().QtVersionMajor != 4) {
  1591. if (!addFilter("Q_PLUGIN_METADATA",
  1592. "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
  1593. "[^\\)]*FILE[ \t]*\"([^\"]+)\"")) {
  1594. return false;
  1595. }
  1596. }
  1597. // Insert user defined dependency filters
  1598. std::vector<std::string> flts = InfoGetList("AM_MOC_DEPEND_FILTERS");
  1599. if ((flts.size() % 2) != 0) {
  1600. return LogInfoError(
  1601. "AUTOMOC_DEPEND_FILTERS list size is not a multiple of 2");
  1602. }
  1603. for (auto itC = flts.begin(), itE = flts.end(); itC != itE; itC += 2) {
  1604. if (!addFilter(*itC, *(itC + 1))) {
  1605. return false;
  1606. }
  1607. }
  1608. }
  1609. MocConst_.PredefsCmd = InfoGetList("AM_MOC_PREDEFS_CMD");
  1610. }
  1611. // - Uic
  1612. UicConst_.Executable = InfoGet("AM_QT_UIC_EXECUTABLE");
  1613. if (!UicConst().Executable.empty()) {
  1614. UicConst_.Enabled = true;
  1615. // Load the executable file time
  1616. if (!UicConst_.ExecutableTime.Load(UicConst_.Executable)) {
  1617. return LogInfoError(cmStrCat("The uic executable ",
  1618. MessagePath(UicConst_.Executable),
  1619. " does not exist."));
  1620. }
  1621. for (std::string& sfl : InfoGetList("AM_UIC_SKIP")) {
  1622. UicConst_.SkipList.insert(std::move(sfl));
  1623. }
  1624. UicConst_.SearchPaths = InfoGetList("AM_UIC_SEARCH_PATHS");
  1625. UicConst_.TargetOptions = InfoGetConfigList("AM_UIC_TARGET_OPTIONS");
  1626. {
  1627. cm::string_view const keyFiles = "AM_UIC_OPTIONS_FILES";
  1628. cm::string_view const keyOpts = "AM_UIC_OPTIONS_OPTIONS";
  1629. auto sources = InfoGetList(keyFiles);
  1630. auto options = InfoGetLists(keyOpts);
  1631. if (!MatchSizes(keyFiles, keyOpts, sources.size(), options.size())) {
  1632. return false;
  1633. }
  1634. auto fitEnd = sources.cend();
  1635. auto fit = sources.begin();
  1636. auto oit = options.begin();
  1637. while (fit != fitEnd) {
  1638. UicConst_.Options[*fit] = std::move(*oit);
  1639. ++fit;
  1640. ++oit;
  1641. }
  1642. }
  1643. }
  1644. // Headers
  1645. {
  1646. // Get file lists
  1647. cm::string_view const keyFiles = "AM_HEADERS";
  1648. cm::string_view const keyFlags = "AM_HEADERS_FLAGS";
  1649. std::vector<std::string> files = InfoGetList(keyFiles);
  1650. std::vector<std::string> flags = InfoGetList(keyFlags);
  1651. std::vector<std::string> builds;
  1652. if (!MatchSizes(keyFiles, keyFlags, files.size(), flags.size())) {
  1653. return false;
  1654. }
  1655. if (MocConst().Enabled) {
  1656. cm::string_view const keyPaths = "AM_HEADERS_BUILD_PATHS";
  1657. builds = InfoGetList(keyPaths);
  1658. if (!MatchSizes(keyFiles, keyPaths, files.size(), builds.size())) {
  1659. return false;
  1660. }
  1661. }
  1662. // Process file lists
  1663. for (std::size_t ii = 0; ii != files.size(); ++ii) {
  1664. std::string& fileName(files[ii]);
  1665. std::string const& fileFlags(flags[ii]);
  1666. if (fileFlags.size() != 2) {
  1667. LogInfoError(cmStrCat("Invalid flags string size ", fileFlags.size(),
  1668. "in ", keyFlags));
  1669. return false;
  1670. }
  1671. cmFileTime fileTime;
  1672. if (!fileTime.Load(fileName)) {
  1673. LogInfoError(cmStrCat("The header file ", this->MessagePath(fileName),
  1674. " does not exist."));
  1675. return false;
  1676. }
  1677. SourceFileHandleT sourceHandle = std::make_shared<SourceFileT>(fileName);
  1678. sourceHandle->FileTime = fileTime;
  1679. sourceHandle->IsHeader = true;
  1680. sourceHandle->Moc = (fileFlags[0] == 'M');
  1681. sourceHandle->Uic = (fileFlags[1] == 'U');
  1682. if (sourceHandle->Moc && MocConst().Enabled) {
  1683. sourceHandle->BuildPath = std::move(builds[ii]);
  1684. if (sourceHandle->BuildPath.empty()) {
  1685. return LogInfoError("Header file build path is empty");
  1686. }
  1687. }
  1688. BaseEval().Headers.emplace(std::move(fileName), std::move(sourceHandle));
  1689. }
  1690. }
  1691. // Sources
  1692. {
  1693. cm::string_view const keyFiles = "AM_SOURCES";
  1694. cm::string_view const keyFlags = "AM_SOURCES_FLAGS";
  1695. std::vector<std::string> files = InfoGetList(keyFiles);
  1696. std::vector<std::string> flags = InfoGetList(keyFlags);
  1697. if (!MatchSizes(keyFiles, keyFlags, files.size(), flags.size())) {
  1698. return false;
  1699. }
  1700. // Process file lists
  1701. for (std::size_t ii = 0; ii != files.size(); ++ii) {
  1702. std::string& fileName(files[ii]);
  1703. std::string const& fileFlags(flags[ii]);
  1704. if (fileFlags.size() != 2) {
  1705. LogInfoError(cmStrCat("Invalid flags string size ", fileFlags.size(),
  1706. "in ", keyFlags));
  1707. return false;
  1708. }
  1709. cmFileTime fileTime;
  1710. if (!fileTime.Load(fileName)) {
  1711. LogInfoError(cmStrCat("The source file ", this->MessagePath(fileName),
  1712. " does not exist."));
  1713. return false;
  1714. }
  1715. SourceFileHandleT sourceHandle = std::make_shared<SourceFileT>(fileName);
  1716. sourceHandle->FileTime = fileTime;
  1717. sourceHandle->IsHeader = false;
  1718. sourceHandle->Moc = (fileFlags[0] == 'M');
  1719. sourceHandle->Uic = (fileFlags[1] == 'U');
  1720. BaseEval().Sources.emplace(std::move(fileName), std::move(sourceHandle));
  1721. }
  1722. }
  1723. // Init derived information
  1724. // ------------------------
  1725. // Moc variables
  1726. if (MocConst().Enabled) {
  1727. // Mocs compilation file
  1728. MocConst_.CompFileAbs = AbsoluteBuildPath("mocs_compilation.cpp");
  1729. // Moc predefs file
  1730. if (!MocConst_.PredefsCmd.empty()) {
  1731. std::string pathRel;
  1732. if (BaseConst_.MultiConfig) {
  1733. pathRel = cmStrCat("moc_predefs_", InfoConfig(), ".h");
  1734. } else {
  1735. pathRel = "moc_predefs.h";
  1736. }
  1737. MocConst_.PredefsFileAbs = AbsoluteBuildPath(pathRel);
  1738. }
  1739. // Compose moc includes list
  1740. {
  1741. // Compute framework paths
  1742. std::set<std::string> frameworkPaths;
  1743. for (std::string const& path : MocConst().IncludePaths) {
  1744. // Extract framework path
  1745. if (cmHasLiteralSuffix(path, ".framework/Headers")) {
  1746. // Go up twice to get to the framework root
  1747. std::vector<std::string> pathComponents;
  1748. cmSystemTools::SplitPath(path, pathComponents);
  1749. frameworkPaths.emplace(cmSystemTools::JoinPath(
  1750. pathComponents.begin(), pathComponents.end() - 2));
  1751. }
  1752. }
  1753. // Reserve options
  1754. MocConst_.OptionsIncludes.reserve(MocConst().IncludePaths.size() +
  1755. frameworkPaths.size() * 2);
  1756. // Append includes
  1757. for (std::string const& path : MocConst().IncludePaths) {
  1758. MocConst_.OptionsIncludes.emplace_back("-I" + path);
  1759. }
  1760. // Append framework includes
  1761. for (std::string const& path : frameworkPaths) {
  1762. MocConst_.OptionsIncludes.emplace_back("-F");
  1763. MocConst_.OptionsIncludes.push_back(path);
  1764. }
  1765. }
  1766. // Compose moc definitions list
  1767. {
  1768. MocConst_.OptionsDefinitions.reserve(MocConst().Definitions.size());
  1769. for (std::string const& def : MocConst().Definitions) {
  1770. MocConst_.OptionsDefinitions.emplace_back("-D" + def);
  1771. }
  1772. }
  1773. }
  1774. return true;
  1775. }
  1776. template <class JOBTYPE>
  1777. void cmQtAutoMocUic::CreateParseJobs(SourceFileMapT const& sourceMap)
  1778. {
  1779. cmFileTime const parseCacheTime = BaseEval().ParseCacheTime;
  1780. ParseCacheT& parseCache = BaseEval().ParseCache;
  1781. for (auto& src : sourceMap) {
  1782. // Get or create the file parse data reference
  1783. ParseCacheT::GetOrInsertT cacheEntry = parseCache.GetOrInsert(src.first);
  1784. src.second->ParseData = std::move(cacheEntry.first);
  1785. // Create a parse job if the cache file was missing or is older
  1786. if (cacheEntry.second || src.second->FileTime.Newer(parseCacheTime)) {
  1787. BaseEval().ParseCacheChanged = true;
  1788. WorkerPool().EmplaceJob<JOBTYPE>(src.second);
  1789. }
  1790. }
  1791. }
  1792. /** Concurrently callable implementation of cmSystemTools::CollapseFullPath */
  1793. std::string cmQtAutoMocUic::CollapseFullPathTS(std::string const& path) const
  1794. {
  1795. std::lock_guard<std::mutex> guard(CMakeLibMutex_);
  1796. return cmSystemTools::CollapseFullPath(path, ProjectDirs().CurrentSource);
  1797. }
  1798. void cmQtAutoMocUic::InitJobs()
  1799. {
  1800. // Add moc_predefs.h job
  1801. if (MocConst().Enabled && !MocConst().PredefsCmd.empty()) {
  1802. WorkerPool().EmplaceJob<JobMocPredefsT>();
  1803. }
  1804. // Add header parse jobs
  1805. CreateParseJobs<JobParseHeaderT>(BaseEval().Headers);
  1806. // Add source parse jobs
  1807. CreateParseJobs<JobParseSourceT>(BaseEval().Sources);
  1808. // Add parse cache evaluations jobs
  1809. {
  1810. // Add a fence job to ensure all parsing has finished
  1811. WorkerPool().EmplaceJob<JobFenceT>();
  1812. if (MocConst().Enabled) {
  1813. WorkerPool().EmplaceJob<JobEvalCacheMocT>();
  1814. }
  1815. if (UicConst().Enabled) {
  1816. WorkerPool().EmplaceJob<JobEvalCacheUicT>();
  1817. }
  1818. // Add evaluate job
  1819. WorkerPool().EmplaceJob<JobEvalCacheFinishT>();
  1820. }
  1821. }
  1822. bool cmQtAutoMocUic::Process()
  1823. {
  1824. SettingsFileRead();
  1825. ParseCacheRead();
  1826. if (!CreateDirectories()) {
  1827. return false;
  1828. }
  1829. InitJobs();
  1830. if (!WorkerPool_.Process(this)) {
  1831. return false;
  1832. }
  1833. if (JobError_) {
  1834. return false;
  1835. }
  1836. if (!ParseCacheWrite()) {
  1837. return false;
  1838. }
  1839. if (!SettingsFileWrite()) {
  1840. return false;
  1841. }
  1842. return true;
  1843. }
  1844. void cmQtAutoMocUic::SettingsFileRead()
  1845. {
  1846. // Compose current settings strings
  1847. {
  1848. cmCryptoHash cryptoHash(cmCryptoHash::AlgoSHA256);
  1849. auto cha = [&cryptoHash](cm::string_view value) {
  1850. cryptoHash.Append(value);
  1851. cryptoHash.Append(";");
  1852. };
  1853. if (MocConst_.Enabled) {
  1854. cryptoHash.Initialize();
  1855. cha(MocConst().Executable);
  1856. for (auto const& item : MocConst().OptionsDefinitions) {
  1857. cha(item);
  1858. }
  1859. for (auto const& item : MocConst().OptionsIncludes) {
  1860. cha(item);
  1861. }
  1862. for (auto const& item : MocConst().OptionsExtra) {
  1863. cha(item);
  1864. }
  1865. for (auto const& item : MocConst().PredefsCmd) {
  1866. cha(item);
  1867. }
  1868. for (auto const& filter : MocConst().DependFilters) {
  1869. cha(filter.Key);
  1870. }
  1871. for (auto const& filter : MocConst().MacroFilters) {
  1872. cha(filter.Key);
  1873. }
  1874. SettingsStringMoc_ = cryptoHash.FinalizeHex();
  1875. }
  1876. if (UicConst().Enabled) {
  1877. cryptoHash.Initialize();
  1878. cha(UicConst().Executable);
  1879. std::for_each(UicConst().TargetOptions.begin(),
  1880. UicConst().TargetOptions.end(), cha);
  1881. for (const auto& item : UicConst().Options) {
  1882. cha(item.first);
  1883. std::for_each(item.second.begin(), item.second.end(), cha);
  1884. }
  1885. SettingsStringUic_ = cryptoHash.FinalizeHex();
  1886. }
  1887. }
  1888. // Read old settings and compare
  1889. {
  1890. std::string content;
  1891. if (cmQtAutoGenerator::FileRead(content, SettingsFile_)) {
  1892. if (MocConst().Enabled) {
  1893. if (SettingsStringMoc_ != SettingsFind(content, "moc")) {
  1894. MocConst_.SettingsChanged = true;
  1895. }
  1896. }
  1897. if (UicConst().Enabled) {
  1898. if (SettingsStringUic_ != SettingsFind(content, "uic")) {
  1899. UicConst_.SettingsChanged = true;
  1900. }
  1901. }
  1902. // In case any setting changed remove the old settings file.
  1903. // This triggers a full rebuild on the next run if the current
  1904. // build is aborted before writing the current settings in the end.
  1905. if (MocConst().SettingsChanged || UicConst().SettingsChanged) {
  1906. cmSystemTools::RemoveFile(SettingsFile_);
  1907. }
  1908. } else {
  1909. // Settings file read failed
  1910. if (MocConst().Enabled) {
  1911. MocConst_.SettingsChanged = true;
  1912. }
  1913. if (UicConst().Enabled) {
  1914. UicConst_.SettingsChanged = true;
  1915. }
  1916. }
  1917. }
  1918. }
  1919. bool cmQtAutoMocUic::SettingsFileWrite()
  1920. {
  1921. // Only write if any setting changed
  1922. if (MocConst().SettingsChanged || UicConst().SettingsChanged) {
  1923. if (Log().Verbose()) {
  1924. Log().Info(
  1925. GenT::GEN,
  1926. cmStrCat("Writing settings file ", MessagePath(SettingsFile_)));
  1927. }
  1928. // Compose settings file content
  1929. std::string content;
  1930. {
  1931. auto SettingAppend = [&content](cm::string_view key,
  1932. cm::string_view value) {
  1933. if (!value.empty()) {
  1934. content += cmStrCat(key, ':', value, '\n');
  1935. }
  1936. };
  1937. SettingAppend("moc", SettingsStringMoc_);
  1938. SettingAppend("uic", SettingsStringUic_);
  1939. }
  1940. // Write settings file
  1941. std::string error;
  1942. if (!cmQtAutoGenerator::FileWrite(SettingsFile_, content, &error)) {
  1943. Log().Error(GenT::GEN,
  1944. cmStrCat("Writing the settings file ",
  1945. MessagePath(SettingsFile_), " failed.\n", error));
  1946. // Remove old settings file to trigger a full rebuild on the next run
  1947. cmSystemTools::RemoveFile(SettingsFile_);
  1948. return false;
  1949. }
  1950. }
  1951. return true;
  1952. }
  1953. void cmQtAutoMocUic::ParseCacheRead()
  1954. {
  1955. cm::string_view reason;
  1956. // Don't read the cache if it is invalid
  1957. if (!BaseEval().ParseCacheTime.Load(BaseConst().ParseCacheFile)) {
  1958. reason = "Refreshing parse cache because it doesn't exist.";
  1959. } else if (MocConst().SettingsChanged || UicConst().SettingsChanged) {
  1960. reason = "Refreshing parse cache because the settings changed.";
  1961. } else if (BaseEval().ParseCacheTime.Older(
  1962. BaseConst().CMakeExecutableTime)) {
  1963. reason =
  1964. "Refreshing parse cache because it is older than the CMake executable.";
  1965. }
  1966. if (!reason.empty()) {
  1967. // Don't read but refresh the complete parse cache
  1968. if (Log().Verbose()) {
  1969. Log().Info(GenT::GEN, reason);
  1970. }
  1971. BaseEval().ParseCacheChanged = true;
  1972. } else {
  1973. // Read parse cache
  1974. BaseEval().ParseCache.ReadFromFile(BaseConst().ParseCacheFile);
  1975. }
  1976. }
  1977. bool cmQtAutoMocUic::ParseCacheWrite()
  1978. {
  1979. if (BaseEval().ParseCacheChanged) {
  1980. if (Log().Verbose()) {
  1981. Log().Info(GenT::GEN,
  1982. cmStrCat("Writing the parse cache file ",
  1983. MessagePath(BaseConst().ParseCacheFile)));
  1984. }
  1985. if (!BaseEval().ParseCache.WriteToFile(BaseConst().ParseCacheFile)) {
  1986. Log().Error(GenT::GEN,
  1987. cmStrCat("Writing the parse cache file ",
  1988. MessagePath(BaseConst().ParseCacheFile),
  1989. " failed."));
  1990. return false;
  1991. }
  1992. }
  1993. return true;
  1994. }
  1995. bool cmQtAutoMocUic::CreateDirectories()
  1996. {
  1997. // Create AUTOGEN include directory
  1998. if (!cmSystemTools::MakeDirectory(BaseConst().AutogenIncludeDir)) {
  1999. Log().Error(GenT::GEN,
  2000. cmStrCat("Creating the AUTOGEN include directory ",
  2001. MessagePath(BaseConst().AutogenIncludeDir),
  2002. " failed."));
  2003. return false;
  2004. }
  2005. return true;
  2006. }
  2007. void cmQtAutoMocUic::Abort(bool error)
  2008. {
  2009. if (error) {
  2010. JobError_.store(true);
  2011. }
  2012. WorkerPool_.Abort();
  2013. }
  2014. std::string cmQtAutoMocUic::AbsoluteBuildPath(
  2015. cm::string_view relativePath) const
  2016. {
  2017. return cmStrCat(BaseConst().AutogenBuildDir, '/', relativePath);
  2018. }
  2019. std::string cmQtAutoMocUic::AbsoluteIncludePath(
  2020. cm::string_view relativePath) const
  2021. {
  2022. return cmStrCat(BaseConst().AutogenIncludeDir, '/', relativePath);
  2023. }