Avoid name clashes in foreach loops when the iteration variable is named 'index', and generate humain-friendly name

This commit is contained in:
Renaud Pawlak 2021-03-09 07:23:15 +01:00
parent 1e274cb9cb
commit 73e94fe7e9

View File

@ -5061,6 +5061,8 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
name = variablePrefix + (++index);
}
System.out.println(" => " + getCurrent());
int position = stack.size() - 2;
while (position >= 0 && !(stack.get(position) instanceof JCMethodDecl)) {
if (stack.get(position) instanceof JCBlock) {
@ -5087,6 +5089,23 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
}
}
}
if (getCurrent() instanceof JCEnhancedForLoop) {
JCEnhancedForLoop loop = (JCEnhancedForLoop) getCurrent();
if (name.equals(loop.var.name.toString())) {
return getFreeVariableName(variablePrefix, index + 1);
}
JCStatement body = loop.body;
if (body instanceof JCBlock) {
JCBlock block = (JCBlock) body;
// analyze all the previous declarations in the loop body
for (JCTree t : block.stats) {
// name clash: we try again with another index
if (t instanceof JCVariableDecl && name.equals(((JCVariableDecl) t).name.toString())) {
return getFreeVariableName(variablePrefix, index + 1);
}
}
}
}
return name;
}
@ -5095,7 +5114,8 @@ public class Java2TypeScriptTranslator extends AbstractTreePrinter {
*/
@Override
public void visitForeachLoop(JCEnhancedForLoop foreachLoop) {
String indexVarName = getFreeVariableName("index", getIndexVariableCount());
String indexVarName = getFreeVariableName(
"index".equals(foreachLoop.var.name.toString()) ? "loopIndex" : "index", getIndexVariableCount());
boolean[] hasLength = { false };
TypeSymbol targetType = foreachLoop.expr.type.tsym;
Util.scanMemberDeclarationsInType(targetType, getAdapter().getErasedTypes(), element -> {