File: BuildSystemFrontend.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (824 lines) | stat: -rw-r--r-- 26,091 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
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
221
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
284
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
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
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
//===-- BuildSystemFrontend.cpp -------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "llbuild/BuildSystem/BuildSystemFrontend.h"

#include "llbuild/Basic/Defer.h"
#include "llbuild/Basic/ExecutionQueue.h"
#include "llbuild/Basic/FileSystem.h"
#include "llbuild/Basic/LLVM.h"
#include "llbuild/Basic/PlatformUtility.h"
#include "llbuild/BuildSystem/BuildDescription.h"
#include "llbuild/BuildSystem/BuildFile.h"
#include "llbuild/BuildSystem/BuildKey.h"
#include "llbuild/BuildSystem/BuildValue.h"
#include "llbuild/BuildSystem/Command.h"

#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"

#include <atomic>
#include <memory>
#include <mutex>
#include <thread>

using namespace llbuild;
using namespace llbuild::basic;
using namespace llbuild::buildsystem;

#pragma mark - BuildSystemInvocation implementation

void BuildSystemInvocation::getUsage(int optionWidth, raw_ostream& os) {
  const struct Options {
    llvm::StringRef option, helpText;
  } options[] = {
    { "--help", "show this help message and exit" },
    { "--version", "show the tool version" },
    { "-C <PATH>, --chdir <PATH>", "change directory to PATH before building" },
    { "--no-db", "disable use of a build database" },
    { "--db <PATH>", "enable building against the database at PATH" },
    { "-f <PATH>", "load the build task file at PATH" },
    { "--serial", "do not build in parallel" },
    { "--scheduler <SCHEDULER>", "set scheduler algorithm" },
    { "-j,--jobs <JOBS>", "set how many concurrent jobs (lanes) to run" },
    { "-v, --verbose", "show verbose status information" },
    { "--trace <PATH>", "trace build engine operation to PATH" },
  };
  
  for (const auto& entry: options) {
    os << "  " << llvm::format("%-*s", optionWidth, entry.option.str().c_str()) << " "
       << entry.helpText << "\n";
  }
}

void BuildSystemInvocation::parse(llvm::ArrayRef<std::string> args,
                                  llvm::SourceMgr& sourceMgr) {
  auto error = [&](const Twine &message) {
    sourceMgr.PrintMessage(llvm::SMLoc{}, llvm::SourceMgr::DK_Error, message);
    hadErrors = true;
  };

  while (!args.empty()) {
    const auto& option = args.front();
    args = args.slice(1);

    if (option == "-") {
      for (const auto& arg: args) {
        positionalArgs.push_back(arg);
      }
      break;
    }

    if (!option.empty() && option[0] != '-') {
      positionalArgs.push_back(option);
      continue;
    }
    
    if (option == "--help") {
      showUsage = true;
      break;
    } else if (option == "--version") {
      showVersion = true;
      break;
    } else if (option == "--no-db") {
      dbPath = "";
    } else if (option == "--db") {
      if (args.empty()) {
        error("missing argument to '" + option + "'");
        break;
      }
      dbPath = args[0];
      args = args.slice(1);
    } else if (option == "-C" || option == "--chdir") {
      if (args.empty()) {
        error("missing argument to '" + option + "'");
        break;
      }
      chdirPath = args[0];
      args = args.slice(1);
    } else if (option == "-f") {
      if (args.empty()) {
        error("missing argument to '" + option + "'");
        break;
      }
      buildFilePath = args[0];
      args = args.slice(1);
    } else if (option == "--serial") {
      useSerialBuild = true;
    } else if (option == "--scheduler") {
      if (args.empty()) {
        error("missing argument to '" + option + "'");
        break;
      }
      auto algorithm = args[0];
      if (algorithm == "commandNamePriority" || algorithm == "default") {
        schedulerAlgorithm = SchedulerAlgorithm::NamePriority;
      } else if (algorithm == "fifo") {
        schedulerAlgorithm = SchedulerAlgorithm::FIFO;
      } else {
        error("unknown scheduler algorithm '" + algorithm + "'");
        break;
      }
      args = args.slice(1);
    } else if (option == "-j" || option == "--jobs") {
      if (args.empty()) {
        error("missing argument to '" + option + "'");
        break;
      }
      char *end;
      schedulerLanes = ::strtol(args[0].c_str(), &end, 10);
      if (*end != '\0') {
        error("invalid argument '" + args[0] + "' to '" + option + "'");
      }
      args = args.slice(1);
    } else if (StringRef(option).startswith("-j")) {
      char *end;
      schedulerLanes = ::strtol(&option[2], &end, 10);
      if (*end != '\0') {
        error("invalid argument to '-j'");
      }
    } else if (option == "-v" || option == "--verbose") {
      showVerboseStatus = true;
    } else if (option == "--trace") {
      if (args.empty()) {
        error("missing argument to '" + option + "'");
        break;
      }
      traceFilePath = args[0];
      args = args.slice(1);
    } else {
      error("invalid option '" + option + "'");
      break;
    }
  }
}

