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