/
CompilationDatabaseGenerator.java
419 lines (364 loc) · 15.6 KB
/
CompilationDatabaseGenerator.java
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
/********************************************************************************
* Copyright (c) 2023, 2024 Renesas Electronics Corp. and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
package org.eclipse.cdt.managedbuilder.internal.core.jsoncdb.generator;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import org.eclipse.cdt.core.settings.model.ICSourceEntry;
import org.eclipse.cdt.core.settings.model.util.CDataUtil;
import org.eclipse.cdt.managedbuilder.core.BuildException;
import org.eclipse.cdt.managedbuilder.core.IConfiguration;
import org.eclipse.cdt.managedbuilder.core.IFileInfo;
import org.eclipse.cdt.managedbuilder.core.IFolderInfo;
import org.eclipse.cdt.managedbuilder.core.IManagedCommandLineGenerator;
import org.eclipse.cdt.managedbuilder.core.IManagedCommandLineInfo;
import org.eclipse.cdt.managedbuilder.core.IOutputType;
import org.eclipse.cdt.managedbuilder.core.IResourceInfo;
import org.eclipse.cdt.managedbuilder.core.ITool;
import org.eclipse.cdt.managedbuilder.core.ManagedBuildManager;
import org.eclipse.cdt.managedbuilder.core.jsoncdb.CompilationDatabaseInformation;
import org.eclipse.cdt.managedbuilder.core.jsoncdb.ICompilationDatabaseContributor;
import org.eclipse.cdt.managedbuilder.internal.macros.FileContextData;
import org.eclipse.cdt.managedbuilder.macros.BuildMacroException;
import org.eclipse.cdt.managedbuilder.macros.IBuildMacroProvider;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceProxy;
import org.eclipse.core.resources.IResourceProxyVisitor;
import org.eclipse.core.resources.IResourceStatus;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.annotation.NonNull;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public final class CompilationDatabaseGenerator {
private static final String CDB_FILENAME = "compile_commands.json"; //$NON-NLS-1$
private static final String BUILD_FOLDER = "build"; //$NON-NLS-1$
private static final String ERROR_MESSAGE = "Can not set contents to compile_commands.json file"; //$NON-NLS-1$
private IProject project;
private IConfiguration configuration;
private ICSourceEntry[] srcEntries;
private Collection<IResource> fileList;
public CompilationDatabaseGenerator(IProject proj, IConfiguration config) {
project = proj;
configuration = config;
srcEntries = config.getSourceEntries();
}
/**
* @param proj
* Creates and populates compilation database file
* @param config
*/
public void generate() {
IPath buildDirectory = project.getFullPath()
.append(IPath.SEPARATOR + CompilationDatabaseGenerator.BUILD_FOLDER);
IPath compilationDatabasePath = buildDirectory
.append(IPath.SEPARATOR + CompilationDatabaseGenerator.CDB_FILENAME);
try {
if (!buildDirectory.toFile().exists()) {
createDirectory(CompilationDatabaseGenerator.BUILD_FOLDER);
}
IFile compileCommandsFile = createFile(compilationDatabasePath);
addToCompilationdatabase(project, compileCommandsFile, configuration);
} catch (CoreException e) {
Platform.getLog(getClass())
.log(Status.error("Unable to initialize the creation of compile_commands.json file", e)); //$NON-NLS-1$
}
}
private IFile createFile(IPath compilationDatabasePath) throws CoreException {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IFile newFile = workspace.getRoot().getFile(compilationDatabasePath);
try {
if (!newFile.exists()) {
try (InputStream inputStream = new ByteArrayInputStream("".getBytes())) { //$NON-NLS-1$
newFile.create(inputStream, true, null);
}
} else {
try (InputStream inputStream = new ByteArrayInputStream("".getBytes())) { //$NON-NLS-1$
newFile.setContents(inputStream, true, false, null);
}
}
} catch (Exception e) {
IStatus status = new Status(IStatus.ERROR, getClass(), CompilationDatabaseGenerator.ERROR_MESSAGE, e);
Platform.getLog(getClass()).log(status);
}
return newFile;
}
private void addToCompilationdatabase(IProject project, IFile compileCommandsFile, @NonNull IConfiguration config)
throws CoreException {
List<CompilationDatabaseInformation> objList = new ArrayList<>();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
ResourceProxyVisitor resourceVisitor = new ResourceProxyVisitor(this, config);
project.accept(resourceVisitor, IResource.NONE);
try {
objList.addAll(populateObjList(project, config));
objList.addAll(getRunnerForToolchain(config).getAdditionalFiles(config));
CompilationDatabaseGenerator.save(gson.toJson(objList), compileCommandsFile);
} catch (Exception e) {
IStatus status = new Status(IStatus.ERROR, getClass(), CompilationDatabaseGenerator.ERROR_MESSAGE, e);
Platform.getLog(getClass()).log(status);
}
}
private static void save(String buffer, IFile file) throws CoreException {
byte[] bytes = buffer.getBytes(StandardCharsets.UTF_8);
ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
boolean force = true;
file.setContents(stream, force, false, null); // Don't record history
}
@NonNull
private ICompilationDatabaseContributor getRunnerForToolchain(@NonNull IConfiguration config) throws CoreException {
return CompilationDatabaseContributionManager.getInstance().getCompilationDatabaseContributor(config);
}
private List<CompilationDatabaseInformation> populateObjList(IProject project, IConfiguration config)
throws CoreException, BuildException {
List<CompilationDatabaseInformation> objList = new ArrayList<>();
for (IResource resource : getFileList()) {
IPath moduleRelativePath = resource.getParent().getProjectRelativePath();
String relativePath = moduleRelativePath.toString();
IFolder folder = project.getFolder(config.getName());
IPath sourceLocation = getPathForResource(resource);
String ext = sourceLocation.getFileExtension();
IResourceInfo rcInfo = config.getResourceInfo(resource.getProjectRelativePath(), false);
ITool tool = null;
if (rcInfo instanceof IFileInfo fi) {
ITool[] tools = fi.getToolsToInvoke();
if (tools != null && tools.length > 0) {
tool = tools[0];
for (ITool tool2 : tools) {
if (!tool2.getCustomBuildStep()) {
tool = tool2;
break;
}
}
}
} else if (rcInfo instanceof IFolderInfo foInfo) {
tool = foInfo.getToolFromInputExtension(ext);
}
if (tool != null) {
ArrayList<IPath> enumeratedPrimaryOutputs = new ArrayList<>();
calculateOutputsForSource(tool, relativePath, sourceLocation, enumeratedPrimaryOutputs);
ArrayList<String> inputs = new ArrayList<>();
inputs.add(resource.getLocation().toString());
IPath[] addlInputPaths = tool.getAdditionalDependencies();
for (IPath addlInputPath : addlInputPaths) {
IPath addlPath = addlInputPath;
if (!(addlPath.toString().startsWith("$(")) && !addlPath.isAbsolute()) { //$NON-NLS-1$
IPath tempPath = getPathForResource(project).append(addlPath);
if (tempPath != null) {
addlPath = ManagedBuildManager.calculateRelativePath(folder.getLocation(), tempPath);
}
}
inputs.add(addlPath.toString());
}
String[] inputStrings = inputs.toArray(new String[inputs.size()]);
String primaryOutputName = null;
String resourceName = sourceLocation.removeFileExtension().lastSegment();
if (!enumeratedPrimaryOutputs.isEmpty()) {
if (enumeratedPrimaryOutputs.size() > 1) {
StringBuilder resultBuilder = new StringBuilder();
for (IPath outputPath : enumeratedPrimaryOutputs) {
resultBuilder.append(outputPath.toString()).append(" "); //$NON-NLS-1$
}
primaryOutputName = resultBuilder.toString().trim();
} else {
primaryOutputName = enumeratedPrimaryOutputs.get(0).toString();
}
} else {
primaryOutputName = relativePath + IPath.SEPARATOR + resourceName + ".o"; //$NON-NLS-1$
}
IPath outputLocation = Path.fromOSString(primaryOutputName);
if (!outputLocation.isAbsolute()) {
outputLocation = getPathForResource(project).append(folder.getName()).append(primaryOutputName);
}
String outflag = tool.getOutputFlag();
String outputPrefix = tool.getOutputPrefix();
String[] flags = tool.getToolCommandFlags(sourceLocation, folder.getFullPath());
IManagedCommandLineInfo cmdLInfo = generateToolCommandLineInfo(tool, flags, outflag, outputPrefix,
outputLocation + "", inputStrings, sourceLocation, outputLocation); //$NON-NLS-1$
IBuildMacroProvider provider = ManagedBuildManager.getBuildMacroProvider();
String resolvedOptionFileContents = provider.resolveValueToMakefileFormat(cmdLInfo.getCommandLine(), "", //$NON-NLS-1$
" ", IBuildMacroProvider.CONTEXT_FILE, //$NON-NLS-1$
new FileContextData(sourceLocation, outputLocation, null, tool));
objList.add(new CompilationDatabaseInformation(project.getLocation().toString(),
resolvedOptionFileContents, resource.getLocation().toString()));
}
}
return objList;
}
private IManagedCommandLineInfo generateToolCommandLineInfo(ITool tool, String[] flags, String outputFlag,
String outputPrefix, String outputName, String[] inputResources, IPath inputLocation,
IPath outputLocation) {
String cmd = tool.getToolCommand();
try {
String resolvedCommand = null;
if ((inputLocation != null && inputLocation.toString().indexOf(" ") != -1) || //$NON-NLS-1$
(outputLocation != null && outputLocation.toString().indexOf(" ") != -1)) { //$NON-NLS-1$
resolvedCommand = ManagedBuildManager.getBuildMacroProvider().resolveValue(cmd, "", //$NON-NLS-1$
" ", //$NON-NLS-1$
IBuildMacroProvider.CONTEXT_FILE,
new FileContextData(inputLocation, outputLocation, null, tool));
} else {
resolvedCommand = ManagedBuildManager.getBuildMacroProvider().resolveValueToMakefileFormat(cmd, "", //$NON-NLS-1$
" ", //$NON-NLS-1$
IBuildMacroProvider.CONTEXT_FILE,
new FileContextData(inputLocation, outputLocation, null, tool));
}
if ((resolvedCommand = resolvedCommand.trim()).length() > 0) {
cmd = resolvedCommand;
}
} catch (BuildMacroException e) {
Platform.getLog(getClass()).log(Status.error(CompilationDatabaseGenerator.ERROR_MESSAGE, e));
}
IManagedCommandLineGenerator gen = tool.getCommandLineGenerator();
return gen.generateCommandLineInfo(tool, cmd, flags, outputFlag, outputPrefix, outputName, inputResources,
tool.getCommandLinePattern());
}
private void calculateOutputsForSource(ITool tool, String relativePath, IPath sourceLocation,
ArrayList<IPath> enumeratedPrimaryOutputs) {
IOutputType[] outTypes = tool.getOutputTypes();
if (outTypes != null && outTypes.length > 0) {
IOutputType type = tool.getPrimaryOutputType();
boolean primaryOutput = (type == tool.getPrimaryOutputType());
String[] extensions = type.getOutputExtensions(tool);
if (primaryOutput) {
for (String extension : extensions) {
String prefix = type.getOutputPrefix();
String fileName = sourceLocation.removeFileExtension().lastSegment();
IPath outPath = Path.fromOSString(relativePath + IPath.SEPARATOR + prefix + fileName);
outPath = outPath.addFileExtension(extension);
enumeratedPrimaryOutputs.add(0, outPath);
}
}
}
}
private IPath getPathForResource(IResource resource) {
return new Path(resource.getLocationURI().getPath());
}
private boolean isSource(IPath path) {
return !CDataUtil.isExcluded(path, srcEntries);
}
private void appendFileList(IResource resource) {
getFileList().add(resource);
}
private Collection<IResource> getFileList() {
if (fileList == null) {
fileList = new LinkedHashSet<>();
}
return fileList;
}
private boolean isGeneratedResource(IResource resource) {
// Is this a generated directory ...
IPath path = resource.getProjectRelativePath();
String[] configNames = ManagedBuildManager.getBuildInfo(project).getConfigurationNames();
for (String name : configNames) {
IPath root = new Path(name);
// It is if it is a root of the resource pathname
if (root.isPrefixOf(path)) {
return true;
}
}
return false;
}
private IPath createDirectory(String dirName) throws CoreException {
// Create or get the handle for the build directory
IFolder folder = project.getFolder(dirName);
if (!folder.exists()) {
// Make sure that parent folders exist
IPath parentPath = (new Path(dirName)).removeLastSegments(1);
// Assume that the parent exists if the path is empty
if (!parentPath.isEmpty()) {
IFolder parent = project.getFolder(parentPath);
if (!parent.exists()) {
createDirectory(parentPath.toString());
}
}
// Now make the requested folder
try {
folder.create(true, true, null);
} catch (CoreException e) {
if (e.getStatus().getCode() == IResourceStatus.PATH_OCCUPIED) {
folder.refreshLocal(IResource.DEPTH_ZERO, null);
} else {
throw e;
}
}
// Make sure the folder is marked as derived so it is not added to CM
if (!folder.isDerived()) {
folder.setDerived(true, null);
}
}
return folder.getFullPath();
}
/**
* This class is used to recursively walk the project and determine which
* modules contribute buildable source files.
*/
private class ResourceProxyVisitor implements IResourceProxyVisitor {
private final CompilationDatabaseGenerator generator;
private final IConfiguration config;
public ResourceProxyVisitor(CompilationDatabaseGenerator generator, IConfiguration cfg) {
this.generator = generator;
this.config = cfg;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.
* resources.IResourceProxy)
*/
@Override
public boolean visit(IResourceProxy proxy) throws CoreException {
// No point in proceeding, is there
if (generator == null) {
return false;
}
IResource resource = proxy.requestResource();
boolean isSource = isSource(resource.getProjectRelativePath());
// Is this a resource we should even consider
if (proxy.getType() == IResource.FILE) {
// If this resource has a Resource Configuration and is not excluded or
// if it has a file extension that one of the tools builds, add the sudirectory
// to the list
IResourceInfo rcInfo = config.getResourceInfo(resource.getProjectRelativePath(), false);
if (isSource/* && !rcInfo.isExcluded() */) {
if (rcInfo instanceof IFolderInfo) {
String ext = resource.getFileExtension();
boolean buildFile = ((IFolderInfo) rcInfo).buildsFileType(ext);
if (buildFile &&
// If this file resource is a generated resource, then it is uninteresting
!generator.isGeneratedResource(resource)) {
generator.appendFileList(resource);
}
} else {
generator.appendFileList(resource);
}
}
} else if (proxy.getType() == IResource.FOLDER) {
if (!isSource || generator.isGeneratedResource(resource)) {
return false;
}
return true;
}
return true;
}
}
}