[英]How to use ASTRewrite to replace a particular SimpleType with a PrimitiveType?
在編譯基於Java的語言-處理之前,我需要預處理一些代碼。 用這種語言,所有類型為color的實例都需要替換為int。 例如,這是一個代碼片段:
color red = 0xffaabbcc;
color[][] primary = new color[10][10];
預處理后,上面的代碼應如下所示:
int red = 0xffaabbcc;
int[][] primary = new int[10][10];
我在非日食環境中工作。 我正在使用Eclipse JDT ASTParser來做到這一點。 我已經實現了訪問所有SimpleType節點的ASTVisitor。 這是ASTVisitor實現的代碼片段:
public boolean visit(SimpleType node) {
if (node.toString().equals("color")) {
System.out.println("ST color type detected: "
+ node.getStartPosition());
// 1
rewrite.replace(node,
rewrite.getAST().newPrimitiveType(PrimitiveType.INT), null);
// 2
node.setStructuralProperty(SimpleType.NAME_PROPERTY, rewrite
.getAST().newSimpleName("int")); // 2
}
return true;
}
這里重寫是ASTRewrite的實例。 第1行無效(第2行已注釋掉)。 第2行會引發IllegalArgumentException,因為newSimpleName()將不接受任何int這樣的Java關鍵字。
對我來說,查找所有顏色實例並將其替換為正則表達式似乎不正確,因為這可能導致不必要的更改。 但是我可能是錯的。
我該如何實現? 還是我可以采取其他替代解決方案或方法?
謝謝
更新編輯:這是執行ASTRewrite的代碼段:
CompilationUnit cu = (CompilationUnit) parser.createAST(null);
cu.recordModifications();
rewrite = ASTRewrite.create(cu.getAST());
cu.accept(new XQASTVisitor());
TextEdit edits = cu.rewrite(doc, null);
try {
edits.apply(doc);
} catch (MalformedTreeException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
XQAstVisitor是包含上述visit方法的訪問者類。 我正在執行的其他替換操作可以正確執行。 僅這一點會引起問題。
我發現了您的錯誤! 這個說法:
TextEdit edits = cu.rewrite(doc, null);
是不正確的。 並且應替換為以下語句:
TextEdit edits = rewrite.rewriteAST(doc, null);
最后,再次將修改后的文檔解析到CompilationUnit中,更改將被應用。 此外,該語句:
node.setStructuralProperty(SimpleType.NAME_PROPERTY, rewrite.getAST().newSimpleName("int"));
不需要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.