std::string BuildSystemInvocation::formatDetectedCycle(const std::vector<core::Rule*>& cycle) {
  // Compute a description of the cycle path.
  SmallString<256> message;
  llvm::raw_svector_ostream os(message);
  os << "cycle detected while building: ";
  bool first = true;
  for (const auto* rule: cycle) {
    if (!first)
      os << " -> ";

    // Convert to a build key.
    auto key = BuildKey::fromData(rule->key);
    switch (key.getKind()) {
      case BuildKey::Kind::Unknown:
        os << "((unknown))";
        break;
      case BuildKey::Kind::Command:
        os << "command '" << key.getCommandName() << "'";
        break;
      case BuildKey::Kind::CustomTask:
        os << "custom task '" << key.getCustomTaskName() << "'";
        break;
      case BuildKey::Kind::DirectoryContents:
        os << "directory-contents '" << key.getDirectoryPath() << "'";
        break;
      case BuildKey::Kind::FilteredDirectoryContents:
        os << "filtered-directory-contents '"
        << key.getFilteredDirectoryPath() << "'";
        break;
      case BuildKey::Kind::DirectoryTreeSignature:
        os << "directory-tree-signature '"
        << key.getDirectoryTreeSignaturePath() << "'";
        break;
      case BuildKey::Kind::DirectoryTreeStructureSignature:
        os << "directory-tree-structure-signature '"
        << key.getFilteredDirectoryPath() << "'";
        break;
      case BuildKey::Kind::Node:
        os << "node '" << key.getNodeName() << "'";
        break;
      case BuildKey::Kind::Stat:
        os << "stat '" << key.getStatName() << "'";
        break;
      case BuildKey::Kind::Target:
        os << "target '" << key.getTargetName() << "'";
        break;
    }
    first = false;
  }

  return os.str().str();
}

#pragma mark - BuildSystemFrontendDelegate implementation

namespace {

struct BuildSystemFrontendImpl;
struct BuildSystemFrontendDelegateImpl;

class BuildSystemFrontendExecutionQueueDelegate
      : public ExecutionQueueDelegate {
  BuildSystemFrontendDelegateImpl& delegateImpl;
  
  bool showVerboseOutput() const;

  BuildSystem& getSystem() const;
    
public:
  BuildSystemFrontendExecutionQueueDelegate(
      BuildSystemFrontendDelegateImpl& delegateImpl)
      : delegateImpl(delegateImpl) { }
  
  virtual void queueJobStarted(JobDescriptor* command) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandJobStarted(reinterpret_cast<Command*>(command));
  }

  virtual void queueJobFinished(JobDescriptor* command) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandJobFinished(reinterpret_cast<Command*>(command));
  }

  virtual void processStarted(ProcessContext* command,
                              ProcessHandle handle,
                              llbuild_pid_t pid) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandProcessStarted(
          reinterpret_cast<Command*>(command),
          BuildSystemFrontendDelegate::ProcessHandle { handle.id });
  }
  
  virtual void processHadError(ProcessContext* command, ProcessHandle handle,
                               const Twine& message) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandProcessHadError(
          reinterpret_cast<Command*>(command),
          BuildSystemFrontendDelegate::ProcessHandle { handle.id },
          message);
  }
  
  virtual void processHadOutput(ProcessContext* command, ProcessHandle handle,
                                StringRef data) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandProcessHadOutput(
          reinterpret_cast<Command*>(command),
          BuildSystemFrontendDelegate::ProcessHandle { handle.id },
          data);
  }

  virtual void processFinished(ProcessContext* command, ProcessHandle handle,
                               const ProcessResult& result) override {
    static_cast<BuildSystemFrontendDelegate*>(&getSystem().getDelegate())->
      commandProcessFinished(
          reinterpret_cast<Command*>(command),
          BuildSystemFrontendDelegate::ProcessHandle { handle.id },
          result);
  }
};

