1 //===- Diagnostic.cpp - Dialect unit tests -------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "mlir/IR/Diagnostics.h"
10 #include "mlir/Support/TypeID.h"
11 #include "gtest/gtest.h"
14 using namespace mlir::detail
;
18 TEST(DiagnosticLifetime
, TestCopiesConstCharStar
) {
19 const auto *expectedMessage
= "Error 1, don't mutate this";
21 // Copy expected message into a mutable container, and call the constructor.
22 std::string
myStr(expectedMessage
);
24 mlir::MLIRContext context
;
25 Diagnostic
diagnostic(mlir::UnknownLoc::get(&context
),
26 DiagnosticSeverity::Note
);
27 diagnostic
<< myStr
.c_str();
29 // Mutate underlying pointer, but ensure diagnostic still has orig. message
32 std::string resultMessage
;
33 llvm::raw_string_ostream
stringStream(resultMessage
);
34 diagnostic
.print(stringStream
);
35 ASSERT_STREQ(expectedMessage
, resultMessage
.c_str());
38 TEST(DiagnosticLifetime
, TestLazyCopyStringLiteral
) {
39 char charArr
[21] = "Error 1, mutate this";
40 mlir::MLIRContext context
;
41 Diagnostic
diagnostic(mlir::UnknownLoc::get(&context
),
42 DiagnosticSeverity::Note
);
44 // Diagnostic contains optimization which assumes string literals are
45 // represented by `const char[]` type. This is imperfect as we can sometimes
46 // trick the type system as seen below.
48 // Still we use this to check the diagnostic is lazily storing the pointer.
49 auto addToDiagnosticAsConst
= [&diagnostic
](const char(&charArr
)[21]) {
50 diagnostic
<< charArr
;
52 addToDiagnosticAsConst(charArr
);
54 // Mutate the underlying pointer and ensure the string does change
57 std::string resultMessage
;
58 llvm::raw_string_ostream
stringStream(resultMessage
);
59 diagnostic
.print(stringStream
);
60 ASSERT_STREQ("^rror 1, mutate this", resultMessage
.c_str());