| 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 | |
| 9 | #include "ErrorCollector.h" |
| 10 | #include "llvm/Support/Errc.h" |
| 11 | #include "llvm/Support/Error.h" |
| 12 | #include "llvm/Support/WithColor.h" |
| 13 | #include "llvm/Support/raw_ostream.h" |
| 14 | |
| 15 | using namespace llvm; |
| 16 | using namespace llvm::ifs; |
| 17 | |
| 18 | void ErrorCollector::escalateToFatal() { ErrorsAreFatal = true; } |
| 19 | |
| 20 | void ErrorCollector::addError(Error &&Err, StringRef Tag) { |
| 21 | if (Err) { |
| 22 | Errors.push_back(x: std::move(Err)); |
| 23 | Tags.push_back(x: Tag.str()); |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | Error ErrorCollector::makeError() { |
| 28 | // TODO: Make this return something (an AggregateError?) that gives more |
| 29 | // individual control over each error and which might be of interest. |
| 30 | Error JoinedErrors = Error::success(); |
| 31 | for (Error &E : Errors) { |
| 32 | JoinedErrors = joinErrors(E1: std::move(JoinedErrors), E2: std::move(E)); |
| 33 | } |
| 34 | Errors.clear(); |
| 35 | Tags.clear(); |
| 36 | return JoinedErrors; |
| 37 | } |
| 38 | |
| 39 | void ErrorCollector::log(raw_ostream &OS) { |
| 40 | OS << "Encountered multiple errors:\n"; |
| 41 | for (size_t i = 0; i < Errors.size(); ++i) { |
| 42 | WithColor::error(OS) << "("<< Tags[i] << ") "<< Errors[i]; |
| 43 | if (i != Errors.size() - 1) |
| 44 | OS << "\n"; |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | bool ErrorCollector::allErrorsHandled() const { return Errors.empty(); } |
| 49 | |
| 50 | ErrorCollector::~ErrorCollector() { |
| 51 | if (ErrorsAreFatal && !allErrorsHandled()) |
| 52 | fatalUnhandledError(); |
| 53 | |
| 54 | for (Error &E : Errors) { |
| 55 | consumeError(Err: std::move(E)); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | [[noreturn]] void ErrorCollector::fatalUnhandledError() { |
| 60 | errs() << "Program aborted due to unhandled Error(s):\n"; |
| 61 | log(OS&: errs()); |
| 62 | errs() << "\n"; |
| 63 | abort(); |
| 64 | } |
| 65 |