Diagnostic.cpp revision 909c182f6a0e6169475eef6a71add14555b6162c
15c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)//===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===//
25c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)//
35c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)//                     The LLVM Compiler Infrastructure
45c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)//
55c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)// This file is distributed under the University of Illinois Open Source
65c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)// License. See LICENSE.TXT for details.
75c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)//
85c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)//===----------------------------------------------------------------------===//
95c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)//
105c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)//  This file implements the Diagnostic-related interfaces.
115c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)//
125c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)//===----------------------------------------------------------------------===//
135c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)
145c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)#include "clang/Basic/Diagnostic.h"
155c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)
165c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)#include "clang/Lex/LexDiagnostic.h"
175c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)#include "clang/Parse/ParseDiagnostic.h"
185c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)#include "clang/AST/ASTDiagnostic.h"
195c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)#include "clang/Sema/SemaDiagnostic.h"
205c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)#include "clang/Frontend/FrontendDiagnostic.h"
215c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)#include "clang/Analysis/AnalysisDiagnostic.h"
225c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)#include "clang/Driver/DriverDiagnostic.h"
235c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)
245c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)#include "clang/Basic/IdentifierTable.h"
255c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)#include "clang/Basic/SourceLocation.h"
265c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)#include "llvm/ADT/SmallVector.h"
2753e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)#include "llvm/ADT/StringExtras.h"
288abfc5808a4e34d6e03867af8bc440dee641886fTorne (Richard Coles)#include "llvm/Support/raw_ostream.h"
2953e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)#include <vector>
3009380295ba73501a205346becac22c6978e4671dTorne (Richard Coles)#include <map>
3109380295ba73501a205346becac22c6978e4671dTorne (Richard Coles)#include <cstring>
32e1f1df5f01594c0e62e751e4b46e779b85c2faa5Torne (Richard Coles)using namespace clang;
3353e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)
3453e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)//===----------------------------------------------------------------------===//
355267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)// Builtin Diagnostic information
3653e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)//===----------------------------------------------------------------------===//
3753e740f4a82e17f3ae59772501622dc354e42336Torne (Richard Coles)
385c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)// Diagnostic classes.
39c1847b1379d12d0e05df27436bf19a9b1bf12deaTorne (Richard Coles)enum {
405c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)  CLASS_NOTE       = 0x01,
415267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  CLASS_WARNING    = 0x02,
425c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)  CLASS_EXTENSION  = 0x03,
435c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)  CLASS_ERROR      = 0x04
445267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)};
455c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)
465c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)struct StaticDiagInfoRec {
475c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)  unsigned short DiagID;
485c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)  unsigned Mapping : 3;
495267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  unsigned Class : 3;
505267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  bool SFINAE : 1;
515267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  const char *Description;
525267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  const char *OptionGroup;
535267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
545267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  bool operator<(const StaticDiagInfoRec &RHS) const {
555267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    return DiagID < RHS.DiagID;
565267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  }
575267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  bool operator>(const StaticDiagInfoRec &RHS) const {
5809380295ba73501a205346becac22c6978e4671dTorne (Richard Coles)    return DiagID > RHS.DiagID;
59323480423219ecd77329f8326dc5e0e3b50926d4Torne (Richard Coles)  }
6093ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)};
61323480423219ecd77329f8326dc5e0e3b50926d4Torne (Richard Coles)
625267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)static const StaticDiagInfoRec StaticDiagInfo[] = {
6393ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)#define DIAG(ENUM,CLASS,DEFAULT_MAPPING,DESC,GROUP,SFINAE)    \
645267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  { diag::ENUM, DEFAULT_MAPPING, CLASS, SFINAE, DESC, GROUP },
655267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "clang/Basic/DiagnosticCommonKinds.inc"
665267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "clang/Basic/DiagnosticDriverKinds.inc"
675267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "clang/Basic/DiagnosticFrontendKinds.inc"
685267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)#include "clang/Basic/DiagnosticLexKinds.inc"
693c9e4aeaee9f9b0a9a814da07bcb33319c7ea363Ben Murdoch#include "clang/Basic/DiagnosticParseKinds.inc"
70323480423219ecd77329f8326dc5e0e3b50926d4Torne (Richard Coles)#include "clang/Basic/DiagnosticASTKinds.inc"
7193ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)#include "clang/Basic/DiagnosticSemaKinds.inc"
7293ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)#include "clang/Basic/DiagnosticAnalysisKinds.inc"
7393ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)  { 0, 0, 0, 0, 0, 0}
7493ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)};
7593ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)#undef DIAG
7693ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)
7793ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)/// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified DiagID,
7893ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)/// or null if the ID is invalid.
7993ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) {
8093ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)  unsigned NumDiagEntries = sizeof(StaticDiagInfo)/sizeof(StaticDiagInfo[0])-1;
8193ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)
8293ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)  // If assertions are enabled, verify that the StaticDiagInfo array is sorted.
8393ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)#ifndef NDEBUG
8493ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)  static bool IsFirst = true;
8593ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)  if (IsFirst) {
8693ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)    for (unsigned i = 1; i != NumDiagEntries; ++i) {
8793ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)      assert(StaticDiagInfo[i-1].DiagID != StaticDiagInfo[i].DiagID &&
8809380295ba73501a205346becac22c6978e4671dTorne (Richard Coles)             "Diag ID conflict, the enums at the start of clang::diag (in "
8909380295ba73501a205346becac22c6978e4671dTorne (Richard Coles)             "Diagnostic.h) probably need to be increased");
9093ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)
9193ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)      assert(StaticDiagInfo[i-1] < StaticDiagInfo[i] &&
9293ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)             "Improperly sorted diag info");
9393ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)    }
9493ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)    IsFirst = false;
9593ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)  }
9693ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)#endif
9793ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)
9893ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)  // Search the diagnostic table with a binary search.
9993ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)  StaticDiagInfoRec Find = { DiagID, 0, 0, 0, 0, 0 };
10093ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)
10193ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)  const StaticDiagInfoRec *Found =
10293ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)    std::lower_bound(StaticDiagInfo, StaticDiagInfo + NumDiagEntries, Find);
10393ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)  if (Found == StaticDiagInfo + NumDiagEntries ||
10493ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)      Found->DiagID != DiagID)
105d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles)    return 0;
1068abfc5808a4e34d6e03867af8bc440dee641886fTorne (Richard Coles)
10793ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)  return Found;
108323480423219ecd77329f8326dc5e0e3b50926d4Torne (Richard Coles)}
10993ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)
11093ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)static unsigned GetDefaultDiagMapping(unsigned DiagID) {
11193ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
11293ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)    return Info->Mapping;
11393ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)  return diag::MAP_FATAL;
11493ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)}
11593ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)
11693ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)/// getWarningOptionForDiag - Return the lowest-level warning option that
11793ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)/// enables the specified diagnostic.  If there is no -Wfoo flag that controls
1187242dc3dbeb210b5e876a3c42d1ec1a667fc621aPrimiano Tucci/// the diagnostic, this returns null.
1195c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)const char *Diagnostic::getWarningOptionForDiag(unsigned DiagID) {
120323480423219ecd77329f8326dc5e0e3b50926d4Torne (Richard Coles)  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
1215c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)    return Info->OptionGroup;
1225c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)  return 0;
1235c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)}
124a854de003a23bf3c7f95ec0f8154ada64092ff5cTorne (Richard Coles)
12593ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)bool Diagnostic::isBuiltinSFINAEDiag(unsigned DiagID) {
12693ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
12793ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)    return Info->SFINAE && Info->Class == CLASS_ERROR;
1285c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)  return false;
129a854de003a23bf3c7f95ec0f8154ada64092ff5cTorne (Richard Coles)}
1305c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)
1315c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)/// getDiagClass - Return the class field of the diagnostic.
1325c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)///
13343e7502580f146aa5b3db8267ba6dbb5c733a489Torne (Richard Coles)static unsigned getBuiltinDiagClass(unsigned DiagID) {
13443e7502580f146aa5b3db8267ba6dbb5c733a489Torne (Richard Coles)  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
1355c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)    return Info->Class;
136d5428f32f5d1719f774f62e19147104ca245a3abTorne (Richard Coles)  return ~0U;
137d5428f32f5d1719f774f62e19147104ca245a3abTorne (Richard Coles)}
1385267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)
139521d96ec04ace82590870fb04353ec4f82bb150fTorne (Richard Coles)//===----------------------------------------------------------------------===//
1405c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)// Custom Diagnostic information
1415c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)//===----------------------------------------------------------------------===//
1425c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)
14309380295ba73501a205346becac22c6978e4671dTorne (Richard Coles)namespace clang {
1445267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)  namespace diag {
1455267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)    class CustomDiagInfo {
146d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles)      typedef std::pair<Diagnostic::Level, std::string> DiagDesc;
147d6cdb82654e8f3343a693ca752d5c4cee0324e17Torne (Richard Coles)      std::vector<DiagDesc> DiagInfo;
1485c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)      std::map<DiagDesc, unsigned> DiagIDs;
1495c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)    public:
1505c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)
1513c9e4aeaee9f9b0a9a814da07bcb33319c7ea363Ben Murdoch      /// getDescription - Return the description of the specified custom
15209380295ba73501a205346becac22c6978e4671dTorne (Richard Coles)      /// diagnostic.
1535c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)      const char *getDescription(unsigned DiagID) const {
1545c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)        assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
15593ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)               "Invalid diagnosic ID");
15693ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)        return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second.c_str();
15793ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)      }
15893ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)
15909380295ba73501a205346becac22c6978e4671dTorne (Richard Coles)      /// getLevel - Return the level of the specified custom diagnostic.
1605267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)      Diagnostic::Level getLevel(unsigned DiagID) const {
1615267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)        assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() &&
16209380295ba73501a205346becac22c6978e4671dTorne (Richard Coles)               "Invalid diagnosic ID");
16393ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)        return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first;
16443e7502580f146aa5b3db8267ba6dbb5c733a489Torne (Richard Coles)      }
16543e7502580f146aa5b3db8267ba6dbb5c733a489Torne (Richard Coles)
16643e7502580f146aa5b3db8267ba6dbb5c733a489Torne (Richard Coles)      unsigned getOrCreateDiagID(Diagnostic::Level L, llvm::StringRef Message,
16743e7502580f146aa5b3db8267ba6dbb5c733a489Torne (Richard Coles)                                 Diagnostic &Diags) {
168323480423219ecd77329f8326dc5e0e3b50926d4Torne (Richard Coles)        DiagDesc D(L, Message);
169323480423219ecd77329f8326dc5e0e3b50926d4Torne (Richard Coles)        // Check to see if it already exists.
1705c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)        std::map<DiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(D);
171197021e6b966cfb06891637935ef33fff06433d1Ben Murdoch        if (I != DiagIDs.end() && I->first == D)
172926b001d589ce2f10facb93dd4b87578ea35a855Torne (Richard Coles)          return I->second;
1735c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)
1745267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)        // If not, assign a new ID.
1755267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)        unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT;
1765267f701546148b83dfbe1d151cb184385bb5c22Torne (Richard Coles)        DiagIDs.insert(std::make_pair(D, ID));
17793ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)        DiagInfo.push_back(D);
1785c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)        return ID;
1795c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)      }
1805c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)    };
18193ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)
1825c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)  } // end diag namespace
1835c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)} // end clang namespace
18493ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)
18543e7502580f146aa5b3db8267ba6dbb5c733a489Torne (Richard Coles)
18643e7502580f146aa5b3db8267ba6dbb5c733a489Torne (Richard Coles)//===----------------------------------------------------------------------===//
18793ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)// Common Diagnostic implementation
18893ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)//===----------------------------------------------------------------------===//
18993ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)
19009380295ba73501a205346becac22c6978e4671dTorne (Richard Coles)static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT,
1915c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)                               const char *Modifier, unsigned ML,
19293ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)                               const char *Argument, unsigned ArgLen,
193926b001d589ce2f10facb93dd4b87578ea35a855Torne (Richard Coles)                               const Diagnostic::ArgumentValue *PrevArgs,
194926b001d589ce2f10facb93dd4b87578ea35a855Torne (Richard Coles)                               unsigned NumPrevArgs,
195926b001d589ce2f10facb93dd4b87578ea35a855Torne (Richard Coles)                               llvm::SmallVectorImpl<char> &Output,
196926b001d589ce2f10facb93dd4b87578ea35a855Torne (Richard Coles)                               void *Cookie) {
197926b001d589ce2f10facb93dd4b87578ea35a855Torne (Richard Coles)  const char *Str = "<can't format argument>";
198926b001d589ce2f10facb93dd4b87578ea35a855Torne (Richard Coles)  Output.append(Str, Str+strlen(Str));
1995c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)}
2005c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)
20151b2906e11752df6c18351cf520e30522d3b53a1Torne (Richard Coles)
2025c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)Diagnostic::Diagnostic(DiagnosticClient *client) : Client(client) {
203323480423219ecd77329f8326dc5e0e3b50926d4Torne (Richard Coles)  AllExtensionsSilenced = 0;
2045c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)  IgnoreAllWarnings = false;
2055c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)  WarningsAsErrors = false;
2065c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)  ErrorsAsFatal = false;
2075c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)  SuppressSystemWarnings = false;
208323480423219ecd77329f8326dc5e0e3b50926d4Torne (Richard Coles)  SuppressAllDiagnostics = false;
20943e7502580f146aa5b3db8267ba6dbb5c733a489Torne (Richard Coles)  ExtBehavior = Ext_Ignore;
2105c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)
21193ac45cfc74041c8ae536ce58a9534d46db2024eTorne (Richard Coles)  ErrorOccurred = false;
2125c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)  FatalErrorOccurred = false;
2135c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)  NumDiagnostics = 0;
2145c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)
2155c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)  NumErrors = 0;
2167242dc3dbeb210b5e876a3c42d1ec1a667fc621aPrimiano Tucci  CustomDiagInfo = 0;
2175c87bf8b86a7c82ef50fb7a89697d8e02e2553beTorne (Richard Coles)  CurDiagID = ~0U;
2187242dc3dbeb210b5e876a3c42d1ec1a667fc621aPrimiano Tucci  LastDiagLevel = Ignored;
219
220  ArgToStringFn = DummyArgToStringFn;
221  ArgToStringCookie = 0;
222
223  // Set all mappings to 'unset'.
224  DiagMappings BlankDiags(diag::DIAG_UPPER_LIMIT/2, 0);
225  DiagMappingsStack.push_back(BlankDiags);
226}
227
228Diagnostic::~Diagnostic() {
229  delete CustomDiagInfo;
230}
231
232
233void Diagnostic::pushMappings() {
234  // Avoids undefined behavior when the stack has to resize.
235  DiagMappingsStack.reserve(DiagMappingsStack.size() + 1);
236  DiagMappingsStack.push_back(DiagMappingsStack.back());
237}
238
239bool Diagnostic::popMappings() {
240  if (DiagMappingsStack.size() == 1)
241    return false;
242
243  DiagMappingsStack.pop_back();
244  return true;
245}
246
247/// getCustomDiagID - Return an ID for a diagnostic with the specified message
248/// and level.  If this is the first request for this diagnosic, it is
249/// registered and created, otherwise the existing ID is returned.
250unsigned Diagnostic::getCustomDiagID(Level L, llvm::StringRef Message) {
251  if (CustomDiagInfo == 0)
252    CustomDiagInfo = new diag::CustomDiagInfo();
253  return CustomDiagInfo->getOrCreateDiagID(L, Message, *this);
254}
255
256
257/// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic
258/// level of the specified diagnostic ID is a Warning or Extension.
259/// This only works on builtin diagnostics, not custom ones, and is not legal to
260/// call on NOTEs.
261bool Diagnostic::isBuiltinWarningOrExtension(unsigned DiagID) {
262  return DiagID < diag::DIAG_UPPER_LIMIT &&
263         getBuiltinDiagClass(DiagID) != CLASS_ERROR;
264}
265
266/// \brief Determine whether the given built-in diagnostic ID is a
267/// Note.
268bool Diagnostic::isBuiltinNote(unsigned DiagID) {
269  return DiagID < diag::DIAG_UPPER_LIMIT &&
270    getBuiltinDiagClass(DiagID) == CLASS_NOTE;
271}
272
273/// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic
274/// ID is for an extension of some sort.
275///
276bool Diagnostic::isBuiltinExtensionDiag(unsigned DiagID) {
277  return DiagID < diag::DIAG_UPPER_LIMIT &&
278         getBuiltinDiagClass(DiagID) == CLASS_EXTENSION;
279}
280
281
282/// getDescription - Given a diagnostic ID, return a description of the
283/// issue.
284const char *Diagnostic::getDescription(unsigned DiagID) const {
285  if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID))
286    return Info->Description;
287  return CustomDiagInfo->getDescription(DiagID);
288}
289
290/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
291/// object, classify the specified diagnostic ID into a Level, consumable by
292/// the DiagnosticClient.
293Diagnostic::Level Diagnostic::getDiagnosticLevel(unsigned DiagID) const {
294  // Handle custom diagnostics, which cannot be mapped.
295  if (DiagID >= diag::DIAG_UPPER_LIMIT)
296    return CustomDiagInfo->getLevel(DiagID);
297
298  unsigned DiagClass = getBuiltinDiagClass(DiagID);
299  assert(DiagClass != CLASS_NOTE && "Cannot get diagnostic level of a note!");
300  return getDiagnosticLevel(DiagID, DiagClass);
301}
302
303/// getDiagnosticLevel - Based on the way the client configured the Diagnostic
304/// object, classify the specified diagnostic ID into a Level, consumable by
305/// the DiagnosticClient.
306Diagnostic::Level
307Diagnostic::getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const {
308  // Specific non-error diagnostics may be mapped to various levels from ignored
309  // to error.  Errors can only be mapped to fatal.
310  Diagnostic::Level Result = Diagnostic::Fatal;
311
312  // Get the mapping information, if unset, compute it lazily.
313  unsigned MappingInfo = getDiagnosticMappingInfo((diag::kind)DiagID);
314  if (MappingInfo == 0) {
315    MappingInfo = GetDefaultDiagMapping(DiagID);
316    setDiagnosticMappingInternal(DiagID, MappingInfo, false);
317  }
318
319  switch (MappingInfo & 7) {
320  default: assert(0 && "Unknown mapping!");
321  case diag::MAP_IGNORE:
322    // Ignore this, unless this is an extension diagnostic and we're mapping
323    // them onto warnings or errors.
324    if (!isBuiltinExtensionDiag(DiagID) ||  // Not an extension
325        ExtBehavior == Ext_Ignore ||        // Extensions ignored anyway
326        (MappingInfo & 8) != 0)             // User explicitly mapped it.
327      return Diagnostic::Ignored;
328    Result = Diagnostic::Warning;
329    if (ExtBehavior == Ext_Error) Result = Diagnostic::Error;
330    if (Result == Diagnostic::Error && ErrorsAsFatal)
331      Result = Diagnostic::Fatal;
332    break;
333  case diag::MAP_ERROR:
334    Result = Diagnostic::Error;
335    if (ErrorsAsFatal)
336      Result = Diagnostic::Fatal;
337    break;
338  case diag::MAP_FATAL:
339    Result = Diagnostic::Fatal;
340    break;
341  case diag::MAP_WARNING:
342    // If warnings are globally mapped to ignore or error, do it.
343    if (IgnoreAllWarnings)
344      return Diagnostic::Ignored;
345
346    Result = Diagnostic::Warning;
347
348    // If this is an extension diagnostic and we're in -pedantic-error mode, and
349    // if the user didn't explicitly map it, upgrade to an error.
350    if (ExtBehavior == Ext_Error &&
351        (MappingInfo & 8) == 0 &&
352        isBuiltinExtensionDiag(DiagID))
353      Result = Diagnostic::Error;
354
355    if (WarningsAsErrors)
356      Result = Diagnostic::Error;
357    if (Result == Diagnostic::Error && ErrorsAsFatal)
358      Result = Diagnostic::Fatal;
359    break;
360
361  case diag::MAP_WARNING_NO_WERROR:
362    // Diagnostics specified with -Wno-error=foo should be set to warnings, but
363    // not be adjusted by -Werror or -pedantic-errors.
364    Result = Diagnostic::Warning;
365
366    // If warnings are globally mapped to ignore or error, do it.
367    if (IgnoreAllWarnings)
368      return Diagnostic::Ignored;
369
370    break;
371
372  case diag::MAP_ERROR_NO_WFATAL:
373    // Diagnostics specified as -Wno-fatal-error=foo should be errors, but
374    // unaffected by -Wfatal-errors.
375    Result = Diagnostic::Error;
376    break;
377  }
378
379  // Okay, we're about to return this as a "diagnostic to emit" one last check:
380  // if this is any sort of extension warning, and if we're in an __extension__
381  // block, silence it.
382  if (AllExtensionsSilenced && isBuiltinExtensionDiag(DiagID))
383    return Diagnostic::Ignored;
384
385  return Result;
386}
387
388struct WarningOption {
389  const char  *Name;
390  const short *Members;
391  const char  *SubGroups;
392};
393
394#define GET_DIAG_ARRAYS
395#include "clang/Basic/DiagnosticGroups.inc"
396#undef GET_DIAG_ARRAYS
397
398// Second the table of options, sorted by name for fast binary lookup.
399static const WarningOption OptionTable[] = {
400#define GET_DIAG_TABLE
401#include "clang/Basic/DiagnosticGroups.inc"
402#undef GET_DIAG_TABLE
403};
404static const size_t OptionTableSize =
405sizeof(OptionTable) / sizeof(OptionTable[0]);
406
407static bool WarningOptionCompare(const WarningOption &LHS,
408                                 const WarningOption &RHS) {
409  return strcmp(LHS.Name, RHS.Name) < 0;
410}
411
412static void MapGroupMembers(const WarningOption *Group, diag::Mapping Mapping,
413                            Diagnostic &Diags) {
414  // Option exists, poke all the members of its diagnostic set.
415  if (const short *Member = Group->Members) {
416    for (; *Member != -1; ++Member)
417      Diags.setDiagnosticMapping(*Member, Mapping);
418  }
419
420  // Enable/disable all subgroups along with this one.
421  if (const char *SubGroups = Group->SubGroups) {
422    for (; *SubGroups != (char)-1; ++SubGroups)
423      MapGroupMembers(&OptionTable[(unsigned char)*SubGroups], Mapping, Diags);
424  }
425}
426
427/// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g.
428/// "unknown-pragmas" to have the specified mapping.  This returns true and
429/// ignores the request if "Group" was unknown, false otherwise.
430bool Diagnostic::setDiagnosticGroupMapping(const char *Group,
431                                           diag::Mapping Map) {
432
433  WarningOption Key = { Group, 0, 0 };
434  const WarningOption *Found =
435  std::lower_bound(OptionTable, OptionTable + OptionTableSize, Key,
436                   WarningOptionCompare);
437  if (Found == OptionTable + OptionTableSize ||
438      strcmp(Found->Name, Group) != 0)
439    return true;  // Option not found.
440
441  MapGroupMembers(Found, Map, *this);
442  return false;
443}
444
445
446/// ProcessDiag - This is the method used to report a diagnostic that is
447/// finally fully formed.
448bool Diagnostic::ProcessDiag() {
449  DiagnosticInfo Info(this);
450
451  if (SuppressAllDiagnostics)
452    return false;
453
454  // Figure out the diagnostic level of this message.
455  Diagnostic::Level DiagLevel;
456  unsigned DiagID = Info.getID();
457
458  // ShouldEmitInSystemHeader - True if this diagnostic should be produced even
459  // in a system header.
460  bool ShouldEmitInSystemHeader;
461
462  if (DiagID >= diag::DIAG_UPPER_LIMIT) {
463    // Handle custom diagnostics, which cannot be mapped.
464    DiagLevel = CustomDiagInfo->getLevel(DiagID);
465
466    // Custom diagnostics always are emitted in system headers.
467    ShouldEmitInSystemHeader = true;
468  } else {
469    // Get the class of the diagnostic.  If this is a NOTE, map it onto whatever
470    // the diagnostic level was for the previous diagnostic so that it is
471    // filtered the same as the previous diagnostic.
472    unsigned DiagClass = getBuiltinDiagClass(DiagID);
473    if (DiagClass == CLASS_NOTE) {
474      DiagLevel = Diagnostic::Note;
475      ShouldEmitInSystemHeader = false;  // extra consideration is needed
476    } else {
477      // If this is not an error and we are in a system header, we ignore it.
478      // Check the original Diag ID here, because we also want to ignore
479      // extensions and warnings in -Werror and -pedantic-errors modes, which
480      // *map* warnings/extensions to errors.
481      ShouldEmitInSystemHeader = DiagClass == CLASS_ERROR;
482
483      DiagLevel = getDiagnosticLevel(DiagID, DiagClass);
484    }
485  }
486
487  if (DiagLevel != Diagnostic::Note) {
488    // Record that a fatal error occurred only when we see a second
489    // non-note diagnostic. This allows notes to be attached to the
490    // fatal error, but suppresses any diagnostics that follow those
491    // notes.
492    if (LastDiagLevel == Diagnostic::Fatal)
493      FatalErrorOccurred = true;
494
495    LastDiagLevel = DiagLevel;
496  }
497
498  // If a fatal error has already been emitted, silence all subsequent
499  // diagnostics.
500  if (FatalErrorOccurred)
501    return false;
502
503  // If the client doesn't care about this message, don't issue it.  If this is
504  // a note and the last real diagnostic was ignored, ignore it too.
505  if (DiagLevel == Diagnostic::Ignored ||
506      (DiagLevel == Diagnostic::Note && LastDiagLevel == Diagnostic::Ignored))
507    return false;
508
509  // If this diagnostic is in a system header and is not a clang error, suppress
510  // it.
511  if (SuppressSystemWarnings && !ShouldEmitInSystemHeader &&
512      Info.getLocation().isValid() &&
513      Info.getLocation().getSpellingLoc().isInSystemHeader() &&
514      (DiagLevel != Diagnostic::Note || LastDiagLevel == Diagnostic::Ignored)) {
515    LastDiagLevel = Diagnostic::Ignored;
516    return false;
517  }
518
519  if (DiagLevel >= Diagnostic::Error) {
520    ErrorOccurred = true;
521    ++NumErrors;
522  }
523
524  // Finally, report it.
525  Client->HandleDiagnostic(DiagLevel, Info);
526  if (Client->IncludeInDiagnosticCounts()) ++NumDiagnostics;
527
528  CurDiagID = ~0U;
529
530  return true;
531}
532
533
534DiagnosticClient::~DiagnosticClient() {}
535
536
537/// ModifierIs - Return true if the specified modifier matches specified string.
538template <std::size_t StrLen>
539static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
540                       const char (&Str)[StrLen]) {
541  return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
542}
543
544/// ScanForward - Scans forward, looking for the given character, skipping
545/// nested clauses and escaped characters.
546static const char *ScanFormat(const char *I, const char *E, char Target) {
547  unsigned Depth = 0;
548
549  for ( ; I != E; ++I) {
550    if (Depth == 0 && *I == Target) return I;
551    if (Depth != 0 && *I == '}') Depth--;
552
553    if (*I == '%') {
554      I++;
555      if (I == E) break;
556
557      // Escaped characters get implicitly skipped here.
558
559      // Format specifier.
560      if (!isdigit(*I) && !ispunct(*I)) {
561        for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ;
562        if (I == E) break;
563        if (*I == '{')
564          Depth++;
565      }
566    }
567  }
568  return E;
569}
570
571/// HandleSelectModifier - Handle the integer 'select' modifier.  This is used
572/// like this:  %select{foo|bar|baz}2.  This means that the integer argument
573/// "%2" has a value from 0-2.  If the value is 0, the diagnostic prints 'foo'.
574/// If the value is 1, it prints 'bar'.  If it has the value 2, it prints 'baz'.
575/// This is very useful for certain classes of variant diagnostics.
576static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo,
577                                 const char *Argument, unsigned ArgumentLen,
578                                 llvm::SmallVectorImpl<char> &OutStr) {
579  const char *ArgumentEnd = Argument+ArgumentLen;
580
581  // Skip over 'ValNo' |'s.
582  while (ValNo) {
583    const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
584    assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
585           " larger than the number of options in the diagnostic string!");
586    Argument = NextVal+1;  // Skip this string.
587    --ValNo;
588  }
589
590  // Get the end of the value.  This is either the } or the |.
591  const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
592
593  // Recursively format the result of the select clause into the output string.
594  DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
595}
596
597/// HandleIntegerSModifier - Handle the integer 's' modifier.  This adds the
598/// letter 's' to the string if the value is not 1.  This is used in cases like
599/// this:  "you idiot, you have %4 parameter%s4!".
600static void HandleIntegerSModifier(unsigned ValNo,
601                                   llvm::SmallVectorImpl<char> &OutStr) {
602  if (ValNo != 1)
603    OutStr.push_back('s');
604}
605
606/// HandleOrdinalModifier - Handle the integer 'ord' modifier.  This
607/// prints the ordinal form of the given integer, with 1 corresponding
608/// to the first ordinal.  Currently this is hard-coded to use the
609/// English form.
610static void HandleOrdinalModifier(unsigned ValNo,
611                                  llvm::SmallVectorImpl<char> &OutStr) {
612  assert(ValNo != 0 && "ValNo must be strictly positive!");
613
614  llvm::raw_svector_ostream Out(OutStr);
615
616  // We could use text forms for the first N ordinals, but the numeric
617  // forms are actually nicer in diagnostics because they stand out.
618  Out << ValNo;
619
620  // It is critically important that we do this perfectly for
621  // user-written sequences with over 100 elements.
622  switch (ValNo % 100) {
623  case 11:
624  case 12:
625  case 13:
626    Out << "th"; return;
627  default:
628    switch (ValNo % 10) {
629    case 1: Out << "st"; return;
630    case 2: Out << "nd"; return;
631    case 3: Out << "rd"; return;
632    default: Out << "th"; return;
633    }
634  }
635}
636
637
638/// PluralNumber - Parse an unsigned integer and advance Start.
639static unsigned PluralNumber(const char *&Start, const char *End) {
640  // Programming 101: Parse a decimal number :-)
641  unsigned Val = 0;
642  while (Start != End && *Start >= '0' && *Start <= '9') {
643    Val *= 10;
644    Val += *Start - '0';
645    ++Start;
646  }
647  return Val;
648}
649
650/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
651static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
652  if (*Start != '[') {
653    unsigned Ref = PluralNumber(Start, End);
654    return Ref == Val;
655  }
656
657  ++Start;
658  unsigned Low = PluralNumber(Start, End);
659  assert(*Start == ',' && "Bad plural expression syntax: expected ,");
660  ++Start;
661  unsigned High = PluralNumber(Start, End);
662  assert(*Start == ']' && "Bad plural expression syntax: expected )");
663  ++Start;
664  return Low <= Val && Val <= High;
665}
666
667/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
668static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
669  // Empty condition?
670  if (*Start == ':')
671    return true;
672
673  while (1) {
674    char C = *Start;
675    if (C == '%') {
676      // Modulo expression
677      ++Start;
678      unsigned Arg = PluralNumber(Start, End);
679      assert(*Start == '=' && "Bad plural expression syntax: expected =");
680      ++Start;
681      unsigned ValMod = ValNo % Arg;
682      if (TestPluralRange(ValMod, Start, End))
683        return true;
684    } else {
685      assert((C == '[' || (C >= '0' && C <= '9')) &&
686             "Bad plural expression syntax: unexpected character");
687      // Range expression
688      if (TestPluralRange(ValNo, Start, End))
689        return true;
690    }
691
692    // Scan for next or-expr part.
693    Start = std::find(Start, End, ',');
694    if (Start == End)
695      break;
696    ++Start;
697  }
698  return false;
699}
700
701/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
702/// for complex plural forms, or in languages where all plurals are complex.
703/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
704/// conditions that are tested in order, the form corresponding to the first
705/// that applies being emitted. The empty condition is always true, making the
706/// last form a default case.
707/// Conditions are simple boolean expressions, where n is the number argument.
708/// Here are the rules.
709/// condition  := expression | empty
710/// empty      :=                             -> always true
711/// expression := numeric [',' expression]    -> logical or
712/// numeric    := range                       -> true if n in range
713///             | '%' number '=' range        -> true if n % number in range
714/// range      := number
715///             | '[' number ',' number ']'   -> ranges are inclusive both ends
716///
717/// Here are some examples from the GNU gettext manual written in this form:
718/// English:
719/// {1:form0|:form1}
720/// Latvian:
721/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
722/// Gaeilge:
723/// {1:form0|2:form1|:form2}
724/// Romanian:
725/// {1:form0|0,%100=[1,19]:form1|:form2}
726/// Lithuanian:
727/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
728/// Russian (requires repeated form):
729/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
730/// Slovak
731/// {1:form0|[2,4]:form1|:form2}
732/// Polish (requires repeated form):
733/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
734static void HandlePluralModifier(unsigned ValNo,
735                                 const char *Argument, unsigned ArgumentLen,
736                                 llvm::SmallVectorImpl<char> &OutStr) {
737  const char *ArgumentEnd = Argument + ArgumentLen;
738  while (1) {
739    assert(Argument < ArgumentEnd && "Plural expression didn't match.");
740    const char *ExprEnd = Argument;
741    while (*ExprEnd != ':') {
742      assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
743      ++ExprEnd;
744    }
745    if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
746      Argument = ExprEnd + 1;
747      ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
748      OutStr.append(Argument, ExprEnd);
749      return;
750    }
751    Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
752  }
753}
754
755
756/// FormatDiagnostic - Format this diagnostic into a string, substituting the
757/// formal arguments into the %0 slots.  The result is appended onto the Str
758/// array.
759void DiagnosticInfo::
760FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const {
761  const char *DiagStr = getDiags()->getDescription(getID());
762  const char *DiagEnd = DiagStr+strlen(DiagStr);
763
764  FormatDiagnostic(DiagStr, DiagEnd, OutStr);
765}
766
767void DiagnosticInfo::
768FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
769                 llvm::SmallVectorImpl<char> &OutStr) const {
770
771  /// FormattedArgs - Keep track of all of the arguments formatted by
772  /// ConvertArgToString and pass them into subsequent calls to
773  /// ConvertArgToString, allowing the implementation to avoid redundancies in
774  /// obvious cases.
775  llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs;
776
777  while (DiagStr != DiagEnd) {
778    if (DiagStr[0] != '%') {
779      // Append non-%0 substrings to Str if we have one.
780      const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
781      OutStr.append(DiagStr, StrEnd);
782      DiagStr = StrEnd;
783      continue;
784    } else if (ispunct(DiagStr[1])) {
785      OutStr.push_back(DiagStr[1]);  // %% -> %.
786      DiagStr += 2;
787      continue;
788    }
789
790    // Skip the %.
791    ++DiagStr;
792
793    // This must be a placeholder for a diagnostic argument.  The format for a
794    // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
795    // The digit is a number from 0-9 indicating which argument this comes from.
796    // The modifier is a string of digits from the set [-a-z]+, arguments is a
797    // brace enclosed string.
798    const char *Modifier = 0, *Argument = 0;
799    unsigned ModifierLen = 0, ArgumentLen = 0;
800
801    // Check to see if we have a modifier.  If so eat it.
802    if (!isdigit(DiagStr[0])) {
803      Modifier = DiagStr;
804      while (DiagStr[0] == '-' ||
805             (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
806        ++DiagStr;
807      ModifierLen = DiagStr-Modifier;
808
809      // If we have an argument, get it next.
810      if (DiagStr[0] == '{') {
811        ++DiagStr; // Skip {.
812        Argument = DiagStr;
813
814        DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
815        assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
816        ArgumentLen = DiagStr-Argument;
817        ++DiagStr;  // Skip }.
818      }
819    }
820
821    assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic");
822    unsigned ArgNo = *DiagStr++ - '0';
823
824    Diagnostic::ArgumentKind Kind = getArgKind(ArgNo);
825
826    switch (Kind) {
827    // ---- STRINGS ----
828    case Diagnostic::ak_std_string: {
829      const std::string &S = getArgStdStr(ArgNo);
830      assert(ModifierLen == 0 && "No modifiers for strings yet");
831      OutStr.append(S.begin(), S.end());
832      break;
833    }
834    case Diagnostic::ak_c_string: {
835      const char *S = getArgCStr(ArgNo);
836      assert(ModifierLen == 0 && "No modifiers for strings yet");
837
838      // Don't crash if get passed a null pointer by accident.
839      if (!S)
840        S = "(null)";
841
842      OutStr.append(S, S + strlen(S));
843      break;
844    }
845    // ---- INTEGERS ----
846    case Diagnostic::ak_sint: {
847      int Val = getArgSInt(ArgNo);
848
849      if (ModifierIs(Modifier, ModifierLen, "select")) {
850        HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, OutStr);
851      } else if (ModifierIs(Modifier, ModifierLen, "s")) {
852        HandleIntegerSModifier(Val, OutStr);
853      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
854        HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
855      } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
856        HandleOrdinalModifier((unsigned)Val, OutStr);
857      } else {
858        assert(ModifierLen == 0 && "Unknown integer modifier");
859        llvm::raw_svector_ostream(OutStr) << Val;
860      }
861      break;
862    }
863    case Diagnostic::ak_uint: {
864      unsigned Val = getArgUInt(ArgNo);
865
866      if (ModifierIs(Modifier, ModifierLen, "select")) {
867        HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
868      } else if (ModifierIs(Modifier, ModifierLen, "s")) {
869        HandleIntegerSModifier(Val, OutStr);
870      } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
871        HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr);
872      } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
873        HandleOrdinalModifier(Val, OutStr);
874      } else {
875        assert(ModifierLen == 0 && "Unknown integer modifier");
876        llvm::raw_svector_ostream(OutStr) << Val;
877      }
878      break;
879    }
880    // ---- NAMES and TYPES ----
881    case Diagnostic::ak_identifierinfo: {
882      const IdentifierInfo *II = getArgIdentifier(ArgNo);
883      assert(ModifierLen == 0 && "No modifiers for strings yet");
884
885      // Don't crash if get passed a null pointer by accident.
886      if (!II) {
887        const char *S = "(null)";
888        OutStr.append(S, S + strlen(S));
889        continue;
890      }
891
892      llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
893      break;
894    }
895    case Diagnostic::ak_qualtype:
896    case Diagnostic::ak_declarationname:
897    case Diagnostic::ak_nameddecl:
898    case Diagnostic::ak_nestednamespec:
899    case Diagnostic::ak_declcontext:
900      getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
901                                     Modifier, ModifierLen,
902                                     Argument, ArgumentLen,
903                                     FormattedArgs.data(), FormattedArgs.size(),
904                                     OutStr);
905      break;
906    }
907
908    // Remember this argument info for subsequent formatting operations.  Turn
909    // std::strings into a null terminated string to make it be the same case as
910    // all the other ones.
911    if (Kind != Diagnostic::ak_std_string)
912      FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
913    else
914      FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string,
915                                        (intptr_t)getArgStdStr(ArgNo).c_str()));
916
917  }
918}
919
920/// IncludeInDiagnosticCounts - This method (whose default implementation
921///  returns true) indicates whether the diagnostics handled by this
922///  DiagnosticClient should be included in the number of diagnostics
923///  reported by Diagnostic.
924bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; }
925