我想创建一个树(使用Node
or ADT
),其中每个节点都有一个指向其父节点的注释。下面是一个简单的链表数据结构的例子:
import util::Math;
import IO;
import Node;
anno LinkedList LinkedList@parent;
anno int LinkedList@something;
data LinkedList = item(int val, LinkedList next)
| last(int val)
;
public LinkedList linkedList = item(5,
item(4,
item(3,
item(2,
last(1)[@something=99]
)[@something=99]
)[@something=99]
)[@something=99]
)[@something=99];
public LinkedList addParentAnnotations(LinkedList n) {
return top-down visit (n) {
case LinkedList x: {
/* go through all children whose type is LinkedList */
for (LinkedList cx <- getChildren(x), LinkedList ll := cx) {
/* setting the annotation like this doesn't seem to work */
cx@parent = x;
// DOESN'T WORK EITHER: setAnnotation(cx, getAnnotations(cx) + ("parent": x));
}
}
}
}
执行addParentAnnotations(linkedList)
产生以下结果:
rascal>addParentAnnotations(linkedList);
LinkedList: item(
5,
item(
4,
item(
3,
item(
2,
last(1)[
@something=99
])[
@something=99
])[
@something=99
])[
@something=99
])[
@something=99
]