001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2022 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;
023
024/**
025 * Handler for lambda expressions.
026 *
027 */
028public class LambdaHandler extends AbstractExpressionHandler {
029    /**
030     * Checks whether the lambda is correctly indented, this variable get its value from checking
031     * the lambda handler's indentation, and it is being used in aligning the lambda's children.
032     * A true value depicts lambda is correctly aligned without giving any errors.
033     * This is updated to false where there is any Indentation error log.
034     */
035    private boolean isLambdaCorrectlyIndented = true;
036
037    /**
038     * Construct an instance of this handler with the given indentation check,
039     * abstract syntax tree, and parent handler.
040     *
041     * @param indentCheck the indentation check
042     * @param ast the abstract syntax tree
043     * @param parent the parent handler
044     */
045    public LambdaHandler(IndentationCheck indentCheck,
046                         DetailAST ast, AbstractExpressionHandler parent) {
047        super(indentCheck, "lambda", ast, parent);
048    }
049
050    @Override
051    public IndentLevel getSuggestedChildIndent(AbstractExpressionHandler child) {
052        IndentLevel childIndent = getIndent();
053        if (isLambdaCorrectlyIndented) {
054            childIndent = IndentLevel.addAcceptable(childIndent, getLineStart(getMainAst()),
055                    getLineStart(getMainAst().getFirstChild()));
056        }
057
058        return childIndent;
059    }
060
061    /**
062     * {@inheritDoc}.
063     *
064     * @noinspection MethodWithMultipleReturnPoints
065     */
066    @Override
067    protected IndentLevel getIndentImpl() {
068        if (getParent() instanceof MethodCallHandler) {
069            return getParent().getSuggestedChildIndent(this);
070        }
071
072        DetailAST parent = getMainAst().getParent();
073        if (getParent() instanceof NewHandler) {
074            parent = parent.getParent();
075        }
076
077        // Use the start of the parent's line as the reference indentation level.
078        IndentLevel level = new IndentLevel(getLineStart(parent));
079
080        // If the start of the lambda is the first element on the line;
081        // assume line wrapping with respect to its parent.
082        final DetailAST firstChild = getMainAst().getFirstChild();
083        if (getLineStart(firstChild) == expandedTabsColumnNo(firstChild)) {
084            level = new IndentLevel(level, getIndentCheck().getLineWrappingIndentation());
085        }
086
087        return level;
088    }
089
090    @Override
091    public void checkIndentation() {
092        final DetailAST mainAst = getMainAst();
093        final DetailAST firstChild = mainAst.getFirstChild();
094
095        // If the "->" has no children, it is a switch
096        // rule lambda (i.e. 'case ONE -> 1;')
097        final boolean isSwitchRuleLambda = firstChild == null;
098
099        if (!isSwitchRuleLambda
100            && getLineStart(firstChild) == expandedTabsColumnNo(firstChild)) {
101            final int firstChildColumnNo = expandedTabsColumnNo(firstChild);
102            final IndentLevel level = getIndent();
103
104            if (isNonAcceptableIndent(firstChildColumnNo, level)) {
105                isLambdaCorrectlyIndented = false;
106                logError(firstChild, "arguments", firstChildColumnNo, level);
107            }
108        }
109
110        // If the "->" is the first element on the line, assume line wrapping.
111        final int mainAstColumnNo = expandedTabsColumnNo(mainAst);
112        final boolean isLineWrappedLambda = mainAstColumnNo == getLineStart(mainAst);
113        if (isLineWrappedLambda) {
114            checkLineWrappedLambda(isSwitchRuleLambda, mainAstColumnNo);
115        }
116    }
117
118    /**
119     * Checks that given indent is acceptable or not.
120     *
121     * @param astColumnNo indent value to check
122     * @param level indent level
123     * @return true if indent is not acceptable
124     */
125    private boolean isNonAcceptableIndent(int astColumnNo, IndentLevel level) {
126        return astColumnNo < level.getFirstIndentLevel()
127            || getIndentCheck().isForceStrictCondition()
128               && !level.isAcceptable(astColumnNo);
129    }
130
131    /**
132     * This method checks a line wrapped lambda, whether it is a lambda
133     * expression or switch rule lambda.
134     *
135     * @param isSwitchRuleLambda if mainAst is a switch rule lambda
136     * @param mainAstColumnNo the column number of the lambda we are checking
137     */
138    private void checkLineWrappedLambda(final boolean isSwitchRuleLambda,
139                                        final int mainAstColumnNo) {
140        final IndentLevel level;
141        final DetailAST mainAst = getMainAst();
142
143        if (isSwitchRuleLambda) {
144            // We check the indentation of the case literal or default literal
145            // on the previous line and use that to determine the correct
146            // indentation for the line wrapped "->"
147            final DetailAST previousSibling = mainAst.getPreviousSibling();
148            final int previousLineStart = getLineStart(previousSibling);
149
150            level = new IndentLevel(new IndentLevel(previousLineStart),
151                    getIndentCheck().getLineWrappingIndentation());
152        }
153        else {
154            level = new IndentLevel(getIndent(),
155                getIndentCheck().getLineWrappingIndentation());
156        }
157
158        if (isNonAcceptableIndent(mainAstColumnNo, level)) {
159            isLambdaCorrectlyIndented = false;
160            logError(mainAst, "", mainAstColumnNo, level);
161        }
162    }
163}