Skip to content

Commit fec96ed

Browse files
SONARPY-2181 Ensure UnionType can never contain LazyType (#2043)
1 parent 7f58c92 commit fec96ed

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

python-frontend/src/main/java/org/sonar/python/types/v2/UnionType.java

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ public TypeSource typeSource() {
7474

7575
@Beta
7676
public static PythonType or(Collection<PythonType> candidates) {
77+
ensureCandidatesAreNotLazyTypes(candidates);
7778
if (candidates.isEmpty()) {
7879
return PythonType.UNKNOWN;
7980
}
@@ -102,6 +103,7 @@ public static PythonType or(@Nullable PythonType type1, @Nullable PythonType typ
102103
if (types.size() == 1) {
103104
return types.iterator().next();
104105
}
106+
ensureCandidatesAreNotLazyTypes(types);
105107
return new UnionType(types);
106108
}
107109

@@ -112,4 +114,10 @@ private static void addTypes(PythonType type, Set<PythonType> types) {
112114
types.add(type);
113115
}
114116
}
117+
118+
private static void ensureCandidatesAreNotLazyTypes(Collection<PythonType> types) {
119+
if (types.stream().anyMatch(LazyType.class::isInstance)) {
120+
throw new IllegalArgumentException("UnionType cannot contain Lazy types");
121+
}
122+
}
115123
}

python-frontend/src/test/java/org/sonar/python/types/v2/UnionTypeTest.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,14 @@
2424
import java.util.Set;
2525
import org.assertj.core.api.InstanceOfAssertFactories;
2626
import org.junit.jupiter.api.Test;
27+
import org.mockito.Mockito;
2728
import org.sonar.plugins.python.api.tree.ExpressionStatement;
2829
import org.sonar.plugins.python.api.tree.FileInput;
2930
import org.sonar.python.semantic.v2.FunctionTypeBuilder;
31+
import org.sonar.python.semantic.v2.LazyTypesContext;
3032

3133
import static org.assertj.core.api.Assertions.assertThat;
34+
import static org.assertj.core.api.Assertions.assertThatThrownBy;
3235
import static org.sonar.python.types.v2.TypesTestUtils.BOOL_TYPE;
3336
import static org.sonar.python.types.v2.TypesTestUtils.INT_TYPE;
3437
import static org.sonar.python.types.v2.TypesTestUtils.STR_TYPE;
@@ -148,4 +151,12 @@ void unionTypeCandidatesResolution() {
148151
.hasSize(2)
149152
.contains(candidate1, candidate2);
150153
}
154+
155+
@Test
156+
void noLazyTypeInUnionType() {
157+
PythonType lazyType = new LazyType("foo", Mockito.mock(LazyTypesContext.class));
158+
assertThatThrownBy(() -> UnionType.or(INT_TYPE, lazyType))
159+
.isInstanceOf(IllegalArgumentException.class)
160+
.hasMessage("UnionType cannot contain Lazy types");
161+
}
151162
}

0 commit comments

Comments
 (0)