cmQtAutoMocUic.cxx 96.7 KB
Newer Older
1
2
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */
3
#include "cmQtAutoMocUic.h"
Brad King's avatar
Brad King committed
4

5
6
7
8
9
10
11
12
13
14
15
#include <algorithm>
#include <atomic>
#include <cstddef>
#include <map>
#include <mutex>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
16

17
#include <cm/memory>
18
#include <cm/optional>
19
#include <cm/string_view>
20
#include <cmext/algorithm>
21

22
23
#include <cm3p/json/value.h>

24
25
26
27
28
#include "cmsys/FStream.hxx"
#include "cmsys/RegularExpression.hxx"

#include "cmCryptoHash.h"
#include "cmFileTime.h"
29
#include "cmGccDepfileReader.h"
30
31
32
33
34
35
36
#include "cmGeneratedFileStream.h"
#include "cmQtAutoGen.h"
#include "cmQtAutoGenerator.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
#include "cmWorkerPool.h"

37
#if defined(__APPLE__)
38
#  include <unistd.h>
39
#endif
40

41
42
43
44
45
namespace {

constexpr std::size_t MocUnderscoreLength = 4; // Length of "moc_"
constexpr std::size_t UiUnderscoreLength = 3;  // Length of "ui_"

46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
/** \class cmQtAutoMocUicT
 * \brief AUTOMOC and AUTOUIC generator
 */
class cmQtAutoMocUicT : public cmQtAutoGenerator
{
public:
  cmQtAutoMocUicT();
  ~cmQtAutoMocUicT() override;

  cmQtAutoMocUicT(cmQtAutoMocUicT const&) = delete;
  cmQtAutoMocUicT& operator=(cmQtAutoMocUicT const&) = delete;

  // -- Types

  /** Include string with sub parts.  */
  struct IncludeKeyT
  {
    IncludeKeyT(std::string const& key, std::size_t basePrefixLength);

    std::string Key;  // Full include string
    std::string Dir;  // Include directory
    std::string Base; // Base part of the include file name
  };

  /** Search key plus regular expression pair.  */
  struct KeyExpT
  {
    KeyExpT(std::string key, std::string const& exp)
      : Key(std::move(key))
      , Exp(exp)
    {
    }

    std::string Key;
    cmsys::RegularExpression Exp;
  };

  /** Source file parsing cache.  */
  class ParseCacheT
  {
  public:
    // -- Types

    /** Entry of the file parsing cache.  */
    struct FileT
    {
      void Clear();

      struct MocT
      {
        std::string Macro;
        struct IncludeT
        {
          std::vector<IncludeKeyT> Underscore;
          std::vector<IncludeKeyT> Dot;
        } Include;
        std::vector<std::string> Depends;
      } Moc;

      struct UicT
      {
        std::vector<IncludeKeyT> Include;
        std::vector<std::string> Depends;
      } Uic;
    };
    using FileHandleT = std::shared_ptr<FileT>;
    using GetOrInsertT = std::pair<FileHandleT, bool>;

    ParseCacheT();
    ~ParseCacheT();

    bool ReadFromFile(std::string const& fileName);
    bool WriteToFile(std::string const& fileName);

    //! Always returns a valid handle
    GetOrInsertT GetOrInsert(std::string const& fileName);

  private:
    std::unordered_map<std::string, FileHandleT> Map_;
  };

  /** Source file data.  */
  class SourceFileT
  {
  public:
    SourceFileT(std::string fileName)
      : FileName(std::move(fileName))
    {
    }

    std::string FileName;
    cmFileTime FileTime;
    ParseCacheT::FileHandleT ParseData;
    std::string BuildPath;
    bool IsHeader = false;
    bool Moc = false;
    bool Uic = false;
  };
  using SourceFileHandleT = std::shared_ptr<SourceFileT>;
  using SourceFileMapT = std::map<std::string, SourceFileHandleT>;

  /** Meta compiler file mapping information.  */
  struct MappingT
  {
    SourceFileHandleT SourceFile;
    std::string OutputFile;
    std::string IncludeString;
    std::vector<SourceFileHandleT> IncluderFiles;
  };
  using MappingHandleT = std::shared_ptr<MappingT>;
  using MappingMapT = std::map<std::string, MappingHandleT>;

