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.indentation;
021
022import com.puppycrawl.tools.checkstyle.api.DetailAST;
023import com.puppycrawl.tools.checkstyle.api.TokenTypes;
024import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
025
026/**
027 * Handler for parents of blocks ('if', 'else', 'while', etc).
028 * <P>
029 * The "block" handler classes use a common superclass BlockParentHandler,
030 * employing the Template Method pattern.
031 * </P>
032 *
033 * <UL>
034 *   <LI>template method to get the lcurly</LI>
035 *   <LI>template method to get the rcurly</LI>
036 *   <LI>if curlies aren't present, then template method to get expressions
037 *       is called</LI>
038 *   <LI>now all the repetitious code which checks for BOL, if curlies are on
039 *       same line, etc. can be collapsed into the superclass</LI>
040 * </UL>
041 *
042 *
043 */
044public class BlockParentHandler extends AbstractExpressionHandler {
045
046    /**
047     * Children checked by parent handlers.
048     */
049    private static final int[] CHECKED_CHILDREN = {
050        TokenTypes.VARIABLE_DEF,
051        TokenTypes.EXPR,
052        TokenTypes.ANNOTATION,
053        TokenTypes.OBJBLOCK,
054        TokenTypes.LITERAL_BREAK,
055        TokenTypes.LITERAL_RETURN,
056        TokenTypes.LITERAL_THROW,
057        TokenTypes.LITERAL_CONTINUE,
058        TokenTypes.CTOR_CALL,
059        TokenTypes.SUPER_CTOR_CALL,
060    };
061
062    /**
063     * Construct an instance of this handler with the given indentation check,
064     * name, abstract syntax tree, and parent handler.
065     *
066     * @param indentCheck   the indentation check
067     * @param name          the name of the handler
068     * @param ast           the abstract syntax tree
069     * @param parent        the parent handler
070     * @noinspection WeakerAccess
071     * @noinspectionreason WeakerAccess - we avoid 'protected' when possible
072     */
073    public BlockParentHandler(IndentationCheck indentCheck,
074        String name, DetailAST ast, AbstractExpressionHandler parent) {
075        super(indentCheck, name, ast, parent);
076    }
077
078    /**
079     * Returns array of token types which should be checked among children.
080     *
081     * @return array of token types to check.
082     */
083    protected int[] getCheckedChildren() {
084        return CHECKED_CHILDREN.clone();
085    }
086
087    /**
088     * Get the top level expression being managed by this handler.
089     *
090     * @return the top level expression
091     */
092    protected DetailAST getTopLevelAst() {
093        return getMainAst();
094    }
095
096    /**
097     * Check the indent of the top level token.
098     */
099    protected void checkTopLevelToken() {
100        final DetailAST topLevel = getTopLevelAst();
101
102        if (topLevel != null
103                && !getIndent().isAcceptable(expandedTabsColumnNo(topLevel))
104                && isOnStartOfLine(topLevel)) {
105            logError(topLevel, "", expandedTabsColumnNo(topLevel));
106        }
107    }
108
109    /**
110     * Determines if this block expression has curly braces.
111     *
112     * @return true if curly braces are present, false otherwise
113     */
114    private boolean hasCurlies() {
115        return getLeftCurly() != null && getRightCurly() != null;
116    }
117
118    /**
119     * Get the left curly brace portion of the expression we are handling.
120     *
121     * @return the left curly brace expression
122     */
123    protected DetailAST getLeftCurly() {
124        return getMainAst().findFirstToken(TokenTypes.SLIST);
125    }
126
127    /**
128     * Get the right curly brace portion of the expression we are handling.
129     *
130     * @return the right curly brace expression
131     */
132    protected DetailAST getRightCurly() {
133        final DetailAST slist = getMainAst().findFirstToken(TokenTypes.SLIST);
134        return slist.findFirstToken(TokenTypes.RCURLY);
135    }
136
137    /**
138     * Check the indentation of the left curly brace.
139     */
140    private void checkLeftCurly() {
141        // the lcurly can either be at the correct indentation, or nested
142        // with a previous expression
143        final DetailAST lcurly = getLeftCurly();
144        final int lcurlyPos = expandedTabsColumnNo(lcurly);
145
146        if (!curlyIndent().isAcceptable(lcurlyPos) && isOnStartOfLine(lcurly)) {
147            logError(lcurly, "lcurly", lcurlyPos, curlyIndent());
148        }
149    }
150
151    /**
152     * Get the expected indentation level for the curly braces.
153     *
154     * @return the curly brace indentation level
155     */
156    protected IndentLevel curlyIndent() {
157        final DetailAST lcurly = getLeftCurly();
158        IndentLevel expIndentLevel = new IndentLevel(getIndent(), getBraceAdjustment());
159        if (!isOnStartOfLine(lcurly)
160            || lcurly.getParent().getType() == TokenTypes.INSTANCE_INIT) {
161            expIndentLevel = new IndentLevel(getIndent(), 0);
162        }
163
164        return expIndentLevel;
165    }
166
167    /**
168     * Determines if child elements within the expression may be nested.
169     *
170     * @return false
171     */
172    protected boolean canChildrenBeNested() {
173        return false;
174    }
175
176    /**
177     * Check the indentation of the right curly brace.
178     */
179    private void checkRightCurly() {
180        final DetailAST rcurly = getRightCurly();
181        final int rcurlyPos = expandedTabsColumnNo(rcurly);
182
183        if (!curlyIndent().isAcceptable(rcurlyPos)
184                && isOnStartOfLine(rcurly)) {
185            logError(rcurly, "rcurly", rcurlyPos, curlyIndent());
186        }
187    }
188
189    /**
190     * Get the child element that is not a list of statements.
191     *
192     * @return the non-list child element
193     */
194    protected DetailAST getNonListChild() {
195        return getMainAst().findFirstToken(TokenTypes.RPAREN).getNextSibling();
196    }
197
198    /**
199     * Check the indentation level of a child that is not a list of statements.
200     */
201    private void checkNonListChild() {
202        final DetailAST nonList = getNonListChild();
203        if (nonList != null) {
204            final IndentLevel expected = new IndentLevel(getIndent(), getBasicOffset());
205            checkExpressionSubtree(nonList, expected, false, false);
206
207            final DetailAST nonListStartAst = getFirstAstNode(nonList);
208            if (nonList != nonListStartAst) {
209                checkExpressionSubtree(nonListStartAst, expected, false, false);
210            }
211        }
212    }
213
214    /**
215     * Get the child element representing the list of statements.
216     *
217     * @return the statement list child
218     */
219    protected DetailAST getListChild() {
220        return getMainAst().findFirstToken(TokenTypes.SLIST);
221    }
222
223    /**
224     * Get the right parenthesis portion of the expression we are handling.
225     *
226     * @return the right parenthesis expression
227     */
228    private DetailAST getRightParen() {
229        return getMainAst().findFirstToken(TokenTypes.RPAREN);
230    }
231
232    /**
233     * Get the left parenthesis portion of the expression we are handling.
234     *
235     * @return the left parenthesis expression
236     */
237    private DetailAST getLeftParen() {
238        return getMainAst().findFirstToken(TokenTypes.LPAREN);
239    }
240
241    @Override
242    public void checkIndentation() {
243        checkTopLevelToken();
244        // separate to allow for eventual configuration
245        checkLeftParen(getLeftParen());
246        checkRightParen(getLeftParen(), getRightParen());
247        if (hasCurlies()) {
248            checkLeftCurly();
249            checkRightCurly();
250        }
251        final DetailAST listChild = getListChild();
252        if (listChild == null) {
253            checkNonListChild();
254        }
255        else {
256            // NOTE: switch statements usually don't have curlies
257            if (!hasCurlies() || !TokenUtil.areOnSameLine(getLeftCurly(), getRightCurly())) {
258                checkChildren(listChild,
259                        getCheckedChildren(),
260                        getChildrenExpectedIndent(),
261                        true,
262                        canChildrenBeNested());
263            }
264        }
265    }
266
267    /**
268     * Gets indentation level expected for children.
269     *
270     * @return indentation level expected for children
271     */
272    protected IndentLevel getChildrenExpectedIndent() {
273        IndentLevel indentLevel = new IndentLevel(getIndent(), getBasicOffset());
274        // if we have multileveled expected level then we should
275        // try to suggest single level to children using curlies'
276        // levels.
277        if (getIndent().isMultiLevel() && hasCurlies()) {
278            if (isOnStartOfLine(getLeftCurly())) {
279                indentLevel = new IndentLevel(expandedTabsColumnNo(getLeftCurly())
280                        + getBasicOffset());
281            }
282            else if (isOnStartOfLine(getRightCurly())) {
283                final IndentLevel level = new IndentLevel(curlyIndent(), getBasicOffset());
284                indentLevel = IndentLevel.addAcceptable(level, level.getFirstIndentLevel()
285                        + getLineWrappingIndent());
286            }
287        }
288        if (hasCurlies() && isOnStartOfLine(getLeftCurly())) {
289            indentLevel = IndentLevel.addAcceptable(indentLevel,
290                    curlyIndent().getFirstIndentLevel() + getBasicOffset());
291        }
292        return indentLevel;
293    }
294
295    @Override
296    public IndentLevel getSuggestedChildIndent(AbstractExpressionHandler child) {
297        return getChildrenExpectedIndent();
298    }
299
300    /**
301     * A shortcut for {@code IndentationCheck} property.
302     *
303     * @return value of lineWrappingIndentation property
304     *         of {@code IndentationCheck}
305     */
306    private int getLineWrappingIndent() {
307        return getIndentCheck().getLineWrappingIndentation();
308    }
309
310}