struct BuildSystemFrontendDelegateImpl {
  llvm::SourceMgr& sourceMgr;

  StringRef bufferBeingParsed;
  std::atomic<unsigned> numErrors{0};
  std::atomic<unsigned> numFailedCommands{0};

  BuildSystemFrontendExecutionQueueDelegate executionQueueDelegate;

  BuildSystemFrontendImpl* frontend = nullptr;

  /// The set of active command output buffers, by process handle.
  llvm::DenseMap<uintptr_t, std::vector<uint8_t>> processOutputBuffers;

  /// The lock protecting `processOutputBuffers`.
  std::mutex processOutputBuffersMutex;


public:
  BuildSystemFrontendDelegateImpl(llvm::SourceMgr& sourceMgr)
      : sourceMgr(sourceMgr), executionQueueDelegate(*this) {}
};



#pragma mark - BuildSystemFrontendImpl

struct BuildSystemFrontendImpl {
  BuildSystemFrontendDelegate& delegate;
  BuildSystemFrontendDelegateImpl* delegateImpl;
  const BuildSystemInvocation& invocation;

  std::unique_ptr<basic::FileSystem> fileSystem;
  std::unique_ptr<BuildSystem> system;


public:
  BuildSystemFrontendImpl(BuildSystemFrontendDelegate& delegate,
                          BuildSystemFrontendDelegateImpl* delegateImpl,
                          const BuildSystemInvocation& invocation,
                          std::unique_ptr<basic::FileSystem> fileSystem)
      : delegate(delegate), delegateImpl(delegateImpl), invocation(invocation), fileSystem(std::move(fileSystem)) {
        assert(this->fileSystem);
      }


private:
  /// The status of the delegate.
  std::mutex stateMutex;
  bool cancelled{false};

public:
  void cancel() {
    std::lock_guard<std::mutex> lock(stateMutex);

    // Update the status to cancelled.
    cancelled = true;

    if (system) {
      system->cancel();
    }
  }

  void resetAfterBuild() {
    std::lock_guard<std::mutex> lock(stateMutex);
    cancelled = false;
  }

  bool initialize() {
    std::lock_guard<std::mutex> lock(stateMutex);

    delegateImpl->numFailedCommands = 0;
    delegateImpl->numErrors = 0;

    if (cancelled)
      return false;

    if (system) {
      // Already exists, just reset state
      system->resetForBuild();
      return true;
    }

    if (!invocation.chdirPath.empty()) {
      if (!sys::chdir(invocation.chdirPath.c_str())) {
        delegate.error(Twine("unable to honor --chdir: ") + strerror(errno));
        return false;
      }
    }

    if (!fileSystem) {
      // Catch and report client misuse of a failed build system object
      delegate.error(Twine("invalid reuse after initialization failure"));
      return false;
    }

    // Create the build system.
    system = std::make_unique<BuildSystem>(delegate, std::move(fileSystem));

    // Load the build file.
    if (!system->loadDescription(invocation.buildFilePath)) {
      system = nullptr;
      return false;
    }

    // Enable tracing, if requested.
    if (!invocation.traceFilePath.empty()) {
      const auto dir = llvm::sys::path::parent_path(invocation.traceFilePath);
      if (!system->getFileSystem().createDirectories(dir) &&
          !system->getFileSystem().getFileInfo(dir).isDirectory()) {
        delegate.error(Twine("unable to create tracing directory: " + dir));
        system = nullptr;
        return false;
      }

      std::string error;
      if (!system->enableTracing(invocation.traceFilePath, &error)) {
        delegate.error(Twine("unable to enable tracing: ") + error);
        system = nullptr;
        return false;
      }
    }

    // Attach the database.
    if (!invocation.dbPath.empty()) {
      // If the database path is relative, always make it relative to the input
      // file.
      SmallString<256> tmp;
      StringRef dbPath = invocation.dbPath;
      if (llvm::sys::path::is_relative(invocation.dbPath) &&
          dbPath.find("://") == StringRef::npos && !dbPath.startswith(":")) {
        llvm::sys::path::append(
            tmp, llvm::sys::path::parent_path(invocation.buildFilePath),
            invocation.dbPath);
        dbPath = tmp.str();
      }

      std::string error;
      if (!system->attachDB(dbPath, &error)) {
        delegate.error(Twine("unable to attach DB: ") + error);
        system = nullptr;
        return false;
      }
    }

    return true;
  }