  /** Common settings.  */
  class BaseSettingsT
  {
  public:
    // -- Constructors
    BaseSettingsT();
    ~BaseSettingsT();

    BaseSettingsT(BaseSettingsT const&) = delete;
    BaseSettingsT& operator=(BaseSettingsT const&) = delete;

    // -- Attributes
    // - Config
    bool MultiConfig = false;
172
    IntegerVersion QtVersion = { 4, 0 };
173
174
175
176
177
178
179
180
    unsigned int ThreadCount = 0;
    // - Directories
    std::string AutogenBuildDir;
    std::string AutogenIncludeDir;
    // - Files
    std::string CMakeExecutable;
    cmFileTime CMakeExecutableTime;
    std::string ParseCacheFile;
181
182
    std::string DepFile;
    std::string DepFileRuleName;
183
    std::vector<std::string> HeaderExtensions;
184
    std::vector<std::string> ListFiles;
185
186
187
188
189
190
191
  };

  /** Shared common variables.  */
  class BaseEvalT
  {
  public:
    // -- Parse Cache
192
    std::atomic<bool> ParseCacheChanged = ATOMIC_VAR_INIT(false);
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
    cmFileTime ParseCacheTime;
    ParseCacheT ParseCache;

    // -- Sources
    SourceFileMapT Headers;
    SourceFileMapT Sources;
  };

  /** Moc settings.  */
  class MocSettingsT
  {
  public:
    // -- Constructors
    MocSettingsT();
    ~MocSettingsT();

    MocSettingsT(MocSettingsT const&) = delete;
    MocSettingsT& operator=(MocSettingsT const&) = delete;

    // -- Const methods
    bool skipped(std::string const& fileName) const;
    std::string MacrosString() const;

    // -- Attributes
    bool Enabled = false;
    bool SettingsChanged = false;
    bool RelaxedMode = false;
    bool PathPrefix = false;
221
    bool CanOutputDependencies = false;
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
    cmFileTime ExecutableTime;
    std::string Executable;
    std::string CompFileAbs;
    std::string PredefsFileAbs;
    std::unordered_set<std::string> SkipList;
    std::vector<std::string> IncludePaths;
    std::vector<std::string> Definitions;
    std::vector<std::string> OptionsIncludes;
    std::vector<std::string> OptionsDefinitions;
    std::vector<std::string> OptionsExtra;
    std::vector<std::string> PredefsCmd;
    std::vector<KeyExpT> DependFilters;
    std::vector<KeyExpT> MacroFilters;
    cmsys::RegularExpression RegExpInclude;
  };

  /** Moc shared variables.  */
  class MocEvalT
  {
  public:
    // -- predefines file
    cmFileTime PredefsTime;
    // -- Mappings
    MappingMapT HeaderMappings;
    MappingMapT SourceMappings;
    MappingMapT Includes;
    // -- Discovered files
    SourceFileMapT HeadersDiscovered;
    // -- Output directories
    std::unordered_set<std::string> OutputDirs;
    // -- Mocs compilation
    bool CompUpdated = false;
    std::vector<std::string> CompFiles;
  };

  /** Uic settings.  */
  class UicSettingsT
  {
  public:
    struct UiFile
    {
      std::vector<std::string> Options;
    };

    UicSettingsT();
    ~UicSettingsT();

    UicSettingsT(UicSettingsT const&) = delete;
    UicSettingsT& operator=(UicSettingsT const&) = delete;

    // -- Const methods
    bool skipped(std::string const& fileName) const;

    // -- Attributes
    bool Enabled = false;
    bool SettingsChanged = false;
    cmFileTime ExecutableTime;
    std::string Executable;
    std::unordered_set<std::string> SkipList;
    std::vector<std::string> Options;
    std::unordered_map<std::string, UiFile> UiFiles;
    std::vector<std::string> SearchPaths;
284
    cmsys::RegularExpression RegExpInclude;
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
  };

