ErrorCollector.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. //===- ErrorCollector.cpp -------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===-----------------------------------------------------------------------===/
  8. #include "ErrorCollector.h"
  9. #include "llvm/Support/Errc.h"
  10. #include "llvm/Support/Error.h"
  11. #include "llvm/Support/WithColor.h"
  12. #include "llvm/Support/raw_ostream.h"
  13. #include <vector>
  14. using namespace llvm;
  15. using namespace llvm::ifs;
  16. void ErrorCollector::escalateToFatal() { ErrorsAreFatal = true; }
  17. void ErrorCollector::addError(Error &&Err, StringRef Tag) {
  18. if (Err) {
  19. Errors.push_back(std::move(Err));
  20. Tags.push_back(Tag.str());
  21. }
  22. }
  23. Error ErrorCollector::makeError() {
  24. // TODO: Make this return something (an AggregateError?) that gives more
  25. // individual control over each error and which might be of interest.
  26. Error JoinedErrors = Error::success();
  27. for (Error &E : Errors) {
  28. JoinedErrors = joinErrors(std::move(JoinedErrors), std::move(E));
  29. }
  30. Errors.clear();
  31. Tags.clear();
  32. return JoinedErrors;
  33. }
  34. void ErrorCollector::log(raw_ostream &OS) {
  35. OS << "Encountered multiple errors:\n";
  36. for (size_t i = 0; i < Errors.size(); ++i) {
  37. WithColor::error(OS) << "(" << Tags[i] << ") " << Errors[i];
  38. if (i != Errors.size() - 1)
  39. OS << "\n";
  40. }
  41. }
  42. bool ErrorCollector::allErrorsHandled() const { return Errors.empty(); }
  43. ErrorCollector::~ErrorCollector() {
  44. if (ErrorsAreFatal && !allErrorsHandled())
  45. fatalUnhandledError();
  46. for (Error &E : Errors) {
  47. consumeError(std::move(E));
  48. }
  49. }
  50. [[noreturn]] void ErrorCollector::fatalUnhandledError() {
  51. errs() << "Program aborted due to unhandled Error(s):\n";
  52. log(errs());
  53. errs() << "\n";
  54. abort();
  55. }