Last active
August 29, 2015 14:03
-
-
Save tonisuter/8c344c6e023715902f0b to your computer and use it in GitHub Desktop.
Adding include directives using CDT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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