1 //===- Diagnostics.cpp - C Interface for MLIR Diagnostics -----------------===// 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 "mlir-c/Diagnostics.h" 10 #include "mlir/CAPI/Diagnostics.h" 11 #include "mlir/CAPI/IR.h" 12 #include "mlir/CAPI/Support.h" 13 #include "mlir/CAPI/Utils.h" 14 #include "mlir/IR/Diagnostics.h" 15 16 using namespace mlir; 17 18 void mlirDiagnosticPrint(MlirDiagnostic diagnostic, MlirStringCallback callback, 19 void *userData) { 20 detail::CallbackOstream stream(callback, userData); 21 unwrap(diagnostic).print(stream); 22 } 23 24 MlirLocation mlirDiagnosticGetLocation(MlirDiagnostic diagnostic) { 25 return wrap(unwrap(diagnostic).getLocation()); 26 } 27 28 MlirDiagnosticSeverity mlirDiagnosticGetSeverity(MlirDiagnostic diagnostic) { 29 switch (unwrap(diagnostic).getSeverity()) { 30 case mlir::DiagnosticSeverity::Error: 31 return MlirDiagnosticError; 32 case mlir::DiagnosticSeverity::Warning: 33 return MlirDiagnosticWarning; 34 case mlir::DiagnosticSeverity::Note: 35 return MlirDiagnosticNote; 36 case mlir::DiagnosticSeverity::Remark: 37 return MlirDiagnosticRemark; 38 } 39 llvm_unreachable("unhandled diagnostic severity"); 40 } 41 42 // Notes are stored in a vector, so note iterator range is a pair of 43 // random access iterators, for which it is cheap to compute the size. 44 intptr_t mlirDiagnosticGetNumNotes(MlirDiagnostic diagnostic) { 45 return static_cast<intptr_t>(llvm::size(unwrap(diagnostic).getNotes())); 46 } 47 48 // Notes are stored in a vector, so the iterator is a random access iterator, 49 // cheap to advance multiple steps at a time. 50 MlirDiagnostic mlirDiagnosticGetNote(MlirDiagnostic diagnostic, intptr_t pos) { 51 return wrap(*std::next(unwrap(diagnostic).getNotes().begin(), pos)); 52 } 53 54 MlirDiagnosticHandlerID 55 mlirContextAttachDiagnosticHandler(MlirContext context, 56 MlirDiagnosticHandler handler) { 57 assert(handler && "unexpected null diagnostic handler"); 58 DiagnosticEngine::HandlerID id = 59 unwrap(context)->getDiagEngine().registerHandler( 60 [handler](Diagnostic &diagnostic) { 61 return unwrap(handler(wrap(diagnostic))); 62 }); 63 return static_cast<MlirDiagnosticHandlerID>(id); 64 } 65 66 void mlirContextDetachDiagnosticHandler(MlirContext context, 67 MlirDiagnosticHandlerID id) { 68 unwrap(context)->getDiagEngine().eraseHandler( 69 static_cast<DiagnosticEngine::HandlerID>(id)); 70 } 71 72 void mlirEmitError(MlirLocation location, const char *message) { 73 emitError(unwrap(location)) << message; 74 } 75