cmQtAutoMocUic.cxx 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106
  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 <algorithm>
  5. #include <atomic>
  6. #include <cstddef>
  7. #include <limits>
  8. #include <map>
  9. #include <set>
  10. #include <string>
  11. #include <unordered_map>
  12. #include <unordered_set>
  13. #include <utility>
  14. #include <vector>
  15. #include <cm/memory>
  16. #include <cm/optional>
  17. #include <cm/string_view>
  18. #include <cmext/algorithm>
  19. #include <cm3p/json/value.h>
  20. #include "cmsys/FStream.hxx"
  21. #include "cmsys/RegularExpression.hxx"
  22. #include "cmCryptoHash.h"
  23. #include "cmFileTime.h"
  24. #include "cmGccDepfileReader.h"
  25. #include "cmGccDepfileReaderTypes.h"
  26. #include "cmGeneratedFileStream.h"
  27. #include "cmQtAutoGen.h"
  28. #include "cmQtAutoGenerator.h"
  29. #include "cmStringAlgorithms.h"
  30. #include "cmSystemTools.h"
  31. #include "cmWorkerPool.h"
  32. #if defined(__APPLE__)
  33. # include <unistd.h>
  34. #endif
  35. namespace {
  36. constexpr std::size_t MocUnderscoreLength = 4; // Length of "moc_"
  37. constexpr std::size_t UiUnderscoreLength = 3; // Length of "ui_"
  38. /** \class cmQtAutoMocUicT
  39. * \brief AUTOMOC and AUTOUIC generator
  40. */
  41. class cmQtAutoMocUicT : public cmQtAutoGenerator
  42. {
  43. public:
  44. cmQtAutoMocUicT();
  45. ~cmQtAutoMocUicT() override;
  46. cmQtAutoMocUicT(cmQtAutoMocUicT const&) = delete;
  47. cmQtAutoMocUicT& operator=(cmQtAutoMocUicT const&) = delete;
  48. // -- Types
  49. /** Include string with sub parts. */
  50. struct IncludeKeyT
  51. {
  52. IncludeKeyT(std::string const& key, std::size_t basePrefixLength);
  53. std::string Key; // Full include string
  54. std::string Dir; // Include directory
  55. std::string Base; // Base part of the include file name
  56. };
  57. /** Search key plus regular expression pair. */
  58. struct KeyExpT
  59. {
  60. KeyExpT(std::string key, std::string const& exp)
  61. : Key(std::move(key))
  62. , Exp(exp)
  63. {
  64. }
  65. std::string Key;
  66. cmsys::RegularExpression Exp;
  67. };
  68. /** Source file parsing cache. */
  69. class ParseCacheT
  70. {
  71. public:
  72. // -- Types
  73. /** Entry of the file parsing cache. */
  74. struct FileT
  75. {
  76. void Clear();
  77. struct MocT
  78. {
  79. std::string Macro;
  80. struct IncludeT
  81. {
  82. std::vector<IncludeKeyT> Underscore;
  83. std::vector<IncludeKeyT> Dot;
  84. } Include;
  85. std::vector<std::string> Depends;
  86. } Moc;
  87. struct UicT
  88. {
  89. std::vector<IncludeKeyT> Include;
  90. std::vector<std::string> Depends;
  91. } Uic;
  92. };
  93. using FileHandleT = std::shared_ptr<FileT>;
  94. using GetOrInsertT = std::pair<FileHandleT, bool>;
  95. ParseCacheT();
  96. ~ParseCacheT();
  97. bool ReadFromFile(std::string const& fileName);
  98. bool WriteToFile(std::string const& fileName);
  99. //! Always returns a valid handle
  100. GetOrInsertT GetOrInsert(std::string const& fileName);
  101. private:
  102. std::unordered_map<std::string, FileHandleT> Map_;
  103. };
  104. /** Source file data. */
  105. class SourceFileT
  106. {
  107. public:
  108. SourceFileT(std::string fileName)
  109. : FileName(std::move(fileName))
  110. {
  111. }
  112. std::string FileName;
  113. cmFileTime FileTime;
  114. ParseCacheT::FileHandleT ParseData;
  115. std::string BuildPath;
  116. bool IsHeader = false;
  117. bool Moc = false;
  118. bool Uic = false;
  119. };
  120. using SourceFileHandleT = std::shared_ptr<SourceFileT>;
  121. using SourceFileMapT = std::map<std::string, SourceFileHandleT>;
  122. /** Meta compiler file mapping information. */
  123. struct MappingT
  124. {
  125. SourceFileHandleT SourceFile;
  126. std::string OutputFile;
  127. std::string IncludeString;
  128. std::vector<SourceFileHandleT> IncluderFiles;
  129. };
  130. using MappingHandleT = std::shared_ptr<MappingT>;
  131. using MappingMapT = std::map<std::string, MappingHandleT>;
  132. /** Common settings. */
  133. class BaseSettingsT
  134. {
  135. public:
  136. // -- Constructors
  137. BaseSettingsT();
  138. ~BaseSettingsT();
  139. BaseSettingsT(BaseSettingsT const&) = delete;
  140. BaseSettingsT& operator=(BaseSettingsT const&) = delete;
  141. // -- Attributes
  142. // - Config
  143. bool MultiConfig = false;
  144. bool CrossConfig = false;
  145. bool UseBetterGraph = false;
  146. IntegerVersion QtVersion = { 4, 0 };
  147. unsigned int ThreadCount = 0;
  148. unsigned int MaxCommandLineLength =
  149. std::numeric_limits<unsigned int>::max();
  150. // - Directories
  151. std::string AutogenBuildDir;
  152. std::string AutogenIncludeDir;
  153. // - Files
  154. std::string CMakeExecutable;
  155. cmFileTime CMakeExecutableTime;
  156. std::string ParseCacheFile;
  157. std::string DepFile;
  158. std::string DepFileRuleName;
  159. std::vector<std::string> HeaderExtensions;
  160. std::vector<std::string> ListFiles;
  161. };
  162. /** Shared common variables. */
  163. class BaseEvalT
  164. {
  165. public:
  166. // -- Parse Cache
  167. std::atomic<bool> ParseCacheChanged{ false };
  168. cmFileTime ParseCacheTime;
  169. ParseCacheT ParseCache;
  170. // -- Sources
  171. SourceFileMapT Headers;
  172. SourceFileMapT Sources;
  173. };
  174. /** Moc settings. */
  175. class MocSettingsT
  176. {
  177. public:
  178. // -- Constructors
  179. MocSettingsT();
  180. ~MocSettingsT();
  181. MocSettingsT(MocSettingsT const&) = delete;
  182. MocSettingsT& operator=(MocSettingsT const&) = delete;
  183. // -- Const methods
  184. bool skipped(std::string const& fileName) const;
  185. std::string MacrosString() const;
  186. // -- Attributes
  187. bool Enabled = false;
  188. bool SettingsChanged = false;
  189. bool RelaxedMode = false;
  190. bool PathPrefix = false;
  191. bool CanOutputDependencies = false;
  192. cmFileTime ExecutableTime;
  193. std::string Executable;
  194. std::string CompFileAbs;
  195. std::string PredefsFileAbs;
  196. std::unordered_set<std::string> SkipList;
  197. std::vector<std::string> IncludePaths;
  198. std::vector<std::string> Definitions;
  199. std::vector<std::string> OptionsIncludes;
  200. std::vector<std::string> OptionsDefinitions;
  201. std::vector<std::string> OptionsExtra;
  202. std::vector<std::string> PredefsCmd;
  203. std::vector<KeyExpT> DependFilters;
  204. std::vector<KeyExpT> MacroFilters;
  205. cmsys::RegularExpression RegExpInclude;
  206. };
  207. /** Moc shared variables. */
  208. class MocEvalT
  209. {
  210. public:
  211. // -- predefines file
  212. cmFileTime PredefsTime;
  213. // -- Mappings
  214. MappingMapT HeaderMappings;
  215. MappingMapT SourceMappings;
  216. MappingMapT Includes;
  217. // -- Discovered files
  218. SourceFileMapT HeadersDiscovered;
  219. // -- Output directories
  220. std::unordered_set<std::string> OutputDirs;
  221. // -- Mocs compilation
  222. bool CompUpdated = false;
  223. std::vector<std::string> CompFiles;
  224. };
  225. /** Uic settings. */
  226. class UicSettingsT
  227. {
  228. public:
  229. struct UiFile
  230. {
  231. std::vector<std::string> Options;
  232. };
  233. UicSettingsT();
  234. ~UicSettingsT();
  235. UicSettingsT(UicSettingsT const&) = delete;
  236. UicSettingsT& operator=(UicSettingsT const&) = delete;
  237. // -- Const methods
  238. bool skipped(std::string const& fileName) const;
  239. // -- Attributes
  240. bool Enabled = false;
  241. bool SettingsChanged = false;
  242. cmFileTime ExecutableTime;
  243. std::string Executable;
  244. std::unordered_set<std::string> SkipList;
  245. std::vector<std::string> Options;
  246. std::unordered_map<std::string, UiFile> UiFiles;
  247. std::vector<std::string> SearchPaths;
  248. cmsys::RegularExpression RegExpInclude;
  249. };
  250. /** Uic shared variables. */
  251. class UicEvalT
  252. {
  253. public:
  254. // -- Discovered files
  255. SourceFileMapT UiFiles;
  256. // -- Mappings
  257. MappingMapT Includes;
  258. // -- Output directories
  259. std::unordered_set<std::string> OutputDirs;
  260. };
  261. /** Abstract job class for concurrent job processing. */
  262. class JobT : public cmWorkerPool::JobT
  263. {
  264. protected:
  265. /** Protected default constructor. */
  266. JobT(bool fence = false)
  267. : cmWorkerPool::JobT(fence)
  268. {
  269. }
  270. //! Get the generator. Only valid during Process() call!
  271. cmQtAutoMocUicT* Gen() const
  272. {
  273. return static_cast<cmQtAutoMocUicT*>(this->UserData());
  274. }
  275. // -- Accessors. Only valid during Process() call!
  276. Logger const& Log() const { return this->Gen()->Log(); }
  277. BaseSettingsT const& BaseConst() const { return this->Gen()->BaseConst(); }
  278. BaseEvalT& BaseEval() const { return this->Gen()->BaseEval(); }
  279. MocSettingsT const& MocConst() const { return this->Gen()->MocConst(); }
  280. MocEvalT& MocEval() const { return this->Gen()->MocEval(); }
  281. UicSettingsT const& UicConst() const { return this->Gen()->UicConst(); }
  282. UicEvalT& UicEval() const { return this->Gen()->UicEval(); }
  283. // -- Logging
  284. std::string MessagePath(cm::string_view path) const
  285. {
  286. return this->Gen()->MessagePath(path);
  287. }
  288. // - Error logging with automatic abort
  289. void LogError(GenT genType, cm::string_view message) const;
  290. void LogCommandError(GenT genType, cm::string_view message,
  291. std::vector<std::string> const& command,
  292. std::string const& output) const;
  293. /*
  294. * Check if command line exceeds maximum length supported by OS
  295. * (if on Windows) and switch to using a response file instead.
  296. */
  297. void MaybeWriteResponseFile(std::string const& outputFile,
  298. std::vector<std::string>& cmd) const;
  299. /** @brief Run an external process. Use only during Process() call! */
  300. bool RunProcess(GenT genType, cmWorkerPool::ProcessResultT& result,
  301. std::vector<std::string> const& command,
  302. std::string* infoMessage = nullptr);
  303. };
  304. /** Fence job utility class. */
  305. class JobFenceT : public JobT
  306. {
  307. public:
  308. JobFenceT()
  309. : JobT(true)
  310. {
  311. }
  312. void Process() override {}
  313. };
  314. /** Generate moc_predefs.h. */
  315. class JobMocPredefsT : public JobFenceT
  316. {
  317. void Process() override;
  318. bool Update(std::string* reason) const;
  319. };
  320. /** File parse job base class. */
  321. class JobParseT : public JobT
  322. {
  323. public:
  324. JobParseT(SourceFileHandleT fileHandle)
  325. : FileHandle(std::move(fileHandle))
  326. {
  327. }
  328. protected:
  329. bool ReadFile();
  330. void CreateKeys(std::vector<IncludeKeyT>& container,
  331. std::set<std::string> const& source,
  332. std::size_t basePrefixLength);
  333. void MocMacro();
  334. void MocDependencies();
  335. void MocIncludes();
  336. void UicIncludes();
  337. SourceFileHandleT FileHandle;
  338. std::string Content;
  339. };
  340. /** Header file parse job. */
  341. class JobParseHeaderT : public JobParseT
  342. {
  343. public:
  344. using JobParseT::JobParseT;
  345. void Process() override;
  346. };
  347. /** Source file parse job. */
  348. class JobParseSourceT : public JobParseT
  349. {
  350. public:
  351. using JobParseT::JobParseT;
  352. void Process() override;
  353. };
  354. /** Evaluate cached file parse data - moc. */
  355. class JobEvalCacheT : public JobT
  356. {
  357. protected:
  358. std::string MessageSearchLocations() const;
  359. std::vector<std::string> SearchLocations;
  360. };
  361. /** Evaluate cached file parse data - moc. */
  362. class JobEvalCacheMocT : public JobEvalCacheT
  363. {
  364. void Process() override;
  365. bool EvalHeader(SourceFileHandleT source);
  366. bool EvalSource(SourceFileHandleT const& source);
  367. bool FindIncludedHeader(SourceFileHandleT& headerHandle,
  368. cm::string_view includerDir,
  369. cm::string_view includeBase);
  370. bool RegisterIncluded(std::string const& includeString,
  371. SourceFileHandleT includerFileHandle,
  372. SourceFileHandleT sourceFileHandle) const;
  373. void RegisterMapping(MappingHandleT mappingHandle) const;
  374. std::string MessageHeader(cm::string_view headerBase) const;
  375. };
  376. /** Evaluate cached file parse data - uic. */
  377. class JobEvalCacheUicT : public JobEvalCacheT
  378. {
  379. void Process() override;
  380. bool EvalFile(SourceFileHandleT const& sourceFileHandle);
  381. bool FindIncludedUi(cm::string_view sourceDirPrefix,
  382. cm::string_view includePrefix);
  383. bool RegisterMapping(std::string const& includeString,
  384. SourceFileHandleT includerFileHandle);
  385. std::string UiName;
  386. SourceFileHandleT UiFileHandle;
  387. };
  388. /** Evaluate cached file parse data - finish */
  389. class JobEvalCacheFinishT : public JobFenceT
  390. {
  391. void Process() override;
  392. };
  393. /** Dependency probing base job. */
  394. class JobProbeDepsT : public JobT
  395. {
  396. };
  397. /** Probes file dependencies and generates moc compile jobs. */
  398. class JobProbeDepsMocT : public JobProbeDepsT
  399. {
  400. void Process() override;
  401. bool Generate(MappingHandleT const& mapping, bool compFile) const;
  402. bool Probe(MappingT const& mapping, std::string* reason) const;
  403. std::pair<std::string, cmFileTime> FindDependency(
  404. std::string const& sourceDir, std::string const& includeString) const;
  405. };
  406. /** Probes file dependencies and generates uic compile jobs. */
  407. class JobProbeDepsUicT : public JobProbeDepsT
  408. {
  409. void Process() override;
  410. bool Probe(MappingT const& mapping, std::string* reason) const;
  411. };
  412. /** Dependency probing finish job. */
  413. class JobProbeDepsFinishT : public JobFenceT
  414. {
  415. void Process() override;
  416. };
  417. /** Meta compiler base job. */
  418. class JobCompileT : public JobT
  419. {
  420. public:
  421. JobCompileT(MappingHandleT uicMapping, std::unique_ptr<std::string> reason)
  422. : Mapping(std::move(uicMapping))
  423. , Reason(std::move(reason))
  424. {
  425. }
  426. protected:
  427. MappingHandleT Mapping;
  428. std::unique_ptr<std::string> Reason;
  429. };
  430. /** moc compiles a file. */
  431. class JobCompileMocT : public JobCompileT
  432. {
  433. public:
  434. JobCompileMocT(MappingHandleT uicMapping,
  435. std::unique_ptr<std::string> reason,
  436. ParseCacheT::FileHandleT cacheEntry)
  437. : JobCompileT(std::move(uicMapping), std::move(reason))
  438. , CacheEntry(std::move(cacheEntry))
  439. {
  440. }
  441. void Process() override;
  442. protected:
  443. ParseCacheT::FileHandleT CacheEntry;
  444. };
  445. /** uic compiles a file. */
  446. class JobCompileUicT : public JobCompileT
  447. {
  448. public:
  449. using JobCompileT::JobCompileT;
  450. void Process() override;
  451. };
  452. /** Generate mocs_compilation.cpp. */
  453. class JobMocsCompilationT : public JobFenceT
  454. {
  455. private:
  456. void Process() override;
  457. };
  458. class JobDepFilesMergeT : public JobFenceT
  459. {
  460. private:
  461. std::vector<std::string> initialDependencies() const;
  462. void Process() override;
  463. };
  464. /** @brief The last job. */
  465. class JobFinishT : public JobFenceT
  466. {
  467. private:
  468. void Process() override;
  469. };
  470. // -- Const settings interface
  471. BaseSettingsT const& BaseConst() const { return this->BaseConst_; }
  472. BaseEvalT& BaseEval() { return this->BaseEval_; }
  473. MocSettingsT const& MocConst() const { return this->MocConst_; }
  474. MocEvalT& MocEval() { return this->MocEval_; }
  475. UicSettingsT const& UicConst() const { return this->UicConst_; }
  476. UicEvalT& UicEval() { return this->UicEval_; }
  477. // -- Parallel job processing interface
  478. cmWorkerPool& WorkerPool() { return this->WorkerPool_; }
  479. void AbortError() { this->Abort(true); }
  480. void AbortSuccess() { this->Abort(false); }
  481. // -- Utility
  482. std::string AbsoluteBuildPath(cm::string_view relativePath) const;
  483. std::string AbsoluteIncludePath(cm::string_view relativePath) const;
  484. template <class JOBTYPE>
  485. void CreateParseJobs(SourceFileMapT const& sourceMap);
  486. private:
  487. // -- Abstract processing interface
  488. bool InitFromInfo(InfoT const& info) override;
  489. void InitJobs();
  490. bool Process() override;
  491. // -- Settings file
  492. void SettingsFileRead();
  493. bool SettingsFileWrite();
  494. // -- Parse cache
  495. void ParseCacheRead();
  496. bool ParseCacheWrite();
  497. // -- Thread processing
  498. void Abort(bool error);
  499. // -- Generation
  500. bool CreateDirectories();
  501. // -- Support for depfiles
  502. std::vector<std::string> dependenciesFromDepFile(char const* filePath);
  503. // -- Settings
  504. BaseSettingsT BaseConst_;
  505. BaseEvalT BaseEval_;
  506. MocSettingsT MocConst_;
  507. MocEvalT MocEval_;
  508. UicSettingsT UicConst_;
  509. UicEvalT UicEval_;
  510. // -- Settings file
  511. std::string SettingsFile_;
  512. std::string SettingsStringMoc_;
  513. std::string SettingsStringUic_;
  514. // -- Worker thread pool
  515. std::atomic<bool> JobError_{ false };
  516. cmWorkerPool WorkerPool_;
  517. };
  518. cmQtAutoMocUicT::IncludeKeyT::IncludeKeyT(std::string const& key,
  519. std::size_t basePrefixLength)
  520. : Key(key)
  521. , Dir(SubDirPrefix(key))
  522. , Base(cmSystemTools::GetFilenameWithoutLastExtension(key))
  523. {
  524. if (basePrefixLength != 0) {
  525. this->Base = this->Base.substr(basePrefixLength);
  526. }
  527. }
  528. void cmQtAutoMocUicT::ParseCacheT::FileT::Clear()
  529. {
  530. this->Moc.Macro.clear();
  531. this->Moc.Include.Underscore.clear();
  532. this->Moc.Include.Dot.clear();
  533. this->Moc.Depends.clear();
  534. this->Uic.Include.clear();
  535. this->Uic.Depends.clear();
  536. }
  537. cmQtAutoMocUicT::ParseCacheT::GetOrInsertT
  538. cmQtAutoMocUicT::ParseCacheT::GetOrInsert(std::string const& fileName)
  539. {
  540. // Find existing entry
  541. {
  542. auto it = this->Map_.find(fileName);
  543. if (it != this->Map_.end()) {
  544. return GetOrInsertT{ it->second, false };
  545. }
  546. }
  547. // Insert new entry
  548. return GetOrInsertT{
  549. this->Map_.emplace(fileName, std::make_shared<FileT>()).first->second, true
  550. };
  551. }
  552. cmQtAutoMocUicT::ParseCacheT::ParseCacheT() = default;
  553. cmQtAutoMocUicT::ParseCacheT::~ParseCacheT() = default;
  554. bool cmQtAutoMocUicT::ParseCacheT::ReadFromFile(std::string const& fileName)
  555. {
  556. cmsys::ifstream fin(fileName.c_str());
  557. if (!fin) {
  558. return false;
  559. }
  560. FileHandleT fileHandle;
  561. std::string line;
  562. while (std::getline(fin, line)) {
  563. // Check if this an empty or a comment line
  564. if (line.empty() || line.front() == '#') {
  565. continue;
  566. }
  567. // Drop carriage return character at the end
  568. if (line.back() == '\r') {
  569. line.pop_back();
  570. if (line.empty()) {
  571. continue;
  572. }
  573. }
  574. // Check if this a file name line
  575. if (line.front() != ' ') {
  576. fileHandle = this->GetOrInsert(line).first;
  577. continue;
  578. }
  579. // Bad line or bad file handle
  580. if (!fileHandle || (line.size() < 6)) {
  581. continue;
  582. }
  583. constexpr std::size_t offset = 5;
  584. if (cmHasLiteralPrefix(line, " mmc:")) {
  585. fileHandle->Moc.Macro = line.substr(offset);
  586. continue;
  587. }
  588. if (cmHasLiteralPrefix(line, " miu:")) {
  589. fileHandle->Moc.Include.Underscore.emplace_back(line.substr(offset),
  590. MocUnderscoreLength);
  591. continue;
  592. }
  593. if (cmHasLiteralPrefix(line, " mid:")) {
  594. fileHandle->Moc.Include.Dot.emplace_back(line.substr(offset), 0);
  595. continue;
  596. }
  597. if (cmHasLiteralPrefix(line, " mdp:")) {
  598. fileHandle->Moc.Depends.emplace_back(line.substr(offset));
  599. continue;
  600. }
  601. if (cmHasLiteralPrefix(line, " uic:")) {
  602. fileHandle->Uic.Include.emplace_back(line.substr(offset),
  603. UiUnderscoreLength);
  604. continue;
  605. }
  606. if (cmHasLiteralPrefix(line, " udp:")) {
  607. fileHandle->Uic.Depends.emplace_back(line.substr(offset));
  608. continue;
  609. }
  610. }
  611. return true;
  612. }
  613. bool cmQtAutoMocUicT::ParseCacheT::WriteToFile(std::string const& fileName)
  614. {
  615. cmGeneratedFileStream ofs(fileName);
  616. if (!ofs) {
  617. return false;
  618. }
  619. ofs << "# Generated by CMake. Changes will be overwritten.\n";
  620. for (auto const& pair : this->Map_) {
  621. ofs << pair.first << '\n';
  622. FileT const& file = *pair.second;
  623. if (!file.Moc.Macro.empty()) {
  624. ofs << " mmc:" << file.Moc.Macro << '\n';
  625. }
  626. for (IncludeKeyT const& item : file.Moc.Include.Underscore) {
  627. ofs << " miu:" << item.Key << '\n';
  628. }
  629. for (IncludeKeyT const& item : file.Moc.Include.Dot) {
  630. ofs << " mid:" << item.Key << '\n';
  631. }
  632. for (std::string const& item : file.Moc.Depends) {
  633. ofs << " mdp:" << item << '\n';
  634. }
  635. for (IncludeKeyT const& item : file.Uic.Include) {
  636. ofs << " uic:" << item.Key << '\n';
  637. }
  638. for (std::string const& item : file.Uic.Depends) {
  639. ofs << " udp:" << item << '\n';
  640. }
  641. }
  642. return ofs.Close();
  643. }
  644. cmQtAutoMocUicT::BaseSettingsT::BaseSettingsT() = default;
  645. cmQtAutoMocUicT::BaseSettingsT::~BaseSettingsT() = default;
  646. cmQtAutoMocUicT::MocSettingsT::MocSettingsT()
  647. {
  648. this->RegExpInclude.compile(
  649. "(^|\n)[ \t]*#[ \t]*include[ \t]+"
  650. "[\"<](([^ \">]+/)?moc_[^ \">/]+\\.cpp|[^ \">]+\\.moc)[\">]");
  651. }
  652. cmQtAutoMocUicT::MocSettingsT::~MocSettingsT() = default;
  653. bool cmQtAutoMocUicT::MocSettingsT::skipped(std::string const& fileName) const
  654. {
  655. return (!this->Enabled ||
  656. (this->SkipList.find(fileName) != this->SkipList.end()));
  657. }
  658. std::string cmQtAutoMocUicT::MocSettingsT::MacrosString() const
  659. {
  660. std::string res;
  661. auto const itB = this->MacroFilters.cbegin();
  662. auto const itE = this->MacroFilters.cend();
  663. auto const itL = itE - 1;
  664. auto itC = itB;
  665. for (; itC != itE; ++itC) {
  666. // Separator
  667. if (itC != itB) {
  668. if (itC != itL) {
  669. res += ", ";
  670. } else {
  671. res += " or ";
  672. }
  673. }
  674. // Key
  675. res += itC->Key;
  676. }
  677. return res;
  678. }
  679. cmQtAutoMocUicT::UicSettingsT::UicSettingsT()
  680. {
  681. this->RegExpInclude.compile("(^|\n)[ \t]*#[ \t]*include[ \t]+"
  682. "[\"<](([^ \">]+/)?ui_[^ \">/]+\\.h)[\">]");
  683. }
  684. cmQtAutoMocUicT::UicSettingsT::~UicSettingsT() = default;
  685. bool cmQtAutoMocUicT::UicSettingsT::skipped(std::string const& fileName) const
  686. {
  687. return (!this->Enabled ||
  688. (this->SkipList.find(fileName) != this->SkipList.end()));
  689. }
  690. void cmQtAutoMocUicT::JobT::LogError(GenT genType,
  691. cm::string_view message) const
  692. {
  693. this->Gen()->AbortError();
  694. this->Gen()->Log().Error(genType, message);
  695. }
  696. void cmQtAutoMocUicT::JobT::LogCommandError(
  697. GenT genType, cm::string_view message,
  698. std::vector<std::string> const& command, std::string const& output) const
  699. {
  700. this->Gen()->AbortError();
  701. this->Gen()->Log().ErrorCommand(genType, message, command, output);
  702. }
  703. /*
  704. * Check if command line exceeds maximum length supported by OS
  705. * (if on Windows) and switch to using a response file instead.
  706. */
  707. void cmQtAutoMocUicT::JobT::MaybeWriteResponseFile(
  708. std::string const& outputFile, std::vector<std::string>& cmd) const
  709. {
  710. #ifdef _WIN32
  711. // Ensure cmd is less than CommandLineLengthMax characters
  712. size_t commandLineLength = cmd.size(); // account for separating spaces
  713. for (std::string const& str : cmd) {
  714. commandLineLength += str.length();
  715. }
  716. if (commandLineLength >= this->BaseConst().MaxCommandLineLength) {
  717. // Command line exceeds maximum size allowed by OS
  718. // => create response file
  719. std::string const responseFile = cmStrCat(outputFile, ".rsp");
  720. cmsys::ofstream fout(responseFile.c_str());
  721. if (!fout) {
  722. this->LogError(
  723. GenT::MOC,
  724. cmStrCat("AUTOMOC was unable to create a response file at\n ",
  725. this->MessagePath(responseFile)));
  726. return;
  727. }
  728. auto it = cmd.begin();
  729. while (++it != cmd.end()) {
  730. fout << *it << "\n";
  731. }
  732. fout.close();
  733. // Keep all but executable
  734. cmd.resize(1);
  735. // Specify response file
  736. cmd.emplace_back(cmStrCat('@', responseFile));
  737. }
  738. #else
  739. static_cast<void>(outputFile);
  740. static_cast<void>(cmd);
  741. #endif
  742. }
  743. bool cmQtAutoMocUicT::JobT::RunProcess(GenT genType,
  744. cmWorkerPool::ProcessResultT& result,
  745. std::vector<std::string> const& command,
  746. std::string* infoMessage)
  747. {
  748. // Log command
  749. if (this->Log().Verbose()) {
  750. cm::string_view info;
  751. if (infoMessage) {
  752. info = *infoMessage;
  753. }
  754. this->Log().Info(
  755. genType,
  756. cmStrCat(info, info.empty() || cmHasSuffix(info, '\n') ? "" : "\n",
  757. QuotedCommand(command), '\n'));
  758. }
  759. // Run command
  760. return this->cmWorkerPool::JobT::RunProcess(
  761. result, command, this->BaseConst().AutogenBuildDir);
  762. }
  763. void cmQtAutoMocUicT::JobMocPredefsT::Process()
  764. {
  765. // (Re)generate moc_predefs.h on demand
  766. std::unique_ptr<std::string> reason;
  767. if (this->Log().Verbose()) {
  768. reason = cm::make_unique<std::string>();
  769. }
  770. if (!this->Update(reason.get())) {
  771. return;
  772. }
  773. std::string const& predefsFileAbs = this->MocConst().PredefsFileAbs;
  774. {
  775. cmWorkerPool::ProcessResultT result;
  776. {
  777. // Compose command
  778. std::vector<std::string> cmd = this->MocConst().PredefsCmd;
  779. // Add definitions
  780. cm::append(cmd, this->MocConst().OptionsDefinitions);
  781. // Add includes
  782. cm::append(cmd, this->MocConst().OptionsIncludes);
  783. // Check if response file is necessary
  784. MaybeWriteResponseFile(this->MocConst().PredefsFileAbs, cmd);
  785. cmSystemTools::MaybePrependCmdExe(cmd);
  786. // Execute command
  787. if (!this->RunProcess(GenT::MOC, result, cmd, reason.get())) {
  788. this->LogCommandError(GenT::MOC,
  789. cmStrCat("The content generation command for ",
  790. this->MessagePath(predefsFileAbs),
  791. " failed.\n", result.ErrorMessage),
  792. cmd, result.StdOut);
  793. return;
  794. }
  795. }
  796. // (Re)write predefs file only on demand
  797. if (cmQtAutoGenerator::FileDiffers(predefsFileAbs, result.StdOut)) {
  798. if (!cmQtAutoGenerator::FileWrite(predefsFileAbs, result.StdOut)) {
  799. this->LogError(
  800. GenT::MOC,
  801. cmStrCat("Writing ", this->MessagePath(predefsFileAbs), " failed."));
  802. return;
  803. }
  804. } else {
  805. // Touch to update the time stamp
  806. if (this->Log().Verbose()) {
  807. this->Log().Info(GenT::MOC,
  808. "Touching " + this->MessagePath(predefsFileAbs));
  809. }
  810. if (!cmSystemTools::Touch(predefsFileAbs, false)) {
  811. this->LogError(GenT::MOC,
  812. cmStrCat("Touching ", this->MessagePath(predefsFileAbs),
  813. " failed."));
  814. return;
  815. }
  816. }
  817. }
  818. // Read file time afterwards
  819. if (!this->MocEval().PredefsTime.Load(predefsFileAbs)) {
  820. this->LogError(GenT::MOC,
  821. cmStrCat("Reading the file time of ",
  822. this->MessagePath(predefsFileAbs), " failed."));
  823. return;
  824. }
  825. }
  826. bool cmQtAutoMocUicT::JobMocPredefsT::Update(std::string* reason) const
  827. {
  828. // Test if the file exists
  829. if (!this->MocEval().PredefsTime.Load(this->MocConst().PredefsFileAbs)) {
  830. if (reason) {
  831. *reason = cmStrCat("Generating ",
  832. this->MessagePath(this->MocConst().PredefsFileAbs),
  833. ", because it doesn't exist.");
  834. }
  835. return true;
  836. }
  837. // Test if the settings changed
  838. if (this->MocConst().SettingsChanged) {
  839. if (reason) {
  840. *reason = cmStrCat("Generating ",
  841. this->MessagePath(this->MocConst().PredefsFileAbs),
  842. ", because the moc settings changed.");
  843. }
  844. return true;
  845. }
  846. // Test if the executable is newer
  847. {
  848. std::string const& exec = this->MocConst().PredefsCmd.at(0);
  849. cmFileTime execTime;
  850. if (execTime.Load(exec)) {
  851. if (this->MocEval().PredefsTime.Older(execTime)) {
  852. if (reason) {
  853. *reason = cmStrCat(
  854. "Generating ", this->MessagePath(this->MocConst().PredefsFileAbs),
  855. " because it is older than ", this->MessagePath(exec), '.');
  856. }
  857. return true;
  858. }
  859. }
  860. }
  861. return false;
  862. }
  863. bool cmQtAutoMocUicT::JobParseT::ReadFile()
  864. {
  865. // Clear old parse information
  866. this->FileHandle->ParseData->Clear();
  867. std::string const& fileName = this->FileHandle->FileName;
  868. // Write info
  869. if (this->Log().Verbose()) {
  870. this->Log().Info(GenT::GEN,
  871. cmStrCat("Parsing ", this->MessagePath(fileName)));
  872. }
  873. // Read file content
  874. {
  875. std::string error;
  876. if (!cmQtAutoGenerator::FileRead(this->Content, fileName, &error)) {
  877. this->LogError(GenT::GEN,
  878. cmStrCat("Could not read ", this->MessagePath(fileName),
  879. ".\n", error));
  880. return false;
  881. }
  882. }
  883. // Warn if empty
  884. if (this->Content.empty()) {
  885. this->Log().Warning(GenT::GEN,
  886. cmStrCat(this->MessagePath(fileName), " is empty."));
  887. return false;
  888. }
  889. return true;
  890. }
  891. void cmQtAutoMocUicT::JobParseT::CreateKeys(
  892. std::vector<IncludeKeyT>& container, std::set<std::string> const& source,
  893. std::size_t basePrefixLength)
  894. {
  895. if (source.empty()) {
  896. return;
  897. }
  898. container.reserve(source.size());
  899. for (std::string const& src : source) {
  900. container.emplace_back(src, basePrefixLength);
  901. }
  902. }
  903. void cmQtAutoMocUicT::JobParseT::MocMacro()
  904. {
  905. for (KeyExpT const& filter : this->MocConst().MacroFilters) {
  906. // Run a simple find string check
  907. if (this->Content.find(filter.Key) == std::string::npos) {
  908. continue;
  909. }
  910. // Run the expensive regular expression check loop
  911. cmsys::RegularExpressionMatch match;
  912. if (filter.Exp.find(this->Content.c_str(), match)) {
  913. // Keep detected macro name
  914. this->FileHandle->ParseData->Moc.Macro = filter.Key;
  915. return;
  916. }
  917. }
  918. }
  919. void cmQtAutoMocUicT::JobParseT::MocDependencies()
  920. {
  921. if (this->MocConst().DependFilters.empty() ||
  922. this->MocConst().CanOutputDependencies) {
  923. return;
  924. }
  925. // Find dependency strings
  926. std::set<std::string> parseDepends;
  927. for (KeyExpT const& filter : this->MocConst().DependFilters) {
  928. // Run a simple find string check
  929. if (this->Content.find(filter.Key) == std::string::npos) {
  930. continue;
  931. }
  932. // Run the expensive regular expression check loop
  933. char const* contentChars = this->Content.c_str();
  934. cmsys::RegularExpressionMatch match;
  935. while (filter.Exp.find(contentChars, match)) {
  936. {
  937. std::string dep = match.match(1);
  938. if (!dep.empty()) {
  939. parseDepends.emplace(std::move(dep));
  940. }
  941. }
  942. contentChars += match.end();
  943. }
  944. }
  945. // Store dependency strings
  946. {
  947. auto& Depends = this->FileHandle->ParseData->Moc.Depends;
  948. Depends.reserve(parseDepends.size());
  949. for (std::string const& item : parseDepends) {
  950. Depends.emplace_back(item);
  951. // Replace end of line characters in filenames
  952. std::string& path = Depends.back();
  953. std::replace(path.begin(), path.end(), '\n', ' ');
  954. std::replace(path.begin(), path.end(), '\r', ' ');
  955. }
  956. }
  957. }
  958. void cmQtAutoMocUicT::JobParseT::MocIncludes()
  959. {
  960. if (this->Content.find("moc") == std::string::npos) {
  961. return;
  962. }
  963. std::set<std::string> underscore;
  964. std::set<std::string> dot;
  965. {
  966. char const* contentChars = this->Content.c_str();
  967. cmsys::RegularExpression const& regExp = this->MocConst().RegExpInclude;
  968. cmsys::RegularExpressionMatch match;
  969. while (regExp.find(contentChars, match)) {
  970. std::string incString = match.match(2);
  971. std::string const incBase =
  972. cmSystemTools::GetFilenameWithoutLastExtension(incString);
  973. if (cmHasLiteralPrefix(incBase, "moc_")) {
  974. // moc_<BASE>.cpp
  975. // Remove the moc_ part from the base name
  976. underscore.emplace(std::move(incString));
  977. } else {
  978. // <BASE>.moc
  979. dot.emplace(std::move(incString));
  980. }
  981. // Forward content pointer
  982. contentChars += match.end();
  983. }
  984. }
  985. auto& Include = this->FileHandle->ParseData->Moc.Include;
  986. this->CreateKeys(Include.Underscore, underscore, MocUnderscoreLength);
  987. this->CreateKeys(Include.Dot, dot, 0);
  988. }
  989. void cmQtAutoMocUicT::JobParseT::UicIncludes()
  990. {
  991. if (this->Content.find("ui_") == std::string::npos) {
  992. return;
  993. }
  994. std::set<std::string> includes;
  995. {
  996. char const* contentChars = this->Content.c_str();
  997. cmsys::RegularExpression const& regExp = this->UicConst().RegExpInclude;
  998. cmsys::RegularExpressionMatch match;
  999. while (regExp.find(contentChars, match)) {
  1000. includes.emplace(match.match(2));
  1001. // Forward content pointer
  1002. contentChars += match.end();
  1003. }
  1004. }
  1005. this->CreateKeys(this->FileHandle->ParseData->Uic.Include, includes,
  1006. UiUnderscoreLength);
  1007. }
  1008. void cmQtAutoMocUicT::JobParseHeaderT::Process()
  1009. {
  1010. if (!this->ReadFile()) {
  1011. return;
  1012. }
  1013. // Moc parsing
  1014. if (this->FileHandle->Moc) {
  1015. this->MocMacro();
  1016. this->MocDependencies();
  1017. }
  1018. // Uic parsing
  1019. if (this->FileHandle->Uic) {
  1020. this->UicIncludes();
  1021. }
  1022. }
  1023. void cmQtAutoMocUicT::JobParseSourceT::Process()
  1024. {
  1025. if (!this->ReadFile()) {
  1026. return;
  1027. }
  1028. // Moc parsing
  1029. if (this->FileHandle->Moc) {
  1030. this->MocMacro();
  1031. this->MocDependencies();
  1032. this->MocIncludes();
  1033. }
  1034. // Uic parsing
  1035. if (this->FileHandle->Uic) {
  1036. this->UicIncludes();
  1037. }
  1038. }
  1039. std::string cmQtAutoMocUicT::JobEvalCacheT::MessageSearchLocations() const
  1040. {
  1041. std::string res;
  1042. res.reserve(512);
  1043. for (std::string const& path : this->SearchLocations) {
  1044. res += " ";
  1045. res += this->MessagePath(path);
  1046. res += '\n';
  1047. }
  1048. return res;
  1049. }
  1050. void cmQtAutoMocUicT::JobEvalCacheMocT::Process()
  1051. {
  1052. // Evaluate headers
  1053. for (auto const& pair : this->BaseEval().Headers) {
  1054. if (!this->EvalHeader(pair.second)) {
  1055. return;
  1056. }
  1057. }
  1058. // Evaluate sources
  1059. for (auto const& pair : this->BaseEval().Sources) {
  1060. if (!this->EvalSource(pair.second)) {
  1061. return;
  1062. }
  1063. }
  1064. }
  1065. bool cmQtAutoMocUicT::JobEvalCacheMocT::EvalHeader(SourceFileHandleT source)
  1066. {
  1067. SourceFileT const& sourceFile = *source;
  1068. auto const& parseData = sourceFile.ParseData->Moc;
  1069. if (!source->Moc) {
  1070. return true;
  1071. }
  1072. if (!parseData.Macro.empty()) {
  1073. // Create a new mapping
  1074. MappingHandleT handle = std::make_shared<MappingT>();
  1075. handle->SourceFile = std::move(source);
  1076. // Absolute build path
  1077. if (this->BaseConst().MultiConfig) {
  1078. handle->OutputFile =
  1079. this->Gen()->AbsoluteIncludePath(sourceFile.BuildPath);
  1080. } else {
  1081. handle->OutputFile =
  1082. this->Gen()->AbsoluteBuildPath(sourceFile.BuildPath);
  1083. }
  1084. // Register mapping in headers map
  1085. this->RegisterMapping(handle);
  1086. }
  1087. return true;
  1088. }
  1089. bool cmQtAutoMocUicT::JobEvalCacheMocT::EvalSource(
  1090. SourceFileHandleT const& source)
  1091. {
  1092. SourceFileT const& sourceFile = *source;
  1093. auto const& parseData = sourceFile.ParseData->Moc;
  1094. if (!sourceFile.Moc ||
  1095. (parseData.Macro.empty() && parseData.Include.Underscore.empty() &&
  1096. parseData.Include.Dot.empty())) {
  1097. return true;
  1098. }
  1099. std::string const sourceDirPrefix = SubDirPrefix(sourceFile.FileName);
  1100. std::string const sourceBase =
  1101. cmSystemTools::GetFilenameWithoutLastExtension(sourceFile.FileName);
  1102. // For relaxed mode check if the own "moc_" or ".moc" file is included
  1103. bool const relaxedMode = this->MocConst().RelaxedMode;
  1104. bool sourceIncludesMocUnderscore = false;
  1105. bool sourceIncludesDotMoc = false;
  1106. // Check if the sources own "moc_" or ".moc" file is included
  1107. if (relaxedMode) {
  1108. for (IncludeKeyT const& incKey : parseData.Include.Underscore) {
  1109. if (incKey.Base == sourceBase) {
  1110. sourceIncludesMocUnderscore = true;
  1111. break;
  1112. }
  1113. }
  1114. }
  1115. for (IncludeKeyT const& incKey : parseData.Include.Dot) {
  1116. if (incKey.Base == sourceBase) {
  1117. sourceIncludesDotMoc = true;
  1118. break;
  1119. }
  1120. }
  1121. // Check if this source needs to be moc processed but doesn't.
  1122. if (!sourceIncludesDotMoc && !parseData.Macro.empty() &&
  1123. !(relaxedMode && sourceIncludesMocUnderscore)) {
  1124. this->LogError(GenT::MOC,
  1125. cmStrCat(this->MessagePath(sourceFile.FileName),
  1126. "\ncontains a ", Quoted(parseData.Macro),
  1127. " macro, but does not include ",
  1128. this->MessagePath(sourceBase + ".moc"),
  1129. "!\nConsider to\n - add #include \"", sourceBase,
  1130. ".moc\"\n - enable SKIP_AUTOMOC for this file"));
  1131. return false;
  1132. }
  1133. // Evaluate "moc_" includes
  1134. for (IncludeKeyT const& incKey : parseData.Include.Underscore) {
  1135. SourceFileHandleT headerHandle;
  1136. {
  1137. std::string const headerBase = cmStrCat(incKey.Dir, incKey.Base);
  1138. if (!this->FindIncludedHeader(headerHandle, sourceDirPrefix,
  1139. headerBase)) {
  1140. this->LogError(
  1141. GenT::MOC,
  1142. cmStrCat(this->MessagePath(sourceFile.FileName),
  1143. "\nincludes the moc file ", this->MessagePath(incKey.Key),
  1144. ",\nbut a header ", this->MessageHeader(headerBase),
  1145. "\ncould not be found "
  1146. "in the following directories\n",
  1147. this->MessageSearchLocations()));
  1148. return false;
  1149. }
  1150. }
  1151. // The include might be handled differently in relaxed mode
  1152. if (relaxedMode && !sourceIncludesDotMoc && !parseData.Macro.empty() &&
  1153. (incKey.Base == sourceBase)) {
  1154. // The <BASE>.cpp file includes a Qt macro but does not include the
  1155. // <BASE>.moc file. In this case, the moc_<BASE>.cpp should probably
  1156. // be generated from <BASE>.cpp instead of <BASE>.h, because otherwise
  1157. // it won't build. But warn, since this is not how it is supposed to be
  1158. // used. This is for KDE4 compatibility.
  1159. // Issue a warning
  1160. this->Log().Warning(
  1161. GenT::MOC,
  1162. cmStrCat(this->MessagePath(sourceFile.FileName), "\ncontains a ",
  1163. Quoted(parseData.Macro), " macro, but does not include ",
  1164. this->MessagePath(sourceBase + ".moc"),
  1165. ".\nInstead it includes ", this->MessagePath(incKey.Key),
  1166. ".\nRunning moc on the source\n ",
  1167. this->MessagePath(sourceFile.FileName), "!\nBetter include ",
  1168. this->MessagePath(sourceBase + ".moc"),
  1169. " for compatibility with regular mode.\n",
  1170. "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n"));
  1171. // Create mapping
  1172. if (!this->RegisterIncluded(incKey.Key, source, source)) {
  1173. return false;
  1174. }
  1175. continue;
  1176. }
  1177. // Check if header is skipped
  1178. if (this->MocConst().skipped(headerHandle->FileName)) {
  1179. continue;
  1180. }
  1181. // Create mapping
  1182. if (!this->RegisterIncluded(incKey.Key, source, std::move(headerHandle))) {
  1183. return false;
  1184. }
  1185. }
  1186. // Evaluate ".moc" includes
  1187. if (relaxedMode) {
  1188. // Relaxed mode
  1189. for (IncludeKeyT const& incKey : parseData.Include.Dot) {
  1190. // Check if this is the sources own .moc file
  1191. bool const ownMoc = (incKey.Base == sourceBase);
  1192. if (ownMoc && !parseData.Macro.empty()) {
  1193. // Create mapping for the regular use case
  1194. if (!this->RegisterIncluded(incKey.Key, source, source)) {
  1195. return false;
  1196. }
  1197. continue;
  1198. }
  1199. // Try to find a header instead but issue a warning.
  1200. // This is for KDE4 compatibility.
  1201. SourceFileHandleT headerHandle;
  1202. {
  1203. std::string const headerBase = cmStrCat(incKey.Dir, incKey.Base);
  1204. if (!this->FindIncludedHeader(headerHandle, sourceDirPrefix,
  1205. headerBase)) {
  1206. this->LogError(
  1207. GenT::MOC,
  1208. cmStrCat(
  1209. this->MessagePath(sourceFile.FileName),
  1210. "\nincludes the moc file ", this->MessagePath(incKey.Key),
  1211. ",\nwhich seems to be the moc file from a different source "
  1212. "file.\nCMAKE_AUTOMOC_RELAXED_MODE:\nAlso a matching header ",
  1213. this->MessageHeader(headerBase),
  1214. "\ncould not be found in the following directories\n",
  1215. this->MessageSearchLocations()));
  1216. return false;
  1217. }
  1218. }
  1219. // Check if header is skipped
  1220. if (this->MocConst().skipped(headerHandle->FileName)) {
  1221. continue;
  1222. }
  1223. // Issue a warning
  1224. if (ownMoc && parseData.Macro.empty()) {
  1225. this->Log().Warning(
  1226. GenT::MOC,
  1227. cmStrCat(
  1228. this->MessagePath(sourceFile.FileName), "\nincludes the moc file ",
  1229. this->MessagePath(incKey.Key), ", but does not contain a\n",
  1230. this->MocConst().MacrosString(),
  1231. " macro.\nRunning moc on the header\n ",
  1232. this->MessagePath(headerHandle->FileName), "!\nBetter include ",
  1233. this->MessagePath("moc_" + incKey.Base + ".cpp"),
  1234. " for a compatibility with regular mode.\n",
  1235. "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n"));
  1236. } else {
  1237. this->Log().Warning(
  1238. GenT::MOC,
  1239. cmStrCat(
  1240. this->MessagePath(sourceFile.FileName), "\nincludes the moc file ",
  1241. this->MessagePath(incKey.Key), " instead of ",
  1242. this->MessagePath("moc_" + incKey.Base + ".cpp"),
  1243. ".\nRunning moc on the header\n ",
  1244. this->MessagePath(headerHandle->FileName), "!\nBetter include ",
  1245. this->MessagePath("moc_" + incKey.Base + ".cpp"),
  1246. " for compatibility with regular mode.\n",
  1247. "This is a CMAKE_AUTOMOC_RELAXED_MODE warning.\n"));
  1248. }
  1249. // Create mapping
  1250. if (!this->RegisterIncluded(incKey.Key, source,
  1251. std::move(headerHandle))) {
  1252. return false;
  1253. }
  1254. }
  1255. } else {
  1256. // Strict mode
  1257. for (IncludeKeyT const& incKey : parseData.Include.Dot) {
  1258. // Check if this is the sources own .moc file
  1259. bool const ownMoc = (incKey.Base == sourceBase);
  1260. if (!ownMoc) {
  1261. // Don't allow <BASE>.moc include other than own in regular mode
  1262. this->LogError(
  1263. GenT::MOC,
  1264. cmStrCat(this->MessagePath(sourceFile.FileName),
  1265. "\nincludes the moc file ", this->MessagePath(incKey.Key),
  1266. ",\nwhich seems to be the moc file from a different "
  1267. "source file.\nThis is not supported. Include ",
  1268. this->MessagePath(sourceBase + ".moc"),
  1269. " to run moc on this source file."));
  1270. return false;
  1271. }
  1272. // Accept but issue a warning if moc isn't required
  1273. if (parseData.Macro.empty()) {
  1274. this->Log().Warning(
  1275. GenT::MOC,
  1276. cmStrCat(this->MessagePath(sourceFile.FileName),
  1277. "\nincludes the moc file ", this->MessagePath(incKey.Key),
  1278. ", but does not contain a ",
  1279. this->MocConst().MacrosString(), " macro."));
  1280. }
  1281. // Create mapping
  1282. if (!this->RegisterIncluded(incKey.Key, source, source)) {
  1283. return false;
  1284. }
  1285. }
  1286. }
  1287. return true;
  1288. }
  1289. bool cmQtAutoMocUicT::JobEvalCacheMocT::FindIncludedHeader(
  1290. SourceFileHandleT& headerHandle, cm::string_view includerDir,
  1291. cm::string_view includeBase)
  1292. {
  1293. // Clear search locations
  1294. this->SearchLocations.clear();
  1295. auto findHeader = [this,
  1296. &headerHandle](std::string const& basePath) -> bool {
  1297. bool found = false;
  1298. for (std::string const& ext : this->BaseConst().HeaderExtensions) {
  1299. std::string const testPath = cmSystemTools::CollapseFullPath(
  1300. cmStrCat(basePath, '.', ext),
  1301. this->Gen()->ProjectDirs().CurrentSource);
  1302. cmFileTime fileTime;
  1303. if (!fileTime.Load(testPath)) {
  1304. // File not found
  1305. continue;
  1306. }
  1307. // Return a known file if it exists already
  1308. {
  1309. auto it = this->BaseEval().Headers.find(testPath);
  1310. if (it != this->BaseEval().Headers.end()) {
  1311. headerHandle = it->second;
  1312. found = true;
  1313. break;
  1314. }
  1315. }
  1316. // Created and return discovered file entry
  1317. {
  1318. SourceFileHandleT& handle =
  1319. this->MocEval().HeadersDiscovered[testPath];
  1320. if (!handle) {
  1321. handle = std::make_shared<SourceFileT>(testPath);
  1322. handle->FileTime = fileTime;
  1323. handle->IsHeader = true;
  1324. handle->Moc = true;
  1325. }
  1326. headerHandle = handle;
  1327. found = true;
  1328. break;
  1329. }
  1330. }
  1331. if (!found) {
  1332. this->SearchLocations.emplace_back(cmQtAutoGen::ParentDir(basePath));
  1333. }
  1334. return found;
  1335. };
  1336. // Search in vicinity of the source
  1337. if (findHeader(cmStrCat(includerDir, includeBase))) {
  1338. return true;
  1339. }
  1340. // Search in include directories
  1341. auto const& includePaths = this->MocConst().IncludePaths;
  1342. return std::any_of(
  1343. includePaths.begin(), includePaths.end(),
  1344. [&findHeader, &includeBase](std::string const& path) -> bool {
  1345. return findHeader(cmStrCat(path, '/', includeBase));
  1346. });
  1347. }
  1348. bool cmQtAutoMocUicT::JobEvalCacheMocT::RegisterIncluded(
  1349. std::string const& includeString, SourceFileHandleT includerFileHandle,
  1350. SourceFileHandleT sourceFileHandle) const
  1351. {
  1352. // Check if this file is already included
  1353. MappingHandleT& handle = this->MocEval().Includes[includeString];
  1354. if (handle) {
  1355. // Check if the output file would be generated from different source files
  1356. if (handle->SourceFile != sourceFileHandle) {
  1357. std::string files =
  1358. cmStrCat(" ", this->MessagePath(includerFileHandle->FileName), '\n');
  1359. for (auto const& item : handle->IncluderFiles) {
  1360. files += cmStrCat(" ", this->MessagePath(item->FileName), '\n');
  1361. }
  1362. this->LogError(
  1363. GenT::MOC,
  1364. cmStrCat("The source files\n", files,
  1365. "contain the same include string ",
  1366. this->MessagePath(includeString),
  1367. ", but\nthe moc file would be generated from different "
  1368. "source files\n ",
  1369. this->MessagePath(sourceFileHandle->FileName), " and\n ",
  1370. this->MessagePath(handle->SourceFile->FileName),
  1371. ".\nConsider to\n"
  1372. " - not include the \"moc_<NAME>.cpp\" file\n"
  1373. " - add a directory prefix to a \"<NAME>.moc\" include "
  1374. "(e.g \"sub/<NAME>.moc\")\n"
  1375. " - rename the source file(s)\n"));
  1376. return false;
  1377. }
  1378. // The same mapping already exists. Just add to the includers list.
  1379. handle->IncluderFiles.emplace_back(std::move(includerFileHandle));
  1380. return true;
  1381. }
  1382. // Create a new mapping
  1383. handle = std::make_shared<MappingT>();
  1384. handle->IncludeString = includeString;
  1385. handle->IncluderFiles.emplace_back(std::move(includerFileHandle));
  1386. handle->SourceFile = std::move(sourceFileHandle);
  1387. handle->OutputFile = this->Gen()->AbsoluteIncludePath(includeString);
  1388. // Register mapping in sources/headers map
  1389. this->RegisterMapping(handle);
  1390. return true;
  1391. }
  1392. void cmQtAutoMocUicT::JobEvalCacheMocT::RegisterMapping(
  1393. MappingHandleT mappingHandle) const
  1394. {
  1395. auto& regMap = mappingHandle->SourceFile->IsHeader
  1396. ? this->MocEval().HeaderMappings
  1397. : this->MocEval().SourceMappings;
  1398. // Check if source file already gets mapped
  1399. auto& regHandle = regMap[mappingHandle->SourceFile->FileName];
  1400. if (!regHandle) {
  1401. // Yet unknown mapping
  1402. regHandle = std::move(mappingHandle);
  1403. } else {
  1404. // Mappings with include string override those without
  1405. if (!mappingHandle->IncludeString.empty()) {
  1406. regHandle = std::move(mappingHandle);
  1407. }
  1408. }
  1409. }
  1410. std::string cmQtAutoMocUicT::JobEvalCacheMocT::MessageHeader(
  1411. cm::string_view headerBase) const
  1412. {
  1413. return this->MessagePath(cmStrCat(
  1414. headerBase, ".{", cmJoin(this->BaseConst().HeaderExtensions, ","), '}'));
  1415. }
  1416. void cmQtAutoMocUicT::JobEvalCacheUicT::Process()
  1417. {
  1418. // Prepare buffers
  1419. this->SearchLocations.reserve((this->UicConst().SearchPaths.size() + 1) * 2);
  1420. // Evaluate headers
  1421. for (auto const& pair : this->BaseEval().Headers) {
  1422. if (!this->EvalFile(pair.second)) {
  1423. return;
  1424. }
  1425. }
  1426. // Evaluate sources
  1427. for (auto const& pair : this->BaseEval().Sources) {
  1428. if (!this->EvalFile(pair.second)) {
  1429. return;
  1430. }
  1431. }
  1432. }
  1433. bool cmQtAutoMocUicT::JobEvalCacheUicT::EvalFile(
  1434. SourceFileHandleT const& sourceFileHandle)
  1435. {
  1436. SourceFileT const& sourceFile = *sourceFileHandle;
  1437. auto const& Include = sourceFile.ParseData->Uic.Include;
  1438. if (!sourceFile.Uic || Include.empty()) {
  1439. return true;
  1440. }
  1441. std::string const sourceDirPrefix = SubDirPrefix(sourceFile.FileName);
  1442. return std::all_of(
  1443. Include.begin(), Include.end(),
  1444. [this, &sourceDirPrefix, &sourceFile,
  1445. &sourceFileHandle](IncludeKeyT const& incKey) -> bool {
  1446. // Find .ui file
  1447. this->UiName = cmStrCat(incKey.Base, ".ui");
  1448. if (!this->FindIncludedUi(sourceDirPrefix, incKey.Dir)) {
  1449. this->LogError(
  1450. GenT::UIC,
  1451. cmStrCat(this->MessagePath(sourceFile.FileName),
  1452. "\nincludes the uic file ", this->MessagePath(incKey.Key),
  1453. ",\nbut the user interface file ",
  1454. this->MessagePath(this->UiName),
  1455. "\ncould not be found in the following directories\n",
  1456. this->MessageSearchLocations()));
  1457. return false;
  1458. }
  1459. // Check if the file is skipped
  1460. if (this->UicConst().skipped(this->UiFileHandle->FileName)) {
  1461. return true;
  1462. }
  1463. // Register mapping
  1464. return this->RegisterMapping(incKey.Key, sourceFileHandle);
  1465. });
  1466. }
  1467. bool cmQtAutoMocUicT::JobEvalCacheUicT::FindIncludedUi(
  1468. cm::string_view sourceDirPrefix, cm::string_view includePrefix)
  1469. {
  1470. // Clear locations buffer
  1471. this->SearchLocations.clear();
  1472. auto findUi = [this](std::string const& testPath) -> bool {
  1473. std::string const fullPath = cmSystemTools::CollapseFullPath(
  1474. testPath, this->Gen()->ProjectDirs().CurrentSource);
  1475. cmFileTime fileTime;
  1476. if (!fileTime.Load(fullPath)) {
  1477. this->SearchLocations.emplace_back(cmQtAutoGen::ParentDir(fullPath));
  1478. return false;
  1479. }
  1480. // .ui file found in files system!
  1481. // Get or create .ui file handle
  1482. SourceFileHandleT& handle = this->UicEval().UiFiles[fullPath];
  1483. if (!handle) {
  1484. // The file wasn't registered, yet
  1485. handle = std::make_shared<SourceFileT>(fullPath);
  1486. handle->FileTime = fileTime;
  1487. }
  1488. this->UiFileHandle = handle;
  1489. return true;
  1490. };
  1491. // Vicinity of the source
  1492. if (!includePrefix.empty()) {
  1493. if (findUi(cmStrCat(sourceDirPrefix, includePrefix, this->UiName))) {
  1494. return true;
  1495. }
  1496. }
  1497. if (findUi(cmStrCat(sourceDirPrefix, this->UiName))) {
  1498. return true;
  1499. }
  1500. // Additional AUTOUIC search paths
  1501. auto const& searchPaths = this->UicConst().SearchPaths;
  1502. if (!searchPaths.empty()) {
  1503. for (std::string const& sPath : searchPaths) {
  1504. if (findUi(cmStrCat(sPath, '/', this->UiName))) {
  1505. return true;
  1506. }
  1507. }
  1508. if (!includePrefix.empty()) {
  1509. for (std::string const& sPath : searchPaths) {
  1510. if (findUi(cmStrCat(sPath, '/', includePrefix, this->UiName))) {
  1511. return true;
  1512. }
  1513. }
  1514. }
  1515. }
  1516. return false;
  1517. }
  1518. bool cmQtAutoMocUicT::JobEvalCacheUicT::RegisterMapping(
  1519. std::string const& includeString, SourceFileHandleT includerFileHandle)
  1520. {
  1521. auto& Includes = this->Gen()->UicEval().Includes;
  1522. auto it = Includes.find(includeString);
  1523. if (it != Includes.end()) {
  1524. MappingHandleT const& handle = it->second;
  1525. if (handle->SourceFile != this->UiFileHandle) {
  1526. // The output file already gets generated - from a different .ui file!
  1527. std::string files =
  1528. cmStrCat(" ", this->MessagePath(includerFileHandle->FileName), '\n');
  1529. for (auto const& item : handle->IncluderFiles) {
  1530. files += cmStrCat(" ", this->MessagePath(item->FileName), '\n');
  1531. }
  1532. this->LogError(
  1533. GenT::UIC,
  1534. cmStrCat(
  1535. "The source files\n", files, "contain the same include string ",
  1536. Quoted(includeString),
  1537. ", but\nthe uic file would be generated from different "
  1538. "user interface files\n ",
  1539. this->MessagePath(this->UiFileHandle->FileName), " and\n ",
  1540. this->MessagePath(handle->SourceFile->FileName),
  1541. ".\nConsider to\n"
  1542. " - add a directory prefix to a \"ui_<NAME>.h\" include "
  1543. "(e.g \"sub/ui_<NAME>.h\")\n"
  1544. " - rename the <NAME>.ui file(s) and adjust the \"ui_<NAME>.h\" "
  1545. "include(s)\n"));
  1546. return false;
  1547. }
  1548. // Add includer file to existing mapping
  1549. handle->IncluderFiles.emplace_back(std::move(includerFileHandle));
  1550. } else {
  1551. // New mapping handle
  1552. MappingHandleT handle = std::make_shared<MappingT>();
  1553. handle->IncludeString = includeString;
  1554. handle->IncluderFiles.emplace_back(std::move(includerFileHandle));
  1555. handle->SourceFile = this->UiFileHandle;
  1556. handle->OutputFile = this->Gen()->AbsoluteIncludePath(includeString);
  1557. // Register mapping
  1558. Includes.emplace(includeString, std::move(handle));
  1559. }
  1560. return true;
  1561. }
  1562. void cmQtAutoMocUicT::JobEvalCacheFinishT::Process()
  1563. {
  1564. // Add discovered header parse jobs
  1565. this->Gen()->CreateParseJobs<JobParseHeaderT>(
  1566. this->MocEval().HeadersDiscovered);
  1567. // Add dependency probing jobs
  1568. {
  1569. // Add fence job to ensure all parsing has finished
  1570. this->Gen()->WorkerPool().EmplaceJob<JobFenceT>();
  1571. if (this->MocConst().Enabled) {
  1572. this->Gen()->WorkerPool().EmplaceJob<JobProbeDepsMocT>();
  1573. }
  1574. if (this->UicConst().Enabled) {
  1575. this->Gen()->WorkerPool().EmplaceJob<JobProbeDepsUicT>();
  1576. }
  1577. // Add probe finish job
  1578. this->Gen()->WorkerPool().EmplaceJob<JobProbeDepsFinishT>();
  1579. }
  1580. }
  1581. void cmQtAutoMocUicT::JobProbeDepsMocT::Process()
  1582. {
  1583. // Create moc header jobs
  1584. for (auto const& pair : this->MocEval().HeaderMappings) {
  1585. // Register if this mapping is a candidate for mocs_compilation.cpp
  1586. bool const compFile = pair.second->IncludeString.empty();
  1587. if (compFile) {
  1588. this->MocEval().CompFiles.emplace_back(
  1589. pair.second->SourceFile->BuildPath);
  1590. }
  1591. if (!this->Generate(pair.second, compFile)) {
  1592. return;
  1593. }
  1594. }
  1595. // Create moc source jobs
  1596. for (auto const& pair : this->MocEval().SourceMappings) {
  1597. if (!this->Generate(pair.second, false)) {
  1598. return;
  1599. }
  1600. }
  1601. }
  1602. bool cmQtAutoMocUicT::JobProbeDepsMocT::Generate(MappingHandleT const& mapping,
  1603. bool compFile) const
  1604. {
  1605. std::unique_ptr<std::string> reason;
  1606. if (this->Log().Verbose()) {
  1607. reason = cm::make_unique<std::string>();
  1608. }
  1609. if (this->Probe(*mapping, reason.get())) {
  1610. // Register the parent directory for creation
  1611. this->MocEval().OutputDirs.emplace(
  1612. cmQtAutoGen::ParentDir(mapping->OutputFile));
  1613. // Fetch the cache entry for the source file
  1614. std::string const& sourceFile = mapping->SourceFile->FileName;
  1615. ParseCacheT::GetOrInsertT cacheEntry =
  1616. this->BaseEval().ParseCache.GetOrInsert(sourceFile);
  1617. // Add moc job
  1618. this->Gen()->WorkerPool().EmplaceJob<JobCompileMocT>(
  1619. mapping, std::move(reason), std::move(cacheEntry.first));
  1620. // Check if a moc job for a mocs_compilation.cpp entry was generated
  1621. if (compFile) {
  1622. this->MocEval().CompUpdated = true;
  1623. }
  1624. }
  1625. return true;
  1626. }
  1627. bool cmQtAutoMocUicT::JobProbeDepsMocT::Probe(MappingT const& mapping,
  1628. std::string* reason) const
  1629. {
  1630. std::string const& sourceFile = mapping.SourceFile->FileName;
  1631. std::string const& outputFile = mapping.OutputFile;
  1632. // Test if the output file exists
  1633. cmFileTime outputFileTime;
  1634. if (!outputFileTime.Load(outputFile)) {
  1635. if (reason) {
  1636. *reason = cmStrCat("Generating ", this->MessagePath(outputFile),
  1637. ", because it doesn't exist, from ",
  1638. this->MessagePath(sourceFile));
  1639. }
  1640. return true;
  1641. }
  1642. // Test if any setting changed
  1643. if (this->MocConst().SettingsChanged) {
  1644. if (reason) {
  1645. *reason = cmStrCat("Generating ", this->MessagePath(outputFile),
  1646. ", because the moc settings changed, from ",
  1647. this->MessagePath(sourceFile));
  1648. }
  1649. return true;
  1650. }
  1651. // Test if the source file is newer
  1652. if (outputFileTime.Older(mapping.SourceFile->FileTime)) {
  1653. if (reason) {
  1654. *reason = cmStrCat("Generating ", this->MessagePath(outputFile),
  1655. ", because it's older than its source file, from ",
  1656. this->MessagePath(sourceFile));
  1657. }
  1658. return true;
  1659. }
  1660. // Test if the moc_predefs file is newer
  1661. if (!this->MocConst().PredefsFileAbs.empty()) {
  1662. if (outputFileTime.Older(this->MocEval().PredefsTime)) {
  1663. if (reason) {
  1664. *reason = cmStrCat("Generating ", this->MessagePath(outputFile),
  1665. ", because it's older than ",
  1666. this->MessagePath(this->MocConst().PredefsFileAbs),
  1667. ", from ", this->MessagePath(sourceFile));
  1668. }
  1669. return true;
  1670. }
  1671. }
  1672. // Test if the moc executable is newer
  1673. if (outputFileTime.Older(this->MocConst().ExecutableTime)) {
  1674. if (reason) {
  1675. *reason = cmStrCat("Generating ", this->MessagePath(outputFile),
  1676. ", because it's older than the moc executable, from ",
  1677. this->MessagePath(sourceFile));
  1678. }
  1679. return true;
  1680. }
  1681. // Test if a dependency file is newer
  1682. {
  1683. // Check dependency timestamps
  1684. std::string const sourceDir = SubDirPrefix(sourceFile);
  1685. auto& dependencies = mapping.SourceFile->ParseData->Moc.Depends;
  1686. for (auto it = dependencies.begin(); it != dependencies.end(); ++it) {
  1687. auto& dep = *it;
  1688. // Find dependency file
  1689. auto const depMatch = this->FindDependency(sourceDir, dep);
  1690. if (depMatch.first.empty()) {
  1691. if (reason) {
  1692. *reason = cmStrCat("Generating ", this->MessagePath(outputFile),
  1693. " from ", this->MessagePath(sourceFile),
  1694. ", because its dependency ",
  1695. this->MessagePath(dep), " vanished.");
  1696. }
  1697. dependencies.erase(it);
  1698. this->BaseEval().ParseCacheChanged = true;
  1699. return true;
  1700. }
  1701. // Test if dependency file is older
  1702. if (outputFileTime.Older(depMatch.second)) {
  1703. if (reason) {
  1704. *reason = cmStrCat("Generating ", this->MessagePath(outputFile),
  1705. ", because it's older than its dependency file ",
  1706. this->MessagePath(depMatch.first), ", from ",
  1707. this->MessagePath(sourceFile));
  1708. }
  1709. return true;
  1710. }
  1711. }
  1712. }
  1713. return false;
  1714. }
  1715. std::pair<std::string, cmFileTime>
  1716. cmQtAutoMocUicT::JobProbeDepsMocT::FindDependency(
  1717. std::string const& sourceDir, std::string const& includeString) const
  1718. {
  1719. using ResPair = std::pair<std::string, cmFileTime>;
  1720. // moc's dependency file contains absolute paths
  1721. if (this->MocConst().CanOutputDependencies) {
  1722. ResPair res{ includeString, {} };
  1723. if (res.second.Load(res.first)) {
  1724. return res;
  1725. }
  1726. return {};
  1727. }
  1728. // Search in vicinity of the source
  1729. {
  1730. ResPair res{ sourceDir + includeString, {} };
  1731. if (res.second.Load(res.first)) {
  1732. return res;
  1733. }
  1734. }
  1735. // Search in include directories
  1736. for (std::string const& includePath : this->MocConst().IncludePaths) {
  1737. ResPair res{ cmStrCat(includePath, '/', includeString), {} };
  1738. if (res.second.Load(res.first)) {
  1739. return res;
  1740. }
  1741. }
  1742. // Return empty
  1743. return ResPair();
  1744. }
  1745. void cmQtAutoMocUicT::JobProbeDepsUicT::Process()
  1746. {
  1747. for (auto const& pair : this->Gen()->UicEval().Includes) {
  1748. MappingHandleT const& mapping = pair.second;
  1749. std::unique_ptr<std::string> reason;
  1750. if (this->Log().Verbose()) {
  1751. reason = cm::make_unique<std::string>();
  1752. }
  1753. if (!this->Probe(*mapping, reason.get())) {
  1754. continue;
  1755. }
  1756. // Register the parent directory for creation
  1757. this->UicEval().OutputDirs.emplace(
  1758. cmQtAutoGen::ParentDir(mapping->OutputFile));
  1759. // Add uic job
  1760. this->Gen()->WorkerPool().EmplaceJob<JobCompileUicT>(mapping,
  1761. std::move(reason));
  1762. }
  1763. }
  1764. bool cmQtAutoMocUicT::JobProbeDepsUicT::Probe(MappingT const& mapping,
  1765. std::string* reason) const
  1766. {
  1767. std::string const& sourceFile = mapping.SourceFile->FileName;
  1768. std::string const& outputFile = mapping.OutputFile;
  1769. // Test if the build file exists
  1770. cmFileTime outputFileTime;
  1771. if (!outputFileTime.Load(outputFile)) {
  1772. if (reason) {
  1773. *reason = cmStrCat("Generating ", this->MessagePath(outputFile),
  1774. ", because it doesn't exist, from ",
  1775. this->MessagePath(sourceFile));
  1776. }
  1777. return true;
  1778. }
  1779. // Test if the uic settings changed
  1780. if (this->UicConst().SettingsChanged) {
  1781. if (reason) {
  1782. *reason = cmStrCat("Generating ", this->MessagePath(outputFile),
  1783. ", because the uic settings changed, from ",
  1784. this->MessagePath(sourceFile));
  1785. }
  1786. return true;
  1787. }
  1788. // Test if the source file is newer
  1789. if (outputFileTime.Older(mapping.SourceFile->FileTime)) {
  1790. if (reason) {
  1791. *reason = cmStrCat("Generating ", this->MessagePath(outputFile),
  1792. " because it's older than the source file ",
  1793. this->MessagePath(sourceFile));
  1794. }
  1795. return true;
  1796. }
  1797. // Test if the uic executable is newer
  1798. if (outputFileTime.Older(this->UicConst().ExecutableTime)) {
  1799. if (reason) {
  1800. *reason = cmStrCat("Generating ", this->MessagePath(outputFile),
  1801. ", because it's older than the uic executable, from ",
  1802. this->MessagePath(sourceFile));
  1803. }
  1804. return true;
  1805. }
  1806. return false;
  1807. }
  1808. void cmQtAutoMocUicT::JobProbeDepsFinishT::Process()
  1809. {
  1810. // Create output directories
  1811. {
  1812. using StringSet = std::unordered_set<std::string>;
  1813. auto createDirs = [this](GenT genType, StringSet const& dirSet) {
  1814. for (std::string const& dirName : dirSet) {
  1815. if (!cmSystemTools::MakeDirectory(dirName)) {
  1816. this->LogError(genType,
  1817. cmStrCat("Creating directory ",
  1818. this->MessagePath(dirName), " failed."));
  1819. return;
  1820. }
  1821. }
  1822. };
  1823. if (this->MocConst().Enabled && this->UicConst().Enabled) {
  1824. StringSet outputDirs = this->MocEval().OutputDirs;
  1825. outputDirs.insert(this->UicEval().OutputDirs.begin(),
  1826. this->UicEval().OutputDirs.end());
  1827. createDirs(GenT::GEN, outputDirs);
  1828. } else if (this->MocConst().Enabled) {
  1829. createDirs(GenT::MOC, this->MocEval().OutputDirs);
  1830. } else if (this->UicConst().Enabled) {
  1831. createDirs(GenT::UIC, this->UicEval().OutputDirs);
  1832. }
  1833. }
  1834. if (this->MocConst().Enabled) {
  1835. // Add mocs compilations job
  1836. this->Gen()->WorkerPool().EmplaceJob<JobMocsCompilationT>();
  1837. }
  1838. if (!this->BaseConst().DepFile.empty()) {
  1839. // Add job to merge dep files
  1840. this->Gen()->WorkerPool().EmplaceJob<JobDepFilesMergeT>();
  1841. }
  1842. // Add finish job
  1843. this->Gen()->WorkerPool().EmplaceJob<JobFinishT>();
  1844. }
  1845. void cmQtAutoMocUicT::JobCompileMocT::Process()
  1846. {
  1847. std::string const& sourceFile = this->Mapping->SourceFile->FileName;
  1848. std::string const& outputFile = this->Mapping->OutputFile;
  1849. // Remove output file in case the case of the source file has changed
  1850. cmSystemTools::RemoveFile(outputFile);
  1851. // Compose moc command
  1852. std::vector<std::string> cmd;
  1853. {
  1854. // Reserve large enough
  1855. cmd.reserve(this->MocConst().OptionsDefinitions.size() +
  1856. this->MocConst().OptionsIncludes.size() +
  1857. this->MocConst().OptionsExtra.size() + 16);
  1858. cmd.push_back(this->MocConst().Executable);
  1859. // Add definitions
  1860. cm::append(cmd, this->MocConst().OptionsDefinitions);
  1861. // Add includes
  1862. cm::append(cmd, this->MocConst().OptionsIncludes);
  1863. // Add predefs include
  1864. if (!this->MocConst().PredefsFileAbs.empty()) {
  1865. cmd.emplace_back("--include");
  1866. cmd.push_back(this->MocConst().PredefsFileAbs);
  1867. }
  1868. // Add path prefix on demand
  1869. if (this->MocConst().PathPrefix && this->Mapping->SourceFile->IsHeader) {
  1870. for (std::string const& dir : this->MocConst().IncludePaths) {
  1871. cm::string_view prefix = sourceFile;
  1872. if (cmHasPrefix(prefix, dir)) {
  1873. prefix.remove_prefix(dir.size());
  1874. if (cmHasPrefix(prefix, '/')) {
  1875. prefix.remove_prefix(1);
  1876. auto slashPos = prefix.rfind('/');
  1877. if (slashPos != cm::string_view::npos) {
  1878. cmd.emplace_back("-p");
  1879. cmd.emplace_back(prefix.substr(0, slashPos));
  1880. } else {
  1881. cmd.emplace_back("-p");
  1882. cmd.emplace_back("./");
  1883. }
  1884. break;
  1885. }
  1886. }
  1887. }
  1888. }
  1889. // Add extra options
  1890. cm::append(cmd, this->MocConst().OptionsExtra);
  1891. if (this->MocConst().CanOutputDependencies) {
  1892. cmd.emplace_back("--output-dep-file");
  1893. }
  1894. // Add output file
  1895. cmd.emplace_back("-o");
  1896. cmd.push_back(outputFile);
  1897. // Add source file
  1898. cmd.push_back(sourceFile);
  1899. MaybeWriteResponseFile(outputFile, cmd);
  1900. cmSystemTools::MaybePrependCmdExe(cmd);
  1901. }
  1902. // Execute moc command
  1903. cmWorkerPool::ProcessResultT result;
  1904. if (!this->RunProcess(GenT::MOC, result, cmd, this->Reason.get())) {
  1905. // Moc command failed
  1906. std::string includers;
  1907. if (!this->Mapping->IncluderFiles.empty()) {
  1908. includers = "included by\n";
  1909. for (auto const& item : this->Mapping->IncluderFiles) {
  1910. includers += cmStrCat(" ", this->MessagePath(item->FileName), '\n');
  1911. }
  1912. }
  1913. this->LogCommandError(GenT::MOC,
  1914. cmStrCat("The moc process failed to compile\n ",
  1915. this->MessagePath(sourceFile), "\ninto\n ",
  1916. this->MessagePath(outputFile), '\n',
  1917. includers, result.ErrorMessage),
  1918. cmd, result.StdOut);
  1919. return;
  1920. }
  1921. // Moc command success. Print moc output.
  1922. if (!result.StdOut.empty()) {
  1923. this->Log().Info(GenT::MOC, result.StdOut);
  1924. }
  1925. // Extract dependencies from the dep file moc generated for us
  1926. if (this->MocConst().CanOutputDependencies) {
  1927. std::string const depfile = outputFile + ".d";
  1928. if (this->Log().Verbose()) {
  1929. this->Log().Info(
  1930. GenT::MOC, "Reading dependencies from " + this->MessagePath(depfile));
  1931. }
  1932. if (!cmSystemTools::FileExists(depfile)) {
  1933. this->Log().Warning(GenT::MOC,
  1934. "Dependency file " + this->MessagePath(depfile) +
  1935. " does not exist.");
  1936. return;
  1937. }
  1938. this->CacheEntry->Moc.Depends =
  1939. this->Gen()->dependenciesFromDepFile(depfile.c_str());
  1940. }
  1941. }
  1942. void cmQtAutoMocUicT::JobCompileUicT::Process()
  1943. {
  1944. std::string const& sourceFile = this->Mapping->SourceFile->FileName;
  1945. std::string const& outputFile = this->Mapping->OutputFile;
  1946. // Compose uic command
  1947. std::vector<std::string> cmd;
  1948. cmd.push_back(this->UicConst().Executable);
  1949. {
  1950. std::vector<std::string> allOpts = this->UicConst().Options;
  1951. auto optionIt = this->UicConst().UiFiles.find(sourceFile);
  1952. if (optionIt != this->UicConst().UiFiles.end()) {
  1953. UicMergeOptions(allOpts, optionIt->second.Options,
  1954. (this->BaseConst().QtVersion.Major >= 5));
  1955. }
  1956. cm::append(cmd, allOpts);
  1957. }
  1958. cmd.emplace_back("-o");
  1959. cmd.emplace_back(outputFile);
  1960. cmd.emplace_back(sourceFile);
  1961. cmSystemTools::MaybePrependCmdExe(cmd);
  1962. cmWorkerPool::ProcessResultT result;
  1963. if (this->RunProcess(GenT::UIC, result, cmd, this->Reason.get())) {
  1964. // Uic command success
  1965. // Print uic output
  1966. if (!result.StdOut.empty()) {
  1967. this->Log().Info(GenT::UIC, result.StdOut);
  1968. }
  1969. } else {
  1970. // Uic command failed
  1971. std::string includers;
  1972. for (auto const& item : this->Mapping->IncluderFiles) {
  1973. includers += cmStrCat(" ", this->MessagePath(item->FileName), '\n');
  1974. }
  1975. this->LogCommandError(GenT::UIC,
  1976. cmStrCat("The uic process failed to compile\n ",
  1977. this->MessagePath(sourceFile), "\ninto\n ",
  1978. this->MessagePath(outputFile),
  1979. "\nincluded by\n", includers,
  1980. result.ErrorMessage),
  1981. cmd, result.StdOut);
  1982. }
  1983. }
  1984. void cmQtAutoMocUicT::JobMocsCompilationT::Process()
  1985. {
  1986. std::string const& compAbs = this->MocConst().CompFileAbs;
  1987. // Compose mocs compilation file content
  1988. std::string content =
  1989. "// This file is autogenerated. Changes will be overwritten.\n";
  1990. if (this->MocEval().CompFiles.empty()) {
  1991. // Placeholder content
  1992. content += "// No files found that require moc or the moc files are "
  1993. "included\n"
  1994. "enum some_compilers { need_more_than_nothing };\n";
  1995. } else {
  1996. // Valid content
  1997. bool const mc = this->BaseConst().MultiConfig;
  1998. cm::string_view const wrapFront = mc ? "#include <" : "#include \"";
  1999. cm::string_view const wrapBack = mc ? ">\n" : "\"\n";
  2000. content += cmWrap(wrapFront, this->MocEval().CompFiles, wrapBack, "");
  2001. }
  2002. if (cmQtAutoGenerator::FileDiffers(compAbs, content)) {
  2003. // Actually write mocs compilation file
  2004. if (this->Log().Verbose()) {
  2005. this->Log().Info(
  2006. GenT::MOC, "Generating MOC compilation " + this->MessagePath(compAbs));
  2007. }
  2008. if (!FileWrite(compAbs, content)) {
  2009. this->LogError(GenT::MOC,
  2010. cmStrCat("Writing MOC compilation ",
  2011. this->MessagePath(compAbs), " failed."));
  2012. }
  2013. } else if (this->MocEval().CompUpdated) {
  2014. // Only touch mocs compilation file
  2015. if (this->Log().Verbose()) {
  2016. this->Log().Info(
  2017. GenT::MOC, "Touching MOC compilation " + this->MessagePath(compAbs));
  2018. }
  2019. if (!cmSystemTools::Touch(compAbs, false)) {
  2020. this->LogError(GenT::MOC,
  2021. cmStrCat("Touching MOC compilation ",
  2022. this->MessagePath(compAbs), " failed."));
  2023. }
  2024. }
  2025. }
  2026. /*
  2027. * Escapes paths for Ninja depfiles.
  2028. * This is a re-implementation of what moc does when writing depfiles.
  2029. */
  2030. std::string escapeDependencyPath(cm::string_view path)
  2031. {
  2032. std::string escapedPath;
  2033. escapedPath.reserve(path.size());
  2034. size_t const s = path.size();
  2035. int backslashCount = 0;
  2036. for (size_t i = 0; i < s; ++i) {
  2037. if (path[i] == '\\') {
  2038. ++backslashCount;
  2039. } else {
  2040. if (path[i] == '$') {
  2041. escapedPath.push_back('$');
  2042. } else if (path[i] == '#') {
  2043. escapedPath.push_back('\\');
  2044. } else if (path[i] == ' ') {
  2045. // Double the amount of written backslashes,
  2046. // and add one more to escape the space.
  2047. while (backslashCount-- >= 0) {
  2048. escapedPath.push_back('\\');
  2049. }
  2050. }
  2051. backslashCount = 0;
  2052. }
  2053. escapedPath.push_back(path[i]);
  2054. }
  2055. return escapedPath;
  2056. }
  2057. /*
  2058. * Return the initial dependencies of the merged depfile.
  2059. * Those are dependencies from the project files, not from moc runs.
  2060. */
  2061. std::vector<std::string>
  2062. cmQtAutoMocUicT::JobDepFilesMergeT::initialDependencies() const
  2063. {
  2064. std::vector<std::string> dependencies;
  2065. dependencies.reserve(this->BaseConst().ListFiles.size() +
  2066. this->BaseEval().Headers.size() +
  2067. this->BaseEval().Sources.size());
  2068. cm::append(dependencies, this->BaseConst().ListFiles);
  2069. auto append_file_path =
  2070. [&dependencies](SourceFileMapT::value_type const& p) {
  2071. dependencies.push_back(p.first);
  2072. };
  2073. std::for_each(this->BaseEval().Headers.begin(),
  2074. this->BaseEval().Headers.end(), append_file_path);
  2075. std::for_each(this->BaseEval().Sources.begin(),
  2076. this->BaseEval().Sources.end(), append_file_path);
  2077. return dependencies;
  2078. }
  2079. void cmQtAutoMocUicT::JobDepFilesMergeT::Process()
  2080. {
  2081. if (this->Log().Verbose()) {
  2082. this->Log().Info(GenT::MOC,
  2083. cmStrCat("Merging MOC dependencies into ",
  2084. this->MessagePath(this->BaseConst().DepFile)));
  2085. }
  2086. auto processDepFile =
  2087. [this](std::string const& mocOutputFile) -> std::vector<std::string> {
  2088. std::string f = mocOutputFile + ".d";
  2089. if (!cmSystemTools::FileExists(f)) {
  2090. return {};
  2091. }
  2092. return this->Gen()->dependenciesFromDepFile(f.c_str());
  2093. };
  2094. std::vector<std::string> dependencies = this->initialDependencies();
  2095. ParseCacheT& parseCache = this->BaseEval().ParseCache;
  2096. auto processMappingEntry = [&](MappingMapT::value_type const& m) {
  2097. auto cacheEntry = parseCache.GetOrInsert(m.first);
  2098. if (cacheEntry.first->Moc.Depends.empty()) {
  2099. cacheEntry.first->Moc.Depends = processDepFile(m.second->OutputFile);
  2100. }
  2101. dependencies.insert(dependencies.end(),
  2102. cacheEntry.first->Moc.Depends.begin(),
  2103. cacheEntry.first->Moc.Depends.end());
  2104. };
  2105. std::for_each(this->MocEval().HeaderMappings.begin(),
  2106. this->MocEval().HeaderMappings.end(), processMappingEntry);
  2107. std::for_each(this->MocEval().SourceMappings.begin(),
  2108. this->MocEval().SourceMappings.end(), processMappingEntry);
  2109. // Remove SKIP_AUTOMOC files.
  2110. // Also remove AUTOUIC header files to avoid cyclic dependency.
  2111. dependencies.erase(
  2112. std::remove_if(dependencies.begin(), dependencies.end(),
  2113. [this](std::string const& dep) {
  2114. return this->MocConst().skipped(dep) ||
  2115. std::any_of(
  2116. this->UicEval().Includes.begin(),
  2117. this->UicEval().Includes.end(),
  2118. [&dep](MappingMapT::value_type const& mapping) {
  2119. return dep == mapping.second->OutputFile;
  2120. });
  2121. }),
  2122. dependencies.end());
  2123. // Remove duplicates to make the depfile smaller
  2124. std::sort(dependencies.begin(), dependencies.end());
  2125. dependencies.erase(std::unique(dependencies.begin(), dependencies.end()),
  2126. dependencies.end());
  2127. // Add form files
  2128. for (auto const& uif : this->UicEval().UiFiles) {
  2129. dependencies.push_back(uif.first);
  2130. }
  2131. // Write the file
  2132. cmsys::ofstream ofs;
  2133. ofs.open(this->BaseConst().DepFile.c_str(),
  2134. (std::ios::out | std::ios::binary | std::ios::trunc));
  2135. if (!ofs) {
  2136. this->LogError(GenT::GEN,
  2137. cmStrCat("Cannot open ",
  2138. this->MessagePath(this->BaseConst().DepFile),
  2139. " for writing."));
  2140. return;
  2141. }
  2142. ofs << this->BaseConst().DepFileRuleName << ": \\\n";
  2143. for (std::string const& file : dependencies) {
  2144. ofs << '\t' << escapeDependencyPath(file) << " \\\n";
  2145. if (!ofs.good()) {
  2146. this->LogError(GenT::GEN,
  2147. cmStrCat("Writing depfile",
  2148. this->MessagePath(this->BaseConst().DepFile),
  2149. " failed."));
  2150. return;
  2151. }
  2152. }
  2153. // Add the CMake executable to re-new cache data if necessary.
  2154. // Also, this is the last entry, so don't add a backslash.
  2155. ofs << '\t' << escapeDependencyPath(this->BaseConst().CMakeExecutable)
  2156. << '\n';
  2157. }
  2158. void cmQtAutoMocUicT::JobFinishT::Process()
  2159. {
  2160. this->Gen()->AbortSuccess();
  2161. }
  2162. cmQtAutoMocUicT::cmQtAutoMocUicT()
  2163. : cmQtAutoGenerator(GenT::GEN)
  2164. {
  2165. }
  2166. cmQtAutoMocUicT::~cmQtAutoMocUicT() = default;
  2167. bool cmQtAutoMocUicT::InitFromInfo(InfoT const& info)
  2168. {
  2169. // -- Required settings
  2170. if (!info.GetBool("MULTI_CONFIG", this->BaseConst_.MultiConfig, true) ||
  2171. !info.GetBool("CROSS_CONFIG", this->BaseConst_.CrossConfig, true) ||
  2172. !info.GetBool("USE_BETTER_GRAPH", this->BaseConst_.UseBetterGraph,
  2173. true) ||
  2174. !info.GetUInt("QT_VERSION_MAJOR", this->BaseConst_.QtVersion.Major,
  2175. true) ||
  2176. !info.GetUInt("QT_VERSION_MINOR", this->BaseConst_.QtVersion.Minor,
  2177. true) ||
  2178. !info.GetUInt("PARALLEL", this->BaseConst_.ThreadCount, false) ||
  2179. #ifdef _WIN32
  2180. !info.GetUInt("AUTOGEN_COMMAND_LINE_LENGTH_MAX",
  2181. this->BaseConst_.MaxCommandLineLength, false) ||
  2182. #endif
  2183. !info.GetString("BUILD_DIR", this->BaseConst_.AutogenBuildDir, true) ||
  2184. !info.GetStringConfig("INCLUDE_DIR", this->BaseConst_.AutogenIncludeDir,
  2185. true) ||
  2186. !info.GetString("CMAKE_EXECUTABLE", this->BaseConst_.CMakeExecutable,
  2187. true) ||
  2188. !info.GetStringConfig("PARSE_CACHE_FILE",
  2189. this->BaseConst_.ParseCacheFile, true) ||
  2190. !info.GetStringConfig("SETTINGS_FILE", this->SettingsFile_, true) ||
  2191. !info.GetArray("CMAKE_LIST_FILES", this->BaseConst_.ListFiles, true) ||
  2192. !info.GetArray("HEADER_EXTENSIONS", this->BaseConst_.HeaderExtensions,
  2193. true)) {
  2194. return false;
  2195. }
  2196. if (this->BaseConst().UseBetterGraph) {
  2197. if (!info.GetStringConfig("DEP_FILE", this->BaseConst_.DepFile, false) ||
  2198. !info.GetStringConfig("DEP_FILE_RULE_NAME",
  2199. this->BaseConst_.DepFileRuleName, false)) {
  2200. return false;
  2201. }
  2202. if (this->BaseConst_.CrossConfig) {
  2203. std::string const mocExecutableWithConfig =
  2204. "QT_MOC_EXECUTABLE_" + this->ExecutableConfig();
  2205. std::string const uicExecutableWithConfig =
  2206. "QT_UIC_EXECUTABLE_" + this->ExecutableConfig();
  2207. if (!info.GetString(mocExecutableWithConfig, this->MocConst_.Executable,
  2208. false) ||
  2209. !info.GetString(uicExecutableWithConfig, this->UicConst_.Executable,
  2210. false)) {
  2211. return false;
  2212. }
  2213. } else {
  2214. if (!info.GetStringConfig("QT_MOC_EXECUTABLE",
  2215. this->MocConst_.Executable, false) ||
  2216. !info.GetStringConfig("QT_UIC_EXECUTABLE",
  2217. this->UicConst_.Executable, false)) {
  2218. return false;
  2219. }
  2220. }
  2221. } else {
  2222. if (!info.GetString("QT_MOC_EXECUTABLE", this->MocConst_.Executable,
  2223. false) ||
  2224. !info.GetString("QT_UIC_EXECUTABLE", this->UicConst_.Executable,
  2225. false) ||
  2226. !info.GetString("DEP_FILE", this->BaseConst_.DepFile, false) ||
  2227. !info.GetString("DEP_FILE_RULE_NAME", this->BaseConst_.DepFileRuleName,
  2228. false)) {
  2229. return false;
  2230. }
  2231. }
  2232. // -- Checks
  2233. if (!this->BaseConst_.CMakeExecutableTime.Load(
  2234. this->BaseConst_.CMakeExecutable)) {
  2235. return info.LogError(
  2236. cmStrCat("The CMake executable ",
  2237. this->MessagePath(this->BaseConst_.CMakeExecutable),
  2238. " does not exist."));
  2239. }
  2240. // -- Evaluate values
  2241. this->BaseConst_.ThreadCount =
  2242. std::min(this->BaseConst_.ThreadCount, ParallelMax);
  2243. this->WorkerPool_.SetThreadCount(this->BaseConst_.ThreadCount);
  2244. // -- Moc
  2245. if (!this->MocConst_.Executable.empty()) {
  2246. // -- Moc is enabled
  2247. this->MocConst_.Enabled = true;
  2248. // -- Temporary buffers
  2249. struct
  2250. {
  2251. std::vector<std::string> MacroNames;
  2252. std::vector<std::string> DependFilters;
  2253. } tmp;
  2254. // -- Required settings
  2255. if (!info.GetBool("MOC_RELAXED_MODE", this->MocConst_.RelaxedMode,
  2256. false) ||
  2257. !info.GetBool("MOC_PATH_PREFIX", this->MocConst_.PathPrefix, true) ||
  2258. !info.GetArray("MOC_SKIP", this->MocConst_.SkipList, false) ||
  2259. !info.GetArrayConfig("MOC_DEFINITIONS", this->MocConst_.Definitions,
  2260. false) ||
  2261. !info.GetArrayConfig("MOC_INCLUDES", this->MocConst_.IncludePaths,
  2262. false) ||
  2263. !info.GetArray("MOC_OPTIONS", this->MocConst_.OptionsExtra, false) ||
  2264. !info.GetStringConfig("MOC_COMPILATION_FILE",
  2265. this->MocConst_.CompFileAbs, true) ||
  2266. !info.GetArray("MOC_PREDEFS_CMD", this->MocConst_.PredefsCmd, false) ||
  2267. !info.GetStringConfig("MOC_PREDEFS_FILE",
  2268. this->MocConst_.PredefsFileAbs,
  2269. !this->MocConst_.PredefsCmd.empty()) ||
  2270. !info.GetArray("MOC_MACRO_NAMES", tmp.MacroNames, true) ||
  2271. !info.GetArray("MOC_DEPEND_FILTERS", tmp.DependFilters, false)) {
  2272. return false;
  2273. }
  2274. // -- Evaluate settings
  2275. for (std::string const& item : tmp.MacroNames) {
  2276. this->MocConst_.MacroFilters.emplace_back(
  2277. item, ("[\n][ \t]*{?[ \t]*" + item).append("[^a-zA-Z0-9_]"));
  2278. }
  2279. // Can moc output dependencies or do we need to setup dependency filters?
  2280. if (this->BaseConst_.QtVersion >= IntegerVersion(5, 15)) {
  2281. this->MocConst_.CanOutputDependencies = true;
  2282. } else {
  2283. Json::Value const& val = info.GetValue("MOC_DEPEND_FILTERS");
  2284. if (!val.isArray()) {
  2285. return info.LogError("MOC_DEPEND_FILTERS JSON value is not an array.");
  2286. }
  2287. Json::ArrayIndex const arraySize = val.size();
  2288. for (Json::ArrayIndex ii = 0; ii != arraySize; ++ii) {
  2289. // Test entry closure
  2290. auto testEntry = [&info, ii](bool test, cm::string_view msg) -> bool {
  2291. if (!test) {
  2292. info.LogError(
  2293. cmStrCat("MOC_DEPEND_FILTERS filter ", ii, ": ", msg));
  2294. }
  2295. return !test;
  2296. };
  2297. Json::Value const& pairVal = val[ii];
  2298. if (testEntry(pairVal.isArray(), "JSON value is not an array.") ||
  2299. testEntry(pairVal.size() == 2, "JSON array size invalid.")) {
  2300. return false;
  2301. }
  2302. Json::Value const& keyVal = pairVal[0u];
  2303. Json::Value const& expVal = pairVal[1u];
  2304. if (testEntry(keyVal.isString(),
  2305. "JSON value for keyword is not a string.") ||
  2306. testEntry(expVal.isString(),
  2307. "JSON value for regular expression is not a string.")) {
  2308. return false;
  2309. }
  2310. std::string const key = keyVal.asString();
  2311. std::string const exp = expVal.asString();
  2312. if (testEntry(!key.empty(), "Keyword is empty.") ||
  2313. testEntry(!exp.empty(), "Regular expression is empty.")) {
  2314. return false;
  2315. }
  2316. this->MocConst_.DependFilters.emplace_back(key, exp);
  2317. if (testEntry(
  2318. this->MocConst_.DependFilters.back().Exp.is_valid(),
  2319. cmStrCat("Regular expression compilation failed.\nKeyword: ",
  2320. Quoted(key), "\nExpression: ", Quoted(exp)))) {
  2321. return false;
  2322. }
  2323. }
  2324. }
  2325. // Check if moc executable exists (by reading the file time)
  2326. if (!this->MocConst_.ExecutableTime.Load(this->MocConst_.Executable)) {
  2327. return info.LogError(cmStrCat(
  2328. "The moc executable ", this->MessagePath(this->MocConst_.Executable),
  2329. " does not exist."));
  2330. }
  2331. }
  2332. // -- Uic
  2333. if (!this->UicConst_.Executable.empty()) {
  2334. // Uic is enabled
  2335. this->UicConst_.Enabled = true;
  2336. // -- Required settings
  2337. if (!info.GetArray("UIC_SKIP", this->UicConst_.SkipList, false) ||
  2338. !info.GetArray("UIC_SEARCH_PATHS", this->UicConst_.SearchPaths,
  2339. false) ||
  2340. !info.GetArrayConfig("UIC_OPTIONS", this->UicConst_.Options, false)) {
  2341. return false;
  2342. }
  2343. // .ui files
  2344. {
  2345. Json::Value const& val = info.GetValue("UIC_UI_FILES");
  2346. if (!val.isArray()) {
  2347. return info.LogError("UIC_UI_FILES JSON value is not an array.");
  2348. }
  2349. Json::ArrayIndex const arraySize = val.size();
  2350. for (Json::ArrayIndex ii = 0; ii != arraySize; ++ii) {
  2351. // Test entry closure
  2352. auto testEntry = [&info, ii](bool test, cm::string_view msg) -> bool {
  2353. if (!test) {
  2354. info.LogError(cmStrCat("UIC_UI_FILES entry ", ii, ": ", msg));
  2355. }
  2356. return !test;
  2357. };
  2358. Json::Value const& entry = val[ii];
  2359. if (testEntry(entry.isArray(), "JSON value is not an array.") ||
  2360. testEntry(entry.size() == 2, "JSON array size invalid.")) {
  2361. return false;
  2362. }
  2363. Json::Value const& entryName = entry[0u];
  2364. Json::Value const& entryOptions = entry[1u];
  2365. if (testEntry(entryName.isString(),
  2366. "JSON value for name is not a string.") ||
  2367. testEntry(entryOptions.isArray(),
  2368. "JSON value for options is not an array.")) {
  2369. return false;
  2370. }
  2371. auto& uiFile = this->UicConst_.UiFiles[entryName.asString()];
  2372. InfoT::GetJsonArray(uiFile.Options, entryOptions);
  2373. }
  2374. }
  2375. // -- Evaluate settings
  2376. // Check if uic executable exists (by reading the file time)
  2377. if (!this->UicConst_.ExecutableTime.Load(this->UicConst_.Executable)) {
  2378. return info.LogError(cmStrCat(
  2379. "The uic executable ", this->MessagePath(this->UicConst_.Executable),
  2380. " does not exist."));
  2381. }
  2382. }
  2383. // -- Headers
  2384. {
  2385. Json::Value const& val = info.GetValue("HEADERS");
  2386. if (!val.isArray()) {
  2387. return info.LogError("HEADERS JSON value is not an array.");
  2388. }
  2389. Json::ArrayIndex const arraySize = val.size();
  2390. for (Json::ArrayIndex ii = 0; ii != arraySize; ++ii) {
  2391. // Test entry closure
  2392. auto testEntry = [&info, ii](bool test, cm::string_view msg) -> bool {
  2393. if (!test) {
  2394. info.LogError(cmStrCat("HEADERS entry ", ii, ": ", msg));
  2395. }
  2396. return !test;
  2397. };
  2398. Json::Value const& entry = val[ii];
  2399. if (testEntry(entry.isArray(), "JSON value is not an array.") ||
  2400. testEntry(entry.size() == 4, "JSON array size invalid.")) {
  2401. return false;
  2402. }
  2403. Json::Value const& entryName = entry[0u];
  2404. Json::Value const& entryFlags = entry[1u];
  2405. Json::Value const& entryBuild = entry[2u];
  2406. Json::Value const& entryConfigs = entry[3u];
  2407. if (testEntry(entryName.isString(),
  2408. "JSON value for name is not a string.") ||
  2409. testEntry(entryFlags.isString(),
  2410. "JSON value for flags is not a string.") ||
  2411. testEntry(entryConfigs.isNull() || entryConfigs.isArray(),
  2412. "JSON value for configs is not null or array.") ||
  2413. testEntry(entryBuild.isString(),
  2414. "JSON value for build path is not a string.")) {
  2415. return false;
  2416. }
  2417. std::string name = entryName.asString();
  2418. std::string flags = entryFlags.asString();
  2419. std::string build = entryBuild.asString();
  2420. if (testEntry(flags.size() == 2, "Invalid flags string size")) {
  2421. return false;
  2422. }
  2423. if (entryConfigs.isArray()) {
  2424. bool configFound = false;
  2425. Json::ArrayIndex const configArraySize = entryConfigs.size();
  2426. for (Json::ArrayIndex ci = 0; ci != configArraySize; ++ci) {
  2427. Json::Value const& config = entryConfigs[ci];
  2428. if (testEntry(config.isString(),
  2429. "JSON value in config array is not a string.")) {
  2430. return false;
  2431. }
  2432. configFound = configFound || config.asString() == this->InfoConfig();
  2433. }
  2434. if (!configFound) {
  2435. continue;
  2436. }
  2437. }
  2438. cmFileTime fileTime;
  2439. if (!fileTime.Load(name)) {
  2440. return info.LogError(cmStrCat(
  2441. "The header file ", this->MessagePath(name), " does not exist."));
  2442. }
  2443. SourceFileHandleT sourceHandle = std::make_shared<SourceFileT>(name);
  2444. sourceHandle->FileTime = fileTime;
  2445. sourceHandle->IsHeader = true;
  2446. sourceHandle->Moc = (flags[0] == 'M');
  2447. sourceHandle->Uic = (flags[1] == 'U');
  2448. if (sourceHandle->Moc && this->MocConst().Enabled) {
  2449. if (build.empty()) {
  2450. return info.LogError(
  2451. cmStrCat("Header file ", ii, " build path is empty"));
  2452. }
  2453. sourceHandle->BuildPath = std::move(build);
  2454. }
  2455. this->BaseEval().Headers.emplace(std::move(name),
  2456. std::move(sourceHandle));
  2457. }
  2458. }
  2459. // -- Sources
  2460. {
  2461. Json::Value const& val = info.GetValue("SOURCES");
  2462. if (!val.isArray()) {
  2463. return info.LogError("SOURCES JSON value is not an array.");
  2464. }
  2465. Json::ArrayIndex const arraySize = val.size();
  2466. for (Json::ArrayIndex ii = 0; ii != arraySize; ++ii) {
  2467. // Test entry closure
  2468. auto testEntry = [&info, ii](bool test, cm::string_view msg) -> bool {
  2469. if (!test) {
  2470. info.LogError(cmStrCat("SOURCES entry ", ii, ": ", msg));
  2471. }
  2472. return !test;
  2473. };
  2474. Json::Value const& entry = val[ii];
  2475. if (testEntry(entry.isArray(), "JSON value is not an array.") ||
  2476. testEntry(entry.size() == 3, "JSON array size invalid.")) {
  2477. return false;
  2478. }
  2479. Json::Value const& entryName = entry[0u];
  2480. Json::Value const& entryFlags = entry[1u];
  2481. Json::Value const& entryConfigs = entry[2u];
  2482. if (testEntry(entryName.isString(),
  2483. "JSON value for name is not a string.") ||
  2484. testEntry(entryFlags.isString(),
  2485. "JSON value for flags is not a string.") ||
  2486. testEntry(entryConfigs.isNull() || entryConfigs.isArray(),
  2487. "JSON value for configs is not null or array.")) {
  2488. return false;
  2489. }
  2490. std::string name = entryName.asString();
  2491. std::string flags = entryFlags.asString();
  2492. if (testEntry(flags.size() == 2, "Invalid flags string size")) {
  2493. return false;
  2494. }
  2495. if (entryConfigs.isArray()) {
  2496. bool configFound = false;
  2497. Json::ArrayIndex const configArraySize = entryConfigs.size();
  2498. for (Json::ArrayIndex ci = 0; ci != configArraySize; ++ci) {
  2499. Json::Value const& config = entryConfigs[ci];
  2500. if (testEntry(config.isString(),
  2501. "JSON value in config array is not a string.")) {
  2502. return false;
  2503. }
  2504. configFound = configFound || config.asString() == this->InfoConfig();
  2505. }
  2506. if (!configFound) {
  2507. continue;
  2508. }
  2509. }
  2510. cmFileTime fileTime;
  2511. if (!fileTime.Load(name)) {
  2512. return info.LogError(cmStrCat(
  2513. "The source file ", this->MessagePath(name), " does not exist."));
  2514. }
  2515. SourceFileHandleT sourceHandle = std::make_shared<SourceFileT>(name);
  2516. sourceHandle->FileTime = fileTime;
  2517. sourceHandle->IsHeader = false;
  2518. sourceHandle->Moc = (flags[0] == 'M');
  2519. sourceHandle->Uic = (flags[1] == 'U');
  2520. this->BaseEval().Sources.emplace(std::move(name),
  2521. std::move(sourceHandle));
  2522. }
  2523. }
  2524. // -- Init derived information
  2525. // Moc variables
  2526. if (this->MocConst().Enabled) {
  2527. // Compose moc includes list
  2528. {
  2529. // Compute framework paths
  2530. std::set<std::string> frameworkPaths;
  2531. for (std::string const& path : this->MocConst().IncludePaths) {
  2532. // Extract framework path
  2533. if (cmHasLiteralSuffix(path, ".framework/Headers")) {
  2534. // Go up twice to get to the framework root
  2535. std::vector<std::string> pathComponents;
  2536. cmSystemTools::SplitPath(path, pathComponents);
  2537. frameworkPaths.emplace(cmSystemTools::JoinPath(
  2538. pathComponents.begin(), pathComponents.end() - 2));
  2539. }
  2540. }
  2541. // Reserve options
  2542. this->MocConst_.OptionsIncludes.reserve(
  2543. this->MocConst().IncludePaths.size() + frameworkPaths.size() * 2);
  2544. // Append includes
  2545. for (std::string const& path : this->MocConst().IncludePaths) {
  2546. this->MocConst_.OptionsIncludes.emplace_back("-I" + path);
  2547. }
  2548. // Append framework includes
  2549. for (std::string const& path : frameworkPaths) {
  2550. this->MocConst_.OptionsIncludes.emplace_back("-F");
  2551. this->MocConst_.OptionsIncludes.push_back(path);
  2552. }
  2553. }
  2554. // Compose moc definitions list
  2555. {
  2556. this->MocConst_.OptionsDefinitions.reserve(
  2557. this->MocConst().Definitions.size());
  2558. for (std::string const& def : this->MocConst().Definitions) {
  2559. this->MocConst_.OptionsDefinitions.emplace_back("-D" + def);
  2560. }
  2561. }
  2562. }
  2563. return true;
  2564. }
  2565. template <class JOBTYPE>
  2566. void cmQtAutoMocUicT::CreateParseJobs(SourceFileMapT const& sourceMap)
  2567. {
  2568. cmFileTime const parseCacheTime = this->BaseEval().ParseCacheTime;
  2569. ParseCacheT& parseCache = this->BaseEval().ParseCache;
  2570. for (auto const& src : sourceMap) {
  2571. // Get or create the file parse data reference
  2572. ParseCacheT::GetOrInsertT cacheEntry = parseCache.GetOrInsert(src.first);
  2573. src.second->ParseData = std::move(cacheEntry.first);
  2574. // Create a parse job if the cache file was missing or is older
  2575. if (cacheEntry.second || src.second->FileTime.Newer(parseCacheTime)) {
  2576. this->BaseEval().ParseCacheChanged = true;
  2577. this->WorkerPool().EmplaceJob<JOBTYPE>(src.second);
  2578. }
  2579. }
  2580. }
  2581. void cmQtAutoMocUicT::InitJobs()
  2582. {
  2583. // Add moc_predefs.h job
  2584. if (this->MocConst().Enabled && !this->MocConst().PredefsCmd.empty()) {
  2585. this->WorkerPool().EmplaceJob<JobMocPredefsT>();
  2586. }
  2587. // Add header parse jobs
  2588. this->CreateParseJobs<JobParseHeaderT>(this->BaseEval().Headers);
  2589. // Add source parse jobs
  2590. this->CreateParseJobs<JobParseSourceT>(this->BaseEval().Sources);
  2591. // Add parse cache evaluations jobs
  2592. {
  2593. // Add a fence job to ensure all parsing has finished
  2594. this->WorkerPool().EmplaceJob<JobFenceT>();
  2595. if (this->MocConst().Enabled) {
  2596. this->WorkerPool().EmplaceJob<JobEvalCacheMocT>();
  2597. }
  2598. if (this->UicConst().Enabled) {
  2599. this->WorkerPool().EmplaceJob<JobEvalCacheUicT>();
  2600. }
  2601. // Add evaluate job
  2602. this->WorkerPool().EmplaceJob<JobEvalCacheFinishT>();
  2603. }
  2604. }
  2605. bool cmQtAutoMocUicT::Process()
  2606. {
  2607. this->SettingsFileRead();
  2608. this->ParseCacheRead();
  2609. if (!this->CreateDirectories()) {
  2610. return false;
  2611. }
  2612. this->InitJobs();
  2613. if (!this->WorkerPool_.Process(this)) {
  2614. return false;
  2615. }
  2616. if (this->JobError_) {
  2617. return false;
  2618. }
  2619. if (!this->ParseCacheWrite()) {
  2620. return false;
  2621. }
  2622. if (!this->SettingsFileWrite()) {
  2623. return false;
  2624. }
  2625. return true;
  2626. }
  2627. void cmQtAutoMocUicT::SettingsFileRead()
  2628. {
  2629. // Compose current settings strings
  2630. {
  2631. cmCryptoHash cryptoHash(cmCryptoHash::AlgoSHA256);
  2632. auto cha = [&cryptoHash](cm::string_view value) {
  2633. cryptoHash.Append(value);
  2634. cryptoHash.Append(";");
  2635. };
  2636. if (this->MocConst_.Enabled) {
  2637. cryptoHash.Initialize();
  2638. cha(this->MocConst().Executable);
  2639. for (auto const& item : this->MocConst().OptionsDefinitions) {
  2640. cha(item);
  2641. }
  2642. for (auto const& item : this->MocConst().OptionsIncludes) {
  2643. cha(item);
  2644. }
  2645. for (auto const& item : this->MocConst().OptionsExtra) {
  2646. cha(item);
  2647. }
  2648. for (auto const& item : this->MocConst().PredefsCmd) {
  2649. cha(item);
  2650. }
  2651. for (auto const& filter : this->MocConst().DependFilters) {
  2652. cha(filter.Key);
  2653. }
  2654. for (auto const& filter : this->MocConst().MacroFilters) {
  2655. cha(filter.Key);
  2656. }
  2657. this->SettingsStringMoc_ = cryptoHash.FinalizeHex();
  2658. }
  2659. if (this->UicConst().Enabled) {
  2660. cryptoHash.Initialize();
  2661. cha(this->UicConst().Executable);
  2662. std::for_each(this->UicConst().Options.begin(),
  2663. this->UicConst().Options.end(), cha);
  2664. for (auto const& item : this->UicConst().UiFiles) {
  2665. cha(item.first);
  2666. auto const& opts = item.second.Options;
  2667. std::for_each(opts.begin(), opts.end(), cha);
  2668. }
  2669. this->SettingsStringUic_ = cryptoHash.FinalizeHex();
  2670. }
  2671. }
  2672. // Read old settings and compare
  2673. {
  2674. std::string content;
  2675. if (cmQtAutoGenerator::FileRead(content, this->SettingsFile_)) {
  2676. if (this->MocConst().Enabled) {
  2677. if (this->SettingsStringMoc_ != SettingsFind(content, "moc")) {
  2678. this->MocConst_.SettingsChanged = true;
  2679. }
  2680. }
  2681. if (this->UicConst().Enabled) {
  2682. if (this->SettingsStringUic_ != SettingsFind(content, "uic")) {
  2683. this->UicConst_.SettingsChanged = true;
  2684. }
  2685. }
  2686. // In case any setting changed remove the old settings file.
  2687. // This triggers a full rebuild on the next run if the current
  2688. // build is aborted before writing the current settings in the end.
  2689. if (this->MocConst().SettingsChanged ||
  2690. this->UicConst().SettingsChanged) {
  2691. cmSystemTools::RemoveFile(this->SettingsFile_);
  2692. }
  2693. } else {
  2694. // Settings file read failed
  2695. if (this->MocConst().Enabled) {
  2696. this->MocConst_.SettingsChanged = true;
  2697. }
  2698. if (this->UicConst().Enabled) {
  2699. this->UicConst_.SettingsChanged = true;
  2700. }
  2701. }
  2702. }
  2703. }
  2704. bool cmQtAutoMocUicT::SettingsFileWrite()
  2705. {
  2706. // Only write if any setting changed
  2707. if (this->MocConst().SettingsChanged || this->UicConst().SettingsChanged) {
  2708. if (this->Log().Verbose()) {
  2709. this->Log().Info(GenT::GEN,
  2710. cmStrCat("Writing the settings file ",
  2711. this->MessagePath(this->SettingsFile_)));
  2712. }
  2713. // Compose settings file content
  2714. std::string content;
  2715. {
  2716. auto SettingAppend = [&content](cm::string_view key,
  2717. cm::string_view value) {
  2718. if (!value.empty()) {
  2719. content += cmStrCat(key, ':', value, '\n');
  2720. }
  2721. };
  2722. SettingAppend("moc", this->SettingsStringMoc_);
  2723. SettingAppend("uic", this->SettingsStringUic_);
  2724. }
  2725. // Write settings file
  2726. std::string error;
  2727. if (!cmQtAutoGenerator::FileWrite(this->SettingsFile_, content, &error)) {
  2728. this->Log().Error(GenT::GEN,
  2729. cmStrCat("Writing the settings file ",
  2730. this->MessagePath(this->SettingsFile_),
  2731. " failed.\n", error));
  2732. // Remove old settings file to trigger a full rebuild on the next run
  2733. cmSystemTools::RemoveFile(this->SettingsFile_);
  2734. return false;
  2735. }
  2736. }
  2737. return true;
  2738. }
  2739. void cmQtAutoMocUicT::ParseCacheRead()
  2740. {
  2741. cm::string_view reason;
  2742. // Don't read the cache if it is invalid
  2743. if (!this->BaseEval().ParseCacheTime.Load(
  2744. this->BaseConst().ParseCacheFile)) {
  2745. reason = "Refreshing parse cache because it doesn't exist.";
  2746. } else if (this->MocConst().SettingsChanged ||
  2747. this->UicConst().SettingsChanged) {
  2748. reason = "Refreshing parse cache because the settings changed.";
  2749. } else if (this->BaseEval().ParseCacheTime.Older(
  2750. this->BaseConst().CMakeExecutableTime)) {
  2751. reason =
  2752. "Refreshing parse cache because it is older than the CMake executable.";
  2753. }
  2754. if (!reason.empty()) {
  2755. // Don't read but refresh the complete parse cache
  2756. if (this->Log().Verbose()) {
  2757. this->Log().Info(GenT::GEN, reason);
  2758. }
  2759. this->BaseEval().ParseCacheChanged = true;
  2760. } else {
  2761. // Read parse cache
  2762. this->BaseEval().ParseCache.ReadFromFile(this->BaseConst().ParseCacheFile);
  2763. }
  2764. }
  2765. bool cmQtAutoMocUicT::ParseCacheWrite()
  2766. {
  2767. if (this->BaseEval().ParseCacheChanged) {
  2768. if (this->Log().Verbose()) {
  2769. this->Log().Info(
  2770. GenT::GEN,
  2771. cmStrCat("Writing the parse cache file ",
  2772. this->MessagePath(this->BaseConst().ParseCacheFile)));
  2773. }
  2774. if (!this->BaseEval().ParseCache.WriteToFile(
  2775. this->BaseConst().ParseCacheFile)) {
  2776. this->Log().Error(
  2777. GenT::GEN,
  2778. cmStrCat("Writing the parse cache file ",
  2779. this->MessagePath(this->BaseConst().ParseCacheFile),
  2780. " failed."));
  2781. return false;
  2782. }
  2783. }
  2784. return true;
  2785. }
  2786. bool cmQtAutoMocUicT::CreateDirectories()
  2787. {
  2788. // Create AUTOGEN include directory
  2789. if (!cmSystemTools::MakeDirectory(this->BaseConst().AutogenIncludeDir)) {
  2790. this->Log().Error(
  2791. GenT::GEN,
  2792. cmStrCat("Creating the AUTOGEN include directory ",
  2793. this->MessagePath(this->BaseConst().AutogenIncludeDir),
  2794. " failed."));
  2795. return false;
  2796. }
  2797. return true;
  2798. }
  2799. std::vector<std::string> cmQtAutoMocUicT::dependenciesFromDepFile(
  2800. char const* filePath)
  2801. {
  2802. auto const content = cmReadGccDepfile(filePath);
  2803. if (!content || content->empty()) {
  2804. return {};
  2805. }
  2806. // Moc outputs a depfile with exactly one rule.
  2807. // Discard the rule and return the dependencies.
  2808. return content->front().paths;
  2809. }
  2810. void cmQtAutoMocUicT::Abort(bool error)
  2811. {
  2812. if (error) {
  2813. this->JobError_.store(true);
  2814. }
  2815. this->WorkerPool_.Abort();
  2816. }
  2817. std::string cmQtAutoMocUicT::AbsoluteBuildPath(
  2818. cm::string_view relativePath) const
  2819. {
  2820. return cmStrCat(this->BaseConst().AutogenBuildDir, '/', relativePath);
  2821. }
  2822. std::string cmQtAutoMocUicT::AbsoluteIncludePath(
  2823. cm::string_view relativePath) const
  2824. {
  2825. return cmStrCat(this->BaseConst().AutogenIncludeDir, '/', relativePath);
  2826. }
  2827. } // End of unnamed namespace
  2828. bool cmQtAutoMocUic(cm::string_view infoFile, cm::string_view config,
  2829. cm::string_view executableConfig)
  2830. {
  2831. return cmQtAutoMocUicT().Run(infoFile, config, executableConfig);
  2832. }