5a33349b19a09520d537f3eda2bdbae16f4eefbf
[platform/upstream/cmake.git] / Source / cmExportFileGenerator.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 "cmExportFileGenerator.h"
4
5 #include <array>
6 #include <cassert>
7 #include <cstring>
8 #include <sstream>
9 #include <utility>
10
11 #include <cm/memory>
12
13 #include "cmsys/FStream.hxx"
14
15 #include "cmComputeLinkInformation.h"
16 #include "cmFileSet.h"
17 #include "cmGeneratedFileStream.h"
18 #include "cmGeneratorTarget.h"
19 #include "cmLinkItem.h"
20 #include "cmLocalGenerator.h"
21 #include "cmMakefile.h"
22 #include "cmMessageType.h"
23 #include "cmOutputConverter.h"
24 #include "cmPolicies.h"
25 #include "cmPropertyMap.h"
26 #include "cmStateTypes.h"
27 #include "cmStringAlgorithms.h"
28 #include "cmSystemTools.h"
29 #include "cmTarget.h"
30 #include "cmValue.h"
31
32 static std::string cmExportFileGeneratorEscape(std::string const& str)
33 {
34   // Escape a property value for writing into a .cmake file.
35   std::string result = cmOutputConverter::EscapeForCMake(str);
36   // Un-escape variable references generated by our own export code.
37   cmSystemTools::ReplaceString(result, "\\${_IMPORT_PREFIX}",
38                                "${_IMPORT_PREFIX}");
39   cmSystemTools::ReplaceString(result, "\\${CMAKE_IMPORT_LIBRARY_SUFFIX}",
40                                "${CMAKE_IMPORT_LIBRARY_SUFFIX}");
41   return result;
42 }
43
44 cmExportFileGenerator::cmExportFileGenerator()
45 {
46   this->AppendMode = false;
47   this->ExportOld = false;
48 }
49
50 void cmExportFileGenerator::AddConfiguration(const std::string& config)
51 {
52   this->Configurations.push_back(config);
53 }
54
55 void cmExportFileGenerator::SetExportFile(const char* mainFile)
56 {
57   this->MainImportFile = mainFile;
58   this->FileDir = cmSystemTools::GetFilenamePath(this->MainImportFile);
59   this->FileBase =
60     cmSystemTools::GetFilenameWithoutLastExtension(this->MainImportFile);
61   this->FileExt =
62     cmSystemTools::GetFilenameLastExtension(this->MainImportFile);
63 }
64
65 const std::string& cmExportFileGenerator::GetMainExportFileName() const
66 {
67   return this->MainImportFile;
68 }
69
70 bool cmExportFileGenerator::GenerateImportFile()
71 {
72   // Open the output file to generate it.
73   std::unique_ptr<cmsys::ofstream> foutPtr;
74   if (this->AppendMode) {
75     // Open for append.
76     auto openmodeApp = std::ios::app;
77     foutPtr = cm::make_unique<cmsys::ofstream>(this->MainImportFile.c_str(),
78                                                openmodeApp);
79   } else {
80     // Generate atomically and with copy-if-different.
81     std::unique_ptr<cmGeneratedFileStream> ap(
82       new cmGeneratedFileStream(this->MainImportFile, true));
83     ap->SetCopyIfDifferent(true);
84     foutPtr = std::move(ap);
85   }
86   if (!foutPtr || !*foutPtr) {
87     std::string se = cmSystemTools::GetLastSystemError();
88     std::ostringstream e;
89     e << "cannot write to file \"" << this->MainImportFile << "\": " << se;
90     cmSystemTools::Error(e.str());
91     return false;
92   }
93   std::ostream& os = *foutPtr;
94
95   // Start with the import file header.
96   this->GeneratePolicyHeaderCode(os);
97   this->GenerateImportHeaderCode(os);
98
99   // Create all the imported targets.
100   bool result = this->GenerateMainFile(os);
101
102   // End with the import file footer.
103   this->GenerateImportFooterCode(os);
104   this->GeneratePolicyFooterCode(os);
105
106   return result;
107 }
108
109 void cmExportFileGenerator::GenerateImportConfig(std::ostream& os,
110                                                  const std::string& config)
111 {
112   // Construct the property configuration suffix.
113   std::string suffix = "_";
114   if (!config.empty()) {
115     suffix += cmSystemTools::UpperCase(config);
116   } else {
117     suffix += "NOCONFIG";
118   }
119
120   // Generate the per-config target information.
121   this->GenerateImportTargetsConfig(os, config, suffix);
122 }
123
124 void cmExportFileGenerator::PopulateInterfaceProperty(
125   const std::string& propName, cmGeneratorTarget const* target,
126   ImportPropertyMap& properties)
127 {
128   cmValue input = target->GetProperty(propName);
129   if (input) {
130     properties[propName] = *input;
131   }
132 }
133
134 void cmExportFileGenerator::PopulateInterfaceProperty(
135   const std::string& propName, const std::string& outputName,
136   cmGeneratorTarget const* target,
137   cmGeneratorExpression::PreprocessContext preprocessRule,
138   ImportPropertyMap& properties)
139 {
140   cmValue input = target->GetProperty(propName);
141   if (input) {
142     if (input->empty()) {
143       // Set to empty
144       properties[outputName].clear();
145       return;
146     }
147
148     std::string prepro =
149       cmGeneratorExpression::Preprocess(*input, preprocessRule);
150     if (!prepro.empty()) {
151       this->ResolveTargetsInGeneratorExpressions(prepro, target);
152       properties[outputName] = prepro;
153     }
154   }
155 }
156
157 void cmExportFileGenerator::GenerateRequiredCMakeVersion(
158   std::ostream& os, const char* versionString)
159 {
160   /* clang-format off */
161   os << "if(CMAKE_VERSION VERSION_LESS " << versionString << ")\n"
162         "  message(FATAL_ERROR \"This file relies on consumers using "
163         "CMake " << versionString << " or greater.\")\n"
164         "endif()\n\n";
165   /* clang-format on */
166 }
167
168 bool cmExportFileGenerator::PopulateInterfaceLinkLibrariesProperty(
169   cmGeneratorTarget const* target,
170   cmGeneratorExpression::PreprocessContext preprocessRule,
171   ImportPropertyMap& properties)
172 {
173   if (!target->IsLinkable()) {
174     return false;
175   }
176   static const std::array<std::string, 3> linkIfaceProps = {
177     { "INTERFACE_LINK_LIBRARIES", "INTERFACE_LINK_LIBRARIES_DIRECT",
178       "INTERFACE_LINK_LIBRARIES_DIRECT_EXCLUDE" }
179   };
180   bool hadINTERFACE_LINK_LIBRARIES = false;
181   for (std::string const& linkIfaceProp : linkIfaceProps) {
182     if (cmValue input = target->GetProperty(linkIfaceProp)) {
183       std::string prepro =
184         cmGeneratorExpression::Preprocess(*input, preprocessRule);
185       if (!prepro.empty()) {
186         this->ResolveTargetsInGeneratorExpressions(prepro, target,
187                                                    ReplaceFreeTargets);
188         properties[linkIfaceProp] = prepro;
189         hadINTERFACE_LINK_LIBRARIES = true;
190       }
191     }
192   }
193   return hadINTERFACE_LINK_LIBRARIES;
194 }
195
196 static bool isSubDirectory(std::string const& a, std::string const& b)
197 {
198   return (cmSystemTools::ComparePath(a, b) ||
199           cmSystemTools::IsSubDirectory(a, b));
200 }
201
202 static bool checkInterfaceDirs(const std::string& prepro,
203                                cmGeneratorTarget const* target,
204                                const std::string& prop)
205 {
206   std::string const& installDir =
207     target->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX");
208   std::string const& topSourceDir =
209     target->GetLocalGenerator()->GetSourceDirectory();
210   std::string const& topBinaryDir =
211     target->GetLocalGenerator()->GetBinaryDirectory();
212
213   std::vector<std::string> parts;
214   cmGeneratorExpression::Split(prepro, parts);
215
216   const bool inSourceBuild = topSourceDir == topBinaryDir;
217
218   bool hadFatalError = false;
219
220   for (std::string const& li : parts) {
221     size_t genexPos = cmGeneratorExpression::Find(li);
222     if (genexPos == 0) {
223       continue;
224     }
225     if (cmHasLiteralPrefix(li, "${_IMPORT_PREFIX}")) {
226       continue;
227     }
228     MessageType messageType = MessageType::FATAL_ERROR;
229     std::ostringstream e;
230     if (genexPos != std::string::npos) {
231       if (prop == "INTERFACE_INCLUDE_DIRECTORIES") {
232         switch (target->GetPolicyStatusCMP0041()) {
233           case cmPolicies::WARN:
234             messageType = MessageType::WARNING;
235             e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0041) << "\n";
236             break;
237           case cmPolicies::OLD:
238             continue;
239           case cmPolicies::REQUIRED_IF_USED:
240           case cmPolicies::REQUIRED_ALWAYS:
241           case cmPolicies::NEW:
242             hadFatalError = true;
243             break; // Issue fatal message.
244         }
245       } else {
246         hadFatalError = true;
247       }
248     }
249     if (!cmSystemTools::FileIsFullPath(li)) {
250       /* clang-format off */
251       e << "Target \"" << target->GetName() << "\" " << prop <<
252            " property contains relative path:\n"
253            "  \"" << li << "\"";
254       /* clang-format on */
255       target->GetLocalGenerator()->IssueMessage(messageType, e.str());
256     }
257     bool inBinary = isSubDirectory(li, topBinaryDir);
258     bool inSource = isSubDirectory(li, topSourceDir);
259     if (isSubDirectory(li, installDir)) {
260       // The include directory is inside the install tree.  If the
261       // install tree is not inside the source tree or build tree then
262       // fall through to the checks below that the include directory is not
263       // also inside the source tree or build tree.
264       bool shouldContinue =
265         (!inBinary || isSubDirectory(installDir, topBinaryDir)) &&
266         (!inSource || isSubDirectory(installDir, topSourceDir));
267
268       if (prop == "INTERFACE_INCLUDE_DIRECTORIES") {
269         if (!shouldContinue) {
270           switch (target->GetPolicyStatusCMP0052()) {
271             case cmPolicies::WARN: {
272               std::ostringstream s;
273               s << cmPolicies::GetPolicyWarning(cmPolicies::CMP0052) << "\n";
274               s << "Directory:\n    \"" << li
275                 << "\"\nin "
276                    "INTERFACE_INCLUDE_DIRECTORIES of target \""
277                 << target->GetName()
278                 << "\" is a subdirectory of the install "
279                    "directory:\n    \""
280                 << installDir
281                 << "\"\nhowever it is also "
282                    "a subdirectory of the "
283                 << (inBinary ? "build" : "source") << " tree:\n    \""
284                 << (inBinary ? topBinaryDir : topSourceDir) << "\"\n";
285               target->GetLocalGenerator()->IssueMessage(
286                 MessageType::AUTHOR_WARNING, s.str());
287               CM_FALLTHROUGH;
288             }
289             case cmPolicies::OLD:
290               shouldContinue = true;
291               break;
292             case cmPolicies::REQUIRED_ALWAYS:
293             case cmPolicies::REQUIRED_IF_USED:
294             case cmPolicies::NEW:
295               break;
296           }
297         }
298       }
299       if (shouldContinue) {
300         continue;
301       }
302     }
303     if (inBinary) {
304       /* clang-format off */
305       e << "Target \"" << target->GetName() << "\" " << prop <<
306            " property contains path:\n"
307            "  \"" << li << "\"\nwhich is prefixed in the build directory.";
308       /* clang-format on */
309       target->GetLocalGenerator()->IssueMessage(messageType, e.str());
310     }
311     if (!inSourceBuild) {
312       if (inSource) {
313         e << "Target \"" << target->GetName() << "\" " << prop
314           << " property contains path:\n"
315              "  \""
316           << li << "\"\nwhich is prefixed in the source directory.";
317         target->GetLocalGenerator()->IssueMessage(messageType, e.str());
318       }
319     }
320   }
321   return !hadFatalError;
322 }
323
324 static void prefixItems(std::string& exportDirs)
325 {
326   std::vector<std::string> entries;
327   cmGeneratorExpression::Split(exportDirs, entries);
328   exportDirs.clear();
329   const char* sep = "";
330   for (std::string const& e : entries) {
331     exportDirs += sep;
332     sep = ";";
333     if (!cmSystemTools::FileIsFullPath(e) &&
334         e.find("${_IMPORT_PREFIX}") == std::string::npos) {
335       exportDirs += "${_IMPORT_PREFIX}/";
336     }
337     exportDirs += e;
338   }
339 }
340
341 void cmExportFileGenerator::PopulateSourcesInterface(
342   cmGeneratorTarget const* gt,
343   cmGeneratorExpression::PreprocessContext preprocessRule,
344   ImportPropertyMap& properties)
345 {
346   assert(preprocessRule == cmGeneratorExpression::InstallInterface);
347
348   const char* propName = "INTERFACE_SOURCES";
349   cmValue input = gt->GetProperty(propName);
350
351   if (!input) {
352     return;
353   }
354
355   if (input->empty()) {
356     properties[propName].clear();
357     return;
358   }
359
360   std::string prepro =
361     cmGeneratorExpression::Preprocess(*input, preprocessRule, true);
362   if (!prepro.empty()) {
363     this->ResolveTargetsInGeneratorExpressions(prepro, gt);
364
365     if (!checkInterfaceDirs(prepro, gt, propName)) {
366       return;
367     }
368     properties[propName] = prepro;
369   }
370 }
371
372 void cmExportFileGenerator::PopulateIncludeDirectoriesInterface(
373   cmGeneratorTarget const* target,
374   cmGeneratorExpression::PreprocessContext preprocessRule,
375   ImportPropertyMap& properties, cmTargetExport const& te)
376 {
377   assert(preprocessRule == cmGeneratorExpression::InstallInterface);
378
379   const char* propName = "INTERFACE_INCLUDE_DIRECTORIES";
380   cmValue input = target->GetProperty(propName);
381
382   cmGeneratorExpression ge;
383
384   std::string dirs = cmGeneratorExpression::Preprocess(
385     cmJoin(target->Target->GetInstallIncludeDirectoriesEntries(te), ";"),
386     preprocessRule, true);
387   this->ReplaceInstallPrefix(dirs);
388   std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(dirs);
389   std::string exportDirs =
390     cge->Evaluate(target->GetLocalGenerator(), "", target);
391
392   if (cge->GetHadContextSensitiveCondition()) {
393     cmLocalGenerator* lg = target->GetLocalGenerator();
394     std::ostringstream e;
395     e << "Target \"" << target->GetName()
396       << "\" is installed with "
397          "INCLUDES DESTINATION set to a context sensitive path.  Paths which "
398          "depend on the configuration, policy values or the link interface "
399          "are "
400          "not supported.  Consider using target_include_directories instead.";
401     lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
402     return;
403   }
404
405   if (!input && exportDirs.empty()) {
406     return;
407   }
408   if ((input && input->empty()) && exportDirs.empty()) {
409     // Set to empty
410     properties[propName].clear();
411     return;
412   }
413
414   prefixItems(exportDirs);
415
416   std::string includes = (input ? *input : "");
417   const char* sep = input ? ";" : "";
418   includes += sep + exportDirs;
419   std::string prepro =
420     cmGeneratorExpression::Preprocess(includes, preprocessRule, true);
421   if (!prepro.empty()) {
422     this->ResolveTargetsInGeneratorExpressions(prepro, target);
423
424     if (!checkInterfaceDirs(prepro, target, propName)) {
425       return;
426     }
427     properties[propName] = prepro;
428   }
429 }
430
431 void cmExportFileGenerator::PopulateLinkDependsInterface(
432   cmGeneratorTarget const* gt,
433   cmGeneratorExpression::PreprocessContext preprocessRule,
434   ImportPropertyMap& properties)
435 {
436   assert(preprocessRule == cmGeneratorExpression::InstallInterface);
437
438   const char* propName = "INTERFACE_LINK_DEPENDS";
439   cmValue input = gt->GetProperty(propName);
440
441   if (!input) {
442     return;
443   }
444
445   if (input->empty()) {
446     properties[propName].clear();
447     return;
448   }
449
450   std::string prepro =
451     cmGeneratorExpression::Preprocess(*input, preprocessRule, true);
452   if (!prepro.empty()) {
453     this->ResolveTargetsInGeneratorExpressions(prepro, gt);
454
455     if (!checkInterfaceDirs(prepro, gt, propName)) {
456       return;
457     }
458     properties[propName] = prepro;
459   }
460 }
461
462 void cmExportFileGenerator::PopulateLinkDirectoriesInterface(
463   cmGeneratorTarget const* gt,
464   cmGeneratorExpression::PreprocessContext preprocessRule,
465   ImportPropertyMap& properties)
466 {
467   assert(preprocessRule == cmGeneratorExpression::InstallInterface);
468
469   const char* propName = "INTERFACE_LINK_DIRECTORIES";
470   cmValue input = gt->GetProperty(propName);
471
472   if (!input) {
473     return;
474   }
475
476   if (input->empty()) {
477     properties[propName].clear();
478     return;
479   }
480
481   std::string prepro =
482     cmGeneratorExpression::Preprocess(*input, preprocessRule, true);
483   if (!prepro.empty()) {
484     this->ResolveTargetsInGeneratorExpressions(prepro, gt);
485
486     if (!checkInterfaceDirs(prepro, gt, propName)) {
487       return;
488     }
489     properties[propName] = prepro;
490   }
491 }
492
493 void cmExportFileGenerator::PopulateInterfaceProperty(
494   const std::string& propName, cmGeneratorTarget const* target,
495   cmGeneratorExpression::PreprocessContext preprocessRule,
496   ImportPropertyMap& properties)
497 {
498   this->PopulateInterfaceProperty(propName, propName, target, preprocessRule,
499                                   properties);
500 }
501
502 static void getPropertyContents(cmGeneratorTarget const* tgt,
503                                 const std::string& prop,
504                                 std::set<std::string>& ifaceProperties)
505 {
506   cmValue p = tgt->GetProperty(prop);
507   if (!p) {
508     return;
509   }
510   std::vector<std::string> content = cmExpandedList(*p);
511   ifaceProperties.insert(content.begin(), content.end());
512 }
513
514 static void getCompatibleInterfaceProperties(
515   cmGeneratorTarget const* target, std::set<std::string>& ifaceProperties,
516   const std::string& config)
517 {
518   if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) {
519     // object libraries have no link information, so nothing to compute
520     return;
521   }
522
523   cmComputeLinkInformation* info = target->GetLinkInformation(config);
524
525   if (!info) {
526     cmLocalGenerator* lg = target->GetLocalGenerator();
527     std::ostringstream e;
528     e << "Exporting the target \"" << target->GetName()
529       << "\" is not "
530          "allowed since its linker language cannot be determined";
531     lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
532     return;
533   }
534
535   const cmComputeLinkInformation::ItemVector& deps = info->GetItems();
536
537   for (auto const& dep : deps) {
538     if (!dep.Target) {
539       continue;
540     }
541     getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_BOOL",
542                         ifaceProperties);
543     getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_STRING",
544                         ifaceProperties);
545     getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_NUMBER_MIN",
546                         ifaceProperties);
547     getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_NUMBER_MAX",
548                         ifaceProperties);
549   }
550 }
551
552 void cmExportFileGenerator::PopulateCompatibleInterfaceProperties(
553   cmGeneratorTarget const* gtarget, ImportPropertyMap& properties)
554 {
555   this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_BOOL", gtarget,
556                                   properties);
557   this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_STRING", gtarget,
558                                   properties);
559   this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_NUMBER_MIN", gtarget,
560                                   properties);
561   this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_NUMBER_MAX", gtarget,
562                                   properties);
563
564   std::set<std::string> ifaceProperties;
565
566   getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_BOOL", ifaceProperties);
567   getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_STRING", ifaceProperties);
568   getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_NUMBER_MIN",
569                       ifaceProperties);
570   getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_NUMBER_MAX",
571                       ifaceProperties);
572
573   if (gtarget->GetType() != cmStateEnums::INTERFACE_LIBRARY) {
574     std::vector<std::string> configNames =
575       gtarget->Target->GetMakefile()->GetGeneratorConfigs(
576         cmMakefile::IncludeEmptyConfig);
577
578     for (std::string const& cn : configNames) {
579       getCompatibleInterfaceProperties(gtarget, ifaceProperties, cn);
580     }
581   }
582
583   for (std::string const& ip : ifaceProperties) {
584     this->PopulateInterfaceProperty("INTERFACE_" + ip, gtarget, properties);
585   }
586 }
587
588 void cmExportFileGenerator::GenerateInterfaceProperties(
589   const cmGeneratorTarget* target, std::ostream& os,
590   const ImportPropertyMap& properties)
591 {
592   if (!properties.empty()) {
593     std::string targetName =
594       cmStrCat(this->Namespace, target->GetExportName());
595     os << "set_target_properties(" << targetName << " PROPERTIES\n";
596     for (auto const& property : properties) {
597       os << "  " << property.first << " "
598          << cmExportFileGeneratorEscape(property.second) << "\n";
599     }
600     os << ")\n\n";
601   }
602 }
603
604 bool cmExportFileGenerator::AddTargetNamespace(std::string& input,
605                                                cmGeneratorTarget const* target,
606                                                cmLocalGenerator const* lg)
607 {
608   cmGeneratorTarget::TargetOrString resolved =
609     target->ResolveTargetReference(input, lg);
610
611   cmGeneratorTarget* tgt = resolved.Target;
612   if (!tgt) {
613     input = resolved.String;
614     return false;
615   }
616
617   if (tgt->IsImported()) {
618     input = tgt->GetName();
619     return true;
620   }
621   if (this->ExportedTargets.find(tgt) != this->ExportedTargets.end()) {
622     input = this->Namespace + tgt->GetExportName();
623   } else {
624     std::string namespacedTarget;
625     this->HandleMissingTarget(namespacedTarget, target, tgt);
626     if (!namespacedTarget.empty()) {
627       input = namespacedTarget;
628     } else {
629       input = tgt->GetName();
630     }
631   }
632   return true;
633 }
634
635 void cmExportFileGenerator::ResolveTargetsInGeneratorExpressions(
636   std::string& input, cmGeneratorTarget const* target,
637   FreeTargetsReplace replace)
638 {
639   cmLocalGenerator const* lg = target->GetLocalGenerator();
640   if (replace == NoReplaceFreeTargets) {
641     this->ResolveTargetsInGeneratorExpression(input, target, lg);
642     return;
643   }
644   std::vector<std::string> parts;
645   cmGeneratorExpression::Split(input, parts);
646
647   std::string sep;
648   input.clear();
649   for (std::string& li : parts) {
650     if (target->IsLinkLookupScope(li, lg)) {
651       continue;
652     }
653     if (cmGeneratorExpression::Find(li) == std::string::npos) {
654       this->AddTargetNamespace(li, target, lg);
655     } else {
656       this->ResolveTargetsInGeneratorExpression(li, target, lg);
657     }
658     input += sep + li;
659     sep = ";";
660   }
661 }
662
663 void cmExportFileGenerator::ResolveTargetsInGeneratorExpression(
664   std::string& input, cmGeneratorTarget const* target,
665   cmLocalGenerator const* lg)
666 {
667   std::string::size_type pos = 0;
668   std::string::size_type lastPos = pos;
669
670   while ((pos = input.find("$<TARGET_PROPERTY:", lastPos)) !=
671          std::string::npos) {
672     std::string::size_type nameStartPos =
673       pos + sizeof("$<TARGET_PROPERTY:") - 1;
674     std::string::size_type closePos = input.find('>', nameStartPos);
675     std::string::size_type commaPos = input.find(',', nameStartPos);
676     std::string::size_type nextOpenPos = input.find("$<", nameStartPos);
677     if (commaPos == std::string::npos    // Implied 'this' target
678         || closePos == std::string::npos // Incomplete expression.
679         || closePos < commaPos           // Implied 'this' target
680         || nextOpenPos < commaPos)       // Non-literal
681     {
682       lastPos = nameStartPos;
683       continue;
684     }
685
686     std::string targetName =
687       input.substr(nameStartPos, commaPos - nameStartPos);
688
689     if (this->AddTargetNamespace(targetName, target, lg)) {
690       input.replace(nameStartPos, commaPos - nameStartPos, targetName);
691     }
692     lastPos = nameStartPos + targetName.size() + 1;
693   }
694
695   std::string errorString;
696   pos = 0;
697   lastPos = pos;
698   while ((pos = input.find("$<TARGET_NAME:", lastPos)) != std::string::npos) {
699     std::string::size_type nameStartPos = pos + sizeof("$<TARGET_NAME:") - 1;
700     std::string::size_type endPos = input.find('>', nameStartPos);
701     if (endPos == std::string::npos) {
702       errorString = "$<TARGET_NAME:...> expression incomplete";
703       break;
704     }
705     std::string targetName = input.substr(nameStartPos, endPos - nameStartPos);
706     if (targetName.find("$<") != std::string::npos) {
707       errorString = "$<TARGET_NAME:...> requires its parameter to be a "
708                     "literal.";
709       break;
710     }
711     if (!this->AddTargetNamespace(targetName, target, lg)) {
712       errorString = "$<TARGET_NAME:...> requires its parameter to be a "
713                     "reachable target.";
714       break;
715     }
716     input.replace(pos, endPos - pos + 1, targetName);
717     lastPos = pos + targetName.size();
718   }
719
720   pos = 0;
721   lastPos = pos;
722   while (errorString.empty() &&
723          (pos = input.find("$<LINK_ONLY:", lastPos)) != std::string::npos) {
724     std::string::size_type nameStartPos = pos + sizeof("$<LINK_ONLY:") - 1;
725     std::string::size_type endPos = input.find('>', nameStartPos);
726     if (endPos == std::string::npos) {
727       errorString = "$<LINK_ONLY:...> expression incomplete";
728       break;
729     }
730     std::string libName = input.substr(nameStartPos, endPos - nameStartPos);
731     if (cmGeneratorExpression::IsValidTargetName(libName) &&
732         this->AddTargetNamespace(libName, target, lg)) {
733       input.replace(nameStartPos, endPos - nameStartPos, libName);
734     }
735     lastPos = nameStartPos + libName.size() + 1;
736   }
737
738   this->ReplaceInstallPrefix(input);
739
740   if (!errorString.empty()) {
741     target->GetLocalGenerator()->IssueMessage(MessageType::FATAL_ERROR,
742                                               errorString);
743   }
744 }
745
746 void cmExportFileGenerator::ReplaceInstallPrefix(std::string& /*unused*/)
747 {
748   // Do nothing
749 }
750
751 void cmExportFileGenerator::SetImportLinkInterface(
752   const std::string& config, std::string const& suffix,
753   cmGeneratorExpression::PreprocessContext preprocessRule,
754   cmGeneratorTarget const* target, ImportPropertyMap& properties)
755 {
756   // Add the transitive link dependencies for this configuration.
757   cmLinkInterface const* iface = target->GetLinkInterface(config, target);
758   if (!iface) {
759     return;
760   }
761
762   if (iface->ImplementationIsInterface) {
763     // Policy CMP0022 must not be NEW.
764     this->SetImportLinkProperty(
765       suffix, target, "IMPORTED_LINK_INTERFACE_LIBRARIES", iface->Libraries,
766       properties, ImportLinkPropertyTargetNames::Yes);
767     return;
768   }
769
770   cmValue propContent;
771
772   if (cmValue prop_suffixed =
773         target->GetProperty("LINK_INTERFACE_LIBRARIES" + suffix)) {
774     propContent = prop_suffixed;
775   } else if (cmValue prop = target->GetProperty("LINK_INTERFACE_LIBRARIES")) {
776     propContent = prop;
777   } else {
778     return;
779   }
780
781   const bool newCMP0022Behavior =
782     target->GetPolicyStatusCMP0022() != cmPolicies::WARN &&
783     target->GetPolicyStatusCMP0022() != cmPolicies::OLD;
784
785   if (newCMP0022Behavior && !this->ExportOld) {
786     cmLocalGenerator* lg = target->GetLocalGenerator();
787     std::ostringstream e;
788     e << "Target \"" << target->GetName()
789       << "\" has policy CMP0022 enabled, "
790          "but also has old-style LINK_INTERFACE_LIBRARIES properties "
791          "populated, but it was exported without the "
792          "EXPORT_LINK_INTERFACE_LIBRARIES to export the old-style properties";
793     lg->IssueMessage(MessageType::FATAL_ERROR, e.str());
794     return;
795   }
796
797   if (propContent->empty()) {
798     properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix].clear();
799     return;
800   }
801
802   std::string prepro =
803     cmGeneratorExpression::Preprocess(*propContent, preprocessRule);
804   if (!prepro.empty()) {
805     this->ResolveTargetsInGeneratorExpressions(prepro, target,
806                                                ReplaceFreeTargets);
807     properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix] = prepro;
808   }
809 }
810
811 void cmExportFileGenerator::SetImportDetailProperties(
812   const std::string& config, std::string const& suffix,
813   cmGeneratorTarget* target, ImportPropertyMap& properties)
814 {
815   // Get the makefile in which to lookup target information.
816   cmMakefile* mf = target->Makefile;
817
818   // Add the soname for unix shared libraries.
819   if (target->GetType() == cmStateEnums::SHARED_LIBRARY ||
820       target->GetType() == cmStateEnums::MODULE_LIBRARY) {
821     if (!target->IsDLLPlatform()) {
822       std::string prop;
823       std::string value;
824       if (target->HasSOName(config)) {
825         if (mf->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) {
826           value = this->InstallNameDir(target, config);
827         }
828         prop = "IMPORTED_SONAME";
829         value += target->GetSOName(config);
830       } else {
831         prop = "IMPORTED_NO_SONAME";
832         value = "TRUE";
833       }
834       prop += suffix;
835       properties[prop] = value;
836     }
837   }
838
839   // Add the transitive link dependencies for this configuration.
840   if (cmLinkInterface const* iface =
841         target->GetLinkInterface(config, target)) {
842     this->SetImportLinkProperty(
843       suffix, target, "IMPORTED_LINK_INTERFACE_LANGUAGES", iface->Languages,
844       properties, ImportLinkPropertyTargetNames::No);
845
846     // Export IMPORTED_LINK_DEPENDENT_LIBRARIES to help consuming linkers
847     // find private dependencies of shared libraries.
848     std::size_t oldMissingTargetsSize = this->MissingTargets.size();
849     this->SetImportLinkProperty(
850       suffix, target, "IMPORTED_LINK_DEPENDENT_LIBRARIES", iface->SharedDeps,
851       properties, ImportLinkPropertyTargetNames::Yes);
852     // Avoid enforcing shared library private dependencies as public package
853     // dependencies by ignoring missing targets added for them.
854     this->MissingTargets.resize(oldMissingTargetsSize);
855
856     if (iface->Multiplicity > 0) {
857       std::string prop =
858         cmStrCat("IMPORTED_LINK_INTERFACE_MULTIPLICITY", suffix);
859       properties[prop] = std::to_string(iface->Multiplicity);
860     }
861   }
862
863   // Add information if this target is a managed target
864   if (target->GetManagedType(config) !=
865       cmGeneratorTarget::ManagedType::Native) {
866     std::string prop = cmStrCat("IMPORTED_COMMON_LANGUAGE_RUNTIME", suffix);
867     std::string propval;
868     if (cmValue p = target->GetProperty("COMMON_LANGUAGE_RUNTIME")) {
869       propval = *p;
870     } else if (target->IsCSharpOnly()) {
871       // C# projects do not have the /clr flag, so we set the property
872       // here to mark the target as (only) managed (i.e. no .lib file
873       // to link to). Otherwise the  COMMON_LANGUAGE_RUNTIME target
874       // property would have to be set manually for C# targets to make
875       // exporting/importing work.
876       propval = "CSharp";
877     }
878     properties[prop] = propval;
879   }
880 }
881
882 static std::string const& asString(std::string const& l)
883 {
884   return l;
885 }
886
887 static std::string const& asString(cmLinkItem const& l)
888 {
889   return l.AsStr();
890 }
891
892 template <typename T>
893 void cmExportFileGenerator::SetImportLinkProperty(
894   std::string const& suffix, cmGeneratorTarget const* target,
895   const std::string& propName, std::vector<T> const& entries,
896   ImportPropertyMap& properties, ImportLinkPropertyTargetNames targetNames)
897 {
898   // Skip the property if there are no entries.
899   if (entries.empty()) {
900     return;
901   }
902
903   cmLocalGenerator const* lg = target->GetLocalGenerator();
904
905   // Construct the property value.
906   std::string link_entries;
907   const char* sep = "";
908   for (T const& l : entries) {
909     // Separate this from the previous entry.
910     link_entries += sep;
911     sep = ";";
912
913     if (targetNames == ImportLinkPropertyTargetNames::Yes) {
914       std::string temp = asString(l);
915       this->AddTargetNamespace(temp, target, lg);
916       link_entries += temp;
917     } else {
918       link_entries += asString(l);
919     }
920   }
921
922   // Store the property.
923   std::string prop = cmStrCat(propName, suffix);
924   properties[prop] = link_entries;
925 }
926
927 void cmExportFileGenerator::GeneratePolicyHeaderCode(std::ostream& os)
928 {
929   // Protect that file against use with older CMake versions.
930   /* clang-format off */
931   os << "# Generated by CMake\n\n";
932   os << "if(\"${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}\" LESS 2.8)\n"
933      << "   message(FATAL_ERROR \"CMake >= 2.8.0 required\")\n"
934      << "endif()\n"
935      << "if(CMAKE_VERSION VERSION_LESS \"2.8.3\")\n"
936      << "   message(FATAL_ERROR \"CMake >= 2.8.3 required\")\n"
937      << "endif()\n";
938   /* clang-format on */
939
940   // Isolate the file policy level.
941   // Support CMake versions as far back as 2.6 but also support using NEW
942   // policy settings for up to CMake 3.22 (this upper limit may be reviewed
943   // and increased from time to time). This reduces the opportunity for CMake
944   // warnings when an older export file is later used with newer CMake
945   // versions.
946   /* clang-format off */
947   os << "cmake_policy(PUSH)\n"
948      << "cmake_policy(VERSION 2.8.3...3.22)\n";
949   /* clang-format on */
950 }
951
952 void cmExportFileGenerator::GeneratePolicyFooterCode(std::ostream& os)
953 {
954   os << "cmake_policy(POP)\n";
955 }
956
957 void cmExportFileGenerator::GenerateImportHeaderCode(std::ostream& os,
958                                                      const std::string& config)
959 {
960   os << "#----------------------------------------------------------------\n"
961      << "# Generated CMake target import file";
962   if (!config.empty()) {
963     os << " for configuration \"" << config << "\".\n";
964   } else {
965     os << ".\n";
966   }
967   os << "#----------------------------------------------------------------\n"
968      << "\n";
969   this->GenerateImportVersionCode(os);
970 }
971
972 void cmExportFileGenerator::GenerateImportFooterCode(std::ostream& os)
973 {
974   os << "# Commands beyond this point should not need to know the version.\n"
975      << "set(CMAKE_IMPORT_FILE_VERSION)\n";
976 }
977
978 void cmExportFileGenerator::GenerateImportVersionCode(std::ostream& os)
979 {
980   // Store an import file format version.  This will let us change the
981   // format later while still allowing old import files to work.
982   /* clang-format off */
983   os << "# Commands may need to know the format version.\n"
984      << "set(CMAKE_IMPORT_FILE_VERSION 1)\n"
985      << "\n";
986   /* clang-format on */
987 }
988
989 void cmExportFileGenerator::GenerateExpectedTargetsCode(
990   std::ostream& os, const std::string& expectedTargets)
991 {
992   /* clang-format off */
993   os << "# Protect against multiple inclusion, which would fail when already "
994         "imported targets are added once more.\n"
995         "set(_cmake_targets_defined \"\")\n"
996         "set(_cmake_targets_not_defined \"\")\n"
997         "set(_cmake_expected_targets \"\")\n"
998         "foreach(_cmake_expected_target IN ITEMS " << expectedTargets << ")\n"
999         "  list(APPEND _cmake_expected_targets \"${_cmake_expected_target}\")\n"
1000         "  if(TARGET \"${_cmake_expected_target}\")\n"
1001         "    list(APPEND _cmake_targets_defined \"${_cmake_expected_target}\")\n"
1002         "  else()\n"
1003         "    list(APPEND _cmake_targets_not_defined \"${_cmake_expected_target}\")\n"
1004         "  endif()\n"
1005         "endforeach()\n"
1006         "unset(_cmake_expected_target)\n"
1007         "if(_cmake_targets_defined STREQUAL _cmake_expected_targets)\n"
1008         "  unset(_cmake_targets_defined)\n"
1009         "  unset(_cmake_targets_not_defined)\n"
1010         "  unset(_cmake_expected_targets)\n"
1011         "  unset(CMAKE_IMPORT_FILE_VERSION)\n"
1012         "  cmake_policy(POP)\n"
1013         "  return()\n"
1014         "endif()\n"
1015         "if(NOT _cmake_targets_defined STREQUAL \"\")\n"
1016         "  string(REPLACE \";\" \", \" _cmake_targets_defined_text \"${_cmake_targets_defined}\")\n"
1017         "  string(REPLACE \";\" \", \" _cmake_targets_not_defined_text \"${_cmake_targets_not_defined}\")\n"
1018         "  message(FATAL_ERROR \"Some (but not all) targets in this export "
1019         "set were already defined.\\nTargets Defined: ${_cmake_targets_defined_text}\\n"
1020         "Targets not yet defined: ${_cmake_targets_not_defined_text}\\n\")\n"
1021         "endif()\n"
1022         "unset(_cmake_targets_defined)\n"
1023         "unset(_cmake_targets_not_defined)\n"
1024         "unset(_cmake_expected_targets)\n"
1025         "\n\n";
1026   /* clang-format on */
1027 }
1028
1029 void cmExportFileGenerator::GenerateImportTargetCode(
1030   std::ostream& os, cmGeneratorTarget const* target,
1031   cmStateEnums::TargetType targetType)
1032 {
1033   // Construct the imported target name.
1034   std::string targetName = this->Namespace;
1035
1036   targetName += target->GetExportName();
1037
1038   // Create the imported target.
1039   os << "# Create imported target " << targetName << "\n";
1040   switch (targetType) {
1041     case cmStateEnums::EXECUTABLE:
1042       os << "add_executable(" << targetName << " IMPORTED)\n";
1043       break;
1044     case cmStateEnums::STATIC_LIBRARY:
1045       os << "add_library(" << targetName << " STATIC IMPORTED)\n";
1046       break;
1047     case cmStateEnums::SHARED_LIBRARY:
1048       os << "add_library(" << targetName << " SHARED IMPORTED)\n";
1049       break;
1050     case cmStateEnums::MODULE_LIBRARY:
1051       os << "add_library(" << targetName << " MODULE IMPORTED)\n";
1052       break;
1053     case cmStateEnums::UNKNOWN_LIBRARY:
1054       os << "add_library(" << targetName << " UNKNOWN IMPORTED)\n";
1055       break;
1056     case cmStateEnums::OBJECT_LIBRARY:
1057       os << "add_library(" << targetName << " OBJECT IMPORTED)\n";
1058       break;
1059     case cmStateEnums::INTERFACE_LIBRARY:
1060       os << "add_library(" << targetName << " INTERFACE IMPORTED)\n";
1061       break;
1062     default: // should never happen
1063       break;
1064   }
1065
1066   // Mark the imported executable if it has exports.
1067   if (target->IsExecutableWithExports()) {
1068     os << "set_property(TARGET " << targetName
1069        << " PROPERTY ENABLE_EXPORTS 1)\n";
1070   }
1071
1072   // Mark the imported library if it is a framework.
1073   if (target->IsFrameworkOnApple()) {
1074     os << "set_property(TARGET " << targetName << " PROPERTY FRAMEWORK 1)\n";
1075   }
1076
1077   // Mark the imported executable if it is an application bundle.
1078   if (target->IsAppBundleOnApple()) {
1079     os << "set_property(TARGET " << targetName
1080        << " PROPERTY MACOSX_BUNDLE 1)\n";
1081   }
1082
1083   if (target->IsCFBundleOnApple()) {
1084     os << "set_property(TARGET " << targetName << " PROPERTY BUNDLE 1)\n";
1085   }
1086
1087   // generate DEPRECATION
1088   if (target->IsDeprecated()) {
1089     os << "set_property(TARGET " << targetName << " PROPERTY DEPRECATION "
1090        << cmExportFileGeneratorEscape(target->GetDeprecation()) << ")\n";
1091   }
1092
1093   if (target->GetPropertyAsBool("IMPORTED_NO_SYSTEM")) {
1094     os << "set_property(TARGET " << targetName
1095        << " PROPERTY IMPORTED_NO_SYSTEM 1)\n";
1096   }
1097
1098   os << "\n";
1099 }
1100
1101 void cmExportFileGenerator::GenerateImportPropertyCode(
1102   std::ostream& os, const std::string& config, cmGeneratorTarget const* target,
1103   ImportPropertyMap const& properties)
1104 {
1105   // Construct the imported target name.
1106   std::string targetName = this->Namespace;
1107
1108   targetName += target->GetExportName();
1109
1110   // Set the import properties.
1111   os << "# Import target \"" << targetName << "\" for configuration \""
1112      << config << "\"\n";
1113   os << "set_property(TARGET " << targetName
1114      << " APPEND PROPERTY IMPORTED_CONFIGURATIONS ";
1115   if (!config.empty()) {
1116     os << cmSystemTools::UpperCase(config);
1117   } else {
1118     os << "NOCONFIG";
1119   }
1120   os << ")\n";
1121   os << "set_target_properties(" << targetName << " PROPERTIES\n";
1122   for (auto const& property : properties) {
1123     os << "  " << property.first << " "
1124        << cmExportFileGeneratorEscape(property.second) << "\n";
1125   }
1126   os << "  )\n"
1127      << "\n";
1128 }
1129
1130 void cmExportFileGenerator::GenerateMissingTargetsCheckCode(std::ostream& os)
1131 {
1132   if (this->MissingTargets.empty()) {
1133     /* clang-format off */
1134     os << "# This file does not depend on other imported targets which have\n"
1135           "# been exported from the same project but in a separate "
1136             "export set.\n\n";
1137     /* clang-format on */
1138     return;
1139   }
1140   /* clang-format off */
1141   os << "# Make sure the targets which have been exported in some other\n"
1142         "# export set exist.\n"
1143         "unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
1144         "foreach(_target ";
1145   /* clang-format on */
1146   std::set<std::string> emitted;
1147   for (std::string const& missingTarget : this->MissingTargets) {
1148     if (emitted.insert(missingTarget).second) {
1149       os << "\"" << missingTarget << "\" ";
1150     }
1151   }
1152   /* clang-format off */
1153   os << ")\n"
1154         "  if(NOT TARGET \"${_target}\" )\n"
1155         "    set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets \""
1156         "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets} ${_target}\")"
1157         "\n"
1158         "  endif()\n"
1159         "endforeach()\n"
1160         "\n"
1161         "if(DEFINED ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
1162         "  if(CMAKE_FIND_PACKAGE_NAME)\n"
1163         "    set( ${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)\n"
1164         "    set( ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE "
1165         "\"The following imported targets are "
1166         "referenced, but are missing: "
1167                  "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n"
1168         "  else()\n"
1169         "    message(FATAL_ERROR \"The following imported targets are "
1170         "referenced, but are missing: "
1171                 "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n"
1172         "  endif()\n"
1173         "endif()\n"
1174         "unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n"
1175         "\n";
1176   /* clang-format on */
1177 }
1178
1179 void cmExportFileGenerator::GenerateImportedFileCheckLoop(std::ostream& os)
1180 {
1181   // Add code which verifies at cmake time that the file which is being
1182   // imported actually exists on disk. This should in theory always be theory
1183   // case, but still when packages are split into normal and development
1184   // packages this might get broken (e.g. the Config.cmake could be part of
1185   // the non-development package, something similar happened to me without
1186   // on SUSE with a mysql pkg-config file, which claimed everything is fine,
1187   // but the development package was not installed.).
1188   /* clang-format off */
1189   os << "# Loop over all imported files and verify that they actually exist\n"
1190         "foreach(_cmake_target IN LISTS _cmake_import_check_targets)\n"
1191         "  foreach(_cmake_file IN LISTS \"_cmake_import_check_files_for_${_cmake_target}\")\n"
1192         "    if(NOT EXISTS \"${_cmake_file}\")\n"
1193         "      message(FATAL_ERROR \"The imported target \\\"${_cmake_target}\\\""
1194         " references the file\n"
1195         "   \\\"${_cmake_file}\\\"\n"
1196         "but this file does not exist.  Possible reasons include:\n"
1197         "* The file was deleted, renamed, or moved to another location.\n"
1198         "* An install or uninstall procedure did not complete successfully.\n"
1199         "* The installation package was faulty and contained\n"
1200         "   \\\"${CMAKE_CURRENT_LIST_FILE}\\\"\n"
1201         "but not all the files it references.\n"
1202         "\")\n"
1203         "    endif()\n"
1204         "  endforeach()\n"
1205         "  unset(_cmake_file)\n"
1206         "  unset(\"_cmake_import_check_files_for_${_cmake_target}\")\n"
1207         "endforeach()\n"
1208         "unset(_cmake_target)\n"
1209         "unset(_cmake_import_check_targets)\n"
1210         "\n";
1211   /* clang-format on */
1212 }
1213
1214 void cmExportFileGenerator::GenerateImportedFileChecksCode(
1215   std::ostream& os, cmGeneratorTarget* target,
1216   ImportPropertyMap const& properties,
1217   const std::set<std::string>& importedLocations)
1218 {
1219   // Construct the imported target name.
1220   std::string targetName = cmStrCat(this->Namespace, target->GetExportName());
1221
1222   os << "list(APPEND _cmake_import_check_targets " << targetName
1223      << " )\n"
1224         "list(APPEND _cmake_import_check_files_for_"
1225      << targetName << " ";
1226
1227   for (std::string const& li : importedLocations) {
1228     auto pi = properties.find(li);
1229     if (pi != properties.end()) {
1230       os << cmExportFileGeneratorEscape(pi->second) << " ";
1231     }
1232   }
1233
1234   os << ")\n\n";
1235 }
1236
1237 bool cmExportFileGenerator::PopulateExportProperties(
1238   cmGeneratorTarget const* gte, ImportPropertyMap& properties,
1239   std::string& errorMessage)
1240 {
1241   const auto& targetProperties = gte->Target->GetProperties();
1242   if (cmValue exportProperties =
1243         targetProperties.GetPropertyValue("EXPORT_PROPERTIES")) {
1244     for (auto& prop : cmExpandedList(*exportProperties)) {
1245       /* Black list reserved properties */
1246       if (cmHasLiteralPrefix(prop, "IMPORTED_") ||
1247           cmHasLiteralPrefix(prop, "INTERFACE_")) {
1248         std::ostringstream e;
1249         e << "Target \"" << gte->Target->GetName() << "\" contains property \""
1250           << prop << "\" in EXPORT_PROPERTIES but IMPORTED_* and INTERFACE_* "
1251           << "properties are reserved.";
1252         errorMessage = e.str();
1253         return false;
1254       }
1255       cmValue propertyValue = targetProperties.GetPropertyValue(prop);
1256       if (!propertyValue) {
1257         // Asked to export a property that isn't defined on the target. Do not
1258         // consider this an error, there's just nothing to export.
1259         continue;
1260       }
1261       std::string evaluatedValue = cmGeneratorExpression::Preprocess(
1262         *propertyValue, cmGeneratorExpression::StripAllGeneratorExpressions);
1263       if (evaluatedValue != *propertyValue) {
1264         std::ostringstream e;
1265         e << "Target \"" << gte->Target->GetName() << "\" contains property \""
1266           << prop << "\" in EXPORT_PROPERTIES but this property contains a "
1267           << "generator expression. This is not allowed.";
1268         errorMessage = e.str();
1269         return false;
1270       }
1271       properties[prop] = *propertyValue;
1272     }
1273   }
1274   return true;
1275 }
1276
1277 void cmExportFileGenerator::GenerateTargetFileSets(cmGeneratorTarget* gte,
1278                                                    std::ostream& os,
1279                                                    cmTargetExport* te)
1280 {
1281   auto interfaceFileSets = gte->Target->GetAllInterfaceFileSets();
1282   if (!interfaceFileSets.empty()) {
1283     std::string targetName = cmStrCat(this->Namespace, gte->GetExportName());
1284     os << "if(NOT CMAKE_VERSION VERSION_LESS \"3.23.0\")\n"
1285           "  target_sources("
1286        << targetName << "\n";
1287
1288     for (auto const& name : interfaceFileSets) {
1289       auto* fileSet = gte->Target->GetFileSet(name);
1290       if (!fileSet) {
1291         gte->Makefile->IssueMessage(
1292           MessageType::FATAL_ERROR,
1293           cmStrCat("File set \"", name,
1294                    "\" is listed in interface file sets of ", gte->GetName(),
1295                    " but has not been created"));
1296         return;
1297       }
1298
1299       os << "    INTERFACE"
1300          << "\n      FILE_SET " << cmOutputConverter::EscapeForCMake(name)
1301          << "\n      TYPE "
1302          << cmOutputConverter::EscapeForCMake(fileSet->GetType())
1303          << "\n      BASE_DIRS "
1304          << this->GetFileSetDirectories(gte, fileSet, te) << "\n      FILES "
1305          << this->GetFileSetFiles(gte, fileSet, te) << "\n";
1306     }
1307
1308     os << "  )\nendif()\n\n";
1309   }
1310 }