  bool buildNode(StringRef nodeToBuild) {
    llbuild_defer {
      resetAfterBuild();
    };

    if (!initialize()) {
      return false;
    }

    auto buildValue = system->build(BuildKey::makeNode(nodeToBuild));
    if (!buildValue.hasValue()) {
      return false;
    }

    if (!buildValue.getValue().isExistingInput()) {
      if (buildValue.getValue().isMissingInput()) {
        delegate.error((Twine("missing input '") + nodeToBuild + "' and no rule to build it"));
      }
      return false;
    }

    return delegate.getNumFailedCommands() == 0 && delegate.getNumErrors() == 0;
  }

  bool build(StringRef targetToBuild) {
    llbuild_defer {
      resetAfterBuild();
    };

    if (!initialize()) {
      return false;
    }

    // Build the target; if something unspecified failed about the build, return
    // an error.
    if (!system->build(targetToBuild))
      return false;


    // The build was successful if there were no failed commands or unspecified
    // errors, including cancellation. We explicitly include cancellation because
    // it is possible for a build to complete with no failed commands or errors,
    // yet not have done any actual work (i.e. if we are cancelled immediately).
    //
    // It is the job of the client to report a summary, if desired.
    std::lock_guard<std::mutex> lock(stateMutex);
    return !cancelled && delegate.getNumFailedCommands() == 0
        && delegate.getNumErrors() == 0;
  }
};


bool BuildSystemFrontendExecutionQueueDelegate::showVerboseOutput() const {
  return delegateImpl.frontend->invocation.showVerboseStatus;
}

BuildSystem& BuildSystemFrontendExecutionQueueDelegate::getSystem() const {
  assert(delegateImpl.frontend->system);
  return *delegateImpl.frontend->system;
}

}

BuildSystemFrontendDelegate::
BuildSystemFrontendDelegate(llvm::SourceMgr& sourceMgr,
                            StringRef name,
                            uint32_t version)
    : BuildSystemDelegate(name, version),
      impl(new BuildSystemFrontendDelegateImpl(sourceMgr))
{
  
}

BuildSystemFrontendDelegate::~BuildSystemFrontendDelegate() {
  delete static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);
}

void
BuildSystemFrontendDelegate::setFileContentsBeingParsed(StringRef buffer) {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  impl->bufferBeingParsed = buffer;
}

llvm::SourceMgr& BuildSystemFrontendDelegate::getSourceMgr() {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);
  
  return impl->sourceMgr;
}

unsigned BuildSystemFrontendDelegate::getNumErrors() {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);
  
  return impl->numErrors;
}

unsigned BuildSystemFrontendDelegate::getNumFailedCommands() {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  return impl->numFailedCommands;
}

void
BuildSystemFrontendDelegate::error(const Twine& message) {
  error("", {}, message.str());
}

void
BuildSystemFrontendDelegate::error(StringRef filename,
                                   const Token& at,
                                   const Twine& message) {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);
  
  ++impl->numErrors;

  // If we have a file and token, resolve the location and range to one
  // accessible by the source manager.
  //
  // FIXME: We shouldn't need to do this, but should switch llbuild to using
  // SourceMgr natively.
  llvm::SMLoc loc{};
  llvm::SMRange range{};
  if (!filename.empty() && at.start) {
    // FIXME: We ignore errors here, for now, this will be resolved when we move
    // to SourceMgr completely.
    auto buffer = impl->frontend->system->getFileSystem().getFileContents(filename);
    if (buffer) {
      unsigned offset = at.start - impl->bufferBeingParsed.data();
      if (offset + at.length < buffer->getBufferSize()) {
        range.Start = loc = llvm::SMLoc::getFromPointer(
            buffer->getBufferStart() + offset);
        range.End = llvm::SMLoc::getFromPointer(
            buffer->getBufferStart() + (offset + at.length));
        getSourceMgr().AddNewSourceBuffer(std::move(buffer), llvm::SMLoc{});
      }
    }
  }

  if (range.Start.isValid()) {
    getSourceMgr().PrintMessage(loc, llvm::SourceMgr::DK_Error, message, range);
  } else {
    getSourceMgr().PrintMessage(loc, llvm::SourceMgr::DK_Error, message);
  }
  fflush(stderr);
}

