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, OperationPass<FuncOp>> {
22   TestDiagnosticFilterPass() {}
23   TestDiagnosticFilterPass(const TestDiagnosticFilterPass &) {}
24 
25   void runOnOperation() override {
26     llvm::errs() << "Test '" << getOperation().getName() << "'\n";
27 
28     // Build a diagnostic handler that has filtering capabilities.
29     auto filterFn = [&](Location loc) {
30       // Ignore non-file locations.
31       FileLineColLoc fileLoc = loc.dyn_cast<FileLineColLoc>();
32       if (!fileLoc)
33         return true;
34 
35       // Don't show file locations if their name contains a filter.
36       return llvm::none_of(filters, [&](StringRef filter) {
37         return fileLoc.getFilename().strref().contains(filter);
38       });
39     };
40     llvm::SourceMgr sourceMgr;
41     SourceMgrDiagnosticHandler handler(sourceMgr, &getContext(), llvm::errs(),
42                                        filterFn);
43 
44     // Emit a diagnostic for every operation with a valid loc.
45     getOperation()->walk([&](Operation *op) {
46       if (LocationAttr locAttr = op->getAttrOfType<LocationAttr>("test.loc"))
47         emitError(locAttr, "test diagnostic");
48     });
49   }
50 
51   ListOption<std::string> filters{
52       *this, "filters", llvm::cl::MiscFlags::CommaSeparated,
53       llvm::cl::desc("Specifies the diagnostic file name filters.")};
54 };
55 
56 } // end anonymous namespace
57 
58 namespace mlir {
59 namespace test {
60 void registerTestDiagnosticsPass() {
61   PassRegistration<TestDiagnosticFilterPass>(
62       "test-diagnostic-filter", "Test diagnostic filtering support.");
63 }
64 } // namespace test
65 } // namespace mlir
66