001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2026 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018///////////////////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle.utils;
021
022import org.jspecify.annotations.NonNull;
023import org.jspecify.annotations.Nullable;
024
025/**
026 * Utility methods to suppress Checker Framework nullness warnings for cases where
027 * null is theoretically possible but practically impossible due to Java grammar rules.
028 *
029 * <p>Checkstyle only processes compiled Java sources, so certain AST nodes are guaranteed
030 * to exist by Java Language Specification. For example, every {@code METHOD_DEF} must have
031 * a {@code PARAMETERS} child, every definition must have an {@code IDENT} child, etc.
032 *
033 * <p>Use this utility for such grammar-guaranteed cases. Do NOT use for genuinely nullable
034 * values where null should be handled with proper null checks.
035 */
036public final class NullUtil {
037
038    /** Stop instances being created. **/
039    private NullUtil() {
040    }
041
042    /**
043     * Assert that a reference is non-null. The method suppresses nullness warnings from
044     * the Checker Framework and throws {@link AssertionError} if the argument is null
045     * when Java assertions are enabled.
046     *
047     * @param <T> the type of the reference
048     * @param ref a reference of @Nullable type, that is non-null at run time
049     * @return the argument, cast to have the type qualifier {@code @NonNull}
050     * @throws AssertionError if ref is null and assertions are enabled
051     */
052    public static <T> @NonNull T notNull(@Nullable T ref) {
053        if (ref == null) {
054            throw new AssertionError("Misuse of notNull: argument was null");
055        }
056        return ref;
057    }
058}