在Eclipse中使用CDT解析器(如何制作项目?)

时间:2017-02-06 11:26:32

标签: parsing eclipse-cdt indexer

我试图通过使用除日食之外的CDT解析器来解析C ++源代码。

要获得AST,我必须制作,索引,IncludeFileContentProvider。 要制作索引,我需要制作项目。我认为这个项目意味着eclipse项目。

但是我在eclipse之外使用CDT解析器。 在这种情况下如何制作项目。

1 个答案:

答案 0 :(得分:1)

以下是您想要的CDT解析器示例。

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);
    }
}

结果:     找到一个声明:int a;     找到一个声明:void test(){a ++;}