]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/llvm/tools/clang/utils/TableGen/ClangDiagnosticsEmitter.cpp
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / contrib / llvm / tools / clang / utils / TableGen / ClangDiagnosticsEmitter.cpp
1 //=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- 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 // These tablegen backends emit Clang diagnostics tables.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/ADT/DenseSet.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/PointerUnion.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringMap.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/TableGen/Error.h"
26 #include "llvm/TableGen/Record.h"
27 #include "llvm/TableGen/TableGenBackend.h"
28 #include <algorithm>
29 #include <cctype>
30 #include <functional>
31 #include <map>
32 #include <set>
33 using namespace llvm;
34
35 //===----------------------------------------------------------------------===//
36 // Diagnostic category computation code.
37 //===----------------------------------------------------------------------===//
38
39 namespace {
40 class DiagGroupParentMap {
41   RecordKeeper &Records;
42   std::map<const Record*, std::vector<Record*> > Mapping;
43 public:
44   DiagGroupParentMap(RecordKeeper &records) : Records(records) {
45     std::vector<Record*> DiagGroups
46       = Records.getAllDerivedDefinitions("DiagGroup");
47     for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {
48       std::vector<Record*> SubGroups =
49         DiagGroups[i]->getValueAsListOfDefs("SubGroups");
50       for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)
51         Mapping[SubGroups[j]].push_back(DiagGroups[i]);
52     }
53   }
54   
55   const std::vector<Record*> &getParents(const Record *Group) {
56     return Mapping[Group];
57   }
58 };
59 } // end anonymous namespace.
60
61 static std::string
62 getCategoryFromDiagGroup(const Record *Group,
63                          DiagGroupParentMap &DiagGroupParents) {
64   // If the DiagGroup has a category, return it.
65   std::string CatName = Group->getValueAsString("CategoryName");
66   if (!CatName.empty()) return CatName;
67   
68   // The diag group may the subgroup of one or more other diagnostic groups,
69   // check these for a category as well.
70   const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);
71   for (unsigned i = 0, e = Parents.size(); i != e; ++i) {
72     CatName = getCategoryFromDiagGroup(Parents[i], DiagGroupParents);
73     if (!CatName.empty()) return CatName;
74   }
75   return "";
76 }
77
78 /// getDiagnosticCategory - Return the category that the specified diagnostic
79 /// lives in.
80 static std::string getDiagnosticCategory(const Record *R,
81                                          DiagGroupParentMap &DiagGroupParents) {
82   // If the diagnostic is in a group, and that group has a category, use it.
83   if (DefInit *Group = dyn_cast<DefInit>(R->getValueInit("Group"))) {
84     // Check the diagnostic's diag group for a category.
85     std::string CatName = getCategoryFromDiagGroup(Group->getDef(),
86                                                    DiagGroupParents);
87     if (!CatName.empty()) return CatName;
88   }
89
90   // If the diagnostic itself has a category, get it.
91   return R->getValueAsString("CategoryName");
92 }
93
94 namespace {
95   class DiagCategoryIDMap {
96     RecordKeeper &Records;
97     StringMap<unsigned> CategoryIDs;
98     std::vector<std::string> CategoryStrings;
99   public:
100     DiagCategoryIDMap(RecordKeeper &records) : Records(records) {
101       DiagGroupParentMap ParentInfo(Records);
102       
103       // The zero'th category is "".
104       CategoryStrings.push_back("");
105       CategoryIDs[""] = 0;
106       
107       std::vector<Record*> Diags =
108       Records.getAllDerivedDefinitions("Diagnostic");
109       for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
110         std::string Category = getDiagnosticCategory(Diags[i], ParentInfo);
111         if (Category.empty()) continue;  // Skip diags with no category.
112         
113         unsigned &ID = CategoryIDs[Category];
114         if (ID != 0) continue;  // Already seen.
115         
116         ID = CategoryStrings.size();
117         CategoryStrings.push_back(Category);
118       }
119     }
120     
121     unsigned getID(StringRef CategoryString) {
122       return CategoryIDs[CategoryString];
123     }
124     
125     typedef std::vector<std::string>::iterator iterator;
126     iterator begin() { return CategoryStrings.begin(); }
127     iterator end() { return CategoryStrings.end(); }
128   };
129
130   struct GroupInfo {
131     std::vector<const Record*> DiagsInGroup;
132     std::vector<std::string> SubGroups;
133     unsigned IDNo;
134
135     const Record *ExplicitDef;
136
137     GroupInfo() : ExplicitDef(0) {}
138   };
139 } // end anonymous namespace.
140
141 static bool beforeThanCompare(const Record *LHS, const Record *RHS) {
142   assert(!LHS->getLoc().empty() && !RHS->getLoc().empty());
143   return
144     LHS->getLoc().front().getPointer() < RHS->getLoc().front().getPointer();
145 }
146
147 static bool beforeThanCompareGroups(const GroupInfo *LHS, const GroupInfo *RHS){
148   assert(!LHS->DiagsInGroup.empty() && !RHS->DiagsInGroup.empty());
149   return beforeThanCompare(LHS->DiagsInGroup.front(),
150                            RHS->DiagsInGroup.front());
151 }
152
153 static SMRange findSuperClassRange(const Record *R, StringRef SuperName) {
154   ArrayRef<Record *> Supers = R->getSuperClasses();
155
156   for (size_t i = 0, e = Supers.size(); i < e; ++i)
157     if (Supers[i]->getName() == SuperName)
158       return R->getSuperClassRanges()[i];
159
160   return SMRange();
161 }
162
163 /// \brief Invert the 1-[0/1] mapping of diags to group into a one to many
164 /// mapping of groups to diags in the group.
165 static void groupDiagnostics(const std::vector<Record*> &Diags,
166                              const std::vector<Record*> &DiagGroups,
167                              std::map<std::string, GroupInfo> &DiagsInGroup) {
168
169   for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
170     const Record *R = Diags[i];
171     DefInit *DI = dyn_cast<DefInit>(R->getValueInit("Group"));
172     if (DI == 0) continue;
173     assert(R->getValueAsDef("Class")->getName() != "CLASS_NOTE" &&
174            "Note can't be in a DiagGroup");
175     std::string GroupName = DI->getDef()->getValueAsString("GroupName");
176     DiagsInGroup[GroupName].DiagsInGroup.push_back(R);
177   }
178
179   typedef SmallPtrSet<GroupInfo *, 16> GroupSetTy;
180   GroupSetTy ImplicitGroups;
181
182   // Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty
183   // groups (these are warnings that GCC supports that clang never produces).
184   for (unsigned i = 0, e = DiagGroups.size(); i != e; ++i) {
185     Record *Group = DiagGroups[i];
186     GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")];
187     if (Group->isAnonymous()) {
188       if (GI.DiagsInGroup.size() > 1)
189         ImplicitGroups.insert(&GI);
190     } else {
191       if (GI.ExplicitDef)
192         assert(GI.ExplicitDef == Group);
193       else
194         GI.ExplicitDef = Group;
195     }
196
197     std::vector<Record*> SubGroups = Group->getValueAsListOfDefs("SubGroups");
198     for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)
199       GI.SubGroups.push_back(SubGroups[j]->getValueAsString("GroupName"));
200   }
201   
202   // Assign unique ID numbers to the groups.
203   unsigned IDNo = 0;
204   for (std::map<std::string, GroupInfo>::iterator
205        I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I, ++IDNo)
206     I->second.IDNo = IDNo;
207
208   // Sort the implicit groups, so we can warn about them deterministically.
209   SmallVector<GroupInfo *, 16> SortedGroups(ImplicitGroups.begin(),
210                                             ImplicitGroups.end());
211   for (SmallVectorImpl<GroupInfo *>::iterator I = SortedGroups.begin(),
212                                               E = SortedGroups.end();
213        I != E; ++I) {
214     MutableArrayRef<const Record *> GroupDiags = (*I)->DiagsInGroup;
215     std::sort(GroupDiags.begin(), GroupDiags.end(), beforeThanCompare);
216   }
217   std::sort(SortedGroups.begin(), SortedGroups.end(), beforeThanCompareGroups);
218
219   // Warn about the same group being used anonymously in multiple places.
220   for (SmallVectorImpl<GroupInfo *>::const_iterator I = SortedGroups.begin(),
221                                                     E = SortedGroups.end();
222        I != E; ++I) {
223     ArrayRef<const Record *> GroupDiags = (*I)->DiagsInGroup;
224
225     if ((*I)->ExplicitDef) {
226       std::string Name = (*I)->ExplicitDef->getValueAsString("GroupName");
227       for (ArrayRef<const Record *>::const_iterator DI = GroupDiags.begin(),
228                                                     DE = GroupDiags.end();
229            DI != DE; ++DI) {
230         const DefInit *GroupInit = cast<DefInit>((*DI)->getValueInit("Group"));
231         const Record *NextDiagGroup = GroupInit->getDef();
232         if (NextDiagGroup == (*I)->ExplicitDef)
233           continue;
234
235         SMRange InGroupRange = findSuperClassRange(*DI, "InGroup");
236         SmallString<64> Replacement;
237         if (InGroupRange.isValid()) {
238           Replacement += "InGroup<";
239           Replacement += (*I)->ExplicitDef->getName();
240           Replacement += ">";
241         }
242         SMFixIt FixIt(InGroupRange, Replacement.str());
243
244         SrcMgr.PrintMessage(NextDiagGroup->getLoc().front(),
245                             SourceMgr::DK_Error,
246                             Twine("group '") + Name +
247                               "' is referred to anonymously",
248                             None,
249                             InGroupRange.isValid() ? FixIt
250                                                    : ArrayRef<SMFixIt>());
251         SrcMgr.PrintMessage((*I)->ExplicitDef->getLoc().front(),
252                             SourceMgr::DK_Note, "group defined here");
253       }
254     } else {
255       // If there's no existing named group, we should just warn once and use
256       // notes to list all the other cases.
257       ArrayRef<const Record *>::const_iterator DI = GroupDiags.begin(),
258                                                DE = GroupDiags.end();
259       assert(DI != DE && "We only care about groups with multiple uses!");
260
261       const DefInit *GroupInit = cast<DefInit>((*DI)->getValueInit("Group"));
262       const Record *NextDiagGroup = GroupInit->getDef();
263       std::string Name = NextDiagGroup->getValueAsString("GroupName");
264
265       SMRange InGroupRange = findSuperClassRange(*DI, "InGroup");
266       SrcMgr.PrintMessage(NextDiagGroup->getLoc().front(),
267                           SourceMgr::DK_Error,
268                           Twine("group '") + Name +
269                             "' is referred to anonymously",
270                           InGroupRange);
271
272       for (++DI; DI != DE; ++DI) {
273         GroupInit = cast<DefInit>((*DI)->getValueInit("Group"));
274         InGroupRange = findSuperClassRange(*DI, "InGroup");
275         SrcMgr.PrintMessage(GroupInit->getDef()->getLoc().front(),
276                             SourceMgr::DK_Note, "also referenced here",
277                             InGroupRange);
278       }
279     }
280   }
281 }
282
283 //===----------------------------------------------------------------------===//
284 // Infer members of -Wpedantic.
285 //===----------------------------------------------------------------------===//
286
287 typedef std::vector<const Record *> RecordVec;
288 typedef llvm::DenseSet<const Record *> RecordSet;
289 typedef llvm::PointerUnion<RecordVec*, RecordSet*> VecOrSet;
290
291 namespace {
292 class InferPedantic {
293   typedef llvm::DenseMap<const Record*,
294                          std::pair<unsigned, Optional<unsigned> > > GMap;
295
296   DiagGroupParentMap &DiagGroupParents;
297   const std::vector<Record*> &Diags;
298   const std::vector<Record*> DiagGroups;
299   std::map<std::string, GroupInfo> &DiagsInGroup;
300   llvm::DenseSet<const Record*> DiagsSet;
301   GMap GroupCount;
302 public:
303   InferPedantic(DiagGroupParentMap &DiagGroupParents,
304                 const std::vector<Record*> &Diags,
305                 const std::vector<Record*> &DiagGroups,
306                 std::map<std::string, GroupInfo> &DiagsInGroup)
307   : DiagGroupParents(DiagGroupParents),
308   Diags(Diags),
309   DiagGroups(DiagGroups),
310   DiagsInGroup(DiagsInGroup) {}
311
312   /// Compute the set of diagnostics and groups that are immediately
313   /// in -Wpedantic.
314   void compute(VecOrSet DiagsInPedantic,
315                VecOrSet GroupsInPedantic);
316
317 private:
318   /// Determine whether a group is a subgroup of another group.
319   bool isSubGroupOfGroup(const Record *Group,
320                          llvm::StringRef RootGroupName);
321
322   /// Determine if the diagnostic is an extension.
323   bool isExtension(const Record *Diag);
324
325   /// Determine if the diagnostic is off by default.
326   bool isOffByDefault(const Record *Diag);
327
328   /// Increment the count for a group, and transitively marked
329   /// parent groups when appropriate.
330   void markGroup(const Record *Group);
331
332   /// Return true if the diagnostic is in a pedantic group.
333   bool groupInPedantic(const Record *Group, bool increment = false);
334 };
335 } // end anonymous namespace
336
337 bool InferPedantic::isSubGroupOfGroup(const Record *Group,
338                                       llvm::StringRef GName) {
339
340   const std::string &GroupName = Group->getValueAsString("GroupName");
341   if (GName == GroupName)
342     return true;
343
344   const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);
345   for (unsigned i = 0, e = Parents.size(); i != e; ++i)
346     if (isSubGroupOfGroup(Parents[i], GName))
347       return true;
348
349   return false;
350 }
351
352 /// Determine if the diagnostic is an extension.
353 bool InferPedantic::isExtension(const Record *Diag) {
354   const std::string &ClsName = Diag->getValueAsDef("Class")->getName();
355   return ClsName == "CLASS_EXTENSION";
356 }
357
358 bool InferPedantic::isOffByDefault(const Record *Diag) {
359   const std::string &DefMap = Diag->getValueAsDef("DefaultMapping")->getName();
360   return DefMap == "MAP_IGNORE";
361 }
362
363 bool InferPedantic::groupInPedantic(const Record *Group, bool increment) {
364   GMap::mapped_type &V = GroupCount[Group];
365   // Lazily compute the threshold value for the group count.
366   if (!V.second.hasValue()) {
367     const GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")];
368     V.second = GI.SubGroups.size() + GI.DiagsInGroup.size();
369   }
370
371   if (increment)
372     ++V.first;
373
374   // Consider a group in -Wpendatic IFF if has at least one diagnostic
375   // or subgroup AND all of those diagnostics and subgroups are covered
376   // by -Wpedantic via our computation.
377   return V.first != 0 && V.first == V.second.getValue();
378 }
379
380 void InferPedantic::markGroup(const Record *Group) {
381   // If all the diagnostics and subgroups have been marked as being
382   // covered by -Wpedantic, increment the count of parent groups.  Once the
383   // group's count is equal to the number of subgroups and diagnostics in
384   // that group, we can safely add this group to -Wpedantic.
385   if (groupInPedantic(Group, /* increment */ true)) {
386     const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);
387     for (unsigned i = 0, e = Parents.size(); i != e; ++i)
388       markGroup(Parents[i]);
389   }
390 }
391
392 void InferPedantic::compute(VecOrSet DiagsInPedantic,
393                             VecOrSet GroupsInPedantic) {
394   // All extensions that are not on by default are implicitly in the
395   // "pedantic" group.  For those that aren't explicitly included in -Wpedantic,
396   // mark them for consideration to be included in -Wpedantic directly.
397   for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
398     Record *R = Diags[i];
399     if (isExtension(R) && isOffByDefault(R)) {
400       DiagsSet.insert(R);
401       if (DefInit *Group = dyn_cast<DefInit>(R->getValueInit("Group"))) {
402         const Record *GroupRec = Group->getDef();
403         if (!isSubGroupOfGroup(GroupRec, "pedantic")) {
404           markGroup(GroupRec);
405         }
406       }
407     }
408   }
409
410   // Compute the set of diagnostics that are directly in -Wpedantic.  We
411   // march through Diags a second time to ensure the results are emitted
412   // in deterministic order.
413   for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
414     Record *R = Diags[i];
415     if (!DiagsSet.count(R))
416       continue;
417     // Check if the group is implicitly in -Wpedantic.  If so,
418     // the diagnostic should not be directly included in the -Wpedantic
419     // diagnostic group.
420     if (DefInit *Group = dyn_cast<DefInit>(R->getValueInit("Group")))
421       if (groupInPedantic(Group->getDef()))
422         continue;
423
424     // The diagnostic is not included in a group that is (transitively) in
425     // -Wpedantic.  Include it in -Wpedantic directly.
426     if (RecordVec *V = DiagsInPedantic.dyn_cast<RecordVec*>())
427       V->push_back(R);
428     else {
429       DiagsInPedantic.get<RecordSet*>()->insert(R);
430     }
431   }
432
433   if (!GroupsInPedantic)
434     return;
435
436   // Compute the set of groups that are directly in -Wpedantic.  We
437   // march through the groups to ensure the results are emitted
438   /// in a deterministc order.
439   for (unsigned i = 0, ei = DiagGroups.size(); i != ei; ++i) {
440     Record *Group = DiagGroups[i];
441     if (!groupInPedantic(Group))
442       continue;
443
444     unsigned ParentsInPedantic = 0;
445     const std::vector<Record*> &Parents = DiagGroupParents.getParents(Group);
446     for (unsigned j = 0, ej = Parents.size(); j != ej; ++j) {
447       if (groupInPedantic(Parents[j]))
448         ++ParentsInPedantic;
449     }
450     // If all the parents are in -Wpedantic, this means that this diagnostic
451     // group will be indirectly included by -Wpedantic already.  In that
452     // case, do not add it directly to -Wpedantic.  If the group has no
453     // parents, obviously it should go into -Wpedantic.
454     if (Parents.size() > 0 && ParentsInPedantic == Parents.size())
455       continue;
456
457     if (RecordVec *V = GroupsInPedantic.dyn_cast<RecordVec*>())
458       V->push_back(Group);
459     else {
460       GroupsInPedantic.get<RecordSet*>()->insert(Group);
461     }
462   }
463 }
464
465 //===----------------------------------------------------------------------===//
466 // Warning Tables (.inc file) generation.
467 //===----------------------------------------------------------------------===//
468
469 static bool isError(const Record &Diag) {
470   const std::string &ClsName = Diag.getValueAsDef("Class")->getName();
471   return ClsName == "CLASS_ERROR";
472 }
473
474 /// ClangDiagsDefsEmitter - The top-level class emits .def files containing
475 /// declarations of Clang diagnostics.
476 namespace clang {
477 void EmitClangDiagsDefs(RecordKeeper &Records, raw_ostream &OS,
478                         const std::string &Component) {
479   // Write the #if guard
480   if (!Component.empty()) {
481     std::string ComponentName = StringRef(Component).upper();
482     OS << "#ifdef " << ComponentName << "START\n";
483     OS << "__" << ComponentName << "START = DIAG_START_" << ComponentName
484        << ",\n";
485     OS << "#undef " << ComponentName << "START\n";
486     OS << "#endif\n\n";
487   }
488
489   const std::vector<Record*> &Diags =
490     Records.getAllDerivedDefinitions("Diagnostic");
491
492   std::vector<Record*> DiagGroups
493     = Records.getAllDerivedDefinitions("DiagGroup");
494
495   std::map<std::string, GroupInfo> DiagsInGroup;
496   groupDiagnostics(Diags, DiagGroups, DiagsInGroup);
497
498   DiagCategoryIDMap CategoryIDs(Records);
499   DiagGroupParentMap DGParentMap(Records);
500
501   // Compute the set of diagnostics that are in -Wpedantic.
502   RecordSet DiagsInPedantic;
503   InferPedantic inferPedantic(DGParentMap, Diags, DiagGroups, DiagsInGroup);
504   inferPedantic.compute(&DiagsInPedantic, (RecordVec*)0);
505
506   for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
507     const Record &R = *Diags[i];
508     
509     // Check if this is an error that is accidentally in a warning
510     // group.
511     if (isError(R)) {
512       if (DefInit *Group = dyn_cast<DefInit>(R.getValueInit("Group"))) {
513         const Record *GroupRec = Group->getDef();
514         const std::string &GroupName = GroupRec->getValueAsString("GroupName");
515         PrintFatalError(R.getLoc(), "Error " + R.getName() +
516                       " cannot be in a warning group [" + GroupName + "]");
517       }
518     }
519
520     // Filter by component.
521     if (!Component.empty() && Component != R.getValueAsString("Component"))
522       continue;
523
524     OS << "DIAG(" << R.getName() << ", ";
525     OS << R.getValueAsDef("Class")->getName();
526     OS << ", diag::" << R.getValueAsDef("DefaultMapping")->getName();
527     
528     // Description string.
529     OS << ", \"";
530     OS.write_escaped(R.getValueAsString("Text")) << '"';
531     
532     // Warning associated with the diagnostic. This is stored as an index into
533     // the alphabetically sorted warning table.
534     if (DefInit *DI = dyn_cast<DefInit>(R.getValueInit("Group"))) {
535       std::map<std::string, GroupInfo>::iterator I =
536           DiagsInGroup.find(DI->getDef()->getValueAsString("GroupName"));
537       assert(I != DiagsInGroup.end());
538       OS << ", " << I->second.IDNo;
539     } else if (DiagsInPedantic.count(&R)) {
540       std::map<std::string, GroupInfo>::iterator I =
541         DiagsInGroup.find("pedantic");
542       assert(I != DiagsInGroup.end() && "pedantic group not defined");
543       OS << ", " << I->second.IDNo;
544     } else {
545       OS << ", 0";
546     }
547
548     // SFINAE bit
549     if (R.getValueAsBit("SFINAE"))
550       OS << ", true";
551     else
552       OS << ", false";
553
554     // Access control bit
555     if (R.getValueAsBit("AccessControl"))
556       OS << ", true";
557     else
558       OS << ", false";
559
560     // FIXME: This condition is just to avoid temporary revlock, it can be
561     // removed.
562     if (R.getValue("WarningNoWerror")) {
563       // Default warning has no Werror bit.
564       if (R.getValueAsBit("WarningNoWerror"))
565         OS << ", true";
566       else
567         OS << ", false";
568   
569       // Default warning show in system header bit.
570       if (R.getValueAsBit("WarningShowInSystemHeader"))
571         OS << ", true";
572       else
573         OS << ", false";
574     }
575   
576     // Category number.
577     OS << ", " << CategoryIDs.getID(getDiagnosticCategory(&R, DGParentMap));
578     OS << ")\n";
579   }
580 }
581 } // end namespace clang
582
583 //===----------------------------------------------------------------------===//
584 // Warning Group Tables generation
585 //===----------------------------------------------------------------------===//
586
587 static std::string getDiagCategoryEnum(llvm::StringRef name) {
588   if (name.empty())
589     return "DiagCat_None";
590   SmallString<256> enumName = llvm::StringRef("DiagCat_");
591   for (llvm::StringRef::iterator I = name.begin(), E = name.end(); I != E; ++I)
592     enumName += isalnum(*I) ? *I : '_';
593   return enumName.str();
594 }
595   
596 namespace clang {
597 void EmitClangDiagGroups(RecordKeeper &Records, raw_ostream &OS) {
598   // Compute a mapping from a DiagGroup to all of its parents.
599   DiagGroupParentMap DGParentMap(Records);
600
601   std::vector<Record*> Diags =
602     Records.getAllDerivedDefinitions("Diagnostic");
603   
604   std::vector<Record*> DiagGroups
605     = Records.getAllDerivedDefinitions("DiagGroup");
606
607   std::map<std::string, GroupInfo> DiagsInGroup;
608   groupDiagnostics(Diags, DiagGroups, DiagsInGroup);
609
610   // All extensions are implicitly in the "pedantic" group.  Record the
611   // implicit set of groups in the "pedantic" group, and use this information
612   // later when emitting the group information for Pedantic.
613   RecordVec DiagsInPedantic;
614   RecordVec GroupsInPedantic;
615   InferPedantic inferPedantic(DGParentMap, Diags, DiagGroups, DiagsInGroup);
616   inferPedantic.compute(&DiagsInPedantic, &GroupsInPedantic);
617
618   // Walk through the groups emitting an array for each diagnostic of the diags
619   // that are mapped to.
620   OS << "\n#ifdef GET_DIAG_ARRAYS\n";
621   unsigned MaxLen = 0;
622   for (std::map<std::string, GroupInfo>::iterator
623        I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {
624     MaxLen = std::max(MaxLen, (unsigned)I->first.size());
625     const bool IsPedantic = I->first == "pedantic";
626
627     std::vector<const Record*> &V = I->second.DiagsInGroup;
628     if (!V.empty() || (IsPedantic && !DiagsInPedantic.empty())) {
629       OS << "static const short DiagArray" << I->second.IDNo << "[] = { ";
630       for (unsigned i = 0, e = V.size(); i != e; ++i)
631         OS << "diag::" << V[i]->getName() << ", ";
632       // Emit the diagnostics implicitly in "pedantic".
633       if (IsPedantic) {
634         for (unsigned i = 0, e = DiagsInPedantic.size(); i != e; ++i)
635           OS << "diag::" << DiagsInPedantic[i]->getName() << ", ";
636       }
637       OS << "-1 };\n";
638     }
639     
640     const std::vector<std::string> &SubGroups = I->second.SubGroups;
641     if (!SubGroups.empty() || (IsPedantic && !GroupsInPedantic.empty())) {
642       OS << "static const short DiagSubGroup" << I->second.IDNo << "[] = { ";
643       for (unsigned i = 0, e = SubGroups.size(); i != e; ++i) {
644         std::map<std::string, GroupInfo>::iterator RI =
645           DiagsInGroup.find(SubGroups[i]);
646         assert(RI != DiagsInGroup.end() && "Referenced without existing?");
647         OS << RI->second.IDNo << ", ";
648       }
649       // Emit the groups implicitly in "pedantic".
650       if (IsPedantic) {
651         for (unsigned i = 0, e = GroupsInPedantic.size(); i != e; ++i) {
652           const std::string &GroupName =
653             GroupsInPedantic[i]->getValueAsString("GroupName");
654           std::map<std::string, GroupInfo>::iterator RI =
655             DiagsInGroup.find(GroupName);
656           assert(RI != DiagsInGroup.end() && "Referenced without existing?");
657           OS << RI->second.IDNo << ", ";
658         }
659       }
660
661       OS << "-1 };\n";
662     }
663   }
664   OS << "#endif // GET_DIAG_ARRAYS\n\n";
665   
666   // Emit the table now.
667   OS << "\n#ifdef GET_DIAG_TABLE\n";
668   for (std::map<std::string, GroupInfo>::iterator
669        I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {
670     // Group option string.
671     OS << "  { ";
672     OS << I->first.size() << ", ";
673     OS << "\"";
674     if (I->first.find_first_not_of("abcdefghijklmnopqrstuvwxyz"
675                                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
676                                    "0123456789!@#$%^*-+=:?")!=std::string::npos)
677       PrintFatalError("Invalid character in diagnostic group '" +
678                       I->first + "'");
679     OS.write_escaped(I->first) << "\","
680                                << std::string(MaxLen-I->first.size()+1, ' ');
681
682     // Special handling for 'pedantic'.
683     const bool IsPedantic = I->first == "pedantic";
684
685     // Diagnostics in the group.
686     const bool hasDiags = !I->second.DiagsInGroup.empty() ||
687                           (IsPedantic && !DiagsInPedantic.empty());
688     if (!hasDiags)
689       OS << "0, ";
690     else
691       OS << "DiagArray" << I->second.IDNo << ", ";
692     
693     // Subgroups.
694     const bool hasSubGroups = !I->second.SubGroups.empty() ||
695                               (IsPedantic && !GroupsInPedantic.empty());
696     if (!hasSubGroups)
697       OS << 0;
698     else
699       OS << "DiagSubGroup" << I->second.IDNo;
700     OS << " },\n";
701   }
702   OS << "#endif // GET_DIAG_TABLE\n\n";
703   
704   // Emit the category table next.
705   DiagCategoryIDMap CategoriesByID(Records);
706   OS << "\n#ifdef GET_CATEGORY_TABLE\n";
707   for (DiagCategoryIDMap::iterator I = CategoriesByID.begin(),
708        E = CategoriesByID.end(); I != E; ++I)
709     OS << "CATEGORY(\"" << *I << "\", " << getDiagCategoryEnum(*I) << ")\n";
710   OS << "#endif // GET_CATEGORY_TABLE\n\n";
711 }
712 } // end namespace clang
713
714 //===----------------------------------------------------------------------===//
715 // Diagnostic name index generation
716 //===----------------------------------------------------------------------===//
717
718 namespace {
719 struct RecordIndexElement
720 {
721   RecordIndexElement() {}
722   explicit RecordIndexElement(Record const &R):
723     Name(R.getName()) {}
724   
725   std::string Name;
726 };
727
728 struct RecordIndexElementSorter :
729   public std::binary_function<RecordIndexElement, RecordIndexElement, bool> {
730   
731   bool operator()(RecordIndexElement const &Lhs,
732                   RecordIndexElement const &Rhs) const {
733     return Lhs.Name < Rhs.Name;
734   }
735   
736 };
737
738 } // end anonymous namespace.
739
740 namespace clang {
741 void EmitClangDiagsIndexName(RecordKeeper &Records, raw_ostream &OS) {
742   const std::vector<Record*> &Diags =
743     Records.getAllDerivedDefinitions("Diagnostic");
744   
745   std::vector<RecordIndexElement> Index;
746   Index.reserve(Diags.size());
747   for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
748     const Record &R = *(Diags[i]);    
749     Index.push_back(RecordIndexElement(R));
750   }
751   
752   std::sort(Index.begin(), Index.end(), RecordIndexElementSorter());
753   
754   for (unsigned i = 0, e = Index.size(); i != e; ++i) {
755     const RecordIndexElement &R = Index[i];
756     
757     OS << "DIAG_NAME_INDEX(" << R.Name << ")\n";
758   }
759 }
760 } // end namespace clang