gpt4 book ai didi

Javaparser 从内部/嵌套类定义中收集多个孤立且未附加的注释

转载 作者:行者123 更新时间:2023-12-02 08:47:06 28 4
gpt4 key购买 nike

我正在编写一个用于收集类注释的工具,我想收集开发人员逻辑上附加到类的所有注释:

public abstract class A {

private Integer d;



// comment line
/**
* javadoc comment
*/
class B {
int c;
}
}

或(注释顺序相反)

public abstract class A {
/**
* javadoc comment
*/
// comment line
class B {
int c;
}
}

我当前的实现从 CompilationUnit 开始递归遍历到每个子节点(Node),并检查它是否是类(或接口(interface))声明。然后通过 node.getComment() 从 Node 中提取注释。问题是,位于第一个评论之上的其他评论没有父级,因此不被计算在内。

有没有办法以某种方式收集所有这些? (让我们考虑它们彼此相邻,没有新行跳过)

最佳答案

这里有一个解决方案。感谢 Waylon Huang,他 wrote this code .

  /**
* This is stolen from JavaParser's PrettyPrintVisitor.printOrphanCommentsBeforeThisChildNode,
* with light modifications.
*
* @param node the node whose orphan comments to collect
* @param result the list to add orphan comments to. Is side-effected by this method. The
* implementation uses this to minimize the diffs against upstream.
*/
@SuppressWarnings({
"JdkObsolete", // for LinkedList
"ReferenceEquality"
})
private static void getOrphanCommentsBeforeThisChildNode(final Node node, List<Comment> result) {
if (node instanceof Comment) {
return;
}

Node parent = node.getParentNode().orElse(null);
if (parent == null) {
return;
}
List<Node> everything = new LinkedList<>(parent.getChildNodes());
sortByBeginPosition(everything);
int positionOfTheChild = -1;
for (int i = 0; i < everything.size(); i++) {
if (everything.get(i) == node) positionOfTheChild = i;
}
if (positionOfTheChild == -1) {
throw new AssertionError("I am not a child of my parent.");
}
int positionOfPreviousChild = -1;
for (int i = positionOfTheChild - 1; i >= 0 && positionOfPreviousChild == -1; i--) {
if (!(everything.get(i) instanceof Comment)) positionOfPreviousChild = i;
}
for (int i = positionOfPreviousChild + 1; i < positionOfTheChild; i++) {
Node nodeToPrint = everything.get(i);
if (!(nodeToPrint instanceof Comment))
throw new RuntimeException(
"Expected comment, instead "
+ nodeToPrint.getClass()
+ ". Position of previous child: "
+ positionOfPreviousChild
+ ", position of child "
+ positionOfTheChild);
result.add((Comment) nodeToPrint);
}
}
}

关于Javaparser 从内部/嵌套类定义中收集多个孤立且未附加的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61009945/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com