PathDiagnostic.cpp revision 220ac8c175cb1bf9b18d82eefe036995d7a2164d
1//===--- PathDiagnostic.cpp - Path-Specific Diagnostic Handling -*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file defines the PathDiagnostic-related interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
15#include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
16#include "clang/AST/Expr.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/ParentMap.h"
20#include "clang/AST/StmtCXX.h"
21#include "llvm/ADT/SmallString.h"
22
23using namespace clang;
24using namespace ento;
25
26bool PathDiagnosticMacroPiece::containsEvent() const {
27  for (const_iterator I = begin(), E = end(); I!=E; ++I) {
28    if (isa<PathDiagnosticEventPiece>(*I))
29      return true;
30
31    if (PathDiagnosticMacroPiece *MP = dyn_cast<PathDiagnosticMacroPiece>(*I))
32      if (MP->containsEvent())
33        return true;
34  }
35
36  return false;
37}
38
39static StringRef StripTrailingDots(StringRef s) {
40  for (StringRef::size_type i = s.size(); i != 0; --i)
41    if (s[i - 1] != '.')
42      return s.substr(0, i);
43  return "";
44}
45
46PathDiagnosticPiece::PathDiagnosticPiece(StringRef s,
47                                         Kind k, DisplayHint hint)
48  : str(StripTrailingDots(s)), kind(k), Hint(hint) {}
49
50PathDiagnosticPiece::PathDiagnosticPiece(Kind k, DisplayHint hint)
51  : kind(k), Hint(hint) {}
52
53PathDiagnosticPiece::~PathDiagnosticPiece() {}
54PathDiagnosticEventPiece::~PathDiagnosticEventPiece() {}
55PathDiagnosticControlFlowPiece::~PathDiagnosticControlFlowPiece() {}
56
57PathDiagnosticMacroPiece::~PathDiagnosticMacroPiece() {
58  for (iterator I = begin(), E = end(); I != E; ++I) delete *I;
59}
60
61PathDiagnostic::PathDiagnostic() : Size(0) {}
62
63PathDiagnostic::~PathDiagnostic() {
64  for (iterator I = begin(), E = end(); I != E; ++I) delete &*I;
65}
66
67void PathDiagnostic::resetPath(bool deletePieces) {
68  Size = 0;
69
70  if (deletePieces)
71    for (iterator I=begin(), E=end(); I!=E; ++I)
72      delete &*I;
73
74  path.clear();
75}
76
77
78PathDiagnostic::PathDiagnostic(StringRef bugtype, StringRef desc,
79                               StringRef category)
80  : Size(0),
81    BugType(StripTrailingDots(bugtype)),
82    Desc(StripTrailingDots(desc)),
83    Category(StripTrailingDots(category)) {}
84
85void PathDiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel,
86                                            const DiagnosticInfo &Info) {
87  // Default implementation (Warnings/errors count).
88  DiagnosticClient::HandleDiagnostic(DiagLevel, Info);
89
90  // Create a PathDiagnostic with a single piece.
91
92  PathDiagnostic* D = new PathDiagnostic();
93
94  const char *LevelStr;
95  switch (DiagLevel) {
96  default:
97  case Diagnostic::Ignored: assert(0 && "Invalid diagnostic type");
98  case Diagnostic::Note:    LevelStr = "note: "; break;
99  case Diagnostic::Warning: LevelStr = "warning: "; break;
100  case Diagnostic::Error:   LevelStr = "error: "; break;
101  case Diagnostic::Fatal:   LevelStr = "fatal error: "; break;
102  }
103
104  llvm::SmallString<100> StrC;
105  StrC += LevelStr;
106  Info.FormatDiagnostic(StrC);
107
108  PathDiagnosticPiece *P =
109    new PathDiagnosticEventPiece(FullSourceLoc(Info.getLocation(),
110                                               Info.getSourceManager()),
111                                 StrC.str());
112
113  for (unsigned i = 0, e = Info.getNumRanges(); i != e; ++i)
114    P->addRange(Info.getRange(i).getAsRange());
115  for (unsigned i = 0, e = Info.getNumFixItHints(); i != e; ++i)
116    P->addFixItHint(Info.getFixItHint(i));
117  D->push_front(P);
118
119  HandlePathDiagnostic(D);
120}
121
122void PathDiagnosticClient::HandlePathDiagnostic(const PathDiagnostic *D) {
123  // For now this simply forwards to HandlePathDiagnosticImpl.  In the future
124  // we can use this indirection to control for multi-threaded access to
125  // the PathDiagnosticClient from multiple bug reporters.
126  HandlePathDiagnosticImpl(D);
127}
128
129//===----------------------------------------------------------------------===//
130// PathDiagnosticLocation methods.
131//===----------------------------------------------------------------------===//
132
133PathDiagnosticLocation PathDiagnosticLocation::create(const ExplodedNode* N,
134                                                      const SourceManager &SM) {
135  assert(N && "Cannot create a location with a null node.");
136
137  const ExplodedNode *NI = N;
138
139  while (NI) {
140    ProgramPoint P = NI->getLocation();
141    const LocationContext *LC = P.getLocationContext();
142    if (const StmtPoint *PS = dyn_cast<StmtPoint>(&P)) {
143      return PathDiagnosticLocation(PS->getStmt(), SM, LC);
144    }
145    else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
146      const Stmt *Term = BE->getSrc()->getTerminator();
147      assert(Term);
148      return PathDiagnosticLocation(Term, SM, LC);
149    }
150    NI = NI->succ_empty() ? 0 : *(NI->succ_begin());
151  }
152
153  const Decl &D = N->getCodeDecl();
154  return PathDiagnosticLocation(D.getBodyRBrace(), SM);
155}
156
157static SourceLocation getValidSourceLocation(const Stmt* S,
158                                             const LocationContext *LC) {
159  assert(LC);
160  SourceLocation L = S->getLocStart();
161
162  // S might be a temporary statement that does not have a location in the
163  // source code, so find an enclosing statement and use it's location.
164  if (!L.isValid()) {
165    ParentMap & PM = LC->getParentMap();
166
167    while (!L.isValid()) {
168      S = PM.getParent(S);
169      L = S->getLocStart();
170    }
171  }
172
173  return L;
174}
175
176FullSourceLoc PathDiagnosticLocation::asLocation() const {
177  assert(isValid());
178  // Note that we want a 'switch' here so that the compiler can warn us in
179  // case we add more cases.
180  switch (K) {
181    case SingleLocK:
182    case RangeK:
183      break;
184    case StmtK:
185      return FullSourceLoc(getValidSourceLocation(S, LC),
186                           const_cast<SourceManager&>(*SM));
187    case DeclK:
188      return FullSourceLoc(D->getLocation(), const_cast<SourceManager&>(*SM));
189  }
190
191  if (!R.isValid())
192    return FullSourceLoc(LC->getDecl()->getBodyRBrace(),
193                         const_cast<SourceManager&>(*SM));
194
195  return FullSourceLoc(R.getBegin(), const_cast<SourceManager&>(*SM));
196}
197
198PathDiagnosticRange PathDiagnosticLocation::asRange() const {
199  assert(isValid());
200  // Note that we want a 'switch' here so that the compiler can warn us in
201  // case we add more cases.
202  switch (K) {
203    case SingleLocK:
204      return PathDiagnosticRange(R, true);
205    case RangeK:
206      break;
207    case StmtK: {
208      const Stmt *S = asStmt();
209      switch (S->getStmtClass()) {
210        default:
211          break;
212        case Stmt::DeclStmtClass: {
213          const DeclStmt *DS = cast<DeclStmt>(S);
214          if (DS->isSingleDecl()) {
215            // Should always be the case, but we'll be defensive.
216            return SourceRange(DS->getLocStart(),
217                               DS->getSingleDecl()->getLocation());
218          }
219          break;
220        }
221          // FIXME: Provide better range information for different
222          //  terminators.
223        case Stmt::IfStmtClass:
224        case Stmt::WhileStmtClass:
225        case Stmt::DoStmtClass:
226        case Stmt::ForStmtClass:
227        case Stmt::ChooseExprClass:
228        case Stmt::IndirectGotoStmtClass:
229        case Stmt::SwitchStmtClass:
230        case Stmt::BinaryConditionalOperatorClass:
231        case Stmt::ConditionalOperatorClass:
232        case Stmt::ObjCForCollectionStmtClass: {
233          SourceLocation L = getValidSourceLocation(S, LC);
234          return SourceRange(L, L);
235        }
236      }
237
238      return S->getSourceRange();
239    }
240    case DeclK:
241      if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
242        return MD->getSourceRange();
243      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
244        if (Stmt *Body = FD->getBody())
245          return Body->getSourceRange();
246      }
247      else {
248        SourceLocation L = D->getLocation();
249        return PathDiagnosticRange(SourceRange(L, L), true);
250      }
251  }
252
253  return R;
254}
255
256void PathDiagnosticLocation::flatten() {
257  if (K == StmtK) {
258    R = asRange();
259    K = RangeK;
260    S = 0;
261    D = 0;
262  }
263  else if (K == DeclK) {
264    SourceLocation L = D->getLocation();
265    R = SourceRange(L, L);
266    K = SingleLocK;
267    S = 0;
268    D = 0;
269  }
270}
271
272//===----------------------------------------------------------------------===//
273// FoldingSet profiling methods.
274//===----------------------------------------------------------------------===//
275
276void PathDiagnosticLocation::Profile(llvm::FoldingSetNodeID &ID) const {
277  ID.AddInteger((unsigned) K);
278  switch (K) {
279    case RangeK:
280      ID.AddInteger(R.getBegin().getRawEncoding());
281      ID.AddInteger(R.getEnd().getRawEncoding());
282      break;
283    case SingleLocK:
284      ID.AddInteger(R.getBegin().getRawEncoding());
285      break;
286    case StmtK:
287      ID.Add(S);
288      break;
289    case DeclK:
290      ID.Add(D);
291      break;
292  }
293  return;
294}
295
296void PathDiagnosticPiece::Profile(llvm::FoldingSetNodeID &ID) const {
297  ID.AddInteger((unsigned) getKind());
298  ID.AddString(str);
299  // FIXME: Add profiling support for code hints.
300  ID.AddInteger((unsigned) getDisplayHint());
301  for (range_iterator I = ranges_begin(), E = ranges_end(); I != E; ++I) {
302    ID.AddInteger(I->getBegin().getRawEncoding());
303    ID.AddInteger(I->getEnd().getRawEncoding());
304  }
305}
306
307void PathDiagnosticSpotPiece::Profile(llvm::FoldingSetNodeID &ID) const {
308  PathDiagnosticPiece::Profile(ID);
309  ID.Add(Pos);
310}
311
312void PathDiagnosticControlFlowPiece::Profile(llvm::FoldingSetNodeID &ID) const {
313  PathDiagnosticPiece::Profile(ID);
314  for (const_iterator I = begin(), E = end(); I != E; ++I)
315    ID.Add(*I);
316}
317
318void PathDiagnosticMacroPiece::Profile(llvm::FoldingSetNodeID &ID) const {
319  PathDiagnosticSpotPiece::Profile(ID);
320  for (const_iterator I = begin(), E = end(); I != E; ++I)
321    ID.Add(**I);
322}
323
324void PathDiagnostic::Profile(llvm::FoldingSetNodeID &ID) const {
325  ID.AddInteger(Size);
326  ID.AddString(BugType);
327  ID.AddString(Desc);
328  ID.AddString(Category);
329  for (const_iterator I = begin(), E = end(); I != E; ++I)
330    ID.Add(*I);
331
332  for (meta_iterator I = meta_begin(), E = meta_end(); I != E; ++I)
333    ID.AddString(*I);
334}
335