File: NonNullMapValue.java

package info (click to toggle)
checker-framework-java 3.2.0%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 22,840 kB
  • sloc: java: 145,910; xml: 839; sh: 518; makefile: 401; perl: 26
file content (226 lines) | stat: -rw-r--r-- 8,849 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import java.io.PrintStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf;
import org.checkerframework.checker.nullness.qual.KeyFor;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;

public class NonNullMapValue {

    // Discussion:
    //
    // It can be useful to indicate that all the values in a map are non-null.
    // ("@NonNull" is redundant in this declaration, but I've written it
    // explicitly because it is the annotation we are talking about.)
    //   HashMap<String,@NonNull String> myMap;
    //
    // However, the get method's declaration is misleading (in the context of
    // the nullness type system), since it can always return null no matter
    // whether the map values are non-null:
    //   V get(Object key) { ... return null; }
    //
    // Here are potential solutions:
    //  * Forbid declaring values as non-null.  This is the wrong approach.
    //    (It would also be hard to express syntactically.)
    //  * The checker could recognize a special new annotation on the return
    //    value of get, indicating that its return type isn't merely inferred
    //    from the generic type, but is always nullable.  (This special new
    //    annotations could even be "@Nullable".  A different annotation may
    //    be better, becase in general we would like to issue an error
    //    message when someone applies an annotation to a generic type
    //    parameter.)
    // Additionally, to reduce the number of false positive warnings caused
    // by the fact that get's return value is nullable:
    //  * Build a more specialized sophisticated flow analysis that checks
    //    that the passed key to Map.containsKey() is either checked against
    //    Map.containsKey() or Map.keySet().

    Map<String, @NonNull String> myMap;

    NonNullMapValue(Map<String, @NonNull String> myMap) {
        this.myMap = myMap;
    }

    void testMyMap(String key) {
        @NonNull String value;
        // :: error: (assignment.type.incompatible)
        value = myMap.get(key); // should issue warning
        if (myMap.containsKey(key)) {
            value = myMap.get(key);
        }
        for (String keyInMap : myMap.keySet()) {
            // :: error: (assignment.type.incompatible)
            value = myMap.get(key); // should issue warning
        }
        for (String keyInMap : myMap.keySet()) {
            value = myMap.get(keyInMap);
        }
        for (Map.Entry<@KeyFor("myMap") String, @NonNull String> entry : myMap.entrySet()) {
            String keyInMap = entry.getKey();
            value = entry.getValue();
        }
        for (Iterator<@KeyFor("myMap") String> iter = myMap.keySet().iterator(); iter.hasNext(); ) {
            String keyInMap = iter.next();
            // value = myMap.get(keyInMap);
        }
        value = myMap.containsKey(key) ? myMap.get(key) : "hello";
    }

    public static <T> void print(Map<T, List<T>> graph, PrintStream ps, int indent) {
        for (T node : graph.keySet()) {
            for (T child : graph.get(node)) {
                ps.printf("  %s%n", child);
            }
            @NonNull List<T> children = graph.get(node);
            for (T child : children) {
                ps.printf("  %s%n", child);
            }
        }
    }

    public static <T> void testAssertFlow(Map<T, List<T>> preds, T node) {
        assert preds.containsKey(node);
        for (T pred : preds.get(node)) {}
    }

    public static <T> void testContainsKey1(Map<T, List<T>> dom, T pred) {
        assert dom.containsKey(pred);
        // Both of the next two lines should type-check.  The second one won't
        // unless the checker knows that pred is a key in the map.
        List<T> dom_of_pred1 = dom.get(pred);
        @NonNull List<T> dom_of_pred2 = dom.get(pred);
    }

    public static <T> void testContainsKey2(Map<T, List<T>> dom, T pred) {
        if (!dom.containsKey(pred)) {
            throw new Error();
        }
        // Both of the next two lines should type-check.  The second one won't
        // unless the checker knows that pred is a key in the map.
        List<T> dom_of_pred1 = dom.get(pred);
        @NonNull List<T> dom_of_pred2 = dom.get(pred);
    }

