I want to create a tree (using a Node
or ADT
) in which every node has an annotation pointing back to its parent. Below is an example with a simple linked list data structure:
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));
}
}
}
}
Executing addParentAnnotations(linkedList)
yields the following result:
rascal>addParentAnnotations(linkedList);
LinkedList: item(
5,
item(
4,
item(
3,
item(
2,
last(1)[
@something=99
])[
@something=99
])[
@something=99
])[
@something=99
])[
@something=99
]