  /** Uic shared variables.  */
  class UicEvalT
  {
  public:
    // -- Discovered files
    SourceFileMapT UiFiles;
    // -- Mappings
    MappingMapT Includes;
    // -- Output directories
    std::unordered_set<std::string> OutputDirs;
  };

  /** Abstract job class for concurrent job processing.  */
  class JobT : public cmWorkerPool::JobT
  {
  protected:
    /** Protected default constructor.  */
    JobT(bool fence = false)
      : cmWorkerPool::JobT(fence)
    {
    }

    //! Get the generator. Only valid during Process() call!
    cmQtAutoMocUicT* Gen() const
    {
312
      return static_cast<cmQtAutoMocUicT*>(this->UserData());
313
    }
314
315

    // -- Accessors. Only valid during Process() call!
316
317
318
319
320
321
322
    Logger const& Log() const { return this->Gen()->Log(); }
    BaseSettingsT const& BaseConst() const { return this->Gen()->BaseConst(); }
    BaseEvalT& BaseEval() const { return this->Gen()->BaseEval(); }
    MocSettingsT const& MocConst() const { return this->Gen()->MocConst(); }
    MocEvalT& MocEval() const { return this->Gen()->MocEval(); }
    UicSettingsT const& UicConst() const { return this->Gen()->UicConst(); }
    UicEvalT& UicEval() const { return this->Gen()->UicEval(); }
323
324
325
326

    // -- Logging
    std::string MessagePath(cm::string_view path) const
    {
327
      return this->Gen()->MessagePath(path);
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
    }
    // - Error logging with automatic abort
    void LogError(GenT genType, cm::string_view message) const;
    void LogCommandError(GenT genType, cm::string_view message,
                         std::vector<std::string> const& command,
                         std::string const& output) const;

    /** @brief Run an external process. Use only during Process() call!  */
    bool RunProcess(GenT genType, cmWorkerPool::ProcessResultT& result,
                    std::vector<std::string> const& command,
                    std::string* infoMessage = nullptr);
  };

  /** Fence job utility class.  */
  class JobFenceT : public JobT
  {
  public:
    JobFenceT()
      : JobT(true)
    {
    }
349
    void Process() override {}
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
  };

  /** Generate moc_predefs.h.  */
  class JobMocPredefsT : public JobFenceT
  {
    void Process() override;
    bool Update(std::string* reason) const;
  };

  /** File parse job base class.  */
  class JobParseT : public JobT
  {
  public:
    JobParseT(SourceFileHandleT fileHandle)
      : FileHandle(std::move(fileHandle))
    {
    }

  protected:
    bool ReadFile();
    void CreateKeys(std::vector<IncludeKeyT>& container,
                    std::set<std::string> const& source,
                    std::size_t basePrefixLength);
    void MocMacro();
    void MocDependecies();
    void MocIncludes();
    void UicIncludes();

    SourceFileHandleT FileHandle;
    std::string Content;
  };

  /** Header file parse job.  */
  class JobParseHeaderT : public JobParseT
  {
  public:
    using JobParseT::JobParseT;
    void Process() override;
  };
389

390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
  /** Source file parse job.  */
  class JobParseSourceT : public JobParseT
  {
  public:
    using JobParseT::JobParseT;
    void Process() override;
  };

  /** Evaluate cached file parse data - moc.  */
  class JobEvalCacheT : public JobT
  {
  protected:
    std::string MessageSearchLocations() const;
    std::vector<std::string> SearchLocations;
  };

  /** Evaluate cached file parse data - moc.  */
  class JobEvalCacheMocT : public JobEvalCacheT
  {
    void Process() override;
    bool EvalHeader(SourceFileHandleT source);
    bool EvalSource(SourceFileHandleT const& source);
    bool FindIncludedHeader(SourceFileHandleT& headerHandle,
                            cm::string_view includerDir,
                            cm::string_view includeBase);
    bool RegisterIncluded(std::string const& includeString,
                          SourceFileHandleT includerFileHandle,
                          SourceFileHandleT sourceFileHandle) const;
    void RegisterMapping(MappingHandleT mappingHandle) const;
    std::string MessageHeader(cm::string_view headerBase) const;
  };

