Skip to content

Commit

Permalink
fix after review
Browse files Browse the repository at this point in the history
  • Loading branch information
guillaume-dequenne-sonarsource committed May 13, 2024
1 parent d48bdfa commit ffc227a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import java.util.Set;
import org.sonar.plugins.python.api.tree.Expression;
import org.sonar.plugins.python.api.tree.Name;
import org.sonar.plugins.python.api.tree.Tree;
import org.sonar.python.semantic.v2.SymbolV2;
import org.sonar.python.semantic.v2.UsageV2;
import org.sonar.python.tree.NameImpl;
Expand Down Expand Up @@ -55,8 +54,7 @@ void computeDependencies(Expression expression, Set<SymbolV2> trackedVars) {
workList.push(expression);
while (!workList.isEmpty()) {
Expression e = workList.pop();
if (e.is(Tree.Kind.NAME)) {
Name name = (Name) e;
if (e instanceof Name name) {
SymbolV2 symbol = name.symbolV2();
if (symbol != null && trackedVars.contains(symbol)) {
variableDependencies.add(symbol);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Disabled;
Expand Down Expand Up @@ -798,6 +799,36 @@ void try_except_with_dependents() {
assertThat(((UnionType) thirdZ.expression().typeV2()).candidates()).extracting(PythonType::unwrappedType).containsExactlyInAnyOrder(INT_TYPE, STR_TYPE);
}

@Test
void try_except_list_attributes() {
FileInput fileInput = inferTypes("""
try:
my_list = [1, 2, 3]
type(my_list)
except:
my_list = ["a", "b", "c"]
type(my_list)
type(my_list)
""");

List<CallExpression> calls = PythonTestUtils.getAllDescendant(fileInput, tree -> tree.is(Tree.Kind.CALL_EXPR));
RegularArgument list1 = (RegularArgument) calls.get(0).arguments().get(0);
RegularArgument list2 = (RegularArgument) calls.get(1).arguments().get(0);
RegularArgument list3 = (RegularArgument) calls.get(2).arguments().get(0);

UnionType listType = (UnionType) list1.expression().typeV2();
assertThat(listType.candidates()).extracting(PythonType::unwrappedType).containsExactlyInAnyOrder(LIST_TYPE, LIST_TYPE);
assertThat(listType.candidates())
.map(ObjectType.class::cast)
.flatExtracting(ObjectType::attributes)
.extracting(PythonType::unwrappedType)
.containsExactlyInAnyOrder(INT_TYPE, STR_TYPE);

assertThat(list2.expression().typeV2()).isEqualTo(listType);
assertThat(list3.expression().typeV2()).isEqualTo(listType);

}

private static FileInput inferTypes(String lines) {
return inferTypes(lines, new HashMap<>());
}
Expand Down

0 comments on commit ffc227a

Please sign in to comment.