cmQtAutoMocUic.cxx 97 KB

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