Java 收集公园的递归方法
我正在用Xtext编写语法,我正在自定义作用域提供程序,因为我想实现以下示例。我在代码中写了一些注释,以帮助更好地理解Java 收集公园的递归方法,java,eclipse,recursion,xtext,Java,Eclipse,Recursion,Xtext,我正在用Xtext编写语法,我正在自定义作用域提供程序,因为我想实现以下示例。我在代码中写了一些注释,以帮助更好地理解 country C1 { forest F1 { park P1 { enter EN1 exit EX1 park P2 { enter EN2 exit EX2 park P3
country C1 {
forest F1 {
park P1 {
enter EN1
exit EX1
park P2 {
enter EN2
exit EX2
park P3
park P4 {
enter EN3
exit EX3
park P5
workingarea W4 from EN1 to P2 //need to have from: P5, P4.EN3 to: P5,P4.EX3 because P4 only contains P4.EN3,P4.EX3 and P5
}
workingarea W2 from EN1 to P2 //need to have from: P2.EN2, P3, P4, P4.EN3 to: P2.EX2, P3, P4,P4.EX3 because P2 contains P2.EN2, P2.EX2, P3, P4, P4.EN3 and P4.EX3. Contrary to others, here we have two parks contained in one park therefore we also allow P3 and P4, not only P4.EN3 and P4.EX3
}
workingarea W1 from EN1 to P2 //need to have from: P1.EN1 to: P1.EX1
}
park P6 {
enter EN4
exit EX4
}
workingarea WF from EN4 to P6 // From: P1, P6, P1.EN1,P6.EN4. To should be: P1.EX1, P6.EX4, P1,P6
}
}
因此,为了总结属于一个公园的每个工作区,应该允许交叉引用同一个公园的入口和出口、该公园的子公园及其相应的入口和出口
我想使用递归方法来实现我刚才提到的,我试图自定义范围提供程序来提供这一点,但运气不好。这是仅针对from的作用域提供程序,因为to将遵循相同的逻辑:
public class ForestScopeProvider extends AbstractForestScopeProvider {
@Override
public IScope getScope(EObject context, EReference reference) {
if (reference == ForestPackage.Literals.WORKING_AREA__FROM) {
Country rootCountry = (Country) EcoreUtil2.getRootContainer(context);
List<EObject> workingarea = new ArrayList<>();
while (rootCountry != null) {
for (Park park :rootCountry.getForests().getParks())
{
while (park !=null) {
workingarea.addAll(park.getParks());
workingarea.addAll(park.getEnter());
park = (Park) park.getParks();
}
}
rootCountry = rootCountry.getSupercountry();
System.out.println(workingarea);
return Scopes.scopeFor(workingarea);
}
}
}
}
Country:
"country" name=ID ("extends" supercountry=[Country|QualifiedName])? "{"
forests=Forest
"}"
;
Forest:
"forest" name=ID "{"
("park" parks+=Park ("," parks+=Park)*)*
("workingarea" workingarea=WorkingArea)*
"}";
Park:
name=ID ("{"
"enter" enter+=Enter
"exit" exit+=Exit
("park" parks+=Park ("," parks+=Park)*)*
("workingarea" workingarea=WorkingArea)*
"}")*
;
WorkingArea:
name=ID "from" from=[ParkEnter] "to" to=[ParkExit]
;
Enter:
name=ID
;
Exit:
Name=ID
;
ParkEnter:
Park | Enter
;
ParkExit:
Park | Exit
;
QualifiedName:
ID ('.' ID)*
;