在编译基于java的语言处理之前,我需要对一些代码进行预处理。在这种语言中,类型color的所有实例都需要替换为int。对于ex,这里有一个代码片段:
color red = 0xffaabbcc;
color[][] primary = new color[10][10];经过预处理后,上面的代码应该如下所示:
int red = 0xffaabbcc;
int[][] primary = new int[10][10];我在一个非eclipse的环境中工作。我使用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()不接受任何java关键字,比如int。
在我看来,使用regex查找并替换所有颜色实例并不是正确的方法,因为这可能会导致不必要的更改。但我可能错了。
我如何才能做到这一点?或者,是否有其他解决方案或方法可供我采用?
谢谢
Update Edit:下面是执行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是包含上述访问方法的访问者类。我正在执行的其他替换都是正确执行的。只有这一个会引起问题。
发布于 2017-03-08 10:52:38
我发现了你的错误!这句话:
TextEdit edits = cu.rewrite(doc, null);是不对的。并应替换为以下语句:
TextEdit edits = rewrite.rewriteAST(doc, null);最后,再次将修改后的文档解析成CompilationUnit,修改后的文档将被应用。更重要的是,声明:
node.setStructuralProperty(SimpleType.NAME_PROPERTY, rewrite.getAST().newSimpleName("int"));是不需要的。
https://stackoverflow.com/questions/11619929
复制相似问题