https://github.com/joker-eph created https://github.com/llvm/llvm-project/pull/238150
Render owned formatting errors as source-aware messages, preserving inner definition origins, use sites, and multiclass location arrays. Consume every error payload before printing and terminating so joined errors and their notes are not lost. Add eager fatal wrappers for generator boundaries and use them for trait predicates. Missing substitutions now fail in TableGen with the template, failed occurrences, and available bindings instead of generating bad C++. Snapshot the trait context before value verifiers add temporary bindings, so an inline attribute check cannot accidentally bind $_self for a trait. Share message construction between generic logging and source diagnostics. Use portable death-test expressions and handle invalid success payloads defensively at the fatal-reporting boundary. Assisted-by: Codex >From fad8fc9f9a21581090e22e38e9d942cd467e3d37 Mon Sep 17 00:00:00 2001 From: Mehdi Amini <[email protected]> Date: Sun, 1 Nov 2026 04:27:27 -0800 Subject: [PATCH] [mlir][tblgen] Diagnose substitution failures at their source Render owned formatting errors as source-aware messages, preserving inner definition origins, use sites, and multiclass location arrays. Consume every error payload before printing and terminating so joined errors and their notes are not lost. Add eager fatal wrappers for generator boundaries and use them for trait predicates. Missing substitutions now fail in TableGen with the template, failed occurrences, and available bindings instead of generating bad C++. Snapshot the trait context before value verifiers add temporary bindings, so an inline attribute check cannot accidentally bind $_self for a trait. Share message construction between generic logging and source diagnostics. Use portable death-test expressions and handle invalid success payloads defensively at the fatal-reporting boundary. Validation: 74 TableGen unit tests and all 69 mlir-tblgen lit tests pass. Cover multiple missing tokens, multiclass notes, owned rendered messages, outer-location fallback, and printing joined errors before fatal exit. Assisted-by: Codex --- mlir/include/mlir/TableGen/CodeGenHelpers.h | 28 ++++- mlir/include/mlir/TableGen/Format.h | 13 ++ mlir/lib/TableGen/CodeGenHelpers.cpp | 42 +++++++ mlir/lib/TableGen/Format.cpp | 108 ++++++++++++---- mlir/test/mlir-tblgen/op-error.td | 60 +++++++++ mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp | 14 ++- mlir/unittests/TableGen/FormatTest.cpp | 130 +++++++++++++++++++- 7 files changed, 361 insertions(+), 34 deletions(-) diff --git a/mlir/include/mlir/TableGen/CodeGenHelpers.h b/mlir/include/mlir/TableGen/CodeGenHelpers.h index b56172f55a157b..88cc565a69ddba 100644 --- a/mlir/include/mlir/TableGen/CodeGenHelpers.h +++ b/mlir/include/mlir/TableGen/CodeGenHelpers.h @@ -33,6 +33,33 @@ namespace tblgen { class Constraint; class DagLeaf; +/// Consume every error payload, print all messages, then terminate through +/// TableGen's fatal cleanup path. The caller origin is appended after any +/// context already attached by inner helpers. Requires a non-success error. +[[noreturn]] void reportFatalFmtError(llvm::Error error, + const FmtOrigin &callerOrigin); + +/// Eager formatting at a TableGen diagnostic boundary. User-authored templates +/// should supply their definition origin and any known use-site context. +template <typename... Ts> +std::string tgfmtOrFatal(const FmtOrigin &origin, StringRef fmt, + const FmtContext &ctx, Ts &&...values) { + auto result = tgfmtChecked(fmt, ctx, std::forward<Ts>(values)...); + if (!result) + reportFatalFmtError(result.takeError(), origin); + return std::move(*result); +} + +/// Like tgfmtOrFatal, with positional replacements supplied as strings. +inline std::string tgfmtvOrFatal(const FmtOrigin &origin, StringRef fmt, + const FmtContext &ctx, + ArrayRef<std::string> values) { + auto result = tgfmtvChecked(fmt, ctx, values); + if (!result) + reportFatalFmtError(result.takeError(), origin); + return std::move(*result); +} + // Format into a std::string template <typename... Parameters> std::string strfmt(const char *fmt, Parameters &&...parameters) { @@ -264,7 +291,6 @@ std::string stringify(T &&t) { std::string buildErrorStreamingString( StringRef message, const FmtContext &ctx, ErrorStreamType errorStreamType = ErrorStreamType::InString); - } // namespace tblgen } // namespace mlir diff --git a/mlir/include/mlir/TableGen/Format.h b/mlir/include/mlir/TableGen/Format.h index eb259d802d8a33..6d1b1c56d077c7 100644 --- a/mlir/include/mlir/TableGen/Format.h +++ b/mlir/include/mlir/TableGen/Format.h @@ -68,6 +68,7 @@ struct FmtIssue { FmtIssueKind kind; std::string placeholder; size_t offset; + StringRef getDescription() const; }; /// A failed invocation, including all failed occurrences in template order. @@ -97,6 +98,18 @@ class FmtError : public llvm::ErrorInfo<FmtError> { SmallVector<FmtOrigin> origins; }; +/// An owned diagnostic message, independent of the error payload. Complete +/// location arrays retain TableGen's multiclass instantiation notes. +struct FmtDiagnostic { + bool isError; + SmallVector<llvm::SMLoc, 1> locations; + std::string message; +}; + +/// Render a typed formatting failure without printing or terminating. Nonfatal +/// consumers may adapt these messages to their own diagnostic engine. +SmallVector<FmtDiagnostic> getFmtDiagnostics(const FmtError &error); + /// Append owned context without changing the error's type. Other errors pass /// through unchanged, including non-formatting leaves in an ErrorList. llvm::Error addFmtOrigin(llvm::Error error, const FmtOrigin &origin); diff --git a/mlir/lib/TableGen/CodeGenHelpers.cpp b/mlir/lib/TableGen/CodeGenHelpers.cpp index 19439eddcb3339..9f17892a3234ff 100644 --- a/mlir/lib/TableGen/CodeGenHelpers.cpp +++ b/mlir/lib/TableGen/CodeGenHelpers.cpp @@ -37,6 +37,48 @@ using namespace llvm; using namespace mlir; using namespace mlir::tblgen; +void mlir::tblgen::reportFatalFmtError(llvm::Error error, + const FmtOrigin &callerOrigin) { + if (!error) + PrintFatalError("internal formatting error: expected a non-success error"); + SmallVector<FmtDiagnostic> messages; + llvm::handleAllErrors( + addFmtOrigin(std::move(error), callerOrigin), + [&](const FmtError &failure) { + llvm::append_range(messages, getFmtDiagnostics(failure)); + }, + [&](const llvm::ErrorInfoBase &failure) { + const FmtSite &site = callerOrigin.getDefinition(); + messages.push_back({true, site.locations, failure.message()}); + }); + if (messages.empty()) + PrintFatalError("internal formatting error: no diagnostic messages"); + // Use location-free overloads for explanatory messages, avoiding an + // artificial <unknown>:0 prefix on template and availability notes. + for (const FmtDiagnostic &message : llvm::drop_end(messages)) { + if (message.isError) { + if (message.locations.empty()) + PrintError(message.message); + else + PrintError(message.locations, message.message); + } else { + if (message.locations.empty()) + PrintNote(message.message); + else + PrintNote(message.locations, message.message); + } + } + const FmtDiagnostic &last = messages.back(); + if (last.isError) { + if (last.locations.empty()) + PrintFatalError(last.message); + PrintFatalError(last.locations, last.message); + } + if (last.locations.empty()) + PrintFatalNote(last.message); + PrintFatalNote(last.locations, last.message); +} + /// Generate a unique label based on the current file name to prevent name /// collisions if multiple generated files are included at once. static std::string getUniqueOutputLabel(const RecordKeeper &records, diff --git a/mlir/lib/TableGen/Format.cpp b/mlir/lib/TableGen/Format.cpp index 10c31ff1cdeba0..ea044e9cc323a7 100644 --- a/mlir/lib/TableGen/Format.cpp +++ b/mlir/lib/TableGen/Format.cpp @@ -58,39 +58,93 @@ void FmtError::printBindings(raw_ostream &os) const { ::printBindings(os, bindings); } +StringRef FmtIssue::getDescription() const { + switch (kind) { + case FmtIssueKind::MissingNamedBinding: + return "missing named binding"; + case FmtIssueKind::PositionalOutOfRange: + return "positional argument out of range"; + case FmtIssueKind::RangeStartOutOfRange: + return "positional range starts out of range"; + case FmtIssueKind::InvalidPositionalIndex: + return "invalid positional index"; + } + llvm_unreachable("unknown formatting issue kind"); +} + void FmtError::log(raw_ostream &os) const { - for (const FmtIssue &issue : issues) { - os << "cannot substitute '" << issue.placeholder - << "' at template byte offset " << issue.offset; - switch (issue.kind) { - case FmtIssueKind::MissingNamedBinding: - os << ": missing named binding"; - break; - case FmtIssueKind::PositionalOutOfRange: - os << ": positional argument out of range"; - break; - case FmtIssueKind::RangeStartOutOfRange: - os << ": positional range starts out of range"; - break; - case FmtIssueKind::InvalidPositionalIndex: - os << ": invalid positional index"; + llvm::interleave( + getFmtDiagnostics(*this), os, + [&](const FmtDiagnostic &message) { os << message.message; }, "\n"); +} + +SmallVector<FmtDiagnostic> +mlir::tblgen::getFmtDiagnostics(const FmtError &error) { + SmallVector<FmtDiagnostic> messages; + auto add = [&](bool isError, ArrayRef<llvm::SMLoc> locations, + const Twine &message) { + messages.push_back( + {isError, {locations.begin(), locations.end()}, message.str()}); + }; + + const FmtSite *anchor = nullptr; + for (const FmtOrigin &origin : error.getOrigins()) { + const FmtSite &site = origin.getDefinition(); + if (!site.locations.empty() && site.locations.front().isValid()) { + anchor = &site; break; } - os << '\n'; } - os << "template: "; - os.write_escaped(format, /*UseHexEscapes=*/true) << '\n'; - os << "available named substitutions:"; - if (bindings.empty()) - os << " (none)"; - for (const FmtBinding &binding : bindings) - os << " $" << binding.name; - os << "\npositional arguments supplied: " << numPositionalArgs; - for (const FmtOrigin &origin : origins) { - os << "\nwhile formatting " << origin.getDefinition().description; + ArrayRef<llvm::SMLoc> locations = + anchor ? ArrayRef<llvm::SMLoc>(anchor->locations) + : ArrayRef<llvm::SMLoc>{}; + StringRef purpose = "template"; + if (!error.getOrigins().empty()) + purpose = error.getOrigins().front().getDefinition().description; + const FmtIssue &first = error.getIssues().front(); + add(true, locations, + "cannot substitute '" + first.placeholder + "' while formatting " + + purpose + ": " + first.getDescription()); + for (const FmtIssue &issue : error.getIssues().drop_front()) + add(false, {}, + "cannot substitute '" + issue.placeholder + + "' at template byte offset " + Twine(issue.offset) + ": " + + issue.getDescription()); + + std::string escaped; + llvm::raw_string_ostream(escaped).write_escaped(error.getTemplate(), true); + add(false, {}, "template: " + escaped); + add(false, {}, + "failed occurrence starts at template byte offset " + + Twine(first.offset)); + for (const auto &[index, origin] : llvm::enumerate(error.getOrigins())) { + const FmtSite &definition = origin.getDefinition(); + if (index != 0) + add(false, definition.locations, + "while formatting " + definition.description); for (const FmtSite &use : origin.getUses()) - os << "\nwhile expanding " << use.description; + add(false, use.locations, "while expanding " + use.description); } + + std::string available; + llvm::raw_string_ostream availableStream(available); + availableStream << "available named substitutions: "; + if (error.getBindings().empty()) + availableStream << "(none)"; + else + llvm::interleaveComma(error.getBindings(), availableStream, + [&](const FmtBinding &binding) { + availableStream << '$' << binding.name; + }); + add(false, {}, available); + size_t count = error.getNumPositionalArgs(); + if (!count) + add(false, {}, "no positional substitutions were supplied"); + else + add(false, {}, + "positional substitutions supplied: " + Twine(count) + + " (available indices: $0 through $" + Twine(count - 1) + ")"); + return messages; } llvm::Error mlir::tblgen::addFmtOrigin(llvm::Error error, diff --git a/mlir/test/mlir-tblgen/op-error.td b/mlir/test/mlir-tblgen/op-error.td index ec90891034fbef..7a42753eab8fd9 100644 --- a/mlir/test/mlir-tblgen/op-error.td +++ b/mlir/test/mlir-tblgen/op-error.td @@ -15,6 +15,10 @@ // RUN: not mlir-tblgen -gen-op-decls -I %S/../../include -DERROR15 %s 2>&1 | FileCheck --check-prefix=ERROR15 %s // RUN: not mlir-tblgen -gen-op-decls -I %S/../../include -DERROR16 %s 2>&1 | FileCheck --check-prefix=ERROR16 %s // RUN: not mlir-tblgen -gen-op-decls -I %S/../../include -DERROR17 %s 2>&1 | FileCheck --check-prefix=ERROR17 %s +// RUN: not mlir-tblgen -gen-op-defs -I %S/../../include -DERROR18 %s 2>&1 | FileCheck --check-prefix=ERROR18 %s +// RUN: not mlir-tblgen -gen-op-defs -I %S/../../include -DERROR19 %s 2>&1 | FileCheck --check-prefix=ERROR19 %s +// RUN: not mlir-tblgen -gen-op-defs -I %S/../../include -DERROR20 %s 2>&1 | FileCheck --check-prefix=ERROR20 %s +// RUN: not mlir-tblgen -gen-op-defs -I %S/../../include -DERROR21 %s 2>&1 | FileCheck --check-prefix=ERROR21 %s include "mlir/IR/OpBase.td" @@ -22,6 +26,62 @@ def Test_Dialect : Dialect { let name = "test_dialect"; } +#ifdef ERROR18 +// ERROR18: error: cannot substitute '$_self' while formatting trait predicate: missing named binding +// ERROR18: note: template: {{.*}}$_self.getType() == $_op.getOperand(0).getType() +// ERROR18: note: failed occurrence starts at template byte offset +// ERROR18: note: while expanding operation 'test_dialect.unbound_self' +// ERROR18: note: available named substitutions: $_ctxt, $_op, $a, $b +// ERROR18: note: no positional substitutions were supplied +def UnboundSelfOp : Op<Test_Dialect, "unbound_self", [ + PredOpTrait<"same type", + CPred<"$_self.getType() == $_op.getOperand(0).getType()">>]> { + let arguments = (ins AnyType:$a, AnyType:$b); +} +#endif + +#ifdef ERROR19 +// ERROR19: error: cannot substitute '$missing' while formatting trait predicate: missing named binding +// ERROR19: note: cannot substitute '$9' at template byte offset {{[0-9]+}}: positional argument out of range +// ERROR19: note: cannot substitute '$missing' at template byte offset {{[0-9]+}}: missing named binding +// ERROR19: note: template: {{.*}}$missing && $9 && $missing +// ERROR19: note: while expanding operation 'test_dialect.unbound_multiple' +// ERROR19: note: available named substitutions: $_ctxt, $_op +// ERROR19: note: no positional substitutions were supplied +def UnboundMultipleOp : Op<Test_Dialect, "unbound_multiple", [ + PredOpTrait<"multiple failures", CPred<"$missing && $9 && $missing">>]>; +#endif + +#ifdef ERROR20 +// ERROR20: error: cannot substitute '$missing' while formatting trait predicate +// ERROR20: note: template: +// ERROR20: note: while expanding operation 'test_dialect.multiclass' +// ERROR20: note: instantiated from multiclass +// ERROR20: note: available named substitutions: $_ctxt, $_op +// ERROR20: note: no positional substitutions were supplied +multiclass UnboundTraitMulticlass { + def Op : Op<Test_Dialect, "multiclass", [ + PredOpTrait<"missing", CPred<"$missing">>]>; +} +defm Broken : UnboundTraitMulticlass; +#endif + +#ifdef ERROR21 +// An inline attribute predicate binds $_self while checking that attribute. +// That temporary binding must not make $_self available to an operation trait. +// ERROR21: error: cannot substitute '$_self' while formatting trait predicate: missing named binding +// ERROR21: note: while expanding operation 'test_dialect.inline_attr' +// ERROR21: note: available named substitutions: $_ctxt, $_op, $input, $value +// ERROR21: note: no positional substitutions were supplied +def DependentAttr : Attr<CPred<"$_self && $input">, "dependent"> { + let convertFromStorage = "$_self"; +} +def InlineAttrOp : Op<Test_Dialect, "inline_attr", [ + PredOpTrait<"unbound self", CPred<"$_self">>]> { + let arguments = (ins DependentAttr:$value, I32:$input); +} +#endif + #ifdef ERROR1 // ERROR1: error: expected 'ins' def OpInsMissing : Op<Test_Dialect, "ins_missing"> { diff --git a/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp b/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp index 62d057af2132b4..a388e01f0dc379 100644 --- a/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp +++ b/mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp @@ -420,7 +420,6 @@ class OpOrAdaptorHelper { uint32_t operandSegmentSizesLegacyIndex = 0; uint32_t resultSegmentSizesLegacyIndex = 0; }; - } // namespace void OpOrAdaptorHelper::computeAttrMetadata() { @@ -771,7 +770,6 @@ class OpEmitter { // avoid duplicates. llvm::StringSet<> interfaceUsingNames; }; - } // namespace // Populate the format context `ctx` with substitutions of attributes, operands @@ -3769,6 +3767,9 @@ void OpEmitter::genVerifier() { ERROR_IF_PRUNED(implMethod, "verifyInvariantsImpl", op); auto &implBody = implMethod->body(); populateSubstitutions(emitHelper, verifyCtx); + // Value verifiers may add a temporary $_self binding. Traits refer to the + // whole operation and must not inherit a binding to the last checked value. + FmtContext traitCtx = verifyCtx; genPropertyVerifier(emitHelper, verifyCtx, implBody, staticVerifierEmitter); genAttributeVerifier(emitHelper, verifyCtx, implBody, staticVerifierEmitter); genOperandResultVerifier(implBody, op.getOperands(), "operand"); @@ -3776,10 +3777,15 @@ void OpEmitter::genVerifier() { for (auto &trait : op.getTraits()) { if (auto *t = dyn_cast<tblgen::PredTrait>(&trait)) { + FmtOrigin origin = + FmtOrigin::at(t->getDef().getLoc(), "trait predicate") + .withUse(op.getLoc(), + "operation '" + op.getOperationName() + "'"); + std::string predicate = + tgfmtOrFatal(origin, t->getPredTemplate(), traitCtx); implBody << tgfmt(" if (!($0))\n " "return emitOpError(\"failed to verify that $1\");\n", - &verifyCtx, tgfmt(t->getPredTemplate(), &verifyCtx), - t->getSummary()); + &traitCtx, predicate, t->getSummary()); } } diff --git a/mlir/unittests/TableGen/FormatTest.cpp b/mlir/unittests/TableGen/FormatTest.cpp index ae36ac1c2930c7..fe8e4028bae3b6 100644 --- a/mlir/unittests/TableGen/FormatTest.cpp +++ b/mlir/unittests/TableGen/FormatTest.cpp @@ -7,6 +7,7 @@ //===----------------------------------------------------------------------===// #include "mlir/TableGen/Format.h" +#include "mlir/TableGen/CodeGenHelpers.h" #include "gmock/gmock.h" using ::testing::StrEq; @@ -275,14 +276,16 @@ TEST(FormatTest, ErrorLogIncludesFailureAndAvailability) { ASSERT_FALSE(static_cast<bool>(result)); std::string log = llvm::toString(addFmtOrigin( result.takeError(), FmtOrigin::describe("predicate").withUse({}, "op"))); - EXPECT_THAT(log, ::testing::HasSubstr("'$_self' at template byte offset 0")); + EXPECT_THAT(log, ::testing::HasSubstr("cannot substitute '$_self'")); + EXPECT_THAT(log, ::testing::HasSubstr("template byte offset 0")); EXPECT_THAT(log, ::testing::HasSubstr("missing named binding")); EXPECT_THAT(log, ::testing::HasSubstr("'$2' at template byte offset 7")); EXPECT_THAT(log, ::testing::HasSubstr("positional argument out of range")); EXPECT_THAT(log, ::testing::HasSubstr("template: $_self $2")); EXPECT_THAT(log, ::testing::HasSubstr("available named substitutions: (none)")); - EXPECT_THAT(log, ::testing::HasSubstr("positional arguments supplied: 1")); + EXPECT_THAT(log, + ::testing::HasSubstr("positional substitutions supplied: 1")); EXPECT_THAT(log, ::testing::HasSubstr("while formatting predicate")); EXPECT_THAT(log, ::testing::HasSubstr("while expanding op")); } @@ -374,3 +377,126 @@ TEST(FormatTest, LegacyRemainsLazy) { EXPECT_EQ(legacy.str(), "after"); EXPECT_EQ(*eager, "before"); } + +TEST(FormatTest, DiagnosticsPreserveSourceContextsAndOwnMessages) { + const char source[] = "definition multiclass use outer"; + llvm::SMLoc def = llvm::SMLoc::getFromPointer(source); + llvm::SMLoc instantiation = llvm::SMLoc::getFromPointer(source + 11); + llvm::SMLoc use = llvm::SMLoc::getFromPointer(source + 22); + llvm::SMLoc outer = llvm::SMLoc::getFromPointer(source + 26); + auto result = + tgfmtChecked("$missing $3", FmtContext({{"_self", "self"}}), "one"); + ASSERT_FALSE(static_cast<bool>(result)); + llvm::Error error = addFmtOrigin( + result.takeError(), FmtOrigin::at({def, instantiation}, "predicate") + .withUse({use}, "operation")); + error = + addFmtOrigin(std::move(error), FmtOrigin::at({outer}, "outer helper")); + llvm::SmallVector<FmtDiagnostic> messages; + llvm::handleAllErrors(std::move(error), [&](const FmtError &e) { + messages = getFmtDiagnostics(e); + }); + // The error is already destroyed; messages own text and location arrays. + ASSERT_EQ(messages.size(), 8u); + EXPECT_TRUE(messages[0].isError); + ASSERT_EQ(messages[0].locations.size(), 2u); + EXPECT_EQ(messages[0].locations[0], def); + EXPECT_EQ(messages[0].locations[1], instantiation); + EXPECT_THAT(messages[0].message, + ::testing::HasSubstr("while formatting predicate")); + EXPECT_THAT(messages[1].message, + ::testing::HasSubstr("'$3' at template byte offset 9")); + EXPECT_EQ(messages[2].message, "template: $missing $3"); + EXPECT_EQ(messages[3].message, + "failed occurrence starts at template byte offset 0"); + EXPECT_EQ(messages[4].locations[0], use); + EXPECT_EQ(messages[4].message, "while expanding operation"); + EXPECT_EQ(messages[5].locations[0], outer); + EXPECT_EQ(messages[5].message, "while formatting outer helper"); + EXPECT_EQ(messages[6].message, "available named substitutions: $_self"); + EXPECT_EQ(messages[7].message, "positional substitutions supplied: 1 " + "(available indices: $0 through $0)"); +} + +TEST(FormatTest, DiagnosticsFallBackToAnOuterLocation) { + const char source[] = "outer"; + llvm::SMLoc outer = llvm::SMLoc::getFromPointer(source); + auto result = tgfmtChecked("$_self", FmtContext{}); + ASSERT_FALSE(static_cast<bool>(result)); + auto error = addFmtOrigin(result.takeError(), FmtOrigin::describe("inner")); + error = addFmtOrigin(std::move(error), FmtOrigin::at({outer}, "outer")); + llvm::handleAllErrors(std::move(error), [&](const FmtError &e) { + auto messages = getFmtDiagnostics(e); + ASSERT_EQ(messages.front().locations.size(), 1u); + EXPECT_EQ(messages.front().locations[0], outer); + EXPECT_THAT(messages.front().message, + ::testing::HasSubstr("formatting inner")); + EXPECT_TRUE(llvm::any_of(messages, [](const FmtDiagnostic &message) { + return message.message == "while formatting outer"; + })); + EXPECT_EQ(messages.back().message, + "no positional substitutions were supplied"); + }); +} + +TEST(FormatTest, FatalArrayFormattingSuccess) { + std::string values[] = {"zero", "one"}; + FmtContext ctx({{"_self", "self"}}); + EXPECT_EQ(tgfmtvOrFatal(FmtOrigin::describe("array template"), "$1 $0 $_self", + ctx, values), + "one zero self"); +} + +TEST(FormatTest, DiagnosticsWithoutOrigins) { + auto error = takeFormatError(tgfmtChecked("$missing", FmtContext{})); + ASSERT_TRUE(error); + auto messages = getFmtDiagnostics(*error); + EXPECT_THAT(messages.front().message, + ::testing::HasSubstr("while formatting template")); + EXPECT_TRUE(messages.front().locations.empty()); + EXPECT_EQ(messages[messages.size() - 2].message, + "available named substitutions: (none)"); +} + +TEST(FormatTest, ArrayDiagnosticsForInvalidIndicesAndRanges) { + auto error = takeFormatError(tgfmtvChecked( + "$99999999999999999999999999999999999999999999 $2...", FmtContext{}, {})); + ASSERT_TRUE(error); + auto messages = getFmtDiagnostics(*error); + EXPECT_THAT(messages[0].message, + ::testing::HasSubstr("invalid positional index")); + EXPECT_THAT(messages[1].message, + ::testing::HasSubstr("positional range starts out of range")); +} + +#if GTEST_HAS_DEATH_TEST +TEST(FormatTest, FatalFormattingRejectsSuccessErrors) { + EXPECT_EXIT( + reportFatalFmtError(llvm::Error::success(), FmtOrigin::describe("test")), + ::testing::ExitedWithCode(1), "expected a non-success error"); +} + +TEST(FormatTest, FatalFormattingPrintsEveryErrorBeforeExit) { + EXPECT_EXIT( + { + auto first = tgfmtChecked("$first", FmtContext{}); + auto second = tgfmtChecked("$second", FmtContext{}); + reportFatalFmtError( + llvm::joinErrors(first.takeError(), second.takeError()), + FmtOrigin::describe("test")); + }, + ::testing::ExitedWithCode(1), "cannot substitute '\\$second'"); +} + +TEST(FormatTest, FatalFormattingPreservesUnrelatedErrors) { + EXPECT_EXIT( + { + auto result = tgfmtChecked("$missing", FmtContext{}); + reportFatalFmtError( + llvm::joinErrors(result.takeError(), + llvm::createStringError("unrelated failure")), + FmtOrigin::describe("test")); + }, + ::testing::ExitedWithCode(1), "unrelated failure"); +} +#endif _______________________________________________ llvm-branch-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits
