1 /* 2 * Copyright 2021 The JSpecify Authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 import org.jspecify.annotations.NullMarked; 17 import org.jspecify.annotations.Nullable; 18 19 @NullMarked 20 class TypeVariableMinusNullVsTypeVariable { 21 interface Supplier<T extends @Nullable Object> {} 22 23 interface NonnullSupplier<T> extends Supplier<T> { caching()24 NonnullSupplier<T> caching(); 25 } 26 cachingIfPossible(Supplier<T> supplier)27 <T extends @Nullable Object> Supplier<T> cachingIfPossible(Supplier<T> supplier) { 28 if (supplier instanceof NonnullSupplier) { 29 // jspecify_nullness_mismatch 30 NonnullSupplier<T> cast = 31 // jspecify_nullness_mismatch 32 (NonnullSupplier<T>) supplier; 33 /* 34 * TODO(cpovirk): Can/should we change the spec to make the following statement not be a 35 * mismatch? 36 * 37 * I actually think I'm OK with the mismatch: The overall operation would still include a 38 * mismatch (above). And the mismatch above makes sense: it's worth, I tested some similar 39 * plain-Java code that uses Supplier<T> and NumberSupplier<N extends Number>, and its 40 * reference to NumberSupplier<T> fails to compile. 41 * 42 * (A related bug different thing: Our checker currently *doesn't* issue an error merely if we 43 * merely *cast* to NonnullSupplier<T>, only if we actually declare a variable of that type. 44 * It might be interesting to see what upstream CF does. Note that the code this sample is 45 * based on, Guava's Lists.java, has a cast without a local variable. So Guava sees no error 46 * except the one below.) 47 * 48 * (Assuming that we keep the error here, there should be a workaround: Cast to 49 * NonnullSupplier<?>, call caching(), and then unchecked-cast the result to Supplier<T>.) 50 */ 51 // jspecify_nullness_mismatch 52 return cast.caching(); 53 } 54 return supplier; 55 } 56 } 57