  /** Evaluate cached file parse data - uic.  */
  class JobEvalCacheUicT : public JobEvalCacheT
  {
    void Process() override;
    bool EvalFile(SourceFileHandleT const& sourceFileHandle);
    bool FindIncludedUi(cm::string_view sourceDirPrefix,
                        cm::string_view includePrefix);
    bool RegisterMapping(std::string const& includeString,
                         SourceFileHandleT includerFileHandle);

    std::string UiName;
    SourceFileHandleT UiFileHandle;
  };

  /** Evaluate cached file parse data - finish  */
  class JobEvalCacheFinishT : public JobFenceT
  {
    void Process() override;
  };

  /** Dependency probing base job.  */
  class JobProbeDepsT : public JobT
  {
  };

  /** Probes file dependencies and generates moc compile jobs.  */
  class JobProbeDepsMocT : public JobProbeDepsT
  {
    void Process() override;
    bool Generate(MappingHandleT const& mapping, bool compFile) const;
    bool Probe(MappingT const& mapping, std::string* reason) const;
    std::pair<std::string, cmFileTime> FindDependency(
      std::string const& sourceDir, std::string const& includeString) const;
  };

  /** Probes file dependencies and generates uic compile jobs.  */
  class JobProbeDepsUicT : public JobProbeDepsT
  {
    void Process() override;
    bool Probe(MappingT const& mapping, std::string* reason) const;
  };

  /** Dependency probing finish job.  */
  class JobProbeDepsFinishT : public JobFenceT
  {
    void Process() override;
  };

  /** Meta compiler base job.  */
  class JobCompileT : public JobT
  {
  public:
    JobCompileT(MappingHandleT uicMapping, std::unique_ptr<std::string> reason)
      : Mapping(std::move(uicMapping))
      , Reason(std::move(reason))
    {
    }

  protected:
    MappingHandleT Mapping;
    std::unique_ptr<std::string> Reason;
  };

  /** moc compiles a file.  */
  class JobCompileMocT : public JobCompileT
  {
  public:
489
490
491
492
493
494
495
    JobCompileMocT(MappingHandleT uicMapping,
                   std::unique_ptr<std::string> reason,
                   ParseCacheT::FileHandleT cacheEntry)
      : JobCompileT(std::move(uicMapping), std::move(reason))
      , CacheEntry(std::move(cacheEntry))
    {
    }
496
    void Process() override;
497
498
499

  protected:
    ParseCacheT::FileHandleT CacheEntry;
500
501
502
503

  private:
    void MaybeWriteMocResponseFile(std::string const& outputFile,
                                   std::vector<std::string>& cmd) const;
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
  };

  /** uic compiles a file.  */
  class JobCompileUicT : public JobCompileT
  {
  public:
    using JobCompileT::JobCompileT;
    void Process() override;
  };

  /** Generate mocs_compilation.cpp.  */
  class JobMocsCompilationT : public JobFenceT
  {
  private:
    void Process() override;
  };

521
522
523
  class JobDepFilesMergeT : public JobFenceT
  {
  private:
524
    std::vector<std::string> initialDependencies() const;
525
526
527
    void Process() override;
  };

528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
  /** @brief The last job.  */
  class JobFinishT : public JobFenceT
  {
  private:
    void Process() override;
  };

  // -- Const settings interface
  BaseSettingsT const& BaseConst() const { return this->BaseConst_; }
  BaseEvalT& BaseEval() { return this->BaseEval_; }
  MocSettingsT const& MocConst() const { return this->MocConst_; }
  MocEvalT& MocEval() { return this->MocEval_; }
  UicSettingsT const& UicConst() const { return this->UicConst_; }
  UicEvalT& UicEval() { return this->UicEval_; }

  // -- Parallel job processing interface
544
545
546
  cmWorkerPool& WorkerPool() { return this->WorkerPool_; }
  void AbortError() { this->Abort(true); }
  void AbortSuccess() { this->Abort(false); }
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569

