64 lines · cpp
1//===- Diagnostic.cpp - Dialect unit tests -------------------------------===//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-exception6//7//===----------------------------------------------------------------------===//8 9#include "mlir/IR/Diagnostics.h"10#include "mlir/Support/TypeID.h"11#include "gtest/gtest.h"12 13using namespace mlir;14using namespace mlir::detail;15 16namespace {17 18TEST(DiagnosticLifetime, TestCopiesConstCharStar) {19 const auto *expectedMessage = "Error 1, don't mutate this";20 21 // Copy expected message into a mutable container, and call the constructor.22 std::string myStr(expectedMessage);23 24 mlir::MLIRContext context;25 Diagnostic diagnostic(mlir::UnknownLoc::get(&context),26 DiagnosticSeverity::Note);27 diagnostic << myStr.c_str();28 29 // Mutate underlying pointer, but ensure diagnostic still has orig. message30 myStr[0] = '^';31 32 std::string resultMessage;33 llvm::raw_string_ostream stringStream(resultMessage);34 diagnostic.print(stringStream);35 ASSERT_STREQ(expectedMessage, resultMessage.c_str());36}37 38TEST(DiagnosticLifetime, TestLazyCopyStringLiteral) {39 char charArr[21] = "Error 1, mutate this";40 mlir::MLIRContext context;41 Diagnostic diagnostic(mlir::UnknownLoc::get(&context),42 DiagnosticSeverity::Note);43 44 // Diagnostic contains optimization which assumes string literals are45 // represented by `const char[]` type. This is imperfect as we can sometimes46 // trick the type system as seen below.47 //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;51 };52 addToDiagnosticAsConst(charArr);53 54 // Mutate the underlying pointer and ensure the string does change55 charArr[0] = '^';56 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());61}62 63} // namespace64