1

我正在嘗試使用Eclipse Indigo和CDT 8.0.2編寫自定義C++重構。 CDT提供了一個類,CRefactoring2,它獲得AST並提供掛鉤。但是這個類是在一個內部包中,所以我認爲它會在未來的Eclipse版本中發生變化,並且我不應該繼承它。不使用內部類創建自定義CDT重構

是否有外部API(在CDT中;我不特別想從頭開始編寫所有AST獲取代碼)我可以用來獲取AST並聲明自己的Eclipse CDT重構?

+0

那你最後做了什麼? – 2013-06-26 02:16:34

回答

1

謝謝傑夫分享你獲得AST的方法。我查看了我的代碼,我有一種獲取AST的不同方法,但它也使用公共API。我想發佈該方法以及:

// Assume there is a variable, 'file', of type IFile 
ICProject cProject = CoreModel.getDefault().create(file.getProject()); 
ITranslationUnit unit = CoreModelUtil.findTranslationUnit(file); 
if (unit == null) { 
    unit = CoreModel.getDefault().createTranslationUnitFrom(cProject, file.getLocation()); 
} 
IASTTranslationUnit ast = null; 
IIndex index = null; 
try { 
    index = CCorePlugin.getIndexManager().getIndex(cProject); 
} catch (CoreException e) { 
    ... 
} 

try { 
    index.acquireReadLock(); 
    ast = unit.getAST(index, ITranslationUnit.AST_PARSE_INACTIVE_CODE); 
    if (ast == null) { 
     throw new IllegalArgumentException(file.getLocation().toPortableString() + ": not a valid C/C++ code file"); 
    } 
} catch (InterruptedException e) { 
    ... 
} catch (CoreException e) { 
    ... 
} finally { 
    index.releaseReadLock(); 
} 

礦是多一點涉及;我基本上一直在不停地變化,直到所有事情始終如一地開始工作。我沒有什麼可以補充你所說的關於實際重構的內容。

編輯:澄清:這是迄今爲止我得到翻譯單元最安全的方式。

1

有關訪問和操作AST的信息,請參閱here(請注意,此代碼是爲Java編寫的,ASTVisitor基類的CDT版本位於org.eclipse.cdt.core.dom.ast.ASTVisitor)。

我們結束了寫訪問文件一個C++ AST的代碼基本上是這樣的:

import org.eclipse.cdt.core.model.CoreModel; 
import org.eclipse.core.resources.IFile; 
import org.eclipse.cdt.core.model.ITranslationUnit; 
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; 

private IASTTranslationUnit getASTFromFile(IFile file) { 
    ITranslationUnit tu = (ITranslationUnit) CoreModel.getDefault().create(file); 
    return tu.getAST(); 
} 

至於定義並註冊一個新的重構,你會想看看this article

相關問題