1 //===---- MatchSwitch.h -----------------------------------------*- C++ -*-===// 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 defines the `ASTMatchSwitch` abstraction for building a "switch" 10 // statement, where each case of the switch is defined by an AST matcher. The 11 // cases are considered in order, like pattern matching in functional 12 // languages. 13 // 14 // Currently, the design is catered towards simplifying the implementation of 15 // `DataflowAnalysis` transfer functions. Based on experience here, this 16 // library may be generalized and moved to ASTMatchers. 17 // 18 //===----------------------------------------------------------------------===// 19 // 20 // FIXME: Rename to ASTMatchSwitch.h 21 22 #ifndef LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_MATCHSWITCH_H_ 23 #define LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_MATCHSWITCH_H_ 24 25 #include "clang/AST/ASTContext.h" 26 #include "clang/AST/Stmt.h" 27 #include "clang/ASTMatchers/ASTMatchFinder.h" 28 #include "clang/ASTMatchers/ASTMatchers.h" 29 #include "clang/Analysis/FlowSensitive/DataflowEnvironment.h" 30 #include "llvm/ADT/StringRef.h" 31 #include <functional> 32 #include <string> 33 #include <type_traits> 34 #include <utility> 35 #include <vector> 36 37 namespace clang { 38 namespace dataflow { 39 40 /// A common form of state shared between the cases of a transfer function. 41 template <typename LatticeT> struct TransferState { 42 TransferState(LatticeT &Lattice, Environment &Env) 43 : Lattice(Lattice), Env(Env) {} 44 45 /// Current lattice element. 46 LatticeT &Lattice; 47 Environment &Env; 48 }; 49 50 /// A read-only version of TransferState. 51 template <typename LatticeT> struct TransferStateForDiagnostics { 52 TransferStateForDiagnostics(const LatticeT &Lattice, const Environment &Env) 53 : Lattice(Lattice), Env(Env) {} 54 55 /// Current lattice element. 56 const LatticeT &Lattice; 57 const Environment &Env; 58 }; 59 60 template <typename T> 61 using MatchSwitchMatcher = ast_matchers::internal::Matcher<T>; 62 63 template <typename T, typename State, typename Result = void> 64 using MatchSwitchAction = std::function<Result( 65 const T *, const ast_matchers::MatchFinder::MatchResult &, State &)>; 66 67 template <typename BaseT, typename State, typename Result = void> 68 using ASTMatchSwitch = 69 std::function<Result(const BaseT &, ASTContext &, State &)>; 70 71 /// Collects cases of a "match switch": a collection of matchers paired with 72 /// callbacks, which together define a switch that can be applied to a node 73 /// whose type derives from `BaseT`. This structure can simplify the definition 74 /// of `transfer` functions that rely on pattern-matching. 75 /// 76 /// For example, consider an analysis that handles particular function calls. It 77 /// can define the `ASTMatchSwitch` once, in the constructor of the analysis, 78 /// and then reuse it each time that `transfer` is called, with a fresh state 79 /// value. 80 /// 81 /// \code 82 /// ASTMatchSwitch<Stmt, TransferState<MyLattice> BuildSwitch() { 83 /// return ASTMatchSwitchBuilder<TransferState<MyLattice>>() 84 /// .CaseOf(callExpr(callee(functionDecl(hasName("foo")))), TransferFooCall) 85 /// .CaseOf(callExpr(argumentCountIs(2), 86 /// callee(functionDecl(hasName("bar")))), 87 /// TransferBarCall) 88 /// .Build(); 89 /// } 90 /// \endcode 91 template <typename BaseT, typename State, typename Result = void> 92 class ASTMatchSwitchBuilder { 93 public: 94 /// Registers an action that will be triggered by the match of a pattern 95 /// against the input statement. 96 /// 97 /// Requirements: 98 /// 99 /// `NodeT` should be derived from `BaseT`. 100 template <typename NodeT> 101 ASTMatchSwitchBuilder &&CaseOf(MatchSwitchMatcher<BaseT> M, 102 MatchSwitchAction<NodeT, State, Result> A) && { 103 static_assert(std::is_base_of<BaseT, NodeT>::value, 104 "NodeT must be derived from BaseT."); 105 Matchers.push_back(std::move(M)); 106 Actions.push_back( 107 [A = std::move(A)](const BaseT *Node, 108 const ast_matchers::MatchFinder::MatchResult &R, 109 State &S) { return A(cast<NodeT>(Node), R, S); }); 110 return std::move(*this); 111 } 112 113 ASTMatchSwitch<BaseT, State, Result> Build() && { 114 return [Matcher = BuildMatcher(), Actions = std::move(Actions)]( 115 const BaseT &Node, ASTContext &Context, State &S) -> Result { 116 auto Results = ast_matchers::matchDynamic(Matcher, Node, Context); 117 if (Results.empty()) { 118 return Result(); 119 } 120 // Look through the map for the first binding of the form "TagN..." use 121 // that to select the action. 122 for (const auto &Element : Results[0].getMap()) { 123 llvm::StringRef ID(Element.first); 124 size_t Index = 0; 125 if (ID.consume_front("Tag") && !ID.getAsInteger(10, Index) && 126 Index < Actions.size()) { 127 return Actions[Index]( 128 &Node, 129 ast_matchers::MatchFinder::MatchResult(Results[0], &Context), S); 130 } 131 } 132 return Result(); 133 }; 134 } 135 136 private: 137 ast_matchers::internal::DynTypedMatcher BuildMatcher() { 138 using ast_matchers::anything; 139 using ast_matchers::stmt; 140 using ast_matchers::unless; 141 using ast_matchers::internal::DynTypedMatcher; 142 if (Matchers.empty()) 143 return stmt(unless(anything())); 144 for (int I = 0, N = Matchers.size(); I < N; ++I) { 145 std::string Tag = ("Tag" + llvm::Twine(I)).str(); 146 // Many matchers are not bindable, so ensure that tryBind will work. 147 Matchers[I].setAllowBind(true); 148 auto M = *Matchers[I].tryBind(Tag); 149 // Each anyOf explicitly controls the traversal kind. The anyOf itself is 150 // set to `TK_AsIs` to ensure no nodes are skipped, thereby deferring to 151 // the kind of the branches. Then, each branch is either left as is, if 152 // the kind is already set, or explicitly set to `TK_AsIs`. We choose this 153 // setting because it is the default interpretation of matchers. 154 Matchers[I] = 155 !M.getTraversalKind() ? M.withTraversalKind(TK_AsIs) : std::move(M); 156 } 157 // The matcher type on the cases ensures that `Expr` kind is compatible with 158 // all of the matchers. 159 return DynTypedMatcher::constructVariadic( 160 DynTypedMatcher::VO_AnyOf, ASTNodeKind::getFromNodeKind<BaseT>(), 161 std::move(Matchers)); 162 } 163 164 std::vector<ast_matchers::internal::DynTypedMatcher> Matchers; 165 std::vector<MatchSwitchAction<BaseT, State, Result>> Actions; 166 }; 167 168 } // namespace dataflow 169 } // namespace clang 170 #endif // LLVM_CLANG_ANALYSIS_FLOWSENSITIVE_MATCHSWITCH_H_ 171