138032Speter//===--- DiagnosticError.h - Diagnostic payload for llvm::Error -*- C++ -*-===//
290795Sgshapiro//
364565Sgshapiro// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
438032Speter// See https://llvm.org/LICENSE.txt for license information.
538032Speter// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
638032Speter//
738032Speter//===----------------------------------------------------------------------===//
838032Speter
938032Speter#ifndef LLVM_CLANG_BASIC_DIAGNOSTIC_ERROR_H
1038032Speter#define LLVM_CLANG_BASIC_DIAGNOSTIC_ERROR_H
1138032Speter
1238032Speter#include "clang/Basic/PartialDiagnostic.h"
1338032Speter#include "llvm/Support/Error.h"
1490795Sgshapiro
1590795Sgshapironamespace clang {
1690795Sgshapiro
1790795Sgshapiro/// Carries a Clang diagnostic in an llvm::Error.
1864565Sgshapiro///
1964565Sgshapiro/// Users should emit the stored diagnostic using the DiagnosticsEngine.
2064565Sgshapiroclass DiagnosticError : public llvm::ErrorInfo<DiagnosticError> {
2190795Sgshapiropublic:
2238032Speter  DiagnosticError(PartialDiagnosticAt Diag) : Diag(std::move(Diag)) {}
2398125Sgshapiro
2464565Sgshapiro  void log(raw_ostream &OS) const override { OS << "clang diagnostic"; }
25111367Sgshapiro
2638032Speter  PartialDiagnosticAt &getDiagnostic() { return Diag; }
2738032Speter  const PartialDiagnosticAt &getDiagnostic() const { return Diag; }
2838032Speter
2964565Sgshapiro  /// Creates a new \c DiagnosticError that contains the given diagnostic at
3064565Sgshapiro  /// the given location.
3164565Sgshapiro  static llvm::Error create(SourceLocation Loc, PartialDiagnostic Diag) {
3264565Sgshapiro    return llvm::make_error<DiagnosticError>(
3364565Sgshapiro        PartialDiagnosticAt(Loc, std::move(Diag)));
3464565Sgshapiro  }
3564565Sgshapiro
3664565Sgshapiro  /// Extracts and returns the diagnostic payload from the given \c Error if
3764565Sgshapiro  /// the error is a \c DiagnosticError. Returns none if the given error is not
3864565Sgshapiro  /// a \c DiagnosticError.
3964565Sgshapiro  static Optional<PartialDiagnosticAt> take(llvm::Error &Err) {
4038032Speter    Optional<PartialDiagnosticAt> Result;
4138032Speter    Err = llvm::handleErrors(std::move(Err), [&](DiagnosticError &E) {
4238032Speter      Result = std::move(E.getDiagnostic());
4338032Speter    });
4438032Speter    return Result;
4538032Speter  }
4638032Speter
4738032Speter  static char ID;
4890795Sgshapiro
4942580Speterprivate:
5064565Sgshapiro  // Users are not expected to use error_code.
5138032Speter  std::error_code convertToErrorCode() const override {
5238032Speter    return llvm::inconvertibleErrorCode();
5390795Sgshapiro  }
5438032Speter
5564565Sgshapiro  PartialDiagnosticAt Diag;
5664565Sgshapiro};
5764565Sgshapiro
5864565Sgshapiro} // end namespace clang
5990795Sgshapiro
6090795Sgshapiro#endif // LLVM_CLANG_BASIC_DIAGNOSTIC_ERROR_H
6190795Sgshapiro