std::unique_ptr<ExecutionQueue>
BuildSystemFrontendDelegate::createExecutionQueue() {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);
  auto invocation = impl->frontend->invocation;
  QualityOfService qos = invocation.qos.hasValue() ?
      invocation.qos.getValue() : getDefaultQualityOfService();
  
  if (invocation.useSerialBuild) {
    return std::unique_ptr<ExecutionQueue>(
        createLaneBasedExecutionQueue(impl->executionQueueDelegate, 1,
                                      invocation.schedulerAlgorithm, qos,
                                      invocation.environment));
  }
    
  // Get the number of CPUs to use.
  unsigned numLanes = invocation.schedulerLanes;
  if (numLanes == 0) {
    unsigned numCPUs = std::thread::hardware_concurrency();
    if (numCPUs == 0) {
      error("<unknown>", {}, "unable to detect number of CPUs");
      numLanes = 1;
    } else {
      numLanes = numCPUs;
    }
  }
    
  return std::unique_ptr<ExecutionQueue>(
      createLaneBasedExecutionQueue(impl->executionQueueDelegate, numLanes,
                                    invocation.schedulerAlgorithm, qos,
                                    invocation.environment));
}

void BuildSystemFrontendDelegate::cancel() {
  auto delegateImpl = static_cast<BuildSystemFrontendDelegateImpl*>(impl);
  delegateImpl->frontend->cancel();
}

void BuildSystemFrontendDelegate::hadCommandFailure() {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);
  
  // Increment the failed command count.
  ++impl->numFailedCommands;
}

void BuildSystemFrontendDelegate::commandStatusChanged(Command*,
                                                       CommandStatusKind) {
}

void BuildSystemFrontendDelegate::commandPreparing(Command*) {
}

bool BuildSystemFrontendDelegate::shouldCommandStart(Command*) {
  return true;
}

void BuildSystemFrontendDelegate::commandStarted(Command* command) {
  // Don't report status if opted out by the command.
  if (!command->shouldShowStatus()) {
    return;
  }

  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);

  // Log the command.
  //
  // FIXME: Design the logging and status output APIs.
  SmallString<64> description;
  if (impl->frontend->invocation.showVerboseStatus) {
    command->getVerboseDescription(description);
  } else {
    command->getShortDescription(description);

    // If the short description is empty, always show the verbose one.
    if (description.empty()) {
      command->getVerboseDescription(description);
    }
  }
  fprintf(stdout, "%s\n", description.c_str());
  fflush(stdout);
}

void BuildSystemFrontendDelegate::commandHadError(Command* command, StringRef data) {
  fwrite(data.data(), data.size(), 1, stderr);
  fflush(stderr);
}

void BuildSystemFrontendDelegate::commandHadNote(Command* command, StringRef data) {
  fwrite(data.data(), data.size(), 1, stdout);
  fflush(stdout);
}

void BuildSystemFrontendDelegate::commandHadWarning(Command* command, StringRef data) {
  fwrite(data.data(), data.size(), 1, stdout);
  fflush(stdout);
}

void BuildSystemFrontendDelegate::commandFinished(Command*, ProcessStatus) {
}

void BuildSystemFrontendDelegate::commandFoundDiscoveredDependency(Command*, StringRef, DiscoveredDependencyKind) {
}

void BuildSystemFrontendDelegate::commandCannotBuildOutputDueToMissingInputs(
     Command * command, Node *output, SmallPtrSet<Node *, 1> inputs) {
  std::string message;
  llvm::raw_string_ostream messageStream(message);

  messageStream << "cannot build '";
  messageStream << output->getName().str();
  messageStream << "' due to missing inputs: ";

  for (Node* input : inputs) {
    if (input != *inputs.begin()) {
      messageStream << ", ";
    }
    messageStream << "'" << input->getName() << "'";
  }

  messageStream.flush();
  fwrite(message.data(), message.size(), 1, stderr);
  fflush(stderr);
}

