1 //===- TestDiagnostics.cpp - Test Diagnostic Utilities --------------------===//
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 // This file contains test passes for constructing and resolving dominance
10 // information.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Pass/Pass.h"
15 #include "llvm/Support/SourceMgr.h"
16 
17 using namespace mlir;
18 
19 namespace {
20 struct TestDiagnosticFilterPass
21     : public PassWrapper<TestDiagnosticFilterPass,
22                          InterfacePass<SymbolOpInterface>> {
23   StringRef getArgument() const final { return "test-diagnostic-filter"; }
24   StringRef getDescription() const final {
25     return "Test diagnostic filtering support.";
26   }
27   TestDiagnosticFilterPass() = default;
28   TestDiagnosticFilterPass(const TestDiagnosticFilterPass &) {}
29 
30   void runOnOperation() override {
31     llvm::errs() << "Test '" << getOperation().getName() << "'\n";
32 
33     // Build a diagnostic handler that has filtering capabilities.
34     auto filterFn = [&](Location loc) {
35       // Ignore non-file locations.
36       FileLineColLoc fileLoc = loc.dyn_cast<FileLineColLoc>();
37       if (!fileLoc)
38         return true;
39 
40       // Don't show file locations if their name contains a filter.
41       return llvm::none_of(filters, [&](StringRef filter) {
42         return fileLoc.getFilename().strref().contains(filter);
43       });
44     };
45     llvm::SourceMgr sourceMgr;
46     SourceMgrDiagnosticHandler handler(sourceMgr, &getContext(), llvm::errs(),
47                                        filterFn);
48 
49     // Emit a diagnostic for every operation with a valid loc.
50     getOperation()->walk([&](Operation *op) {
51       if (LocationAttr locAttr = op->getAttrOfType<LocationAttr>("test.loc"))
52         emitError(locAttr, "test diagnostic");
53     });
54   }
55 
56   ListOption<std::string> filters{
57       *this, "filters", llvm::cl::MiscFlags::CommaSeparated,
58       llvm::cl::desc("Specifies the diagnostic file name filters.")};
59 };
60 
61 } // namespace
62 
63 namespace mlir {
64 namespace test {
65 void registerTestDiagnosticsPass() {
66   PassRegistration<TestDiagnosticFilterPass>{};
67 }
68 } // namespace test
69 } // namespace mlir
70