1 ///////////////////////////////////////////////////////////////////////////////////////////////
2 // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3 // Copyright (C) 2001-2026 the original author or authors.
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
14 //
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 ///////////////////////////////////////////////////////////////////////////////////////////////
19
20 package com.puppycrawl.tools.checkstyle.utils;
21
22 import org.jspecify.annotations.NonNull;
23 import org.jspecify.annotations.Nullable;
24
25 /**
26 * Utility methods to suppress Checker Framework nullness warnings for cases where
27 * null is theoretically possible but practically impossible due to Java grammar rules.
28 *
29 * <p>Checkstyle only processes compiled Java sources, so certain AST nodes are guaranteed
30 * to exist by Java Language Specification. For example, every {@code METHOD_DEF} must have
31 * a {@code PARAMETERS} child, every definition must have an {@code IDENT} child, etc.
32 *
33 * <p>Use this utility for such grammar-guaranteed cases. Do NOT use for genuinely nullable
34 * values where null should be handled with proper null checks.
35 */
36 public final class NullUtil {
37
38 /** Stop instances being created. **/
39 private NullUtil() {
40 }
41
42 /**
43 * Assert that a reference is non-null. The method suppresses nullness warnings from
44 * the Checker Framework and throws {@link AssertionError} if the argument is null
45 * when Java assertions are enabled.
46 *
47 * @param <T> the type of the reference
48 * @param ref a reference of @Nullable type, that is non-null at run time
49 * @return the argument, cast to have the type qualifier {@code @NonNull}
50 * @throws AssertionError if ref is null and assertions are enabled
51 */
52 public static <T> @NonNull T notNull(@Nullable T ref) {
53 if (ref == null) {
54 throw new AssertionError("Misuse of notNull: argument was null");
55 }
56 return ref;
57 }
58 }