-
Notifications
You must be signed in to change notification settings - Fork 22
/
IWYU.cs
360 lines (312 loc) · 15.6 KB
/
IWYU.cs
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
349
350
351
352
353
354
355
356
357
358
359
360
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Task = System.Threading.Tasks.Task;
namespace IncludeToolbox.IncludeWhatYouUse
{
/// <summary>
/// Command handler for include what you use.
/// </summary>
static public class IWYU
{
private static readonly Regex RegexRemoveLine = new Regex(@"^-\s+.+\s+\/\/ lines (\d+)-(\d+)$");
private class FormatTask
{
public override string ToString()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("Remove:\n");
foreach (int i in linesToRemove)
stringBuilder.AppendFormat("{0},", i);
stringBuilder.Append("\nAdd:\n");
foreach (string s in linesToAdd)
stringBuilder.AppendFormat("{0}\n", s);
return stringBuilder.ToString();
}
public readonly HashSet<int> linesToRemove = new HashSet<int>();
public readonly List<string> linesToAdd = new List<string>();
};
static private Dictionary<string, FormatTask> ParseOutput(string iwyuOutput)
{
Dictionary<string, FormatTask> fileTasks = new Dictionary<string, FormatTask>();
FormatTask currentTask = null;
bool removeCommands = true;
//- #include <Core/Basics.h> // lines 3-3
// Parse what to do.
var lines = Regex.Split(iwyuOutput, "\r\n|\r|\n");
bool lastLineWasEmpty = false;
foreach (string line in lines)
{
if (line.Length == 0)
{
if (lastLineWasEmpty)
{
currentTask = null;
}
lastLineWasEmpty = true;
continue;
}
int i = line.IndexOf(" should add these lines:");
if (i < 0)
{
i = line.IndexOf(" should remove these lines:");
if (i >= 0)
removeCommands = true;
}
else
{
removeCommands = false;
}
if (i >= 0)
{
string file = line.Substring(0, i);
if (!fileTasks.TryGetValue(file, out currentTask))
{
currentTask = new FormatTask();
fileTasks.Add(file, currentTask);
}
}
else if (currentTask != null)
{
if (removeCommands)
{
var match = RegexRemoveLine.Match(line);
if (match.Success)
{
int removeStart, removeEnd;
if (int.TryParse(match.Groups[1].Value, out removeStart) &&
int.TryParse(match.Groups[2].Value, out removeEnd))
{
for (int lineIdx = removeStart; lineIdx <= removeEnd; ++lineIdx)
currentTask.linesToRemove.Add(lineIdx - 1);
}
}
else if (lastLineWasEmpty)
{
currentTask = null;
}
}
else
{
if (!string.IsNullOrWhiteSpace(line))
{
currentTask.linesToAdd.Add(line);
}
else if (lastLineWasEmpty)
{
currentTask = null;
}
}
}
lastLineWasEmpty = false;
}
return fileTasks;
}
static private async Task ApplyTasks(Dictionary<string, FormatTask> tasks, bool applyFormatting, FormatterOptionsPage formatSettings)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
var dte = VSUtils.GetDTE();
foreach (KeyValuePair<string, FormatTask> entry in tasks)
{
string filename = entry.Key.Replace('/', '\\'); // Classy. But Necessary.
EnvDTE.Window fileWindow = dte.ItemOperations.OpenFile(filename);
if (fileWindow == null)
{
await Output.Instance.ErrorMsg("Failed to open File {0}", filename);
continue;
}
fileWindow.Activate();
var viewHost = VSUtils.GetCurrentTextViewHost();
using (var edit = viewHost.TextView.TextBuffer.CreateEdit())
{
var originalLines = edit.Snapshot.Lines.ToArray();
// Determine which line ending to use by majority.
string lineEndingToBeUsed = Utils.GetDominantNewLineSeparator(edit.Snapshot.GetText());
// Add lines.
{
// Find last include.
// Will find even if commented out, but we don't care.
int lastIncludeLine = -1;
for (int line = originalLines.Length - 1; line >= 0; --line)
{
if (originalLines[line].GetText().Contains("#include"))
{
lastIncludeLine = line;
break;
}
}
// Build replacement string
StringBuilder stringToInsertBuilder = new StringBuilder();
foreach (string lineToAdd in entry.Value.linesToAdd)
{
stringToInsertBuilder.Append(lineToAdd);
stringToInsertBuilder.Append(lineEndingToBeUsed);
}
string stringToInsert = stringToInsertBuilder.ToString();
// optional, format before adding.
if (applyFormatting)
{
var includeDirectories = VSUtils.GetProjectIncludeDirectories(fileWindow.Document.ProjectItem?.ContainingProject);
stringToInsert = Formatter.IncludeFormatter.FormatIncludes(stringToInsert, fileWindow.Document.FullName, includeDirectories, formatSettings);
// Add a newline if we removed it.
if (formatSettings.RemoveEmptyLines)
stringToInsert += lineEndingToBeUsed;
}
// Insert.
int insertPosition = 0;
if (lastIncludeLine >= 0 && lastIncludeLine < originalLines.Length)
{
insertPosition = originalLines[lastIncludeLine].EndIncludingLineBreak;
}
edit.Insert(insertPosition, stringToInsert.ToString());
}
// Remove lines.
// It should safe to do that last since we added includes at the bottom, this way there is no confusion with the text snapshot.
{
foreach (int lineToRemove in entry.Value.linesToRemove.Reverse())
{
if (!Formatter.IncludeLineInfo.ContainsPreserveFlag(originalLines[lineToRemove].GetText()))
edit.Delete(originalLines[lineToRemove].ExtentIncludingLineBreak);
}
}
edit.Apply();
}
// For Debugging:
//Output.Instance.WriteLine("");
//Output.Instance.WriteLine(entry.Key);
//Output.Instance.WriteLine(entry.Value.ToString());
}
}
static public async Task Apply(string iwyuOutput, bool applyFormatter, FormatterOptionsPage formatOptions)
{
var tasks = ParseOutput(iwyuOutput);
await ApplyTasks(tasks, applyFormatter, formatOptions);
}
/// <summary>
/// Runs iwyu. Blocks until finished.
/// </summary>
static public async Task<string> RunIncludeWhatYouUse(string fullFileName, EnvDTE.Project project, IncludeWhatYouUseOptionsPage settings)
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
string preprocessorDefintions;
try
{
preprocessorDefintions = VSUtils.VCUtils.GetCompilerSetting_PreprocessorDefinitions(project);
}
catch (VCQueryFailure e)
{
await Output.Instance.ErrorMsg("Can't run IWYU: {0}", e.Message);
return null;
}
string output = "";
using (var process = new System.Diagnostics.Process())
{
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.FileName = settings.ExecutablePath;
// Clang options
var clangOptionList = new List<string>();
// Disable all diagnostics
clangOptionList.Add("-w");
// ... despite of that "invalid token paste" comes through a lot. Disable it.
clangOptionList.Add("-Wno-invalid-token-paste");
// MSVC specific. See https://clang.llvm.org/docs/UsersManual.html#microsoft-extensions
clangOptionList.Add("-fms-compatibility -fms-extensions -fdelayed-template-parsing");
// icwyu options
var iwyuOptionList = new List<string>();
iwyuOptionList.Add("--verbose=" + settings.LogVerbosity);
for (int i = 0; i < settings.MappingFiles.Length; ++i)
iwyuOptionList.Add("--mapping_file=\"" + settings.MappingFiles[i] + "\"");
if (settings.NoDefaultMappings)
iwyuOptionList.Add("--no_default_mappings");
if (settings.PCHInCode)
iwyuOptionList.Add("--pch_in_code");
switch (settings.PrefixHeaderIncludes)
{
case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Add:
iwyuOptionList.Add("--prefix_header_includes=add");
break;
case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Remove:
iwyuOptionList.Add("--prefix_header_includes=remove");
break;
case IncludeWhatYouUseOptionsPage.PrefixHeaderMode.Keep:
iwyuOptionList.Add("--prefix_header_includes=keep");
break;
}
if (settings.TransitiveIncludesOnly)
iwyuOptionList.Add("--transitive_includes_only");
// Set max line length so something large so we don't loose comment information.
// Documentation:
// --max_line_length: maximum line length for includes. Note that this only affects comments and alignment thereof,
// the maximum line length can still be exceeded with long file names(default: 80).
iwyuOptionList.Add("--max_line_length=1024");
/// write support file with includes, defines and the targetgile. Long argument lists lead to an error. Support files are the solution here.
/// https://github.com/Wumpf/IncludeToolbox/issues/36
// Include-paths and Preprocessor.
var includes = string.Join(" ", VSUtils.GetProjectIncludeDirectories(project, false).Select(x => "-I \"" + x.Replace("\\", "\\\\") + "\""));
var defines = preprocessorDefintions.Length == 0 ? "" : string.Join(" ", preprocessorDefintions.Split(';').Select(x => "-D" + x));
var filename = "\"" + fullFileName.Replace("\\", "\\\\") + "\"";
var iwyuOptions = string.Join(" ", iwyuOptionList.Select(x => " -Xiwyu " + x));
var ext = Path.GetExtension(fullFileName);
string co = "";
switch (settings.Commentary)
{
case Commentaries.Always: co = (" -Xiwyu --update_comments"); break;
case Commentaries.Never: co = (" -Xiwyu --no_comments"); break;
case Commentaries.Default: break;
}
iwyuOptions += co;
if (ext == ".h" || ext == ".hpp")
{
var tmp_cpp = Path.GetTempFileName();
tmp_cpp = Path.ChangeExtension(tmp_cpp, ".cpp");
File.WriteAllText(tmp_cpp, "#include \"" + fullFileName + "\"");
iwyuOptions += " -Xiwyu --check_also=" + filename;
filename = "\"" + tmp_cpp.Replace("\\", "\\\\") + "\"";
}
else if (settings.HeaderPrefix != "" && Directory.Exists(Path.GetDirectoryName(fullFileName) + settings.HeaderPrefix))
{
var correspond_h = settings.HeaderPrefix + '\\' + Path.GetFileNameWithoutExtension(fullFileName) + ".h";
var correspond_hpp = Path.ChangeExtension(correspond_h, ".hpp");
if (!File.Exists(correspond_h))
iwyuOptions += " -Xiwyu --check_also=" + "\"" + correspond_h.Replace("\\", "\\\\") + "\"";
else if (!File.Exists(correspond_hpp))
iwyuOptions += " -Xiwyu --check_also=" + "\"" + correspond_hpp.Replace("\\", "\\\\") + "\"";
}
var supportFilePath = Path.GetTempFileName();
File.WriteAllText(supportFilePath, includes + " " + defines + " " + filename);
var clangOptions = string.Join(" ", clangOptionList);
// each include-what-you-use parameter has an -Xiwyu prefix
process.StartInfo.Arguments = $"{clangOptions} {iwyuOptions} {settings.AdditionalParameters} \"@{supportFilePath}\"";
Output.Instance.Write("Running command '{0}' with following arguments:\n{1}\n\n", process.StartInfo.FileName, process.StartInfo.Arguments);
// Start the child process.
process.EnableRaisingEvents = true;
process.OutputDataReceived += (s, args) =>
{
Output.Instance.WriteLine(args.Data);
output += args.Data + "\n";
};
process.ErrorDataReceived += (s, args) =>
{
Output.Instance.WriteLine(args.Data);
output += args.Data + "\n";
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
process.CancelOutputRead();
process.CancelErrorRead();
}
return output;
}
}
}