Diagnostic.cpp revision c0a575f9b791a25c94b1c3c832dd73ec564646bb
15821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===//
25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//                     The LLVM Compiler Infrastructure
45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
55821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source
65821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// License. See LICENSE.TXT for details.
75821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
85821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===//
95821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//
102a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//  This file implements the Diagnostic-related interfaces.
112a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)//
125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//===----------------------------------------------------------------------===//
132a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Basic/Diagnostic.h"
155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Basic/IdentifierTable.h"
165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "clang/Basic/PartialDiagnostic.h"
175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/ADT/SmallVector.h"
185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/Support/raw_ostream.h"
195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "llvm/Support/CrashRecoveryContext.h"
205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)using namespace clang;
225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT,
245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                               const char *Modifier, unsigned ML,
255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                               const char *Argument, unsigned ArgLen,
265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                               const Diagnostic::ArgumentValue *PrevArgs,
275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                               unsigned NumPrevArgs,
285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                               SmallVectorImpl<char> &Output,
295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                               void *Cookie,
305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                               SmallVectorImpl<intptr_t> &QualTypeVals) {
315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  const char *Str = "<can't format argument>";
325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  Output.append(Str, Str+strlen(Str));
335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)Diagnostic::Diagnostic(const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &diags,
37c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)                       DiagnosticClient *client, bool ShouldOwnClient)
38c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  : Diags(diags), Client(client), OwnsDiagClient(ShouldOwnClient),
395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    SourceMgr(0) {
405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ArgToStringFn = DummyArgToStringFn;
415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ArgToStringCookie = 0;
425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  AllExtensionsSilenced = 0;
445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  IgnoreAllWarnings = false;
455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  WarningsAsErrors = false;
465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ErrorsAsFatal = false;
475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  SuppressSystemWarnings = false;
485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  SuppressAllDiagnostics = false;
492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ShowOverloads = Ovl_All;
502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ExtBehavior = Ext_Ignore;
512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  ErrorLimit = 0;
532a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  TemplateBacktraceLimit = 0;
542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
552a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  Reset();
562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)Diagnostic::~Diagnostic() {
592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (OwnsDiagClient)
602a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    delete Client;
612a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)void Diagnostic::setClient(DiagnosticClient *client, bool ShouldOwnClient) {
642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (OwnsDiagClient && Client)
652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    delete Client;
662a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
67c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  Client = client;
682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  OwnsDiagClient = ShouldOwnClient;
692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void Diagnostic::pushMappings(SourceLocation Loc) {
725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  DiagStateOnPushStack.push_back(GetCurDiagState());
735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)bool Diagnostic::popMappings(SourceLocation Loc) {
765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (DiagStateOnPushStack.empty())
775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return false;
78c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)
79c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  if (DiagStateOnPushStack.back() != GetCurDiagState()) {
805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // State changed at some point between push/pop.
815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
832a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  DiagStateOnPushStack.pop_back();
842a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return true;
852a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
862a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void Diagnostic::Reset() {
885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  ErrorOccurred = false;
895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  FatalErrorOccurred = false;
905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  UnrecoverableErrorOccurred = false;
915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  NumWarnings = 0;
935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  NumErrors = 0;
945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  NumErrorsSuppressed = 0;
95c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  TrapNumErrorsOccurred = 0;
96c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)  TrapNumUnrecoverableErrorsOccurred = 0;
975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  CurDiagID = ~0U;
995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Set LastDiagLevel to an "unset" state. If we set it to 'Ignored', notes
1005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // using a Diagnostic associated to a translation unit that follow
1015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // diagnostics from a Diagnostic associated to anoter t.u. will not be
1025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // displayed.
1035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  LastDiagLevel = (DiagnosticIDs::Level)-1;
1045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  DelayedDiagID = 0;
1055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1065821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Clear state related to #pragma diagnostic.
1075821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  DiagStates.clear();
1085821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  DiagStatePoints.clear();
1095821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  DiagStateOnPushStack.clear();
1105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Create a DiagState and DiagStatePoint representing diagnostic changes
1125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // through command-line.
1135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  DiagStates.push_back(DiagState());
1145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  PushDiagStatePoint(&DiagStates.back(), SourceLocation());
1155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
1165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void Diagnostic::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
1185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)                                      StringRef Arg2) {
1195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (DelayedDiagID)
1205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return;
1215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  DelayedDiagID = DiagID;
1232a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  DelayedDiagArg1 = Arg1.str();
1242a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  DelayedDiagArg2 = Arg2.str();
1252a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
1262a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1272a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)void Diagnostic::ReportDelayed() {
1282a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2;
1292a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  DelayedDiagID = 0;
1302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  DelayedDiagArg1.clear();
1312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  DelayedDiagArg2.clear();
132c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)}
1332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)Diagnostic::DiagStatePointsTy::iterator
1352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)Diagnostic::GetDiagStatePointForLoc(SourceLocation L) const {
1362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(!DiagStatePoints.empty());
1372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(DiagStatePoints.front().Loc.isInvalid() &&
1382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)         "Should have created a DiagStatePoint for command-line");
1392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  FullSourceLoc Loc(L, *SourceMgr);
1415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (Loc.isInvalid())
1425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return DiagStatePoints.end() - 1;
1435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  DiagStatePointsTy::iterator Pos = DiagStatePoints.end();
1455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
1462a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (LastStateChangePos.isValid() &&
1472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      Loc.isBeforeInTranslationUnitThan(LastStateChangePos))
1482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(),
1492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                           DiagStatePoint(0, Loc));
1502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  --Pos;
1512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return Pos;
1522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
1535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// \brief This allows the client to specify that certain
1555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// warnings are ignored.  Notes can never be mapped, errors can only be
1565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily.
1575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)///
1585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// \param The source location that this change of diagnostic state should
1595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/// take affect. It can be null if we are setting the latest state.
1605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)void Diagnostic::setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
1612a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                                      SourceLocation L) {
1622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(Diag < diag::DIAG_UPPER_LIMIT &&
1632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)         "Can only map builtin diagnostics");
1642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert((Diags->isBuiltinWarningOrExtension(Diag) ||
1652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)          (Map == diag::MAP_FATAL || Map == diag::MAP_ERROR)) &&
1662a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)         "Cannot map errors into warnings!");
1672a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  assert(!DiagStatePoints.empty());
1685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  bool isPragma = L.isValid();
1705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  FullSourceLoc Loc(L, *SourceMgr);
1715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc;
1725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Common case; setting all the diagnostics of a group in one place.
1745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (Loc.isInvalid() || Loc == LastStateChangePos) {
1755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma);
1765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return;
1775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
1785821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Another common case; modifying diagnostic state in a source location
1805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // after the previous one.
1815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if ((Loc.isValid() && LastStateChangePos.isInvalid()) ||
1825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)      LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) {
1835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // A diagnostic pragma occurred, create a new DiagState initialized with
1845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // the current one and a new DiagStatePoint to record at which location
1855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    // the new state became active.
1865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    DiagStates.push_back(*GetCurDiagState());
1875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    PushDiagStatePoint(&DiagStates.back(), Loc);
1885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    setDiagnosticMappingInternal(Diag, Map, GetCurDiagState(), true, isPragma);
1895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return;
1905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
1915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // We allow setting the diagnostic state in random source order for
1935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // completeness but it should not be actually happening in normal practice.
1945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc);
1965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  assert(Pos != DiagStatePoints.end());
1975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
1985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // Update all diagnostic states that are active after the given location.
1995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  for (DiagStatePointsTy::iterator
2005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)         I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) {
2015821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    setDiagnosticMappingInternal(Diag, Map, I->State, true, isPragma);
2025821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  }
2035821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
2045821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  // If the location corresponds to an existing point, just update its state.
2055821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)  if (Pos->Loc == Loc) {
206    setDiagnosticMappingInternal(Diag, Map, Pos->State, true, isPragma);
207    return;
208  }
209
210  // Create a new state/point and fit it into the vector of DiagStatePoints
211  // so that the vector is always ordered according to location.
212  Pos->Loc.isBeforeInTranslationUnitThan(Loc);
213  DiagStates.push_back(*Pos->State);
214  DiagState *NewState = &DiagStates.back();
215  setDiagnosticMappingInternal(Diag, Map, NewState, true, isPragma);
216  DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState,
217                                               FullSourceLoc(Loc, *SourceMgr)));
218}
219
220void Diagnostic::Report(const StoredDiagnostic &storedDiag) {
221  assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
222
223  CurDiagLoc = storedDiag.getLocation();
224  CurDiagID = storedDiag.getID();
225  NumDiagArgs = 0;
226
227  NumDiagRanges = storedDiag.range_size();
228  assert(NumDiagRanges < sizeof(DiagRanges)/sizeof(DiagRanges[0]) &&
229         "Too many arguments to diagnostic!");
230  unsigned i = 0;
231  for (StoredDiagnostic::range_iterator
232         RI = storedDiag.range_begin(),
233         RE = storedDiag.range_end(); RI != RE; ++RI)
234    DiagRanges[i++] = *RI;
235
236  NumFixItHints = storedDiag.fixit_size();
237  assert(NumFixItHints < Diagnostic::MaxFixItHints && "Too many fix-it hints!");
238  i = 0;
239  for (StoredDiagnostic::fixit_iterator
240         FI = storedDiag.fixit_begin(),
241         FE = storedDiag.fixit_end(); FI != FE; ++FI)
242    FixItHints[i++] = *FI;
243
244  assert(Client && "DiagnosticClient not set!");
245  Level DiagLevel = storedDiag.getLevel();
246  DiagnosticInfo Info(this, storedDiag.getMessage());
247  Client->HandleDiagnostic(DiagLevel, Info);
248  if (Client->IncludeInDiagnosticCounts()) {
249    if (DiagLevel == Diagnostic::Warning)
250      ++NumWarnings;
251  }
252
253  CurDiagID = ~0U;
254}
255
256void DiagnosticBuilder::FlushCounts() {
257  DiagObj->NumDiagArgs = NumArgs;
258  DiagObj->NumDiagRanges = NumRanges;
259  DiagObj->NumFixItHints = NumFixItHints;
260}
261
262bool DiagnosticBuilder::Emit() {
263  // If DiagObj is null, then its soul was stolen by the copy ctor
264  // or the user called Emit().
265  if (DiagObj == 0) return false;
266
267  // When emitting diagnostics, we set the final argument count into
268  // the Diagnostic object.
269  FlushCounts();
270
271  // Process the diagnostic, sending the accumulated information to the
272  // DiagnosticClient.
273  bool Emitted = DiagObj->ProcessDiag();
274
275  // Clear out the current diagnostic object.
276  unsigned DiagID = DiagObj->CurDiagID;
277  DiagObj->Clear();
278
279  // If there was a delayed diagnostic, emit it now.
280  if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID)
281    DiagObj->ReportDelayed();
282
283  // This diagnostic is dead.
284  DiagObj = 0;
285
286  return Emitted;
287}
288
289
290DiagnosticClient::~DiagnosticClient() {}
291
292void DiagnosticClient::HandleDiagnostic(Diagnostic::Level DiagLevel,
293                                        const DiagnosticInfo &Info) {
294  if (!IncludeInDiagnosticCounts())
295    return;
296
297  if (DiagLevel == Diagnostic::Warning)
298    ++NumWarnings;
299  else if (DiagLevel >= Diagnostic::Error)
300    ++NumErrors;
301}
302
303/// ModifierIs - Return true if the specified modifier matches specified string.
304template <std::size_t StrLen>
305static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
306                       const char (&Str)[StrLen]) {
307  return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
308}
309
310/// ScanForward - Scans forward, looking for the given character, skipping
311/// nested clauses and escaped characters.
312static const char *ScanFormat(const char *I, const char *E, char Target) {
313  unsigned Depth = 0;
314
315  for ( ; I != E; ++I) {
316    if (Depth == 0 && *I == Target) return I;
317    if (Depth != 0 && *I == '}') Depth--;
318
319    if (*I == '%') {
320      I++;
321      if (I == E) break;
322
323      // Escaped characters get implicitly skipped here.
324
325      // Format specifier.
326      if (!isdigit(*I) && !ispunct(*I)) {
327        for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
328        if (I == E) break;
329        if (*I == '{')
330          Depth++;
331      }
332    }
333  }
334  return E;
335}
336
337/// HandleSelectModifier - Handle the integer 'select' modifier.  This is used
338/// like this:  %select{foo|bar|baz}2.  This means that the integer argument
339/// "%2" has a value from 0-2.  If the value is 0, the diagnostic prints 'foo'.
340/// If the value is 1, it prints 'bar'.  If it has the value 2, it prints 'baz'.
341/// This is very useful for certain classes of variant diagnostics.
342static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
343                                 const char *Argument, unsigned ArgumentLen,
344                                 SmallVectorImpl<char> &OutStr) {
345  const char *ArgumentEnd = Argument+ArgumentLen;
346
347  // Skip over 'ValNo' |'s.
348  while (ValNo) {
349    const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
350    assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
351           " larger than the number of options in the diagnostic string!");
352    Argument = NextVal+1;  // Skip this string.
353    --ValNo;
354  }
355
356  // Get the end of the value.  This is either the } or the |.
357  const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
358
359  // Recursively format the result of the select clause into the output string.
360  DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
361}
362
363/// HandleIntegerSModifier - Handle the integer 's' modifier.  This adds the
364/// letter 's' to the string if the value is not 1.  This is used in cases like
365/// this:  "you idiot, you have %4 parameter%s4!".
366static void HandleIntegerSModifier(unsigned ValNo,
367                                   SmallVectorImpl<char> &OutStr) {
368  if (ValNo != 1)
369    OutStr.push_back('s');
370}
371
372/// HandleOrdinalModifier - Handle the integer 'ord' modifier.  This
373/// prints the ordinal form of the given integer, with 1 corresponding
374/// to the first ordinal.  Currently this is hard-coded to use the
375/// English form.
376static void HandleOrdinalModifier(unsigned ValNo,
377                                  SmallVectorImpl<char> &OutStr) {
378  assert(ValNo != 0 && "ValNo must be strictly positive!");
379
380  llvm::raw_svector_ostream Out(OutStr);
381
382  // We could use text forms for the first N ordinals, but the numeric
383  // forms are actually nicer in diagnostics because they stand out.
384  Out << ValNo;
385
386  // It is critically important that we do this perfectly for
387  // user-written sequences with over 100 elements.
388  switch (ValNo % 100) {
389  case 11:
390  case 12:
391  case 13:
392    Out << "th"; return;
393  default:
394    switch (ValNo % 10) {
395    case 1: Out << "st"; return;
396    case 2: Out << "nd"; return;
397    case 3: Out << "rd"; return;
398    default: Out << "th"; return;
399    }
400  }
401}
402
403
404/// PluralNumber - Parse an unsigned integer and advance Start.
405static unsigned PluralNumber(const char *&Start, const char *End) {
406  // Programming 101: Parse a decimal number :-)
407  unsigned Val = 0;
408  while (Start != End && *Start >= '0' && *Start <= '9') {
409    Val *= 10;
410    Val += *Start - '0';
411    ++Start;
412  }
413  return Val;
414}
415
416/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
417static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
418  if (*Start != '[') {
419    unsigned Ref = PluralNumber(Start, End);
420    return Ref == Val;
421  }
422
423  ++Start;
424  unsigned Low = PluralNumber(Start, End);
425  assert(*Start == ',' && "Bad plural expression syntax: expected ,");
426  ++Start;
427  unsigned High = PluralNumber(Start, End);
428  assert(*Start == ']' && "Bad plural expression syntax: expected )");
429  ++Start;
430  return Low <= Val && Val <= High;
431}
432
433/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
434static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
435  // Empty condition?
436  if (*Start == ':')
437    return true;
438
439  while (1) {
440    char C = *Start;
441    if (C == '%') {
442      // Modulo expression
443      ++Start;
444      unsigned Arg = PluralNumber(Start, End);
445      assert(*Start == '=' && "Bad plural expression syntax: expected =");
446      ++Start;
447      unsigned ValMod = ValNo % Arg;
448      if (TestPluralRange(ValMod, Start, End))
449        return true;
450    } else {
451      assert((C == '[' || (C >= '0' && C <= '9')) &&
452             "Bad plural expression syntax: unexpected character");
453      // Range expression
454      if (TestPluralRange(ValNo, Start, End))
455        return true;
456    }
457
458    // Scan for next or-expr part.
459    Start = std::find(Start, End, ',');
460    if (Start == End)
461      break;
462    ++Start;
463  }
464  return false;
465}
466
467/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
468/// for complex plural forms, or in languages where all plurals are complex.
469/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
470/// conditions that are tested in order, the form corresponding to the first
471/// that applies being emitted. The empty condition is always true, making the
472/// last form a default case.
473/// Conditions are simple boolean expressions, where n is the number argument.
474/// Here are the rules.
475/// condition  := expression | empty
476/// empty      :=                             -> always true
477/// expression := numeric [',' expression]    -> logical or
478/// numeric    := range                       -> true if n in range
479///             | '%' number '=' range        -> true if n % number in range
480/// range      := number
481///             | '[' number ',' number ']'   -> ranges are inclusive both ends
482///
483/// Here are some examples from the GNU gettext manual written in this form:
484/// English:
485/// {1:form0|:form1}
486/// Latvian:
487/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
488/// Gaeilge:
489/// {1:form0|2:form1|:form2}
490/// Romanian:
491/// {1:form0|0,%100=[1,19]:form1|:form2}
492/// Lithuanian:
493/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
494/// Russian (requires repeated form):
495/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
496/// Slovak
497/// {1:form0|[2,4]:form1|:form2}
498/// Polish (requires repeated form):
499/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
500static void HandlePluralModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
501                                 const char *Argument, unsigned ArgumentLen,
502                                 SmallVectorImpl<char> &OutStr) {
503  const char *ArgumentEnd = Argument + ArgumentLen;
504  while (1) {
505    assert(Argument < ArgumentEnd && "Plural expression didn't match.");
506    const char *ExprEnd = Argument;
507    while (*ExprEnd != ':') {
508      assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
509      ++ExprEnd;
510    }
511    if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
512      Argument = ExprEnd + 1;
513      ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
514
515      // Recursively format the result of the plural clause into the
516      // output string.
517      DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
518      return;
519    }
520    Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
521  }
522}
523
524
525/// FormatDiagnostic - Format this diagnostic into a string, substituting the
526/// formal arguments into the %0 slots.  The result is appended onto the Str
527/// array.
528void DiagnosticInfo::
529FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
530  if (!StoredDiagMessage.empty()) {
531    OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
532    return;
533  }
534
535  StringRef Diag =
536    getDiags()->getDiagnosticIDs()->getDescription(getID());
537
538  FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
539}
540
541void DiagnosticInfo::
542FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
543                 SmallVectorImpl<char> &OutStr) const {
544
545  /// FormattedArgs - Keep track of all of the arguments formatted by
546  /// ConvertArgToString and pass them into subsequent calls to
547  /// ConvertArgToString, allowing the implementation to avoid redundancies in
548  /// obvious cases.
549  SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
550
551  /// QualTypeVals - Pass a vector of arrays so that QualType names can be
552  /// compared to see if more information is needed to be printed.
553  SmallVector<intptr_t, 2> QualTypeVals;
554  for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
555    if (getArgKind(i) == Diagnostic::ak_qualtype)
556      QualTypeVals.push_back(getRawArg(i));
557
558  while (DiagStr != DiagEnd) {
559    if (DiagStr[0] != '%') {
560      // Append non-%0 substrings to Str if we have one.
561      const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
562      OutStr.append(DiagStr, StrEnd);
563      DiagStr = StrEnd;
564      continue;
565    } else if (ispunct(DiagStr[1])) {
566      OutStr.push_back(DiagStr[1]);  // %% -> %.
567      DiagStr += 2;
568      continue;
569    }
570
571    // Skip the %.
572    ++DiagStr;
573
574    // This must be a placeholder for a diagnostic argument.  The format for a
575    // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
576    // The digit is a number from 0-9 indicating which argument this comes from.
577    // The modifier is a string of digits from the set [-a-z]+, arguments is a
578    // brace enclosed string.
579    const char *Modifier = 0, *Argument = 0;
580    unsigned ModifierLen = 0, ArgumentLen = 0;
581
582    // Check to see if we have a modifier.  If so eat it.
583    if (!isdigit(DiagStr[0])) {
584      Modifier = DiagStr;
585      while (DiagStr[0] == '-' ||
586             (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
587        ++DiagStr;
588      ModifierLen = DiagStr-Modifier;
589
590      // If we have an argument, get it next.
591      if (DiagStr[0] == '{') {
592        ++DiagStr; // Skip {.
593        Argument = DiagStr;
594
595        DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
596        assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
597        ArgumentLen = DiagStr-Argument;
598        ++DiagStr;  // Skip }.
599      }
600    }
601
602    assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
603    unsigned ArgNo = *DiagStr++ - '0';
604
605    Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
606
607    switch (Kind) {
608    // ---- STRINGS ----
609    case Diagnostic::ak_std_string: {
610      const std::string &S = getArgStdStr(ArgNo);
611      assert(ModifierLen == 0 && "No modifiers for strings yet");
612      OutStr.append(S.begin(), S.end());
613      break;
614    }
615    case Diagnostic::ak_c_string: {
616      const char *S = getArgCStr(ArgNo);
617      assert(ModifierLen == 0 && "No modifiers for strings yet");
618
619      // Don't crash if get passed a null pointer by accident.
620      if (!S)
621        S = "(null)";
622
623      OutStr.append(S, S + strlen(S));
624      break;
625    }
626    // ---- INTEGERS ----
627    case Diagnostic::ak_sint: {
628      int Val = getArgSInt(ArgNo);
629
630      if (ModifierIs(Modifier, ModifierLen, "select")) {
631        HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
632                             OutStr);
633      } else if (ModifierIs(Modifier, ModifierLen, "s")) {
634        HandleIntegerSModifier(Val, OutStr);
635      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
636        HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
637                             OutStr);
638      } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
639        HandleOrdinalModifier((unsigned)Val, OutStr);
640      } else {
641        assert(ModifierLen == 0 && "Unknown integer modifier");
642        llvm::raw_svector_ostream(OutStr) << Val;
643      }
644      break;
645    }
646    case Diagnostic::ak_uint: {
647      unsigned Val = getArgUInt(ArgNo);
648
649      if (ModifierIs(Modifier, ModifierLen, "select")) {
650        HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
651      } else if (ModifierIs(Modifier, ModifierLen, "s")) {
652        HandleIntegerSModifier(Val, OutStr);
653      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
654        HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
655                             OutStr);
656      } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
657        HandleOrdinalModifier(Val, OutStr);
658      } else {
659        assert(ModifierLen == 0 && "Unknown integer modifier");
660        llvm::raw_svector_ostream(OutStr) << Val;
661      }
662      break;
663    }
664    // ---- NAMES and TYPES ----
665    case Diagnostic::ak_identifierinfo: {
666      const IdentifierInfo *II = getArgIdentifier(ArgNo);
667      assert(ModifierLen == 0 && "No modifiers for strings yet");
668
669      // Don't crash if get passed a null pointer by accident.
670      if (!II) {
671        const char *S = "(null)";
672        OutStr.append(S, S + strlen(S));
673        continue;
674      }
675
676      llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
677      break;
678    }
679    case Diagnostic::ak_qualtype:
680    case Diagnostic::ak_declarationname:
681    case Diagnostic::ak_nameddecl:
682    case Diagnostic::ak_nestednamespec:
683    case Diagnostic::ak_declcontext:
684      getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
685                                     Modifier, ModifierLen,
686                                     Argument, ArgumentLen,
687                                     FormattedArgs.data(), FormattedArgs.size(),
688                                     OutStr, QualTypeVals);
689      break;
690    }
691
692    // Remember this argument info for subsequent formatting operations.  Turn
693    // std::strings into a null terminated string to make it be the same case as
694    // all the other ones.
695    if (Kind != Diagnostic::ak_std_string)
696      FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
697    else
698      FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
699                                        (intptr_t)getArgStdStr(ArgNo).c_str()));
700
701  }
702}
703
704StoredDiagnostic::StoredDiagnostic() { }
705
706StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, unsigned ID,
707                                   StringRef Message)
708  : ID(ID), Level(Level), Loc(), Message(Message) { }
709
710StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level,
711                                   const DiagnosticInfo &Info)
712  : ID(Info.getID()), Level(Level)
713{
714  assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
715       "Valid source location without setting a source manager for diagnostic");
716  if (Info.getLocation().isValid())
717    Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
718  llvm::SmallString<64> Message;
719  Info.FormatDiagnostic(Message);
720  this->Message.assign(Message.begin(), Message.end());
721
722  Ranges.reserve(Info.getNumRanges());
723  for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I)
724    Ranges.push_back(Info.getRange(I));
725
726  FixIts.reserve(Info.getNumFixItHints());
727  for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I)
728    FixIts.push_back(Info.getFixItHint(I));
729}
730
731StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, unsigned ID,
732                                   StringRef Message, FullSourceLoc Loc,
733                                   ArrayRef<CharSourceRange> Ranges,
734                                   ArrayRef<FixItHint> Fixits)
735  : ID(ID), Level(Level), Loc(Loc), Message(Message)
736{
737  this->Ranges.assign(Ranges.begin(), Ranges.end());
738  this->FixIts.assign(FixIts.begin(), FixIts.end());
739}
740
741StoredDiagnostic::~StoredDiagnostic() { }
742
743/// IncludeInDiagnosticCounts - This method (whose default implementation
744///  returns true) indicates whether the diagnostics handled by this
745///  DiagnosticClient should be included in the number of diagnostics
746///  reported by Diagnostic.
747bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }
748
749PartialDiagnostic::StorageAllocator::StorageAllocator() {
750  for (unsigned I = 0; I != NumCached; ++I)
751    FreeList[I] = Cached + I;
752  NumFreeListEntries = NumCached;
753}
754
755PartialDiagnostic::StorageAllocator::~StorageAllocator() {
756  // Don't assert if we are in a CrashRecovery context, as this
757  // invariant may be invalidated during a crash.
758  assert((NumFreeListEntries == NumCached || llvm::CrashRecoveryContext::isRecoveringFromCrash()) && "A partial is on the lamb");
759}
760