  // -- Utility
  std::string AbsoluteBuildPath(cm::string_view relativePath) const;
  std::string AbsoluteIncludePath(cm::string_view relativePath) const;
  template <class JOBTYPE>
  void CreateParseJobs(SourceFileMapT const& sourceMap);
  std::string CollapseFullPathTS(std::string const& path) const;

private:
  // -- Abstract processing interface
  bool InitFromInfo(InfoT const& info) override;
  void InitJobs();
  bool Process() override;
  // -- Settings file
  void SettingsFileRead();
  bool SettingsFileWrite();
  // -- Parse cache
  void ParseCacheRead();
  bool ParseCacheWrite();
  // -- Thread processing
  void Abort(bool error);
  // -- Generation
  bool CreateDirectories();
570
  // -- Support for depfiles
571
  std::vector<std::string> dependenciesFromDepFile(const char* filePath);
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592

  // -- Settings
  BaseSettingsT BaseConst_;
  BaseEvalT BaseEval_;
  MocSettingsT MocConst_;
  MocEvalT MocEval_;
  UicSettingsT UicConst_;
  UicEvalT UicEval_;
  // -- Settings file
  std::string SettingsFile_;
  std::string SettingsStringMoc_;
  std::string SettingsStringUic_;
  // -- Worker thread pool
  std::atomic<bool> JobError_ = ATOMIC_VAR_INIT(false);
  cmWorkerPool WorkerPool_;
  // -- Concurrent processing
  mutable std::mutex CMakeLibMutex_;
};

cmQtAutoMocUicT::IncludeKeyT::IncludeKeyT(std::string const& key,
                                          std::size_t basePrefixLength)
593
594
595
  : Key(key)
  , Dir(SubDirPrefix(key))
  , Base(cmSystemTools::GetFilenameWithoutLastExtension(key))
596
{
597
  if (basePrefixLength != 0) {
598
    this->Base = this->Base.substr(basePrefixLength);
599
  }
600
}
601

602
void cmQtAutoMocUicT::ParseCacheT::FileT::Clear()
603
{
604
605
606
607
  this->Moc.Macro.clear();
  this->Moc.Include.Underscore.clear();
  this->Moc.Include.Dot.clear();
  this->Moc.Depends.clear();
608

609
610
  this->Uic.Include.clear();
  this->Uic.Depends.clear();
611
612
}

613
614
cmQtAutoMocUicT::ParseCacheT::GetOrInsertT
cmQtAutoMocUicT::ParseCacheT::GetOrInsert(std::string const& fileName)
615
616
617
{
  // Find existing entry
  {
618
619
    auto it = this->Map_.find(fileName);
    if (it != this->Map_.end()) {
620
      return GetOrInsertT{ it->second, false };
621
    }
622
  }
623
624
625

  // Insert new entry
  return GetOrInsertT{
626
    this->Map_.emplace(fileName, std::make_shared<FileT>()).first->second, true
627
  };
628
629
}

630
631
cmQtAutoMocUicT::ParseCacheT::ParseCacheT() = default;
cmQtAutoMocUicT::ParseCacheT::~ParseCacheT() = default;
632

633
bool cmQtAutoMocUicT::ParseCacheT::ReadFromFile(std::string const& fileName)
634
{
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
  cmsys::ifstream fin(fileName.c_str());
  if (!fin) {
    return false;
  }
  FileHandleT fileHandle;

  std::string line;
  while (std::getline(fin, line)) {
    // Check if this an empty or a comment line
    if (line.empty() || line.front() == '#') {
      continue;
    }
    // Drop carriage return character at the end
    if (line.back() == '\r') {
      line.pop_back();
      if (line.empty()) {
        continue;
652
653
      }
    }
654
655
    // Check if this a file name line
    if (line.front() != ' ') {
656
      fileHandle = this->GetOrInsert(line).first;
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
      continue;
    }

    // Bad line or bad file handle
    if (!fileHandle || (line.size() < 6)) {
      continue;
    }

    constexpr std::size_t offset = 5;
    if (cmHasLiteralPrefix(line, " mmc:")) {
      fileHandle->Moc.Macro = line.substr(offset);
      continue;
    }
    if (cmHasLiteralPrefix(line, " miu:")) {
      fileHandle->Moc.Include.Underscore.emplace_back(line.substr(offset),
                                                      MocUnderscoreLength);
      continue;
    }
    if (cmHasLiteralPrefix(line, " mid:")) {
      fileHandle->Moc.Include.Dot.emplace_back(line.substr(offset), 0);
      continue;
    }
    if (cmHasLiteralPrefix(line, " mdp:")) {
      fileHandle->Moc.Depends.emplace_back(line.substr(offset));
      continue;
    }
    if (cmHasLiteralPrefix(line, " uic:")) {
      fileHandle->Uic.Include.emplace_back(line.substr(offset),
                                           UiUnderscoreLength);
      continue;
    }
    if (cmHasLiteralPrefix(line, " udp:")) {
      fileHandle->Uic.Depends.emplace_back(line.substr(offset));
      continue;
    }
692
  }
693
694
695
  return true;
}

696
bool cmQtAutoMocUicT::ParseCacheT::WriteToFile(std::string const& fileName)
697
698
699
700
701
{
  cmGeneratedFileStream ofs(fileName);
  if (!ofs) {
    return false;
  }
702
  ofs << "# Generated by CMake. Changes will be overwritten.\n";
703
  for (auto const& pair : this->Map_) {
704
    ofs << pair.first << '\n';
705
706
    FileT const& file = *pair.second;
    if (!file.Moc.Macro.empty()) {
707
      ofs << " mmc:" << file.Moc.Macro << '\n';
708
709
    }
    for (IncludeKeyT const& item : file.Moc.Include.Underscore) {
710
      ofs << " miu:" << item.Key << '\n';
711
712
    }
    for (IncludeKeyT const& item : file.Moc.Include.Dot) {
713
      ofs << " mid:" << item.Key << '\n';
714
715
    }
    for (std::string const& item : file.Moc.Depends) {
716
      ofs << " mdp:" << item << '\n';
717
718
    }
    for (IncludeKeyT const& item : file.Uic.Include) {
719
      ofs << " uic:" << item.Key << '\n';
720
721
    }
    for (std::string const& item : file.Uic.Depends) {
722
      ofs << " udp:" << item << '\n';
723
724
725
726
727
    }
  }
  return ofs.Close();
}

728
729
cmQtAutoMocUicT::BaseSettingsT::BaseSettingsT() = default;
cmQtAutoMocUicT::BaseSettingsT::~BaseSettingsT() = default;
730

731
cmQtAutoMocUicT::MocSettingsT::MocSettingsT()
732
{
733
  this->RegExpInclude.compile(
734
735
736
737
    "(^|\n)[ \t]*#[ \t]*include[ \t]+"
    "[\"<](([^ \">]+/)?moc_[^ \">/]+\\.cpp|[^ \">]+\\.moc)[\">]");
}

738
cmQtAutoMocUicT::MocSettingsT::~MocSettingsT() = default;
739

740
bool cmQtAutoMocUicT::MocSettingsT::skipped(std::string const& fileName) const
741
{
742
743
  return (!this->Enabled ||
          (this->SkipList.find(fileName) != this->SkipList.end()));
744
}
745

746
std::string cmQtAutoMocUicT::MocSettingsT::MacrosString() const
747
{
748
  std::string res;
749
750
  const auto itB = this->MacroFilters.cbegin();
  const auto itE = this->MacroFilters.cend();
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
  const auto itL = itE - 1;
  auto itC = itB;
  for (; itC != itE; ++itC) {
    // Separator
    if (itC != itB) {
      if (itC != itL) {
        res += ", ";
      } else {
        res += " or ";
      }
    }
    // Key
    res += itC->Key;
  }
  return res;
766
767
}

768
769
770
771
772
cmQtAutoMocUicT::UicSettingsT::UicSettingsT()
{
  this->RegExpInclude.compile("(^|\n)[ \t]*#[ \t]*include[ \t]+"
                              "[\"<](([^ \">]+/)?ui_[^ \">/]+\\.h)[\">]");
}
773

774
cmQtAutoMocUicT::UicSettingsT::~UicSettingsT() = default;
775

776
bool cmQtAutoMocUicT::UicSettingsT::skipped(std::string const& fileName) const
777
{
778
779
  return (!this->Enabled ||
          (this->SkipList.find(fileName) != this->SkipList.end()));
780
781
}

782
783
void cmQtAutoMocUicT::JobT::LogError(GenT genType,
                                     cm::string_view message) const
784
{
785
786
  this->Gen()->AbortError();
  this->Gen()->Log().Error(genType, message);
787
788
}

789
void cmQtAutoMocUicT::JobT::LogCommandError(
790
  GenT genType, cm::string_view message,
791
792
  std::vector<std::string> const& command, std::string const& output) const
{
793
794
  this->Gen()->AbortError();
  this->Gen()->Log().ErrorCommand(genType, message, command, output);
795
796
}

797
798
799
800
bool cmQtAutoMocUicT::JobT::RunProcess(GenT genType,
                                       cmWorkerPool::ProcessResultT& result,
                                       std::vector<std::string> const& command,
                                       std::string* infoMessage)
801
802
{
  // Log command
803
  if (this->Log().Verbose()) {
804
805
806
    cm::string_view info;
    if (infoMessage != nullptr) {
      info = *infoMessage;
807
    }
808
809
810
811
    this->Log().Info(
      genType,
      cmStrCat(info, info.empty() || cmHasSuffix(info, '\n') ? "" : "\n",
               QuotedCommand(command), '\n'));
812
  }
813
  // Run command
814
815
  return this->cmWorkerPool::JobT::RunProcess(
    result, command, this->BaseConst().AutogenBuildDir);
816
817
}

818
void cmQtAutoMocUicT::JobMocPredefsT::Process()
819
820
{
  // (Re)generate moc_predefs.h on demand
821
  std::unique_ptr<std::string> reason;
822
  if (this->Log().Verbose()) {
823
824
    reason = cm::make_unique<std::string>();
  }
825
  if (!this->Update(reason.get())) {
826
    return;
827
  }
828
  std::string const& predefsFileAbs = this->MocConst().PredefsFileAbs;
829
  {
830
831
832
    cmWorkerPool::ProcessResultT result;
    {
      // Compose command
833
      std::vector<std::string> cmd = this->MocConst().PredefsCmd;
834
      // Add definitions
835
      cm::append(cmd, this->MocConst().OptionsDefinitions);
836
      // Add includes
837
      cm::append(cmd, this->MocConst().OptionsIncludes);
838
      // Execute command
839
840
841
842
843
844
      if (!this->RunProcess(GenT::MOC, result, cmd, reason.get())) {
        this->LogCommandError(GenT::MOC,
                              cmStrCat("The content generation command for ",
                                       this->MessagePath(predefsFileAbs),
                                       " failed.\n", result.ErrorMessage),
                              cmd, result.StdOut);
845
        return;
846
847
848
849
      }
    }

    // (Re)write predefs file only on demand
850
851
    if (cmQtAutoGenerator::FileDiffers(predefsFileAbs, result.StdOut)) {
      if (!cmQtAutoGenerator::FileWrite(predefsFileAbs, result.StdOut)) {
852
        this->LogError(
853
          GenT::MOC,
854
          cmStrCat("Writing ", this->MessagePath(predefsFileAbs), " failed."));
855
856
857
858
        return;
      }
    } else {
      // Touch to update the time stamp
859
860
861
      if (this->Log().Verbose()) {
        this->Log().Info(GenT::MOC,
                         "Touching " + this->MessagePath(predefsFileAbs));
862
863
      }
      if (!cmSystemTools::Touch(predefsFileAbs, false)) {
864
865
866
        this->LogError(GenT::MOC,
                       cmStrCat("Touching ", this->MessagePath(predefsFileAbs),
                                " failed."));
867
        return;
868
869
870
      }
    }
  }
871
872

  // Read file time afterwards
873
874
875
876
  if (!this->MocEval().PredefsTime.Load(predefsFileAbs)) {
    this->LogError(GenT::MOC,
                   cmStrCat("Reading the file time of ",
                            this->MessagePath(predefsFileAbs), " failed."));
877
878
    return;
  }
879
880
}

881
bool cmQtAutoMocUicT::JobMocPredefsT::Update(std::string* reason) const
882
{
883
  // Test if the file exists
884
  if (!this->MocEval().PredefsTime.Load(this->MocConst().PredefsFileAbs)) {
885
    if (reason != nullptr) {
886
887
      *reason = cmStrCat("Generating ",
                         this->MessagePath(this->MocConst().PredefsFileAbs),
888
                         ", because it doesn't exist.");
889
890
891
892
893
    }
    return true;
  }

  // Test if the settings changed
894
  if (this->MocConst().SettingsChanged) {
895
    if (reason != nullptr) {
896
897
      *reason = cmStrCat("Generating ",
                         this->MessagePath(this->MocConst().PredefsFileAbs),
898
                         ", because the moc settings changed.");
899
    }
900
    return true;
901
902
  }

903
904
  // Test if the executable is newer
  {
905
    std::string const& exec = this->MocConst().PredefsCmd.at(0);
906
907
    cmFileTime execTime;
    if (execTime.Load(exec)) {
908
      if (this->MocEval().PredefsTime.Older(execTime)) {
909
        if (reason != nullptr) {
910
911
912
          *reason = cmStrCat(
            "Generating ", this->MessagePath(this->MocConst().PredefsFileAbs),
            " because it is older than ", this->MessagePath(exec), '.');
913
        }
914
        return true;
915
      }
916
    }
917
  }
918
919

  return false;
920
921
}

922
bool cmQtAutoMocUicT::JobParseT::ReadFile()
923
{
924
  // Clear old parse information
925
926
  this->FileHandle->ParseData->Clear();
  std::string const& fileName = this->FileHandle->FileName;
927
  // Write info
928
929
930
  if (this->Log().Verbose()) {
    this->Log().Info(GenT::GEN,
                     cmStrCat("Parsing ", this->MessagePath(fileName)));
931
932
  }
  // Read file content
933
  {
934
    std::string error;
935
936
937
938
    if (!cmQtAutoGenerator::FileRead(this->Content, fileName, &error)) {
      this->LogError(GenT::GEN,
                     cmStrCat("Could not read ", this->MessagePath(fileName),
                              ".\n", error));
939
940
941
942
      return false;
    }
  }
  // Warn if empty
943
944
945
  if (this->Content.empty()) {
    this->Log().Warning(GenT::GEN,
                        cmStrCat(this->MessagePath(fileName), " is empty."));
946
947
948
949
950
    return false;
  }
  return true;
}

951
952
953
void cmQtAutoMocUicT::JobParseT::CreateKeys(
  std::vector<IncludeKeyT>& container, std::set<std::string> const& source,
  std::size_t basePrefixLength)
954
955
956
957
958
959
960
961
962
963
{
  if (source.empty()) {
    return;
  }
  container.reserve(source.size());
  for (std::string const& src : source) {
    container.emplace_back(src, basePrefixLength);
  }
}

964
void cmQtAutoMocUicT::JobParseT::MocMacro()
965
{
966
  for (KeyExpT const& filter : this->MocConst().MacroFilters) {
967
    // Run a simple find string check
968
    if (this->Content.find(filter.Key) == std::string::npos) {
969
970
971
972
      continue;
    }
    // Run the expensive regular expression check loop
    cmsys::RegularExpressionMatch match;
973
    if (filter.Exp.find(this->Content.c_str(), match)) {
974
      // Keep detected macro name
975
      this->FileHandle->ParseData->Moc.Macro = filter.Key;
976
977
978
979
980
      return;
    }
  }
}

981
void cmQtAutoMocUicT::JobParseT::MocDependecies()
982
{
983
984
  if (this->MocConst().DependFilters.empty() ||
      this->MocConst().CanOutputDependencies) {
985
986
987
988
989
    return;
  }

  // Find dependency strings
  std::set<std::string> parseDepends;
990
  for (KeyExpT const& filter : this->MocConst().DependFilters) {
991
    // Run a simple find string check
992
    if (this->Content.find(filter.Key) == std::string::npos) {
993
994
995
      continue;
    }
    // Run the expensive regular expression check loop
996
    const char* contentChars = this->Content.c_str();
997
998
999
1000
    cmsys::RegularExpressionMatch match;
    while (filter.Exp.find(contentChars, match)) {
      {
        std::string dep = match.match(1);
For faster browsing, not all history is shown. View entire blame