Imported Upstream version 3.17.5
[platform/upstream/cmake.git] / Source / cmQtAutoGenInitializer.cxx
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 "cmQtAutoGenInitializer.h"
4
5 #include <cstddef>
6 #include <deque>
7 #include <initializer_list>
8 #include <map>
9 #include <ostream>
10 #include <set>
11 #include <string>
12 #include <unordered_set>
13 #include <utility>
14 #include <vector>
15
16 #include <cm/algorithm>
17 #include <cm/iterator>
18 #include <cm/memory>
19
20 #include "cmsys/SystemInformation.hxx"
21
22 #include "cm_jsoncpp_value.h"
23 #include "cm_jsoncpp_writer.h"
24
25 #include "cmAlgorithms.h"
26 #include "cmCustomCommand.h"
27 #include "cmCustomCommandLines.h"
28 #include "cmGeneratedFileStream.h"
29 #include "cmGeneratorExpression.h"
30 #include "cmGeneratorTarget.h"
31 #include "cmGlobalGenerator.h"
32 #include "cmLinkItem.h"
33 #include "cmListFileCache.h"
34 #include "cmLocalGenerator.h"
35 #include "cmMakefile.h"
36 #include "cmMessageType.h"
37 #include "cmPolicies.h"
38 #include "cmQtAutoGen.h"
39 #include "cmQtAutoGenGlobalInitializer.h"
40 #include "cmSourceFile.h"
41 #include "cmSourceFileLocationKind.h"
42 #include "cmSourceGroup.h"
43 #include "cmState.h"
44 #include "cmStateTypes.h"
45 #include "cmStringAlgorithms.h"
46 #include "cmSystemTools.h"
47 #include "cmTarget.h"
48 #include "cmake.h"
49
50 namespace {
51
52 unsigned int GetParallelCPUCount()
53 {
54   static unsigned int count = 0;
55   // Detect only on the first call
56   if (count == 0) {
57     cmsys::SystemInformation info;
58     info.RunCPUCheck();
59     count =
60       cm::clamp(info.GetNumberOfPhysicalCPU(), 1u, cmQtAutoGen::ParallelMax);
61   }
62   return count;
63 }
64
65 std::string FileProjectRelativePath(cmMakefile* makefile,
66                                     std::string const& fileName)
67 {
68   std::string res;
69   {
70     std::string pSource = cmSystemTools::RelativePath(
71       makefile->GetCurrentSourceDirectory(), fileName);
72     std::string pBinary = cmSystemTools::RelativePath(
73       makefile->GetCurrentBinaryDirectory(), fileName);
74     if (pSource.size() < pBinary.size()) {
75       res = std::move(pSource);
76     } else if (pBinary.size() < fileName.size()) {
77       res = std::move(pBinary);
78     } else {
79       res = fileName;
80     }
81   }
82   return res;
83 }
84
85 /**
86  * Tests if targetDepend is a STATIC_LIBRARY and if any of its
87  * recursive STATIC_LIBRARY dependencies depends on targetOrigin
88  * (STATIC_LIBRARY cycle).
89  */
90 bool StaticLibraryCycle(cmGeneratorTarget const* targetOrigin,
91                         cmGeneratorTarget const* targetDepend,
92                         std::string const& config)
93 {
94   bool cycle = false;
95   if ((targetOrigin->GetType() == cmStateEnums::STATIC_LIBRARY) &&
96       (targetDepend->GetType() == cmStateEnums::STATIC_LIBRARY)) {
97     std::set<cmGeneratorTarget const*> knownLibs;
98     std::deque<cmGeneratorTarget const*> testLibs;
99
100     // Insert initial static_library dependency
101     knownLibs.insert(targetDepend);
102     testLibs.push_back(targetDepend);
103
104     while (!testLibs.empty()) {
105       cmGeneratorTarget const* testTarget = testLibs.front();
106       testLibs.pop_front();
107       // Check if the test target is the origin target (cycle)
108       if (testTarget == targetOrigin) {
109         cycle = true;
110         break;
111       }
112       // Collect all static_library dependencies from the test target
113       cmLinkImplementationLibraries const* libs =
114         testTarget->GetLinkImplementationLibraries(config);
115       if (libs != nullptr) {
116         for (cmLinkItem const& item : libs->Libraries) {
117           cmGeneratorTarget const* depTarget = item.Target;
118           if ((depTarget != nullptr) &&
119               (depTarget->GetType() == cmStateEnums::STATIC_LIBRARY) &&
120               knownLibs.insert(depTarget).second) {
121             testLibs.push_back(depTarget);
122           }
123         }
124       }
125     }
126   }
127   return cycle;
128 }
129
130 /** Sanitizes file search paths.  */
131 class SearchPathSanitizer
132 {
133 public:
134   SearchPathSanitizer(cmMakefile* makefile)
135     : SourcePath_(makefile->GetCurrentSourceDirectory())
136   {
137   }
138   std::vector<std::string> operator()(
139     std::vector<std::string> const& paths) const;
140
141 private:
142   std::string SourcePath_;
143 };
144
145 std::vector<std::string> SearchPathSanitizer::operator()(
146   std::vector<std::string> const& paths) const
147 {
148   std::vector<std::string> res;
149   res.reserve(paths.size());
150   for (std::string const& srcPath : paths) {
151     // Collapse relative paths
152     std::string path = cmSystemTools::CollapseFullPath(srcPath, SourcePath_);
153     // Remove suffix slashes
154     while (cmHasSuffix(path, '/')) {
155       path.pop_back();
156     }
157     // Accept only non empty paths
158     if (!path.empty()) {
159       res.emplace_back(std::move(path));
160     }
161   }
162   return res;
163 }
164
165 /** @brief Writes a CMake info file.  */
166 class InfoWriter
167 {
168 public:
169   // -- Single value
170   void Set(std::string const& key, std::string const& value)
171   {
172     Value_[key] = value;
173   }
174   void SetConfig(std::string const& key,
175                  cmQtAutoGenInitializer::ConfigString const& cfgStr);
176   void SetBool(std::string const& key, bool value) { Value_[key] = value; }
177   void SetUInt(std::string const& key, unsigned int value)
178   {
179     Value_[key] = value;
180   }
181
182   // -- Array utility
183   template <typename CONT>
184   static bool MakeArray(Json::Value& jval, CONT const& container);
185
186   template <typename CONT>
187   static void MakeStringArray(Json::Value& jval, CONT const& container);
188
189   // -- Array value
190   template <typename CONT>
191   void SetArray(std::string const& key, CONT const& container);
192   template <typename CONT>
193   void SetConfigArray(
194     std::string const& key,
195     cmQtAutoGenInitializer::ConfigStrings<CONT> const& cfgStr);
196
197   // -- Array of arrays
198   template <typename CONT, typename FUNC>
199   void SetArrayArray(std::string const& key, CONT const& container, FUNC func);
200
201   // -- Save to json file
202   bool Save(std::string const& filename);
203
204 private:
205   Json::Value Value_;
206 };
207
208 void InfoWriter::SetConfig(std::string const& key,
209                            cmQtAutoGenInitializer::ConfigString const& cfgStr)
210 {
211   Set(key, cfgStr.Default);
212   for (auto const& item : cfgStr.Config) {
213     Set(cmStrCat(key, '_', item.first), item.second);
214   }
215 }
216
217 template <typename CONT>
218 bool InfoWriter::MakeArray(Json::Value& jval, CONT const& container)
219 {
220   jval = Json::arrayValue;
221   std::size_t const listSize = cm::size(container);
222   if (listSize == 0) {
223     return false;
224   }
225   jval.resize(static_cast<unsigned int>(listSize));
226   return true;
227 }
228
229 template <typename CONT>
230 void InfoWriter::MakeStringArray(Json::Value& jval, CONT const& container)
231 {
232   if (MakeArray(jval, container)) {
233     Json::ArrayIndex ii = 0;
234     for (std::string const& item : container) {
235       jval[ii++] = item;
236     }
237   }
238 }
239
240 template <typename CONT>
241 void InfoWriter::SetArray(std::string const& key, CONT const& container)
242 {
243   MakeStringArray(Value_[key], container);
244 }
245
246 template <typename CONT, typename FUNC>
247 void InfoWriter::SetArrayArray(std::string const& key, CONT const& container,
248                                FUNC func)
249 {
250   Json::Value& jval = Value_[key];
251   if (MakeArray(jval, container)) {
252     Json::ArrayIndex ii = 0;
253     for (auto const& citem : container) {
254       Json::Value& aval = jval[ii++];
255       aval = Json::arrayValue;
256       func(aval, citem);
257     }
258   }
259 }
260
261 template <typename CONT>
262 void InfoWriter::SetConfigArray(
263   std::string const& key,
264   cmQtAutoGenInitializer::ConfigStrings<CONT> const& cfgStr)
265 {
266   SetArray(key, cfgStr.Default);
267   for (auto const& item : cfgStr.Config) {
268     SetArray(cmStrCat(key, '_', item.first), item.second);
269   }
270 }
271
272 bool InfoWriter::Save(std::string const& filename)
273 {
274   cmGeneratedFileStream fileStream;
275   fileStream.SetCopyIfDifferent(true);
276   fileStream.Open(filename, false, true);
277   if (!fileStream) {
278     return false;
279   }
280
281   Json::StyledStreamWriter jsonWriter;
282   try {
283     jsonWriter.write(fileStream, Value_);
284   } catch (...) {
285     return false;
286   }
287
288   return fileStream.Close();
289 }
290
291 } // End of unnamed namespace
292
293 cmQtAutoGenInitializer::cmQtAutoGenInitializer(
294   cmQtAutoGenGlobalInitializer* globalInitializer,
295   cmGeneratorTarget* genTarget, IntegerVersion const& qtVersion,
296   bool mocEnabled, bool uicEnabled, bool rccEnabled, bool globalAutogenTarget,
297   bool globalAutoRccTarget)
298   : GlobalInitializer(globalInitializer)
299   , GenTarget(genTarget)
300   , GlobalGen(genTarget->GetGlobalGenerator())
301   , LocalGen(genTarget->GetLocalGenerator())
302   , Makefile(genTarget->Makefile)
303   , PathCheckSum(genTarget->Makefile)
304   , QtVersion(qtVersion)
305 {
306   AutogenTarget.GlobalTarget = globalAutogenTarget;
307   Moc.Enabled = mocEnabled;
308   Uic.Enabled = uicEnabled;
309   Rcc.Enabled = rccEnabled;
310   Rcc.GlobalTarget = globalAutoRccTarget;
311 }
312
313 bool cmQtAutoGenInitializer::InitCustomTargets()
314 {
315   // Configurations
316   this->MultiConfig = this->GlobalGen->IsMultiConfig();
317   this->ConfigDefault = this->Makefile->GetConfigurations(this->ConfigsList);
318   if (this->ConfigsList.empty()) {
319     this->ConfigsList.push_back(this->ConfigDefault);
320   }
321
322   // Verbosity
323   {
324     std::string def =
325       this->Makefile->GetSafeDefinition("CMAKE_AUTOGEN_VERBOSE");
326     if (!def.empty()) {
327       unsigned long iVerb = 0;
328       if (cmStrToULong(def, &iVerb)) {
329         // Numeric verbosity
330         this->Verbosity = static_cast<unsigned int>(iVerb);
331       } else {
332         // Non numeric verbosity
333         if (cmIsOn(def)) {
334           this->Verbosity = 1;
335         }
336       }
337     }
338   }
339
340   // Targets FOLDER
341   {
342     const char* folder =
343       this->Makefile->GetState()->GetGlobalProperty("AUTOMOC_TARGETS_FOLDER");
344     if (folder == nullptr) {
345       folder = this->Makefile->GetState()->GetGlobalProperty(
346         "AUTOGEN_TARGETS_FOLDER");
347     }
348     // Inherit FOLDER property from target (#13688)
349     if (folder == nullptr) {
350       folder = this->GenTarget->GetProperty("FOLDER");
351     }
352     if (folder != nullptr) {
353       this->TargetsFolder = folder;
354     }
355   }
356
357   // Check status of policy CMP0071 regarding handling of GENERATED files
358   switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0071)) {
359     case cmPolicies::WARN:
360       // Ignore GENERATED files but warn
361       this->CMP0071Warn = true;
362       CM_FALLTHROUGH;
363     case cmPolicies::OLD:
364       // Ignore GENERATED files
365       break;
366     case cmPolicies::REQUIRED_IF_USED:
367     case cmPolicies::REQUIRED_ALWAYS:
368     case cmPolicies::NEW:
369       // Process GENERATED files
370       this->CMP0071Accept = true;
371       break;
372   }
373
374   // Check status of policy CMP0100 regarding handling of .hh headers
375   switch (this->Makefile->GetPolicyStatus(cmPolicies::CMP0100)) {
376     case cmPolicies::WARN:
377       // Ignore but .hh files but warn
378       this->CMP0100Warn = true;
379       CM_FALLTHROUGH;
380     case cmPolicies::OLD:
381       // Ignore .hh files
382       break;
383     case cmPolicies::REQUIRED_IF_USED:
384     case cmPolicies::REQUIRED_ALWAYS:
385     case cmPolicies::NEW:
386       // Process .hh file
387       this->CMP0100Accept = true;
388       break;
389   }
390
391   // Common directories
392   {
393     // Collapsed current binary directory
394     std::string const cbd = cmSystemTools::CollapseFullPath(
395       std::string(), this->Makefile->GetCurrentBinaryDirectory());
396
397     // Info directory
398     this->Dir.Info = cmStrCat(cbd, "/CMakeFiles/", this->GenTarget->GetName(),
399                               "_autogen.dir");
400     cmSystemTools::ConvertToUnixSlashes(this->Dir.Info);
401
402     // Build directory
403     this->Dir.Build = this->GenTarget->GetSafeProperty("AUTOGEN_BUILD_DIR");
404     if (this->Dir.Build.empty()) {
405       this->Dir.Build =
406         cmStrCat(cbd, '/', this->GenTarget->GetName(), "_autogen");
407     }
408     cmSystemTools::ConvertToUnixSlashes(this->Dir.Build);
409     // Cleanup build directory
410     this->AddCleanFile(this->Dir.Build);
411
412     // Working directory
413     this->Dir.Work = cbd;
414     cmSystemTools::ConvertToUnixSlashes(this->Dir.Work);
415
416     // Include directory
417     ConfigFileNames(this->Dir.Include, cmStrCat(this->Dir.Build, "/include"),
418                     "");
419     this->Dir.IncludeGenExp = this->Dir.Include.Default;
420     if (this->MultiConfig) {
421       this->Dir.IncludeGenExp += "_$<CONFIG>";
422     }
423   }
424
425   // Moc, Uic and _autogen target settings
426   if (this->MocOrUicEnabled()) {
427     // Init moc specific settings
428     if (this->Moc.Enabled && !InitMoc()) {
429       return false;
430     }
431
432     // Init uic specific settings
433     if (this->Uic.Enabled && !InitUic()) {
434       return false;
435     }
436
437     // Autogen target name
438     this->AutogenTarget.Name =
439       cmStrCat(this->GenTarget->GetName(), "_autogen");
440
441     // Autogen target parallel processing
442     {
443       std::string prop = this->GenTarget->GetSafeProperty("AUTOGEN_PARALLEL");
444       if (prop.empty() || (prop == "AUTO")) {
445         // Autodetect number of CPUs
446         this->AutogenTarget.Parallel = GetParallelCPUCount();
447       } else {
448         this->AutogenTarget.Parallel = 1;
449       }
450     }
451
452     // Autogen target info and settings files
453     {
454       // Info file
455       this->AutogenTarget.InfoFile =
456         cmStrCat(this->Dir.Info, "/AutogenInfo.json");
457
458       // Used settings file
459       ConfigFileNames(this->AutogenTarget.SettingsFile,
460                       cmStrCat(this->Dir.Info, "/AutogenUsed"), ".txt");
461       ConfigFileClean(this->AutogenTarget.SettingsFile);
462
463       // Parse cache file
464       ConfigFileNames(this->AutogenTarget.ParseCacheFile,
465                       cmStrCat(this->Dir.Info, "/ParseCache"), ".txt");
466       ConfigFileClean(this->AutogenTarget.ParseCacheFile);
467     }
468
469     // Autogen target: Compute user defined dependencies
470     {
471       this->AutogenTarget.DependOrigin =
472         this->GenTarget->GetPropertyAsBool("AUTOGEN_ORIGIN_DEPENDS");
473
474       std::string const deps =
475         this->GenTarget->GetSafeProperty("AUTOGEN_TARGET_DEPENDS");
476       if (!deps.empty()) {
477         for (std::string const& depName : cmExpandedList(deps)) {
478           // Allow target and file dependencies
479           auto* depTarget = this->Makefile->FindTargetToUse(depName);
480           if (depTarget != nullptr) {
481             this->AutogenTarget.DependTargets.insert(depTarget);
482           } else {
483             this->AutogenTarget.DependFiles.insert(depName);
484           }
485         }
486       }
487     }
488
489     if (this->Moc.Enabled) {
490       // Path prefix
491       if (cmIsOn(this->GenTarget->GetSafeProperty("AUTOMOC_PATH_PREFIX"))) {
492         this->Moc.PathPrefix = true;
493       }
494
495       // CMAKE_AUTOMOC_RELAXED_MODE
496       if (this->Makefile->IsOn("CMAKE_AUTOMOC_RELAXED_MODE")) {
497         this->Moc.RelaxedMode = true;
498         this->Makefile->IssueMessage(
499           MessageType::AUTHOR_WARNING,
500           cmStrCat("AUTOMOC: CMAKE_AUTOMOC_RELAXED_MODE is "
501                    "deprecated an will be removed in the future.  Consider "
502                    "disabling it and converting the target ",
503                    this->GenTarget->GetName(), " to regular mode."));
504       }
505
506       // Options
507       cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MOC_OPTIONS"),
508                    this->Moc.Options);
509       // Filters
510       cmExpandList(this->GenTarget->GetSafeProperty("AUTOMOC_MACRO_NAMES"),
511                    this->Moc.MacroNames);
512       {
513         auto filterList = cmExpandedList(
514           this->GenTarget->GetSafeProperty("AUTOMOC_DEPEND_FILTERS"));
515         if ((filterList.size() % 2) != 0) {
516           cmSystemTools::Error(
517             cmStrCat("AutoMoc: AUTOMOC_DEPEND_FILTERS predefs size ",
518                      filterList.size(), " is not a multiple of 2."));
519           return false;
520         }
521         this->Moc.DependFilters.reserve(1 + (filterList.size() / 2));
522         this->Moc.DependFilters.emplace_back(
523           "Q_PLUGIN_METADATA",
524           "[\n][ \t]*Q_PLUGIN_METADATA[ \t]*\\("
525           "[^\\)]*FILE[ \t]*\"([^\"]+)\"");
526         for (std::size_t ii = 0; ii != filterList.size(); ii += 2) {
527           this->Moc.DependFilters.emplace_back(filterList[ii],
528                                                filterList[ii + 1]);
529         }
530       }
531     }
532   }
533
534   // Init rcc specific settings
535   if (this->Rcc.Enabled && !InitRcc()) {
536     return false;
537   }
538
539   // Add autogen include directory to the origin target INCLUDE_DIRECTORIES
540   if (this->MocOrUicEnabled() || (this->Rcc.Enabled && this->MultiConfig)) {
541     this->GenTarget->AddIncludeDirectory(this->Dir.IncludeGenExp, true);
542   }
543
544   // Scan files
545   if (!this->InitScanFiles()) {
546     return false;
547   }
548
549   // Create autogen target
550   if (this->MocOrUicEnabled() && !this->InitAutogenTarget()) {
551     return false;
552   }
553
554   // Create rcc targets
555   if (this->Rcc.Enabled && !this->InitRccTargets()) {
556     return false;
557   }
558
559   return true;
560 }
561
562 bool cmQtAutoGenInitializer::InitMoc()
563 {
564   // Mocs compilation file
565   this->Moc.CompilationFile =
566     cmStrCat(this->Dir.Build, "/mocs_compilation.cpp");
567
568   // Moc predefs
569   if (this->GenTarget->GetPropertyAsBool("AUTOMOC_COMPILER_PREDEFINES") &&
570       (this->QtVersion >= IntegerVersion(5, 8))) {
571     // Command
572     cmExpandList(this->Makefile->GetSafeDefinition(
573                    "CMAKE_CXX_COMPILER_PREDEFINES_COMMAND"),
574                  this->Moc.PredefsCmd);
575     // Header
576     if (!this->Moc.PredefsCmd.empty()) {
577       ConfigFileNames(this->Moc.PredefsFile,
578                       cmStrCat(this->Dir.Build, "/moc_predefs"), ".h");
579     }
580   }
581
582   // Moc includes
583   {
584     SearchPathSanitizer sanitizer(this->Makefile);
585     auto getDirs =
586       [this, &sanitizer](std::string const& cfg) -> std::vector<std::string> {
587       // Get the include dirs for this target, without stripping the implicit
588       // include dirs off, see issue #13667.
589       std::vector<std::string> dirs;
590       bool const appendImplicit = (this->QtVersion.Major >= 5);
591       this->LocalGen->GetIncludeDirectoriesImplicit(
592         dirs, this->GenTarget, "CXX", cfg, false, appendImplicit);
593       return sanitizer(dirs);
594     };
595
596     // Default configuration include directories
597     this->Moc.Includes.Default = getDirs(this->ConfigDefault);
598     // Other configuration settings
599     if (this->MultiConfig) {
600       for (std::string const& cfg : this->ConfigsList) {
601         std::vector<std::string> dirs = getDirs(cfg);
602         if (dirs == this->Moc.Includes.Default) {
603           continue;
604         }
605         this->Moc.Includes.Config[cfg] = std::move(dirs);
606       }
607     }
608   }
609
610   // Moc compile definitions
611   {
612     auto getDefs = [this](std::string const& cfg) -> std::set<std::string> {
613       std::set<std::string> defines;
614       this->LocalGen->GetTargetDefines(this->GenTarget, cfg, "CXX", defines);
615 #ifdef _WIN32
616       if (this->Moc.PredefsCmd.empty()) {
617         // Add WIN32 definition if we don't have a moc_predefs.h
618         defines.insert("WIN32");
619       }
620 #endif
621       return defines;
622     };
623
624     // Default configuration defines
625     this->Moc.Defines.Default = getDefs(this->ConfigDefault);
626     // Other configuration defines
627     if (this->MultiConfig) {
628       for (std::string const& cfg : this->ConfigsList) {
629         std::set<std::string> defines = getDefs(cfg);
630         if (defines == this->Moc.Defines.Default) {
631           continue;
632         }
633         this->Moc.Defines.Config[cfg] = std::move(defines);
634       }
635     }
636   }
637
638   // Moc executable
639   {
640     if (!this->GetQtExecutable(this->Moc, "moc", false)) {
641       return false;
642     }
643     // Let the _autogen target depend on the moc executable
644     if (this->Moc.ExecutableTarget != nullptr) {
645       this->AutogenTarget.DependTargets.insert(
646         this->Moc.ExecutableTarget->Target);
647     }
648   }
649
650   return true;
651 }
652
653 bool cmQtAutoGenInitializer::InitUic()
654 {
655   // Uic search paths
656   {
657     std::string const usp =
658       this->GenTarget->GetSafeProperty("AUTOUIC_SEARCH_PATHS");
659     if (!usp.empty()) {
660       this->Uic.SearchPaths =
661         SearchPathSanitizer(this->Makefile)(cmExpandedList(usp));
662     }
663   }
664   // Uic target options
665   {
666     auto getOpts = [this](std::string const& cfg) -> std::vector<std::string> {
667       std::vector<std::string> opts;
668       this->GenTarget->GetAutoUicOptions(opts, cfg);
669       return opts;
670     };
671
672     // Default options
673     this->Uic.Options.Default = getOpts(this->ConfigDefault);
674     // Configuration specific options
675     if (this->MultiConfig) {
676       for (std::string const& cfg : this->ConfigsList) {
677         std::vector<std::string> options = getOpts(cfg);
678         if (options == this->Uic.Options.Default) {
679           continue;
680         }
681         this->Uic.Options.Config[cfg] = std::move(options);
682       }
683     }
684   }
685
686   // Uic executable
687   {
688     if (!this->GetQtExecutable(this->Uic, "uic", true)) {
689       return false;
690     }
691     // Let the _autogen target depend on the uic executable
692     if (this->Uic.ExecutableTarget != nullptr) {
693       this->AutogenTarget.DependTargets.insert(
694         this->Uic.ExecutableTarget->Target);
695     }
696   }
697
698   return true;
699 }
700
701 bool cmQtAutoGenInitializer::InitRcc()
702 {
703   // Rcc executable
704   {
705     if (!this->GetQtExecutable(this->Rcc, "rcc", false)) {
706       return false;
707     }
708     // Evaluate test output on demand
709     CompilerFeatures& features = *this->Rcc.ExecutableFeatures;
710     if (!features.Evaluated) {
711       // Look for list options
712       if (this->QtVersion.Major == 5 || this->QtVersion.Major == 6) {
713         if (features.HelpOutput.find("--list") != std::string::npos) {
714           features.ListOptions.emplace_back("--list");
715         } else if (features.HelpOutput.find("-list") != std::string::npos) {
716           features.ListOptions.emplace_back("-list");
717         }
718       }
719       // Evaluation finished
720       features.Evaluated = true;
721     }
722   }
723
724   return true;
725 }
726
727 bool cmQtAutoGenInitializer::InitScanFiles()
728 {
729   cmake const* cm = this->Makefile->GetCMakeInstance();
730   auto const& kw = this->GlobalInitializer->kw();
731
732   auto makeMUFile = [this, &kw](cmSourceFile* sf, std::string const& fullPath,
733                                 bool muIt) -> MUFileHandle {
734     MUFileHandle muf = cm::make_unique<MUFile>();
735     muf->FullPath = fullPath;
736     muf->SF = sf;
737     muf->Generated = sf->GetIsGenerated();
738     bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
739     muf->SkipMoc = this->Moc.Enabled &&
740       (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOMOC));
741     muf->SkipUic = this->Uic.Enabled &&
742       (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
743     if (muIt) {
744       muf->MocIt = this->Moc.Enabled && !muf->SkipMoc;
745       muf->UicIt = this->Uic.Enabled && !muf->SkipUic;
746     }
747     return muf;
748   };
749
750   auto addMUHeader = [this](MUFileHandle&& muf, cm::string_view extension) {
751     cmSourceFile* sf = muf->SF;
752     const bool muIt = (muf->MocIt || muf->UicIt);
753     if (this->CMP0100Accept || (extension != "hh")) {
754       // Accept
755       if (muIt && muf->Generated) {
756         this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
757       }
758       this->AutogenTarget.Headers.emplace(sf, std::move(muf));
759     } else if (muIt && this->CMP0100Warn) {
760       // Store file for warning message
761       this->AutogenTarget.CMP0100HeadersWarn.push_back(sf);
762     }
763   };
764
765   auto addMUSource = [this](MUFileHandle&& muf) {
766     if ((muf->MocIt || muf->UicIt) && muf->Generated) {
767       this->AutogenTarget.FilesGenerated.emplace_back(muf.get());
768     }
769     this->AutogenTarget.Sources.emplace(muf->SF, std::move(muf));
770   };
771
772   // Scan through target files
773   {
774     // Scan through target files
775     std::vector<cmSourceFile*> srcFiles;
776     this->GenTarget->GetConfigCommonSourceFiles(srcFiles);
777     for (cmSourceFile* sf : srcFiles) {
778       // sf->GetExtension() is only valid after sf->ResolveFullPath() ...
779       // Since we're iterating over source files that might be not in the
780       // target we need to check for path errors (not existing files).
781       std::string pathError;
782       std::string const& fullPath = sf->ResolveFullPath(&pathError);
783       if (!pathError.empty() || fullPath.empty()) {
784         continue;
785       }
786       std::string const& extLower =
787         cmSystemTools::LowerCase(sf->GetExtension());
788
789       // Register files that will be scanned by moc or uic
790       if (this->MocOrUicEnabled()) {
791         if (cm->IsHeaderExtension(extLower)) {
792           addMUHeader(makeMUFile(sf, fullPath, true), extLower);
793         } else if (cm->IsSourceExtension(extLower)) {
794           addMUSource(makeMUFile(sf, fullPath, true));
795         }
796       }
797
798       // Register rcc enabled files
799       if (this->Rcc.Enabled) {
800         if ((extLower == kw.qrc) && !sf->GetPropertyAsBool(kw.SKIP_AUTOGEN) &&
801             !sf->GetPropertyAsBool(kw.SKIP_AUTORCC)) {
802           // Register qrc file
803           Qrc qrc;
804           qrc.QrcFile = fullPath;
805           qrc.QrcName =
806             cmSystemTools::GetFilenameWithoutLastExtension(qrc.QrcFile);
807           qrc.Generated = sf->GetIsGenerated();
808           // RCC options
809           {
810             std::string const opts = sf->GetSafeProperty(kw.AUTORCC_OPTIONS);
811             if (!opts.empty()) {
812               cmExpandList(opts, qrc.Options);
813             }
814           }
815           this->Rcc.Qrcs.push_back(std::move(qrc));
816         }
817       }
818     }
819   }
820   // cmGeneratorTarget::GetConfigCommonSourceFiles computes the target's
821   // sources meta data cache. Clear it so that OBJECT library targets that
822   // are AUTOGEN initialized after this target get their added
823   // mocs_compilation.cpp source acknowledged by this target.
824   this->GenTarget->ClearSourcesCache();
825
826   // For source files find additional headers and private headers
827   if (this->MocOrUicEnabled()) {
828     // Header search suffixes and extensions
829     static std::initializer_list<cm::string_view> const suffixes{ "", "_p" };
830     auto const& exts = cm->GetHeaderExtensions();
831     // Scan through sources
832     for (auto const& pair : this->AutogenTarget.Sources) {
833       MUFile const& muf = *pair.second;
834       if (muf.MocIt || muf.UicIt) {
835         // Search for the default header file and a private header
836         std::string const& srcFullPath = muf.SF->ResolveFullPath();
837         std::string basePath = cmStrCat(
838           cmQtAutoGen::SubDirPrefix(srcFullPath),
839           cmSystemTools::GetFilenameWithoutLastExtension(srcFullPath));
840         for (auto const& suffix : suffixes) {
841           std::string const suffixedPath = cmStrCat(basePath, suffix);
842           for (auto const& ext : exts) {
843             std::string fullPath = cmStrCat(suffixedPath, '.', ext);
844
845             auto constexpr locationKind = cmSourceFileLocationKind::Known;
846             cmSourceFile* sf =
847               this->Makefile->GetSource(fullPath, locationKind);
848             if (sf != nullptr) {
849               // Check if we know about this header already
850               if (cmContains(this->AutogenTarget.Headers, sf)) {
851                 continue;
852               }
853               // We only accept not-GENERATED files that do exist.
854               if (!sf->GetIsGenerated() &&
855                   !cmSystemTools::FileExists(fullPath)) {
856                 continue;
857               }
858             } else if (cmSystemTools::FileExists(fullPath)) {
859               // Create a new source file for the existing file
860               sf = this->Makefile->CreateSource(fullPath, false, locationKind);
861             }
862
863             if (sf != nullptr) {
864               auto eMuf = makeMUFile(sf, fullPath, true);
865               // Ony process moc/uic when the parent is processed as well
866               if (!muf.MocIt) {
867                 eMuf->MocIt = false;
868               }
869               if (!muf.UicIt) {
870                 eMuf->UicIt = false;
871               }
872               addMUHeader(std::move(eMuf), ext);
873             }
874           }
875         }
876       }
877     }
878   }
879
880   // Scan through all source files in the makefile to extract moc and uic
881   // parameters.  Historically we support non target source file parameters.
882   // The reason is that their file names might be discovered from source files
883   // at generation time.
884   if (this->MocOrUicEnabled()) {
885     for (const auto& sf : this->Makefile->GetSourceFiles()) {
886       // sf->GetExtension() is only valid after sf->ResolveFullPath() ...
887       // Since we're iterating over source files that might be not in the
888       // target we need to check for path errors (not existing files).
889       std::string pathError;
890       std::string const& fullPath = sf->ResolveFullPath(&pathError);
891       if (!pathError.empty() || fullPath.empty()) {
892         continue;
893       }
894       std::string const& extLower =
895         cmSystemTools::LowerCase(sf->GetExtension());
896
897       if (cm->IsHeaderExtension(extLower)) {
898         if (!cmContains(this->AutogenTarget.Headers, sf.get())) {
899           auto muf = makeMUFile(sf.get(), fullPath, false);
900           if (muf->SkipMoc || muf->SkipUic) {
901             addMUHeader(std::move(muf), extLower);
902           }
903         }
904       } else if (cm->IsSourceExtension(extLower)) {
905         if (!cmContains(this->AutogenTarget.Sources, sf.get())) {
906           auto muf = makeMUFile(sf.get(), fullPath, false);
907           if (muf->SkipMoc || muf->SkipUic) {
908             addMUSource(std::move(muf));
909           }
910         }
911       } else if (this->Uic.Enabled && (extLower == kw.ui)) {
912         // .ui file
913         bool const skipAutogen = sf->GetPropertyAsBool(kw.SKIP_AUTOGEN);
914         bool const skipUic =
915           (skipAutogen || sf->GetPropertyAsBool(kw.SKIP_AUTOUIC));
916         if (!skipUic) {
917           // Check if the .ui file has uic options
918           std::string const uicOpts = sf->GetSafeProperty(kw.AUTOUIC_OPTIONS);
919           if (!uicOpts.empty()) {
920             this->Uic.UiFiles.emplace_back(fullPath, cmExpandedList(uicOpts));
921           }
922         } else {
923           // Register skipped .ui file
924           this->Uic.SkipUi.insert(fullPath);
925         }
926       }
927     }
928   }
929
930   // Process GENERATED sources and headers
931   if (this->MocOrUicEnabled() && !this->AutogenTarget.FilesGenerated.empty()) {
932     if (this->CMP0071Accept) {
933       // Let the autogen target depend on the GENERATED files
934       for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
935         this->AutogenTarget.DependFiles.insert(muf->FullPath);
936       }
937     } else if (this->CMP0071Warn) {
938       cm::string_view property;
939       if (this->Moc.Enabled && this->Uic.Enabled) {
940         property = "SKIP_AUTOGEN";
941       } else if (this->Moc.Enabled) {
942         property = "SKIP_AUTOMOC";
943       } else if (this->Uic.Enabled) {
944         property = "SKIP_AUTOUIC";
945       }
946       std::string files;
947       for (MUFile* muf : this->AutogenTarget.FilesGenerated) {
948         files += cmStrCat("  ", Quoted(muf->FullPath), '\n');
949       }
950       this->Makefile->IssueMessage(
951         MessageType::AUTHOR_WARNING,
952         cmStrCat(
953           cmPolicies::GetPolicyWarning(cmPolicies::CMP0071), '\n',
954           "For compatibility, CMake is excluding the GENERATED source "
955           "file(s):\n",
956           files, "from processing by ",
957           cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
958           ".  If any of the files should be processed, set CMP0071 to NEW.  "
959           "If any of the files should not be processed, "
960           "explicitly exclude them by setting the source file property ",
961           property, ":\n  set_property(SOURCE file.h PROPERTY ", property,
962           " ON)\n"));
963     }
964   }
965
966   // Generate CMP0100 warning
967   if (this->MocOrUicEnabled() &&
968       !this->AutogenTarget.CMP0100HeadersWarn.empty()) {
969     cm::string_view property;
970     if (this->Moc.Enabled && this->Uic.Enabled) {
971       property = "SKIP_AUTOGEN";
972     } else if (this->Moc.Enabled) {
973       property = "SKIP_AUTOMOC";
974     } else if (this->Uic.Enabled) {
975       property = "SKIP_AUTOUIC";
976     }
977     std::string files;
978     for (cmSourceFile* sf : this->AutogenTarget.CMP0100HeadersWarn) {
979       files += cmStrCat("  ", Quoted(sf->GetFullPath()), '\n');
980     }
981     this->Makefile->IssueMessage(
982       MessageType::AUTHOR_WARNING,
983       cmStrCat(
984         cmPolicies::GetPolicyWarning(cmPolicies::CMP0100), '\n',
985         "For compatibility, CMake is excluding the header file(s):\n", files,
986         "from processing by ",
987         cmQtAutoGen::Tools(this->Moc.Enabled, this->Uic.Enabled, false),
988         ".  If any of the files should be processed, set CMP0100 to NEW.  "
989         "If any of the files should not be processed, "
990         "explicitly exclude them by setting the source file property ",
991         property, ":\n  set_property(SOURCE file.hh PROPERTY ", property,
992         " ON)\n"));
993   }
994
995   // Process qrc files
996   if (!this->Rcc.Qrcs.empty()) {
997     const bool modernQt = (this->QtVersion.Major >= 5);
998     // Target rcc options
999     std::vector<std::string> optionsTarget =
1000       cmExpandedList(this->GenTarget->GetSafeProperty(kw.AUTORCC_OPTIONS));
1001
1002     // Check if file name is unique
1003     for (Qrc& qrc : this->Rcc.Qrcs) {
1004       qrc.Unique = true;
1005       for (Qrc const& qrc2 : this->Rcc.Qrcs) {
1006         if ((&qrc != &qrc2) && (qrc.QrcName == qrc2.QrcName)) {
1007           qrc.Unique = false;
1008           break;
1009         }
1010       }
1011     }
1012     // Path checksum and file names
1013     for (Qrc& qrc : this->Rcc.Qrcs) {
1014       // Path checksum
1015       qrc.QrcPathChecksum = this->PathCheckSum.getPart(qrc.QrcFile);
1016       // Output file name
1017       qrc.OutputFile = cmStrCat(this->Dir.Build, '/', qrc.QrcPathChecksum,
1018                                 "/qrc_", qrc.QrcName, ".cpp");
1019       std::string const base = cmStrCat(this->Dir.Info, "/AutoRcc_",
1020                                         qrc.QrcName, '_', qrc.QrcPathChecksum);
1021       qrc.LockFile = cmStrCat(base, "_Lock.lock");
1022       qrc.InfoFile = cmStrCat(base, "_Info.json");
1023       ConfigFileNames(qrc.SettingsFile, cmStrCat(base, "_Used"), ".txt");
1024     }
1025     // rcc options
1026     for (Qrc& qrc : this->Rcc.Qrcs) {
1027       // Target options
1028       std::vector<std::string> opts = optionsTarget;
1029       // Merge computed "-name XYZ" option
1030       {
1031         std::string name = qrc.QrcName;
1032         // Replace '-' with '_'. The former is not valid for symbol names.
1033         std::replace(name.begin(), name.end(), '-', '_');
1034         if (!qrc.Unique) {
1035           name += cmStrCat('_', qrc.QrcPathChecksum);
1036         }
1037         std::vector<std::string> nameOpts;
1038         nameOpts.emplace_back("-name");
1039         nameOpts.emplace_back(std::move(name));
1040         RccMergeOptions(opts, nameOpts, modernQt);
1041       }
1042       // Merge file option
1043       RccMergeOptions(opts, qrc.Options, modernQt);
1044       qrc.Options = std::move(opts);
1045     }
1046     // rcc resources
1047     for (Qrc& qrc : this->Rcc.Qrcs) {
1048       if (!qrc.Generated) {
1049         std::string error;
1050         RccLister const lister(this->Rcc.Executable,
1051                                this->Rcc.ExecutableFeatures->ListOptions);
1052         if (!lister.list(qrc.QrcFile, qrc.Resources, error)) {
1053           cmSystemTools::Error(error);
1054           return false;
1055         }
1056       }
1057     }
1058   }
1059
1060   return true;
1061 }
1062
1063 bool cmQtAutoGenInitializer::InitAutogenTarget()
1064 {
1065   // Register info file as generated by CMake
1066   this->Makefile->AddCMakeOutputFile(this->AutogenTarget.InfoFile);
1067
1068   // Files provided by the autogen target
1069   std::vector<std::string> autogenProvides;
1070   if (this->Moc.Enabled) {
1071     this->AddGeneratedSource(this->Moc.CompilationFile, this->Moc, true);
1072     autogenProvides.push_back(this->Moc.CompilationFile);
1073   }
1074
1075   // Compose target comment
1076   std::string autogenComment;
1077   {
1078     std::string tools;
1079     if (this->Moc.Enabled) {
1080       tools += "MOC";
1081     }
1082     if (this->Uic.Enabled) {
1083       if (!tools.empty()) {
1084         tools += " and ";
1085       }
1086       tools += "UIC";
1087     }
1088     autogenComment = cmStrCat("Automatic ", tools, " for target ",
1089                               this->GenTarget->GetName());
1090   }
1091
1092   // Compose command lines
1093   // TODO: Refactor autogen to output a per-config mocs_compilation.cpp instead
1094   // of fiddling with the include directories
1095   std::vector<std::string> configs;
1096   this->GlobalGen->GetQtAutoGenConfigs(configs);
1097   cmCustomCommandLines commandLines;
1098   for (auto const& config : configs) {
1099     commandLines.push_back(cmMakeCommandLine(
1100       { cmSystemTools::GetCMakeCommand(), "-E", "cmake_autogen",
1101         this->AutogenTarget.InfoFile, config }));
1102   }
1103
1104   // Use PRE_BUILD on demand
1105   bool usePRE_BUILD = false;
1106   if (this->GlobalGen->GetName().find("Visual Studio") != std::string::npos) {
1107     // Under VS use a PRE_BUILD event instead of a separate target to
1108     // reduce the number of targets loaded into the IDE.
1109     // This also works around a VS 11 bug that may skip updating the target:
1110     //  https://connect.microsoft.com/VisualStudio/feedback/details/769495
1111     usePRE_BUILD = true;
1112   }
1113   // Disable PRE_BUILD in some cases
1114   if (usePRE_BUILD) {
1115     // Cannot use PRE_BUILD with file depends
1116     if (!this->AutogenTarget.DependFiles.empty()) {
1117       usePRE_BUILD = false;
1118     }
1119     // Cannot use PRE_BUILD when a global autogen target is in place
1120     if (AutogenTarget.GlobalTarget) {
1121       usePRE_BUILD = false;
1122     }
1123   }
1124   // Create the autogen target/command
1125   if (usePRE_BUILD) {
1126     // Add additional autogen target dependencies to origin target
1127     for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
1128       this->GenTarget->Target->AddUtility(depTarget->GetName(), false,
1129                                           this->Makefile);
1130     }
1131
1132     // Add the pre-build command directly to bypass the OBJECT_LIBRARY
1133     // rejection in cmMakefile::AddCustomCommandToTarget because we know
1134     // PRE_BUILD will work for an OBJECT_LIBRARY in this specific case.
1135     //
1136     // PRE_BUILD does not support file dependencies!
1137     const std::vector<std::string> no_output;
1138     const std::vector<std::string> no_deps;
1139     cmCustomCommand cc(no_output, autogenProvides, no_deps, commandLines,
1140                        this->Makefile->GetBacktrace(), autogenComment.c_str(),
1141                        this->Dir.Work.c_str());
1142     cc.SetEscapeOldStyle(false);
1143     cc.SetEscapeAllowMakeVars(true);
1144     this->GenTarget->Target->AddPreBuildCommand(std::move(cc));
1145   } else {
1146
1147     // Add link library target dependencies to the autogen target
1148     // dependencies
1149     if (this->AutogenTarget.DependOrigin) {
1150       // add_dependencies/addUtility do not support generator expressions.
1151       // We depend only on the libraries found in all configs therefore.
1152       std::map<cmGeneratorTarget const*, std::size_t> commonTargets;
1153       for (std::string const& config : this->ConfigsList) {
1154         cmLinkImplementationLibraries const* libs =
1155           this->GenTarget->GetLinkImplementationLibraries(config);
1156         if (libs != nullptr) {
1157           for (cmLinkItem const& item : libs->Libraries) {
1158             cmGeneratorTarget const* libTarget = item.Target;
1159             if ((libTarget != nullptr) &&
1160                 !StaticLibraryCycle(this->GenTarget, libTarget, config)) {
1161               // Increment target config count
1162               commonTargets[libTarget]++;
1163             }
1164           }
1165         }
1166       }
1167       for (auto const& item : commonTargets) {
1168         if (item.second == this->ConfigsList.size()) {
1169           this->AutogenTarget.DependTargets.insert(item.first->Target);
1170         }
1171       }
1172     }
1173
1174     std::vector<std::string> dependencies(
1175       this->AutogenTarget.DependFiles.begin(),
1176       this->AutogenTarget.DependFiles.end());
1177
1178     const bool useNinjaDepfile = this->QtVersion >= IntegerVersion(5, 15) &&
1179       this->GlobalGen->GetName().find("Ninja") != std::string::npos;
1180     if (useNinjaDepfile) {
1181       // Create a custom command that generates a timestamp file and
1182       // has a depfile assigned. The depfile is created by JobDepFilesMergeT.
1183       //
1184       // Also create an additional '_autogen_timestamp_deps' that the custom
1185       // command will depend on. It will have no sources or commands to
1186       // execute, but it will have dependencies that would originally be
1187       // assigned to the pre-Qt 5.15 'autogen' target. These dependencies will
1188       // serve as a list of order-only dependencies for the custom command,
1189       // without forcing the custom command to re-execute.
1190       //
1191       // The dependency tree would then look like
1192       // '_autogen_timestamp_deps (order-only)' <- '/timestamp' file <-
1193       // '_autogen' target.
1194       const auto timestampTargetName =
1195         cmStrCat(this->GenTarget->GetName(), "_autogen_timestamp_deps");
1196       std::vector<std::string> timestampTargetProvides;
1197       cmCustomCommandLines timestampTargetCommandLines;
1198
1199       // Add additional autogen target dependencies to
1200       // '_autogen_timestamp_deps'.
1201       for (const cmTarget* t : this->AutogenTarget.DependTargets) {
1202         dependencies.push_back(t->GetName());
1203       }
1204
1205       cmTarget* timestampTarget = this->LocalGen->AddUtilityCommand(
1206         timestampTargetName, true, this->Dir.Work.c_str(),
1207         /*byproducts=*/timestampTargetProvides,
1208         /*depends=*/dependencies, timestampTargetCommandLines, false, nullptr);
1209       this->LocalGen->AddGeneratorTarget(
1210         cm::make_unique<cmGeneratorTarget>(timestampTarget, this->LocalGen));
1211
1212       // Set FOLDER property on the timestamp target, so it appears in the
1213       // appropriate folder in an IDE or in the file api.
1214       if (!this->TargetsFolder.empty()) {
1215         timestampTarget->SetProperty("FOLDER", this->TargetsFolder);
1216       }
1217
1218       // Make '/timestamp' file depend on '_autogen_timestamp_deps' and on the
1219       // moc and uic executables (whichever are enabled).
1220       dependencies.clear();
1221       dependencies.push_back(timestampTargetName);
1222
1223       if (this->Moc.ExecutableTarget != nullptr) {
1224         dependencies.push_back(this->Moc.ExecutableTarget->Target->GetName());
1225       }
1226       if (this->Uic.ExecutableTarget != nullptr) {
1227         dependencies.push_back(this->Uic.ExecutableTarget->Target->GetName());
1228       }
1229
1230       // Create the custom command that outputs the timestamp file.
1231       const char timestampFileName[] = "timestamp";
1232       const std::string outputFile =
1233         cmStrCat(this->Dir.Build, "/", timestampFileName);
1234       this->AutogenTarget.DepFile = cmStrCat(this->Dir.Build, "/deps");
1235       auto relativeBinaryDir = cmSystemTools::RelativePath(
1236         this->LocalGen->GetBinaryDirectory(),
1237         this->LocalGen->GetCurrentBinaryDirectory());
1238       if (!relativeBinaryDir.empty()) {
1239         relativeBinaryDir = cmStrCat(relativeBinaryDir, "/");
1240       }
1241       this->AutogenTarget.DepFileRuleName =
1242         cmStrCat(relativeBinaryDir, this->GenTarget->GetName(), "_autogen/",
1243                  timestampFileName);
1244       commandLines.push_back(cmMakeCommandLine(
1245         { cmSystemTools::GetCMakeCommand(), "-E", "touch", outputFile }));
1246
1247       this->AddGeneratedSource(outputFile, this->Moc);
1248       const std::string no_main_dependency;
1249       this->LocalGen->AddCustomCommandToOutput(
1250         outputFile, dependencies, no_main_dependency, commandLines,
1251         autogenComment.c_str(), this->Dir.Work.c_str(), /*replace=*/false,
1252         /*escapeOldStyle=*/false,
1253         /*uses_terminal=*/false,
1254         /*command_expand_lists=*/false, this->AutogenTarget.DepFile);
1255
1256       // Alter variables for the autogen target which now merely wraps the
1257       // custom command
1258       dependencies.clear();
1259       dependencies.push_back(outputFile);
1260       commandLines.clear();
1261       autogenComment.clear();
1262     }
1263
1264     // Create autogen target
1265     cmTarget* autogenTarget = this->LocalGen->AddUtilityCommand(
1266       this->AutogenTarget.Name, true, this->Dir.Work.c_str(),
1267       /*byproducts=*/autogenProvides,
1268       /*depends=*/dependencies, commandLines, false, autogenComment.c_str());
1269     // Create autogen generator target
1270     this->LocalGen->AddGeneratorTarget(
1271       cm::make_unique<cmGeneratorTarget>(autogenTarget, this->LocalGen));
1272
1273     // Forward origin utilities to autogen target
1274     if (this->AutogenTarget.DependOrigin) {
1275       for (BT<std::pair<std::string, bool>> const& depName :
1276            this->GenTarget->GetUtilities()) {
1277         autogenTarget->AddUtility(depName.Value.first, false, this->Makefile);
1278       }
1279     }
1280     if (!useNinjaDepfile) {
1281       // Add additional autogen target dependencies to autogen target
1282       for (cmTarget* depTarget : this->AutogenTarget.DependTargets) {
1283         autogenTarget->AddUtility(depTarget->GetName(), false, this->Makefile);
1284       }
1285     }
1286
1287     // Set FOLDER property in autogen target
1288     if (!this->TargetsFolder.empty()) {
1289       autogenTarget->SetProperty("FOLDER", this->TargetsFolder);
1290     }
1291
1292     // Add autogen target to the origin target dependencies
1293     this->GenTarget->Target->AddUtility(this->AutogenTarget.Name, false,
1294                                         this->Makefile);
1295
1296     // Add autogen target to the global autogen target dependencies
1297     if (this->AutogenTarget.GlobalTarget) {
1298       this->GlobalInitializer->AddToGlobalAutoGen(this->LocalGen,
1299                                                   this->AutogenTarget.Name);
1300     }
1301   }
1302
1303   return true;
1304 }
1305
1306 bool cmQtAutoGenInitializer::InitRccTargets()
1307 {
1308   for (Qrc const& qrc : this->Rcc.Qrcs) {
1309     // Register info file as generated by CMake
1310     this->Makefile->AddCMakeOutputFile(qrc.InfoFile);
1311     // Register file at target
1312     {
1313       cmSourceFile* sf = this->AddGeneratedSource(qrc.OutputFile, this->Rcc);
1314       sf->SetProperty("SKIP_UNITY_BUILD_INCLUSION", "On");
1315     }
1316
1317     std::vector<std::string> ccOutput;
1318     ccOutput.push_back(qrc.OutputFile);
1319
1320     std::vector<std::string> ccDepends;
1321     // Add the .qrc and info file to the custom command dependencies
1322     ccDepends.push_back(qrc.QrcFile);
1323     ccDepends.push_back(qrc.InfoFile);
1324
1325     cmCustomCommandLines commandLines;
1326     if (this->MultiConfig) {
1327       // Build for all configurations
1328       for (std::string const& config : this->ConfigsList) {
1329         commandLines.push_back(
1330           cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
1331                               "cmake_autorcc", qrc.InfoFile, config }));
1332       }
1333     } else {
1334       commandLines.push_back(
1335         cmMakeCommandLine({ cmSystemTools::GetCMakeCommand(), "-E",
1336                             "cmake_autorcc", qrc.InfoFile, "$<CONFIG>" }));
1337     }
1338     std::string ccComment =
1339       cmStrCat("Automatic RCC for ",
1340                FileProjectRelativePath(this->Makefile, qrc.QrcFile));
1341
1342     if (qrc.Generated || this->Rcc.GlobalTarget) {
1343       // Create custom rcc target
1344       std::string ccName;
1345       {
1346         ccName = cmStrCat(this->GenTarget->GetName(), "_arcc_", qrc.QrcName);
1347         if (!qrc.Unique) {
1348           ccName += cmStrCat('_', qrc.QrcPathChecksum);
1349         }
1350
1351         cmTarget* autoRccTarget = this->LocalGen->AddUtilityCommand(
1352           ccName, true, this->Dir.Work.c_str(), ccOutput, ccDepends,
1353           commandLines, false, ccComment.c_str());
1354
1355         // Create autogen generator target
1356         this->LocalGen->AddGeneratorTarget(
1357           cm::make_unique<cmGeneratorTarget>(autoRccTarget, this->LocalGen));
1358
1359         // Set FOLDER property in autogen target
1360         if (!this->TargetsFolder.empty()) {
1361           autoRccTarget->SetProperty("FOLDER", this->TargetsFolder);
1362         }
1363         if (!this->Rcc.ExecutableTargetName.empty()) {
1364           autoRccTarget->AddUtility(this->Rcc.ExecutableTargetName, false,
1365                                     this->Makefile);
1366         }
1367       }
1368       // Add autogen target to the origin target dependencies
1369       this->GenTarget->Target->AddUtility(ccName, false, this->Makefile);
1370
1371       // Add autogen target to the global autogen target dependencies
1372       if (this->Rcc.GlobalTarget) {
1373         this->GlobalInitializer->AddToGlobalAutoRcc(this->LocalGen, ccName);
1374       }
1375     } else {
1376       // Create custom rcc command
1377       {
1378         std::vector<std::string> ccByproducts;
1379
1380         // Add the resource files to the dependencies
1381         for (std::string const& fileName : qrc.Resources) {
1382           // Add resource file to the custom command dependencies
1383           ccDepends.push_back(fileName);
1384         }
1385         if (!this->Rcc.ExecutableTargetName.empty()) {
1386           ccDepends.push_back(this->Rcc.ExecutableTargetName);
1387         }
1388         std::string no_main_dependency;
1389         cmImplicitDependsList no_implicit_depends;
1390         this->LocalGen->AddCustomCommandToOutput(
1391           ccOutput, ccByproducts, ccDepends, no_main_dependency,
1392           no_implicit_depends, commandLines, ccComment.c_str(),
1393           this->Dir.Work.c_str());
1394       }
1395       // Reconfigure when .qrc file changes
1396       this->Makefile->AddCMakeDependFile(qrc.QrcFile);
1397     }
1398   }
1399
1400   return true;
1401 }
1402
1403 bool cmQtAutoGenInitializer::SetupCustomTargets()
1404 {
1405   // Create info directory on demand
1406   if (!cmSystemTools::MakeDirectory(this->Dir.Info)) {
1407     cmSystemTools::Error(cmStrCat("AutoGen: Could not create directory: ",
1408                                   Quoted(this->Dir.Info)));
1409     return false;
1410   }
1411
1412   // Generate autogen target info file
1413   if (this->MocOrUicEnabled()) {
1414     // Write autogen target info files
1415     if (!this->SetupWriteAutogenInfo()) {
1416       return false;
1417     }
1418   }
1419
1420   // Write AUTORCC info files
1421   return !this->Rcc.Enabled || this->SetupWriteRccInfo();
1422 }
1423
1424 bool cmQtAutoGenInitializer::SetupWriteAutogenInfo()
1425 {
1426   // Utility lambdas
1427   auto MfDef = [this](std::string const& key) {
1428     return this->Makefile->GetSafeDefinition(key);
1429   };
1430
1431   // Filtered headers and sources
1432   std::set<std::string> moc_skip;
1433   std::set<std::string> uic_skip;
1434   std::vector<MUFile const*> headers;
1435   std::vector<MUFile const*> sources;
1436
1437   // Filter headers
1438   {
1439     headers.reserve(this->AutogenTarget.Headers.size());
1440     for (auto const& pair : this->AutogenTarget.Headers) {
1441       MUFile const* const muf = pair.second.get();
1442       if (muf->Generated && !this->CMP0071Accept) {
1443         continue;
1444       }
1445       if (muf->SkipMoc) {
1446         moc_skip.insert(muf->FullPath);
1447       }
1448       if (muf->SkipUic) {
1449         uic_skip.insert(muf->FullPath);
1450       }
1451       if (muf->MocIt || muf->UicIt) {
1452         headers.emplace_back(muf);
1453       }
1454     }
1455     std::sort(headers.begin(), headers.end(),
1456               [](MUFile const* a, MUFile const* b) {
1457                 return (a->FullPath < b->FullPath);
1458               });
1459   }
1460
1461   // Filter sources
1462   {
1463     sources.reserve(this->AutogenTarget.Sources.size());
1464     for (auto const& pair : this->AutogenTarget.Sources) {
1465       MUFile const* const muf = pair.second.get();
1466       if (muf->Generated && !this->CMP0071Accept) {
1467         continue;
1468       }
1469       if (muf->SkipMoc) {
1470         moc_skip.insert(muf->FullPath);
1471       }
1472       if (muf->SkipUic) {
1473         uic_skip.insert(muf->FullPath);
1474       }
1475       if (muf->MocIt || muf->UicIt) {
1476         sources.emplace_back(muf);
1477       }
1478     }
1479     std::sort(sources.begin(), sources.end(),
1480               [](MUFile const* a, MUFile const* b) {
1481                 return (a->FullPath < b->FullPath);
1482               });
1483   }
1484
1485   // Info writer
1486   InfoWriter info;
1487
1488   // General
1489   info.SetBool("MULTI_CONFIG", this->MultiConfig);
1490   info.SetUInt("PARALLEL", this->AutogenTarget.Parallel);
1491   info.SetUInt("VERBOSITY", this->Verbosity);
1492
1493   // Directories
1494   info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
1495   info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
1496   info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
1497   info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
1498   info.Set("BUILD_DIR", this->Dir.Build);
1499   info.SetConfig("INCLUDE_DIR", this->Dir.Include);
1500
1501   info.SetUInt("QT_VERSION_MAJOR", this->QtVersion.Major);
1502   info.SetUInt("QT_VERSION_MINOR", this->QtVersion.Minor);
1503   info.Set("QT_MOC_EXECUTABLE", this->Moc.Executable);
1504   info.Set("QT_UIC_EXECUTABLE", this->Uic.Executable);
1505
1506   info.Set("CMAKE_EXECUTABLE", cmSystemTools::GetCMakeCommand());
1507   info.SetConfig("SETTINGS_FILE", this->AutogenTarget.SettingsFile);
1508   info.SetConfig("PARSE_CACHE_FILE", this->AutogenTarget.ParseCacheFile);
1509   info.Set("DEP_FILE", this->AutogenTarget.DepFile);
1510   info.Set("DEP_FILE_RULE_NAME", this->AutogenTarget.DepFileRuleName);
1511   info.SetArray("CMAKE_LIST_FILES", this->Makefile->GetListFiles());
1512   info.SetArray("HEADER_EXTENSIONS",
1513                 this->Makefile->GetCMakeInstance()->GetHeaderExtensions());
1514   info.SetArrayArray(
1515     "HEADERS", headers, [this](Json::Value& jval, MUFile const* muf) {
1516       jval.resize(3u);
1517       jval[0u] = muf->FullPath;
1518       jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
1519       jval[2u] = this->GetMocBuildPath(*muf);
1520     });
1521   info.SetArrayArray(
1522     "SOURCES", sources, [](Json::Value& jval, MUFile const* muf) {
1523       jval.resize(2u);
1524       jval[0u] = muf->FullPath;
1525       jval[1u] = cmStrCat(muf->MocIt ? 'M' : 'm', muf->UicIt ? 'U' : 'u');
1526     });
1527
1528   // Write moc settings
1529   if (this->Moc.Enabled) {
1530     info.SetArray("MOC_SKIP", moc_skip);
1531     info.SetConfigArray("MOC_DEFINITIONS", this->Moc.Defines);
1532     info.SetConfigArray("MOC_INCLUDES", this->Moc.Includes);
1533     info.SetArray("MOC_OPTIONS", this->Moc.Options);
1534     info.SetBool("MOC_RELAXED_MODE", this->Moc.RelaxedMode);
1535     info.SetBool("MOC_PATH_PREFIX", this->Moc.PathPrefix);
1536     info.SetArray("MOC_MACRO_NAMES", this->Moc.MacroNames);
1537     info.SetArrayArray(
1538       "MOC_DEPEND_FILTERS", this->Moc.DependFilters,
1539       [](Json::Value& jval, std::pair<std::string, std::string> const& pair) {
1540         jval.resize(2u);
1541         jval[0u] = pair.first;
1542         jval[1u] = pair.second;
1543       });
1544     info.Set("MOC_COMPILATION_FILE", this->Moc.CompilationFile);
1545     info.SetArray("MOC_PREDEFS_CMD", this->Moc.PredefsCmd);
1546     info.SetConfig("MOC_PREDEFS_FILE", this->Moc.PredefsFile);
1547   }
1548
1549   // Write uic settings
1550   if (this->Uic.Enabled) {
1551     // Add skipped .ui files
1552     uic_skip.insert(this->Uic.SkipUi.begin(), this->Uic.SkipUi.end());
1553
1554     info.SetArray("UIC_SKIP", uic_skip);
1555     info.SetArrayArray("UIC_UI_FILES", this->Uic.UiFiles,
1556                        [](Json::Value& jval, UicT::UiFileT const& uiFile) {
1557                          jval.resize(2u);
1558                          jval[0u] = uiFile.first;
1559                          InfoWriter::MakeStringArray(jval[1u], uiFile.second);
1560                        });
1561     info.SetConfigArray("UIC_OPTIONS", this->Uic.Options);
1562     info.SetArray("UIC_SEARCH_PATHS", this->Uic.SearchPaths);
1563   }
1564
1565   info.Save(this->AutogenTarget.InfoFile);
1566
1567   return true;
1568 }
1569
1570 bool cmQtAutoGenInitializer::SetupWriteRccInfo()
1571 {
1572   for (Qrc const& qrc : this->Rcc.Qrcs) {
1573     // Utility lambdas
1574     auto MfDef = [this](std::string const& key) {
1575       return this->Makefile->GetSafeDefinition(key);
1576     };
1577
1578     InfoWriter info;
1579
1580     // General
1581     info.SetBool("MULTI_CONFIG", this->MultiConfig);
1582     info.SetUInt("VERBOSITY", this->Verbosity);
1583
1584     // Files
1585     info.Set("LOCK_FILE", qrc.LockFile);
1586     info.SetConfig("SETTINGS_FILE", qrc.SettingsFile);
1587
1588     // Directories
1589     info.Set("CMAKE_SOURCE_DIR", MfDef("CMAKE_SOURCE_DIR"));
1590     info.Set("CMAKE_BINARY_DIR", MfDef("CMAKE_BINARY_DIR"));
1591     info.Set("CMAKE_CURRENT_SOURCE_DIR", MfDef("CMAKE_CURRENT_SOURCE_DIR"));
1592     info.Set("CMAKE_CURRENT_BINARY_DIR", MfDef("CMAKE_CURRENT_BINARY_DIR"));
1593     info.Set("BUILD_DIR", this->Dir.Build);
1594     info.SetConfig("INCLUDE_DIR", this->Dir.Include);
1595
1596     // rcc executable
1597     info.Set("RCC_EXECUTABLE", this->Rcc.Executable);
1598     info.SetArray("RCC_LIST_OPTIONS",
1599                   this->Rcc.ExecutableFeatures->ListOptions);
1600
1601     // qrc file
1602     info.Set("SOURCE", qrc.QrcFile);
1603     info.Set("OUTPUT_CHECKSUM", qrc.QrcPathChecksum);
1604     info.Set("OUTPUT_NAME", cmSystemTools::GetFilenameName(qrc.OutputFile));
1605     info.SetArray("OPTIONS", qrc.Options);
1606     info.SetArray("INPUTS", qrc.Resources);
1607
1608     info.Save(qrc.InfoFile);
1609   }
1610
1611   return true;
1612 }
1613
1614 cmSourceFile* cmQtAutoGenInitializer::RegisterGeneratedSource(
1615   std::string const& filename)
1616 {
1617   cmSourceFile* gFile = this->Makefile->GetOrCreateSource(filename, true);
1618   gFile->SetProperty("GENERATED", "1");
1619   gFile->SetProperty("SKIP_AUTOGEN", "1");
1620   return gFile;
1621 }
1622
1623 cmSourceFile* cmQtAutoGenInitializer::AddGeneratedSource(
1624   std::string const& filename, GenVarsT const& genVars, bool prepend)
1625 {
1626   // Register source at makefile
1627   cmSourceFile* gFile = this->RegisterGeneratedSource(filename);
1628   // Add source file to target
1629   this->GenTarget->AddSource(filename, prepend);
1630
1631   // Add source file to source group
1632   this->AddToSourceGroup(filename, genVars.GenNameUpper);
1633
1634   return gFile;
1635 }
1636
1637 void cmQtAutoGenInitializer::AddToSourceGroup(std::string const& fileName,
1638                                               cm::string_view genNameUpper)
1639 {
1640   cmSourceGroup* sourceGroup = nullptr;
1641   // Acquire source group
1642   {
1643     std::string property;
1644     std::string groupName;
1645     {
1646       // Prefer generator specific source group name
1647       std::initializer_list<std::string> const props{
1648         cmStrCat(genNameUpper, "_SOURCE_GROUP"), "AUTOGEN_SOURCE_GROUP"
1649       };
1650       for (std::string const& prop : props) {
1651         const char* propName =
1652           this->Makefile->GetState()->GetGlobalProperty(prop);
1653         if ((propName != nullptr) && (*propName != '\0')) {
1654           groupName = propName;
1655           property = prop;
1656           break;
1657         }
1658       }
1659     }
1660     // Generate a source group on demand
1661     if (!groupName.empty()) {
1662       sourceGroup = this->Makefile->GetOrCreateSourceGroup(groupName);
1663       if (sourceGroup == nullptr) {
1664         cmSystemTools::Error(
1665           cmStrCat(genNameUpper, " error in ", property,
1666                    ": Could not find or create the source group ",
1667                    cmQtAutoGen::Quoted(groupName)));
1668       }
1669     }
1670   }
1671   if (sourceGroup != nullptr) {
1672     sourceGroup->AddGroupFile(fileName);
1673   }
1674 }
1675
1676 void cmQtAutoGenInitializer::AddCleanFile(std::string const& fileName)
1677 {
1678   this->GenTarget->Target->AppendProperty("ADDITIONAL_CLEAN_FILES", fileName,
1679                                           false);
1680 }
1681
1682 void cmQtAutoGenInitializer::ConfigFileNames(ConfigString& configString,
1683                                              cm::string_view prefix,
1684                                              cm::string_view suffix)
1685 {
1686   configString.Default = cmStrCat(prefix, suffix);
1687   if (this->MultiConfig) {
1688     for (auto const& cfg : this->ConfigsList) {
1689       configString.Config[cfg] = cmStrCat(prefix, '_', cfg, suffix);
1690     }
1691   }
1692 }
1693
1694 void cmQtAutoGenInitializer::ConfigFileClean(ConfigString& configString)
1695 {
1696   this->AddCleanFile(configString.Default);
1697   if (this->MultiConfig) {
1698     for (auto const& pair : configString.Config) {
1699       this->AddCleanFile(pair.second);
1700     }
1701   }
1702 }
1703
1704 std::pair<cmQtAutoGen::IntegerVersion, unsigned int>
1705 cmQtAutoGenInitializer::GetQtVersion(cmGeneratorTarget const* target)
1706 {
1707   // Converts a char ptr to an unsigned int value
1708   auto toUInt = [](const char* const input) -> unsigned int {
1709     unsigned long tmp = 0;
1710     if (input != nullptr && cmStrToULong(input, &tmp)) {
1711       return static_cast<unsigned int>(tmp);
1712     }
1713     return 0u;
1714   };
1715
1716   // Initialize return value to a default
1717   std::pair<IntegerVersion, unsigned int> res(
1718     IntegerVersion(),
1719     toUInt(target->GetLinkInterfaceDependentStringProperty("QT_MAJOR_VERSION",
1720                                                            "")));
1721
1722   // Acquire known Qt versions
1723   std::vector<cmQtAutoGen::IntegerVersion> knownQtVersions;
1724   {
1725     // Qt version variable prefixes
1726     static std::initializer_list<
1727       std::pair<cm::string_view, cm::string_view>> const keys{
1728       { "Qt6Core_VERSION_MAJOR", "Qt6Core_VERSION_MINOR" },
1729       { "Qt5Core_VERSION_MAJOR", "Qt5Core_VERSION_MINOR" },
1730       { "QT_VERSION_MAJOR", "QT_VERSION_MINOR" },
1731     };
1732
1733     knownQtVersions.reserve(keys.size() * 2);
1734
1735     // Adds a version to the result (nullptr safe)
1736     auto addVersion = [&knownQtVersions, &toUInt](const char* major,
1737                                                   const char* minor) {
1738       cmQtAutoGen::IntegerVersion ver(toUInt(major), toUInt(minor));
1739       if (ver.Major != 0) {
1740         knownQtVersions.emplace_back(ver);
1741       }
1742     };
1743
1744     // Read versions from variables
1745     for (auto const& keyPair : keys) {
1746       addVersion(target->Makefile->GetDefinition(std::string(keyPair.first)),
1747                  target->Makefile->GetDefinition(std::string(keyPair.second)));
1748     }
1749
1750     // Read versions from directory properties
1751     for (auto const& keyPair : keys) {
1752       addVersion(target->Makefile->GetProperty(std::string(keyPair.first)),
1753                  target->Makefile->GetProperty(std::string(keyPair.second)));
1754     }
1755   }
1756
1757   // Evaluate known Qt versions
1758   if (!knownQtVersions.empty()) {
1759     if (res.second == 0) {
1760       // No specific version was requested by the target:
1761       // Use highest known Qt version.
1762       res.first = knownQtVersions.at(0);
1763     } else {
1764       // Pick a version from the known versions:
1765       for (auto it : knownQtVersions) {
1766         if (it.Major == res.second) {
1767           res.first = it;
1768           break;
1769         }
1770       }
1771     }
1772   }
1773   return res;
1774 }
1775
1776 std::string cmQtAutoGenInitializer::GetMocBuildPath(MUFile const& muf)
1777 {
1778   std::string res;
1779   if (!muf.MocIt) {
1780     return res;
1781   }
1782
1783   std::string basePath =
1784     cmStrCat(this->PathCheckSum.getPart(muf.FullPath), "/moc_",
1785              FileNameWithoutLastExtension(muf.FullPath));
1786
1787   res = cmStrCat(basePath, ".cpp");
1788   if (this->Moc.EmittedBuildPaths.emplace(res).second) {
1789     return res;
1790   }
1791
1792   // File name already emitted.
1793   // Try appending the header suffix to the base path.
1794   basePath = cmStrCat(basePath, '_', muf.SF->GetExtension());
1795   res = cmStrCat(basePath, ".cpp");
1796   if (this->Moc.EmittedBuildPaths.emplace(res).second) {
1797     return res;
1798   }
1799
1800   // File name with header extension already emitted.
1801   // Try adding a number to the base path.
1802   constexpr std::size_t number_begin = 2;
1803   constexpr std::size_t number_end = 256;
1804   for (std::size_t ii = number_begin; ii != number_end; ++ii) {
1805     res = cmStrCat(basePath, '_', ii, ".cpp");
1806     if (this->Moc.EmittedBuildPaths.emplace(res).second) {
1807       return res;
1808     }
1809   }
1810
1811   // Output file name conflict (unlikely, but still...)
1812   cmSystemTools::Error(
1813     cmStrCat("moc output file name conflict for ", muf.FullPath));
1814
1815   return res;
1816 }
1817
1818 bool cmQtAutoGenInitializer::GetQtExecutable(GenVarsT& genVars,
1819                                              const std::string& executable,
1820                                              bool ignoreMissingTarget) const
1821 {
1822   auto print_err = [this, &genVars](std::string const& err) {
1823     cmSystemTools::Error(cmStrCat(genVars.GenNameUpper, " for target ",
1824                                   this->GenTarget->GetName(), ": ", err));
1825   };
1826
1827   // Custom executable
1828   {
1829     std::string const prop = cmStrCat(genVars.GenNameUpper, "_EXECUTABLE");
1830     std::string const val = this->GenTarget->Target->GetSafeProperty(prop);
1831     if (!val.empty()) {
1832       // Evaluate generator expression
1833       {
1834         cmListFileBacktrace lfbt = this->Makefile->GetBacktrace();
1835         cmGeneratorExpression ge(lfbt);
1836         std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(val);
1837         genVars.Executable = cge->Evaluate(this->LocalGen, "");
1838       }
1839       if (genVars.Executable.empty() && !ignoreMissingTarget) {
1840         print_err(prop + " evaluates to an empty value");
1841         return false;
1842       }
1843
1844       // Create empty compiler features.
1845       genVars.ExecutableFeatures =
1846         std::make_shared<cmQtAutoGen::CompilerFeatures>();
1847       return true;
1848     }
1849   }
1850
1851   // Find executable target
1852   {
1853     // Find executable target name
1854     cm::string_view prefix;
1855     if (this->QtVersion.Major == 4) {
1856       prefix = "Qt4::";
1857     } else if (this->QtVersion.Major == 5) {
1858       prefix = "Qt5::";
1859     } else if (this->QtVersion.Major == 6) {
1860       prefix = "Qt6::";
1861     }
1862     std::string const targetName = cmStrCat(prefix, executable);
1863
1864     // Find target
1865     cmGeneratorTarget* genTarget =
1866       this->LocalGen->FindGeneratorTargetToUse(targetName);
1867     if (genTarget != nullptr) {
1868       genVars.ExecutableTargetName = targetName;
1869       genVars.ExecutableTarget = genTarget;
1870       if (genTarget->IsImported()) {
1871         genVars.Executable = genTarget->ImportedGetLocation("");
1872       } else {
1873         genVars.Executable = genTarget->GetLocation("");
1874       }
1875     } else {
1876       if (ignoreMissingTarget) {
1877         // Create empty compiler features.
1878         genVars.ExecutableFeatures =
1879           std::make_shared<cmQtAutoGen::CompilerFeatures>();
1880         return true;
1881       }
1882       print_err(cmStrCat("Could not find ", executable, " executable target ",
1883                          targetName));
1884       return false;
1885     }
1886   }
1887
1888   // Get executable features
1889   {
1890     std::string err;
1891     genVars.ExecutableFeatures = this->GlobalInitializer->GetCompilerFeatures(
1892       executable, genVars.Executable, err);
1893     if (!genVars.ExecutableFeatures) {
1894       print_err(err);
1895       return false;
1896     }
1897   }
1898
1899   return true;
1900 }