cmQtAutoMocUic.cxx 97 KB

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