    public static void process_unmatched_procedure_entries() {
        HashMap<Integer, Date> call_hashmap = new HashMap<>();
        for (Integer i : call_hashmap.keySet()) {
            @NonNull Date d = call_hashmap.get(i);
        }
        Set<@KeyFor("call_hashmap") Integer> keys = call_hashmap.keySet();
        for (Integer i : keys) {
            @NonNull Date d = call_hashmap.get(i);
        }
        Set<@KeyFor("call_hashmap") Integer> keys_sorted =
                new TreeSet<@KeyFor("call_hashmap") Integer>(call_hashmap.keySet());
        for (Integer i : keys_sorted) {
            @NonNull Date d = call_hashmap.get(i);
        }
    }

    public static Object testPut(Map<Object, Object> map, Object key) {
        if (!map.containsKey(key)) {
            map.put(key, new Object());
        }
        return map.get(key);
    }

    public static Object testAssertGet(Map<Object, Object> map, Object key) {
        assert map.get(key) != null;
        return map.get(key);
    }

    public static Object testThrow(Map<Object, Object> map, Object key) {
        if (!map.containsKey(key)) {
            if (true) {
                return "m";
            } else {
                throw new RuntimeException();
            }
        }
        return map.get(key);
    }

    public void negateMap(Map<Object, Object> map, Object key) {
        if (!map.containsKey(key)) {
        } else {
            @NonNull Object v = map.get(key);
        }
    }

    public void withinElseInvalid(Map<Object, Object> map, Object key) {
        if (map.containsKey(key)) {
        } else {
            // :: error: (assignment.type.incompatible)
            @NonNull Object v = map.get(key); // should issue warning
        }
    }

    // Map.get should be annotated as @org.checkerframework.dataflow.qual.Pure
    public static int mapGetSize(MyMap<Object, List<Object>> covered, Object file) {
        return (covered.get(file) == null) ? 0 : covered.get(file).size();
    }

    interface MyMap<K, V> extends Map<K, V> {
        // TODO: @AssertGenericNullnessIfTrue("get(#1)")
        @org.checkerframework.dataflow.qual.Pure
        public abstract boolean containsKey(@Nullable Object a1);

        // We get an override warning, because we do not use the annotated JDK in the
        // test suite. Ignore this.
        @SuppressWarnings("override.return.invalid")
        @org.checkerframework.dataflow.qual.Pure
        public @Nullable V get(@Nullable Object o);
    }

    private static final String KEY = "key";
    private static final String KEY2 = "key2";

    void testAnd(MyMap<String, String> map, MyMap<String, @Nullable String> map2) {
        if (map.containsKey(KEY)) {
            map.get(KEY).toString();
        }
        // :: warning: (known.nonnull)
        if (map.containsKey(KEY2) && map.get(KEY2).toString() != null) {}
        // :: error: (dereference.of.nullable) :: warning: (known.nonnull)
        if (map2.containsKey(KEY2) && map2.get(KEY2).toString() != null) {}
    }

    void testAndWithIllegalMapAnnotation(MyMap2<String, String> map) {
        if (map.containsKey(KEY)) {
            map.get(KEY).toString();
        }
        // :: warning: (known.nonnull)
        if (map.containsKey(KEY2) && map.get(KEY2).toString() != null) {
            // do nothing
        }
    }

    interface MyMap2<K, V> {
        @org.checkerframework.dataflow.qual.Pure
        // This annotation is not legal on containsKey in general.
        // If the Map is declared as (say) Map<Object, @Nullable Object>,
        // then get returns a nullable value.  We really want to say that if
        // containsKey returns non-null, then get returns V rather than
        // @Nullable V, but I don't know how to say that.
        @EnsuresNonNullIf(result = true, expression = "get(#1)")
        public abstract boolean containsKey(@Nullable Object a1);

        @org.checkerframework.dataflow.qual.Pure
        public abstract @Nullable V get(@Nullable Object a1);
    }

    interface MyMap3<K, V> {
        @org.checkerframework.dataflow.qual.Pure
        @EnsuresNonNullIf(result = true, expression = "get(#1)")
        // The following error is issued because, unlike in interface MyMap2,
        // this interface has no get() method.
        // :: error: (flowexpr.parse.error)
        boolean containsKey(@Nullable Object a1);
    }
}