Ui-Gyun Jeong
Ui-Gyun Jeong

Reputation: 153

Using CDT parser out of Eclipse(How to make project?)

I am trying to parse C++ source by using CDT parser apart from eclipse.

To get AST, I have to make, index, IncludeFileContentProvider. To make index, I need to make project. I think this project means eclipse project.

But I am using CDT parser outside of eclipse. In this case how to make project.

Upvotes: 2

Views: 1673

Answers (1)

ducanhnguyen
ducanhnguyen

Reputation: 171

Here is an example of CDT parser as you want.

import java.util.HashMap;
import java.util.Map;

import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTDeclaration;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.gnu.cpp.GPPLanguage;
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;

public class _CDTParser {
    public static void main(String[] args) throws Exception {
        String sourcecode = "int a; void test() {a++;}";
        IASTTranslationUnit translationUnit = _CDTParser.getIASTTranslationUnit(sourcecode.toCharArray());

        ASTVisitor visitor = new ASTVisitor() {
            @Override
            public int visit(IASTDeclaration declaration) {
                // When CDT visit a declaration
                System.out.println("Found a declaration: " + declaration.getRawSignature());
                return PROCESS_CONTINUE;
            }
        };
        // Enable CDT to visit declaration
        visitor.shouldVisitDeclarations = true;
        // Adapt visitor with source code unit
        translationUnit.accept(visitor);
    }

    public static IASTTranslationUnit getIASTTranslationUnit(char[] code) throws Exception {
        FileContent fc = FileContent.create("", code);
        Map<String, String> macroDefinitions = new HashMap<>();
        String[] includeSearchPaths = new String[0];
        IScannerInfo si = new ScannerInfo(macroDefinitions, includeSearchPaths);
        IncludeFileContentProvider ifcp = IncludeFileContentProvider.getEmptyFilesProvider();
        IIndex idx = null;
        int options = ILanguage.OPTION_IS_SOURCE_UNIT;
        IParserLogService log = new DefaultLogService();
        return GPPLanguage.getDefault().getASTTranslationUnit(fc, si, ifcp, idx, options, log);
    }
}

Results: Found a declaration: int a; Found a declaration: void test() {a++;}

Upvotes: 3

Related Questions