Command* BuildSystemFrontendDelegate::chooseCommandFromMultipleProducers(
     Node *output, std::vector<Command*> commands) {
  return nullptr;
}

void BuildSystemFrontendDelegate::cannotBuildNodeDueToMultipleProducers(
     Node *output, std::vector<Command*> commands) {
  std::string message;
  llvm::raw_string_ostream messageStream(message);

  messageStream << "unable to build node: '";
  messageStream << output->getName();
  messageStream << "' (node is produced by multiple commands: '";

  for (Command* cmd : commands) {
    if (cmd != *commands.begin()) {
      messageStream << ", ";
    }
    messageStream << "'" << cmd->getName() << "'";
  }

  messageStream.flush();
  fwrite(message.data(), message.size(), 1, stderr);
  fflush(stderr);
}

void BuildSystemFrontendDelegate::commandJobStarted(Command*) {
}

void BuildSystemFrontendDelegate::commandJobFinished(Command*) {
}

void BuildSystemFrontendDelegate::commandProcessStarted(Command*,
                                                        ProcessHandle) {
}

void BuildSystemFrontendDelegate::determinedRuleNeedsToRun(core::Rule* ruleNeedingToRun, core::Rule::RunReason reason, core::Rule* inputRule) {}

bool BuildSystemFrontendDelegate::
shouldResolveCycle(const std::vector<core::Rule*>& items,
                   core::Rule* candidateRule,
                   core::Rule::CycleAction action) {
  return false;
}

void BuildSystemFrontendDelegate::
commandProcessHadError(Command* command, ProcessHandle handle,
                       const Twine& message) {
  SmallString<256> buffer;
  auto str = message.toStringRef(buffer);
  
  // FIXME: Design the logging and status output APIs.
  fwrite(str.data(), str.size(), 1, stderr);
  fputc('\n', stderr);
  fflush(stderr);
}
  
void BuildSystemFrontendDelegate::
commandProcessHadOutput(Command* command, ProcessHandle handle,
                        StringRef data) {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);
  std::unique_lock<std::mutex> lock(impl->processOutputBuffersMutex);

  // Append to the output buffer.
  auto& buffer = impl->processOutputBuffers[handle.id];
  buffer.insert(buffer.end(), data.begin(), data.end());
}

void BuildSystemFrontendDelegate::
commandProcessFinished(Command*, ProcessHandle handle,
                       const ProcessResult& result) {
  auto impl = static_cast<BuildSystemFrontendDelegateImpl*>(this->impl);
  std::unique_lock<std::mutex> lock(impl->processOutputBuffersMutex);

  // If there was an output buffer, flush it.
  auto it = impl->processOutputBuffers.find(handle.id);
  if (it == impl->processOutputBuffers.end())
    return;

  fwrite(it->second.data(), it->second.size(), 1, stdout);
  fflush(stdout);

  impl->processOutputBuffers.erase(it);  
}


#pragma mark - BuildSystemFrontend

BuildSystemFrontend::
BuildSystemFrontend(BuildSystemFrontendDelegate& delegate,
                    const BuildSystemInvocation& invocation,
                    std::unique_ptr<basic::FileSystem> fileSystem)
  : impl(new BuildSystemFrontendImpl(delegate,
                                     static_cast<BuildSystemFrontendDelegateImpl*>(delegate.impl),
                                     invocation,
                                     std::move(fileSystem)))
{
  auto implPtr = static_cast<BuildSystemFrontendImpl*>(impl);
  implPtr->delegateImpl->frontend = implPtr;
}

BuildSystemFrontend::~BuildSystemFrontend() {
  delete static_cast<BuildSystemFrontendImpl*>(impl);
  impl = nullptr;
}

bool BuildSystemFrontend::initialize() {
  return static_cast<BuildSystemFrontendImpl*>(impl)->initialize();
}

bool BuildSystemFrontend::build(StringRef targetToBuild) {
  return static_cast<BuildSystemFrontendImpl*>(impl)->build(targetToBuild);
}

bool BuildSystemFrontend::buildNode(StringRef nodeToBuild) {
  return static_cast<BuildSystemFrontendImpl*>(impl)->buildNode(nodeToBuild);
}