Skip to content

Commit

Permalink
allow variable declarations in loop should be for between counter and…
Browse files Browse the repository at this point in the history
  • Loading branch information
Luro02 committed Sep 17, 2024
1 parent 7b33e82 commit 6153116
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package de.firemage.autograder.core.check.general;

import de.firemage.autograder.core.CodeModel;
import de.firemage.autograder.core.LocalizedMessage;
import de.firemage.autograder.core.ProblemType;
import de.firemage.autograder.core.check.ExecutableCheck;
Expand Down Expand Up @@ -63,7 +62,7 @@ public String toString() {
}
}

private static LoopSuggestion getCounter(CtLoop ctLoop, CodeModel model) {
private static LoopSuggestion getCounter(CtLoop ctLoop) {
List<CtStatement> statements = StatementUtil.getEffectiveStatements(ctLoop.getBody());

if (statements.isEmpty()) {
Expand All @@ -72,6 +71,10 @@ private static LoopSuggestion getCounter(CtLoop ctLoop, CodeModel model) {


CtStatement previous = StatementUtil.getPreviousStatement(ctLoop).orElse(null);
while (previous instanceof CtLocalVariable<?> ctLocalVariable && !TypeUtil.isPrimitiveNumeric(ctLocalVariable.getType())) {
previous = StatementUtil.getPreviousStatement(previous).orElse(null);
}

if (!(previous instanceof CtLocalVariable<?> ctLocalVariable) || !TypeUtil.isPrimitiveNumeric(ctLocalVariable.getType())) {
return null;
}
Expand Down Expand Up @@ -203,7 +206,7 @@ public void process(CtLoop ctLoop) {
return;
}

LoopSuggestion forLoop = getCounter(ctLoop, staticAnalysis.getCodeModel());
LoopSuggestion forLoop = getCounter(ctLoop);

if (forLoop != null) {
addLocalProblem(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,43 @@ void test(String[] array) {
problems.assertExhausted();
}

@Test
void testCounterDeclaredWithOtherVariablesBeforeLoop() throws IOException, LinterException {
ProblemIterator problems = this.checkIterator(StringSourceInfo.fromSourceString(
JavaVersion.JAVA_17,
"Test",
"""
class Test {
String test(String sentence) {
int c = 0;
boolean spaceBefore = true;
String word = "";
while (c < sentence.length()) {
if (Character.isWhitespace(sentence.charAt(c))) {
spaceBefore = true;
} else if (spaceBefore) {
word += sentence.charAt(c);
spaceBefore = false;
}
c++;
}
return word;
}
}
"""
), PROBLEM_TYPES);

assertEqualsFor(
problems.next(),
"int c = 0",
"c < sentence.length()",
"c++",
"{%n if (Character.isWhitespace(sentence.charAt(c))) {%n spaceBefore = true;%n } else if (spaceBefore) {%n word += sentence.charAt(c);%n spaceBefore = false;%n }%n}".formatted()
);

problems.assertExhausted();
}

@Test
void testMissingUpdate() throws IOException, LinterException {
ProblemIterator problems = this.checkIterator(StringSourceInfo.fromSourceString(
Expand Down

0 comments on commit 6153116

Please sign in to comment.