001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2024 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.checks.coding;
021
022import java.util.BitSet;
023import java.util.function.Predicate;
024
025import com.puppycrawl.tools.checkstyle.StatelessCheck;
026import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
027import com.puppycrawl.tools.checkstyle.api.DetailAST;
028import com.puppycrawl.tools.checkstyle.api.TokenTypes;
029import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
030
031/**
032 * <div>
033 * Detects double brace initialization.
034 * </div>
035 *
036 * <p>
037 * Rationale: Double brace initialization (set of
038 * <a href="https://docs.oracle.com/javase/specs/jls/se12/html/jls-8.html#jls-8.6">
039 * Instance Initializers</a> in class body) may look cool, but it is considered as anti-pattern
040 * and should be avoided.
041 * This is also can lead to a hard-to-detect memory leak, if the anonymous class instance is
042 * returned outside and other object(s) hold reference to it.
043 * Created anonymous class is not static, it holds an implicit reference to the outer class
044 * instance.
045 * See this
046 * <a href="https://blog.jooq.org/dont-be-clever-the-double-curly-braces-anti-pattern/">
047 * blog post</a> and
048 * <a href="https://www.baeldung.com/java-double-brace-initialization">
049 * article</a> for more details.
050 * Check ignores any comments and semicolons in class body.
051 * </p>
052 *
053 * <p>
054 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
055 * </p>
056 *
057 * <p>
058 * Violation Message Keys:
059 * </p>
060 * <ul>
061 * <li>
062 * {@code avoid.double.brace.init}
063 * </li>
064 * </ul>
065 *
066 * @since 8.30
067 */
068@StatelessCheck
069public class AvoidDoubleBraceInitializationCheck extends AbstractCheck {
070
071    /**
072     * A key is pointing to the warning message text in "messages.properties"
073     * file.
074     */
075    public static final String MSG_KEY = "avoid.double.brace.init";
076
077    /**
078     * Set of token types that are used in {@link #HAS_MEMBERS} predicate.
079     */
080    private static final BitSet IGNORED_TYPES = TokenUtil.asBitSet(
081        TokenTypes.INSTANCE_INIT,
082        TokenTypes.SEMI,
083        TokenTypes.LCURLY,
084        TokenTypes.RCURLY
085    );
086
087    /**
088     * Predicate for tokens that is used in {@link #hasOnlyInitialization(DetailAST)}.
089     */
090    private static final Predicate<DetailAST> HAS_MEMBERS =
091        token -> !IGNORED_TYPES.get(token.getType());
092
093    @Override
094    public int[] getDefaultTokens() {
095        return getRequiredTokens();
096    }
097
098    @Override
099    public int[] getAcceptableTokens() {
100        return getRequiredTokens();
101    }
102
103    @Override
104    public int[] getRequiredTokens() {
105        return new int[] {TokenTypes.OBJBLOCK};
106    }
107
108    @Override
109    public void visitToken(DetailAST ast) {
110        if (ast.getParent().getType() == TokenTypes.LITERAL_NEW
111            && hasOnlyInitialization(ast)) {
112            log(ast, MSG_KEY);
113        }
114    }
115
116    /**
117     * Checks that block has at least one instance init block and no other class members.
118     *
119     * @param objBlock token to check
120     * @return true if there is least one instance init block and no other class members,
121     *     false otherwise
122     */
123    private static boolean hasOnlyInitialization(DetailAST objBlock) {
124        final boolean hasInitBlock = objBlock.findFirstToken(TokenTypes.INSTANCE_INIT) != null;
125        return hasInitBlock
126                  && TokenUtil.findFirstTokenByPredicate(objBlock, HAS_MEMBERS).isEmpty();
127    }
128}