cmQtAutoMocUic.cxx 100 KB

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