cmQtAutoMocUic.cxx 101 KB

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