-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcbClangCompileCommands.cpp
350 lines (305 loc) · 10.8 KB
/
cbClangCompileCommands.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
#include "cbClangCompileCommands.h"
#include <sdk.h> // Code::Blocks SDK
//#ifndef CB_PRECOMP
#include <manager.h>
#include <compilercommandgenerator.h>
#include <cbeditor.h>
#include <cbproject.h>
#include <compilerfactory.h>
#include <configmanager.h>
#include <editorcolourset.h>
#include <editormanager.h>
#include <globals.h>
#include <logmanager.h>
#include <macrosmanager.h>
#include <projectfile.h>
#include <projectmanager.h>
#include <algorithm>
//#endif
#include <wx/tokenzr.h>
#include <wx/sstream.h>
#include <wx/mstream.h>
#include <wx/textfile.h>
//#include <configurationpanel.h>
static const wxString g_InvalidStr(wxT("invalid"));
// Register the plugin with Code::Blocks.
// We are using an anonymous namespace so we don't litter the global one.
namespace
{
PluginRegistrant<cbClangCompileCommands> reg(_T("cbClangCompileCommands"));
}
// events handling
BEGIN_EVENT_TABLE(cbClangCompileCommands, cbPlugin)
// add any events you want to handle here
END_EVENT_TABLE()
// constructor
cbClangCompileCommands::cbClangCompileCommands()
{
// Make sure our resources are available.
// In the generated boilerplate code we have no resources but when
// we add some, it will be nice that this code is in place already ;)
if(!Manager::LoadResource(_T("cbClangCompileCommands.zip")))
{
NotifyMissingFile(_T("cbClangCompileCommands.zip"));
}
}
// destructor
cbClangCompileCommands::~cbClangCompileCommands()
{
}
void cbClangCompileCommands::OnAttach()
{
typedef cbEventFunctor<cbClangCompileCommands, CodeBlocksEvent> CBEvent;
Manager::Get()->RegisterEventSink(cbEVT_PROJECT_OPTIONS_CHANGED, new CBEvent(this, &cbClangCompileCommands::OnProjectOptionsChanged));
Manager::Get()->RegisterEventSink(cbEVT_PROJECT_FILE_ADDED, new CBEvent(this, &cbClangCompileCommands::OnProjectFileAdded));
Manager::Get()->RegisterEventSink(cbEVT_PROJECT_FILE_REMOVED, new CBEvent(this, &cbClangCompileCommands::OnProjectFileRemoved));
Manager::Get()->RegisterEventSink(cbEVT_BUILDTARGET_SELECTED, new CBEvent(this, &cbClangCompileCommands::OnBuildTargetSelected));
}
void cbClangCompileCommands::OnRelease(bool appShutDown)
{
Manager::Get()->RemoveAllEventSinksFor(this);
}
void cbClangCompileCommands::BuildMenu(wxMenuBar* menuBar)
{
}
void cbClangCompileCommands::BuildModuleMenu(const ModuleType type, wxMenu* menu, const FileTreeData* data)
{
}
void cbClangCompileCommands::OnProjectOptionsChanged(CodeBlocksEvent& event)
{
RebuildCompileCommands( event.GetProject() );
}
void cbClangCompileCommands::OnProjectFileAdded(CodeBlocksEvent& event)
{
RebuildCompileCommands( event.GetProject() );
}
void cbClangCompileCommands::OnProjectFileRemoved(CodeBlocksEvent& event)
{
RebuildCompileCommands( event.GetProject() );
}
void cbClangCompileCommands::OnBuildTargetSelected(CodeBlocksEvent& event)
{
RebuildCompileCommands( event.GetProject() );
}
wxString cbClangCompileCommands::GetCompilerInclDirs(const wxString& compId)
{
std::map<wxString, wxString>::const_iterator idItr = m_compInclDirs.find(compId);
if (idItr != m_compInclDirs.end())
return idItr->second;
Compiler* comp = CompilerFactory::GetCompiler(compId);
wxFileName fn(wxEmptyString, comp->GetPrograms().CPP);
wxString masterPath = comp->GetMasterPath();
Manager::Get()->GetMacrosManager()->ReplaceMacros(masterPath);
fn.SetPath(masterPath);
if (!fn.FileExists())
fn.AppendDir(wxT("bin"));
#ifdef __WXMSW__
wxString command = fn.GetFullPath() + wxT(" -v -E -x c++ nul");
#else
wxString command = fn.GetFullPath() + wxT(" -v -E -x c++ /dev/null");
#endif // __WXMSW__
wxArrayString output, errors;
wxExecute(command, output, errors, wxEXEC_NODISABLE);
wxArrayString::const_iterator errItr = errors.begin();
for (; errItr != errors.end(); ++errItr)
{
if (errItr->IsSameAs(wxT("#include <...> search starts here:")))
{
++errItr;
break;
}
}
wxString includeDirs;
for (; errItr != errors.end(); ++errItr)
{
if (errItr->IsSameAs(wxT("End of search list.")))
break;
includeDirs += wxT(" -I\"") + errItr->Strip(wxString::both)+wxT("\"");
}
return m_compInclDirs.insert(std::pair<wxString, wxString>(compId, includeDirs)).first->second;
}
wxString cbClangCompileCommands::GetCompileCommand(ProjectFile* pf, const wxString& filename)
{
wxString compileCommand;
ProjectBuildTarget* target = nullptr;
Compiler* comp = nullptr;
if (!pf)
{
Manager::Get()->GetProjectManager()->FindProjectForFile( filename, &pf, false, false );
}
if (pf && pf->GetParentProject() && !pf->GetBuildTargets().IsEmpty())
{
target = pf->GetParentProject()->GetBuildTarget(pf->GetBuildTargets()[0]);
comp = CompilerFactory::GetCompiler(target->GetCompilerID());
}
cbProject* proj = (pf ? pf->GetParentProject() : nullptr);
if (!comp && proj)
comp = CompilerFactory::GetCompiler(proj->GetCompilerID());
if (!comp)
{
cbProject* tmpPrj = Manager::Get()->GetProjectManager()->GetActiveProject();
if (tmpPrj)
comp = CompilerFactory::GetCompiler(tmpPrj->GetCompilerID());
}
if (!comp)
comp = CompilerFactory::GetDefaultCompiler();
if (pf && (!pf->GetBuildTargets().IsEmpty()) )
{
target = pf->GetParentProject()->GetBuildTarget(pf->GetBuildTargets()[0]);
if (pf->GetUseCustomBuildCommand(target->GetCompilerID() ))
compileCommand = pf->GetCustomBuildCommand(target->GetCompilerID());
}
if (compileCommand.IsEmpty())
compileCommand = /*comp->GetPrograms().CPP +*/ wxT("clang++ $options $includes");
CompilerCommandGenerator* gen = comp->GetCommandGenerator(proj);
if (gen)
gen->GenerateCommandLine(compileCommand, target, pf, filename,
g_InvalidStr, g_InvalidStr, g_InvalidStr );
delete gen;
std::vector<wxString> unknownOptions;
unknownOptions.push_back(wxT("-Wno-unused-local-typedefs"));
unknownOptions.push_back(wxT("-Wzero-as-null-pointer-constant"));
unknownOptions.push_back(wxT("-mthreads"));
std::sort(unknownOptions.begin(), unknownOptions.end());
wxStringTokenizer tokenizer(compileCommand);
compileCommand.Empty();
wxString pathStr;
while (tokenizer.HasMoreTokens())
{
wxString flag = tokenizer.GetNextToken();
if (std::binary_search(unknownOptions.begin(), unknownOptions.end(), flag))
continue;
// make all include paths absolute, so clang does not choke if Code::Blocks switches directories
if (flag.StartsWith(wxT("-I"), &pathStr))
{
if (pathStr.StartsWith(wxT("\""), NULL))
{
pathStr = pathStr.Mid(1);
}
if (pathStr.EndsWith(wxT("\""), NULL))
{
pathStr = pathStr.RemoveLast(1);
}
wxFileName path(pathStr);
if (path.Normalize(wxPATH_NORM_ALL & ~wxPATH_NORM_CASE))
flag = wxT("-I\"") + path.GetFullPath()+wxT("\"");
}
compileCommand += flag + wxT(" ");
}
compileCommand += GetCompilerInclDirs(comp->GetID());
compileCommand += wxT("-c \"") + filename + wxT("\"");
/*
ConfigManager* cfg = Manager::Get()->GetConfigManager(CLANG_CONFIGMANAGER);
if (cfg->ReadBool( _T("/cmdoption_wnoattributes") ))
compileCommand += wxT(" -Wno-attributes ");
else
compileCommand += wxT(" -Wattributes ");
if (cfg->ReadBool( _T("/cmdoption_wextratokens") ))
compileCommand += wxT(" -Wextra-tokens ");
else
compileCommand += wxT(" -Wno-extra-tokens ");
if (cfg->ReadBool( _T("/cmdoption_fparseallcomments") ))
compileCommand += wxT(" -fparse-all-comments ");
wxString extraOptions = cfg->Read(_T("/cmdoption_extra"));
if (extraOptions.length() > 0)
{
extraOptions.Replace( wxT("\r"), wxT(" ") );
extraOptions.Replace( wxT("\n"), wxT(" ") );
extraOptions.Replace( wxT("\t"), wxT(" ") );
compileCommand += wxT(" ") + extraOptions;
}
*/
return compileCommand;
}
void cbClangCompileCommands::WriteStringValue(wxFile& out, const wxString& value) const
{
wxMemoryOutputStream os;
os.PutC('\"');
wxCharBuffer cb = value.ToUTF8();
char* writeBuffer = cb.data();
size_t len = strlen( writeBuffer );
for (size_t i = 0; i < len; ++i)
{
char escapeChar = 0;
switch(*writeBuffer)
{
case '\"':
escapeChar = '\"';
break;
case '\\':
escapeChar = '\\';
break;
case '\n':
escapeChar = 'n';
break;
case '\r':
escapeChar = 'r';
break;
case '\b':
escapeChar = 'b';
break;
case '\t':
escapeChar = 't';
break;
}
if (escapeChar)
{
os.PutC('\\');
os.PutC(escapeChar);
}
else
{
os.PutC(*writeBuffer);
}
writeBuffer++;
}
os.PutC( '\"' );
wxStreamBuffer* osBuffer = os.GetOutputStreamBuffer();
void* bufPtr = osBuffer->GetBufferStart();
wxString str = wxString::FromUTF8( (const char*)bufPtr, os.GetLength() );
out.Write( str );
}
void cbClangCompileCommands::RebuildCompileCommands(cbProject* pProj)
{
wxFileName fn(pProj->GetCommonTopLevelPath(), wxT("compile_commands.json"));
wxFile out(fn.GetFullPath(), wxFile::write);
out.Write( wxT("[") );
bool bInitial = true;
for (FilesList::iterator it = pProj->GetFilesList().begin(); it != pProj->GetFilesList().end(); ++it)
{
ProjectFile* f = *it;
if (FileTypeOf(f->file.GetFullPath()) != ftSource)
{
continue;
}
if (!bInitial)
{
out.Write( wxT(",") );
}
out.Write( wxTextFile::GetEOL() );
out.Write( wxT(" ") );
out.Write( wxT("{ \"directory\": ") );
//wxString executionDir = pProj->GetExecutionDir();
wxString executionDir = f->file.GetPath();
#ifdef __WXMSW__
while( executionDir.Replace( wxT("\\"), wxT("/") ))
;
#endif
WriteStringValue( out, executionDir );
out.Write( wxT(",") );
out.Write( wxTextFile::GetEOL());
out.Write( wxT(" \"command\": ") );
wxString compileCommand = GetCompileCommand(f, f->file.GetFullName() );
WriteStringValue( out, compileCommand );
out.Write( wxT(",") );
out.Write( wxTextFile::GetEOL() );
out.Write( wxT(" \"file\": ") );
WriteStringValue( out, f->file.GetFullName() );
out.Write( wxT(" }") );
bInitial = false;
}
out.Write( wxTextFile::GetEOL() );
out.Write( wxT("]") );
out.Write( wxTextFile::GetEOL() );
out.Close();
}