Skip to content

Instantly share code, notes, and snippets.

@tonisuter
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonisuter/8c344c6e023715902f0b to your computer and use it in GitHub Desktop.
Save tonisuter/8c344c6e023715902f0b to your computer and use it in GitHub Desktop.
Adding include directives using CDT
public static void includeHeaders(HashSet<String> headers, IASTTranslationUnit ast, IDocument document) {
StringBuffer includeText = new StringBuffer();
for(String headerName : headers) {
if(!isHeaderAlreadyIncluded(headerName, ast)) {
includeText.append("\n#include <" + headerName + ">");
}
}
if(includeText.length() > 0) {
try {
includeText.append("\n");
int position = getPositionForIncludeStatements(ast);
document.replace(position, 0, includeText.toString());
}
catch (BadLocationException e) {
Activator activator = Activator.getDefault();
activator.getLog().log(new Status(Status.ERROR, Activator.PLUGIN_ID, Status.OK, "Unable to add include statement", e));
throw new RuntimeException(e);
}
}
}
private static boolean isHeaderAlreadyIncluded(String headerName, IASTTranslationUnit ast) {
IASTPreprocessorIncludeStatement[] includeStatements = ast.getTranslationUnit().getIncludeDirectives();
for(IASTPreprocessorIncludeStatement includeStatement : includeStatements) {
if(includeStatement.getName().getRawSignature().equals(headerName) && includeStatement.isSystemInclude()) {
return true;
}
}
return false;
}
private static int getPositionForIncludeStatements(IASTTranslationUnit ast) {
int position = 0;
IASTPreprocessorIncludeStatement[] includeStatements = ast.getTranslationUnit().getIncludeDirectives();
for(IASTPreprocessorIncludeStatement includeStatement : includeStatements) {
if(includeStatement.isSystemInclude() && includeStatement.isPartOfTranslationUnitFile()) {
IASTNodeLocation nodeLocation = includeStatement.getNodeLocations()[0];
position = nodeLocation.getNodeOffset() + nodeLocation.getNodeLength();
}
}
if(position == 0) {
for(IASTPreprocessorStatement preprocessorStatement : ast.getAllPreprocessorStatements()) {
if(preprocessorStatement instanceof IASTPreprocessorObjectStyleMacroDefinition) {
IASTNodeLocation nodeLocation = preprocessorStatement.getNodeLocations()[0];
position = nodeLocation.getNodeOffset() + nodeLocation.getNodeLength();
}
}
}
return position;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment