Skip to content

Instantly share code, notes, and snippets.

@oguna
Created January 22, 2016 07:40
Show Gist options
  • Select an option

  • Save oguna/228cd8a5a480f3d5bc98 to your computer and use it in GitHub Desktop.

Select an option

Save oguna/228cd8a5a480f3d5bc98 to your computer and use it in GitHub Desktop.
CDTを用いたC言語のパース(org.eclipse.cdt.coreをクラスパスに追加、JDT関係のライブラリも追加)
package cdtparser;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTDeclarator;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.gnu.c.GCCLanguage;
import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.model.ILanguage;
import org.eclipse.cdt.core.parser.DefaultLogService;
import org.eclipse.cdt.core.parser.FileContent;
import org.eclipse.cdt.core.parser.IParserLogService;
import org.eclipse.cdt.core.parser.IScannerInfo;
import org.eclipse.cdt.core.parser.IncludeFileContentProvider;
import org.eclipse.cdt.core.parser.ScannerInfo;
import org.eclipse.core.runtime.CoreException;
public class CdtParser {
public static void main(String[] args) throws CoreException, FileNotFoundException, IOException {
String filePath = "src/main/resources/gcd.c";
StringBuilder source = new StringBuilder();
try(FileReader fr = new FileReader(filePath)) {
int c;
while ((c = fr.read()) >= 0) {
source.append((char)c);
}
}
ILanguage language = GCCLanguage.getDefault();
FileContent reader = FileContent.create(filePath, source.toString().toCharArray());
Map<String, String> macroDefinitions = null;
String[] includeSearchPath = null;
IScannerInfo scanInfo = new ScannerInfo(macroDefinitions, includeSearchPath );
IncludeFileContentProvider fileCreator = IncludeFileContentProvider.getEmptyFilesProvider();
IIndex index = null;
int options = 0;
IParserLogService log = new DefaultLogService();
IASTTranslationUnit translationUnit = language.getASTTranslationUnit(reader, scanInfo, fileCreator, index, options, log);
ASTVisitor visitor = new ASTVisitor(true) {
public int visit(IASTDeclarator decl) {
/* do something */
System.out.println(decl.getName());
return ASTVisitor.PROCESS_CONTINUE;
}
};
translationUnit.accept(visitor);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment