1 //===- DiagTool.cpp - Classes for defining diagtool tools -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the boilerplate for defining diagtool tools.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "DiagTool.h"
14 #include "llvm/ADT/StringMap.h"
15 #include <vector>
16 
17 using namespace diagtool;
18 
DiagTool(llvm::StringRef toolCmd,llvm::StringRef toolDesc)19 DiagTool::DiagTool(llvm::StringRef toolCmd, llvm::StringRef toolDesc)
20     : cmd(std::string(toolCmd)), description(std::string(toolDesc)) {}
21 
~DiagTool()22 DiagTool::~DiagTool() {}
23 
24 typedef llvm::StringMap<DiagTool *> ToolMap;
getTools(void * v)25 static inline ToolMap *getTools(void *v) { return static_cast<ToolMap*>(v); }
26 
DiagTools()27 DiagTools::DiagTools() : tools(new ToolMap()) {}
~DiagTools()28 DiagTools::~DiagTools() { delete getTools(tools); }
29 
getTool(llvm::StringRef toolCmd)30 DiagTool *DiagTools::getTool(llvm::StringRef toolCmd) {
31   ToolMap::iterator it = getTools(tools)->find(toolCmd);
32   return (it == getTools(tools)->end()) ? nullptr : it->getValue();
33 }
34 
registerTool(DiagTool * tool)35 void DiagTools::registerTool(DiagTool *tool) {
36   (*getTools(tools))[tool->getName()] = tool;
37 }
38 
printCommands(llvm::raw_ostream & out)39 void DiagTools::printCommands(llvm::raw_ostream &out) {
40   std::vector<llvm::StringRef> toolNames;
41   unsigned maxName = 0;
42   for (ToolMap::iterator it = getTools(tools)->begin(),
43        ei = getTools(tools)->end(); it != ei; ++it) {
44     toolNames.push_back(it->getKey());
45     unsigned len = it->getKey().size();
46     if (len > maxName)
47       maxName = len;
48   }
49   llvm::sort(toolNames);
50 
51   for (std::vector<llvm::StringRef>::iterator it = toolNames.begin(),
52        ei = toolNames.end(); it != ei; ++it) {
53 
54     out << "  " << (*it);
55     unsigned spaces = (maxName + 3) - (it->size());
56     for (unsigned i = 0; i < spaces; ++i)
57       out << ' ';
58 
59     out << getTool(*it)->getDescription() << '\n';
60   }
61 }
62 
63 namespace diagtool {
64   llvm::ManagedStatic<DiagTools> diagTools;
65 }
66