001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2020 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 java.util.ArrayDeque;
023import java.util.Deque;
024import java.util.HashSet;
025import java.util.Set;
026
027import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
028import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
029import com.puppycrawl.tools.checkstyle.api.DetailAST;
030
031/**
032 * <p>
033 * Checks correct indentation of Java code.
034 * </p>
035 * <p>
036 * The idea behind this is that while
037 * pretty printers are sometimes convenient for bulk reformats of
038 * legacy code, they often either aren't configurable enough or
039 * just can't anticipate how format should be done. Sometimes this is
040 * personal preference, other times it is practical experience. In any
041 * case, this check should just ensure that a minimal set of indentation
042 * rules is followed.
043 * </p>
044 * <p>
045 * Basic offset indentation is used for indentation inside code blocks.
046 * For any lines that span more than 1, line wrapping indentation is used for those lines
047 * after the first. Brace adjustment, case, and throws indentations are all used only if
048 * those specific identifiers start the line. If, for example, a brace is used in the
049 * middle of the line, its indentation will not take effect. All indentations have an
050 * accumulative/recursive effect when they are triggered. If during a line wrapping, another
051 * code block is found and it doesn't end on that same line, then the subsequent lines
052 * afterwards, in that new code block, are increased on top of the line wrap and any
053 * indentations above it.
054 * </p>
055 * <p>
056 * Example:
057 * </p>
058 * <pre>
059 * if ((condition1 &amp;&amp; condition2)
060 *         || (condition3 &amp;&amp; condition4)    // line wrap with bigger indentation
061 *         ||!(condition5 &amp;&amp; condition6)) { // line wrap with bigger indentation
062 *   field.doSomething()                    // basic offset
063 *       .doSomething()                     // line wrap
064 *       .doSomething( c -&gt; {               // line wrap
065 *         return c.doSome();               // basic offset
066 *       });
067 * }
068 * </pre>
069 * <ul>
070 * <li>
071 * Property {@code basicOffset} - Specify how far new indentation level should be
072 * indented when on the next line.
073 * Type is {@code int}.
074 * Default value is {@code 4}.
075 * </li>
076 * <li>
077 * Property {@code braceAdjustment} - Specify how far a braces should be indented
078 * when on the next line.
079 * Type is {@code int}.
080 * Default value is {@code 0}.
081 * </li>
082 * <li>
083 * Property {@code caseIndent} - Specify how far a case label should be indented
084 * when on next line.
085 * Type is {@code int}.
086 * Default value is {@code 4}.
087 * </li>
088 * <li>
089 * Property {@code throwsIndent} - Specify how far a throws clause should be
090 * indented when on next line.
091 * Type is {@code int}.
092 * Default value is {@code 4}.
093 * </li>
094 * <li>
095 * Property {@code arrayInitIndent} - Specify how far an array initialisation
096 * should be indented when on next line.
097 * Type is {@code int}.
098 * Default value is {@code 4}.
099 * </li>
100 * <li>
101 * Property {@code lineWrappingIndentation} - Specify how far continuation line
102 * should be indented when line-wrapping is present.
103 * Type is {@code int}.
104 * Default value is {@code 4}.
105 * </li>
106 * <li>
107 * Property {@code forceStrictCondition} - Force strict indent level in line
108 * wrapping case. If value is true, line wrap indent have to be same as
109 * lineWrappingIndentation parameter. If value is false, line wrap indent
110 * could be bigger on any value user would like.
111 * Type is {@code boolean}.
112 * Default value is {@code false}.
113 * </li>
114 * </ul>
115 * <p>
116 * To configure the check for default behavior:
117 * </p>
118 * <pre>
119 * &lt;module name="Indentation"/&gt;
120 * </pre>
121 * <p>
122 * Example of Compliant code for default configuration (in comment name of property
123 * that controls indentations):
124 * </p>
125 * <pre>
126 * class Test {
127 *    String field;               // basicOffset
128 *    int[] arr = {               // basicOffset
129 *        5,                      // arrayInitIndent
130 *        6 };                    // arrayInitIndent
131 *    void bar() throws Exception // basicOffset
132 *    {                           // braceAdjustment
133 *        foo();                  // basicOffset
134 *    }                           // braceAdjustment
135 *    void foo() {                // basicOffset
136 *        if ((cond1 &amp;&amp; cond2)    // basicOffset
137 *                  || (cond3 &amp;&amp; cond4)    // lineWrappingIndentation, forceStrictCondition
138 *                  ||!(cond5 &amp;&amp; cond6)) { // lineWrappingIndentation, forceStrictCondition
139 *            field.doSomething()          // basicOffset
140 *                .doSomething()           // lineWrappingIndentation and forceStrictCondition
141 *                .doSomething( c -&gt; {     // lineWrappingIndentation and forceStrictCondition
142 *                    return c.doSome();   // basicOffset
143 *                });
144 *        }
145 *    }
146 *    void fooCase()                // basicOffset
147 *        throws Exception {        // throwsIndent
148 *        switch (field) {          // basicOffset
149 *            case "value" : bar(); // caseIndent
150 *        }
151 *    }
152 * }
153 * </pre>
154 * <p>
155 * To configure the check to enforce the indentation style recommended by Oracle:
156 * </p>
157 * <pre>
158 * &lt;module name="Indentation"&gt;
159 *   &lt;property name="caseIndent" value="0"/&gt;
160 * &lt;/module&gt;
161 * </pre>
162 * <p>
163 * Example of Compliant code for default configuration (in comment name of property that controls
164 * indentation):
165 * </p>
166 * <pre>
167 * void fooCase() {          // basicOffset
168 *     switch (field) {      // basicOffset
169 *     case "value" : bar(); // caseIndent
170 *     }
171 * }
172 * </pre>
173 * <p>
174 * To configure the Check to enforce strict condition in line-wrapping validation.
175 * </p>
176 * <pre>
177 * &lt;module name="Indentation"&gt;
178 *   &lt;property name="forceStrictCondition" value="true"/&gt;
179 * &lt;/module&gt;
180 * </pre>
181 * <p>
182 * Such config doesn't allow next cases even code is aligned further to the right for better
183 * reading:
184 * </p>
185 * <pre>
186 * void foo(String aFooString,
187 *         int aFooInt) { // indent:8 ; expected: 4; violation, because 8 != 4
188 *     if (cond1
189 *         || cond2) {
190 *         field.doSomething()
191 *             .doSomething();
192 *     }
193 *     if ((cond1 &amp;&amp; cond2)
194 *               || (cond3 &amp;&amp; cond4)    // violation
195 *               ||!(cond5 &amp;&amp; cond6)) { // violation
196 *         field.doSomething()
197 *              .doSomething()          // violation
198 *              .doSomething( c -&gt; {    // violation
199 *                  return c.doSome();
200 *             });
201 *     }
202 * }
203 * </pre>
204 * <p>
205 * But if forceStrictCondition = false, this code is valid:
206 * </p>
207 * <pre>
208 * void foo(String aFooString,
209 *         int aFooInt) { // indent:8 ; expected: &gt; 4; ok, because 8 &gt; 4
210 *     if (cond1
211 *         || cond2) {
212 *         field.doSomething()
213 *             .doSomething();
214 *     }
215 *     if ((cond1 &amp;&amp; cond2)
216 *               || (cond3 &amp;&amp; cond4)
217 *               ||!(cond5 &amp;&amp; cond6)) {
218 *         field.doSomething()
219 *              .doSomething()
220 *              .doSomething( c -&gt; {
221 *                  return c.doSome();
222 *             });
223 *     }
224 * }
225 * </pre>
226 *
227 * <p>
228 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
229 * </p>
230 * <p>
231 * Violation Message Keys:
232 * </p>
233 * <ul>
234 * <li>
235 * {@code indentation.child.error}
236 * </li>
237 * <li>
238 * {@code indentation.child.error.multi}
239 * </li>
240 * <li>
241 * {@code indentation.error}
242 * </li>
243 * <li>
244 * {@code indentation.error.multi}
245 * </li>
246 * </ul>
247 * @noinspection ThisEscapedInObjectConstruction
248 * @since 3.1
249 */
250@FileStatefulCheck
251public class IndentationCheck extends AbstractCheck {
252
253    /*  -- Implementation --
254     *
255     *  Basically, this check requests visitation for all handled token
256     *  types (those tokens registered in the HandlerFactory).  When visitToken
257     *  is called, a new ExpressionHandler is created for the AST and pushed
258     *  onto the handlers stack.  The new handler then checks the indentation
259     *  for the currently visiting AST.  When leaveToken is called, the
260     *  ExpressionHandler is popped from the stack.
261     *
262     *  While on the stack the ExpressionHandler can be queried for the
263     *  indentation level it suggests for children as well as for other
264     *  values.
265     *
266     *  While an ExpressionHandler checks the indentation level of its own
267     *  AST, it typically also checks surrounding ASTs.  For instance, a
268     *  while loop handler checks the while loop as well as the braces
269     *  and immediate children.
270     *
271     *   - handler class -to-&gt; ID mapping kept in Map
272     *   - parent passed in during construction
273     *   - suggest child indent level
274     *   - allows for some tokens to be on same line (ie inner classes OBJBLOCK)
275     *     and not increase indentation level
276     *   - looked at using double dispatch for getSuggestedChildIndent(), but it
277     *     doesn't seem worthwhile, at least now
278     *   - both tabs and spaces are considered whitespace in front of the line...
279     *     tabs are converted to spaces
280     *   - block parents with parens -- for, while, if, etc... -- are checked that
281     *     they match the level of the parent
282     */
283
284    /**
285     * A key is pointing to the warning message text in "messages.properties"
286     * file.
287     */
288    public static final String MSG_ERROR = "indentation.error";
289
290    /**
291     * A key is pointing to the warning message text in "messages.properties"
292     * file.
293     */
294    public static final String MSG_ERROR_MULTI = "indentation.error.multi";
295
296    /**
297     * A key is pointing to the warning message text in "messages.properties"
298     * file.
299     */
300    public static final String MSG_CHILD_ERROR = "indentation.child.error";
301
302    /**
303     * A key is pointing to the warning message text in "messages.properties"
304     * file.
305     */
306    public static final String MSG_CHILD_ERROR_MULTI = "indentation.child.error.multi";
307
308    /** Default indentation amount - based on Sun. */
309    private static final int DEFAULT_INDENTATION = 4;
310
311    /** Handlers currently in use. */
312    private final Deque<AbstractExpressionHandler> handlers = new ArrayDeque<>();
313
314    /** Instance of line wrapping handler to use. */
315    private final LineWrappingHandler lineWrappingHandler = new LineWrappingHandler(this);
316
317    /** Factory from which handlers are distributed. */
318    private final HandlerFactory handlerFactory = new HandlerFactory();
319
320    /** Lines logged as having incorrect indentation. */
321    private Set<Integer> incorrectIndentationLines;
322
323    /** Specify how far new indentation level should be indented when on the next line. */
324    private int basicOffset = DEFAULT_INDENTATION;
325
326    /** Specify how far a case label should be indented when on next line. */
327    private int caseIndent = DEFAULT_INDENTATION;
328
329    /** Specify how far a braces should be indented when on the next line. */
330    private int braceAdjustment;
331
332    /** Specify how far a throws clause should be indented when on next line. */
333    private int throwsIndent = DEFAULT_INDENTATION;
334
335    /** Specify how far an array initialisation should be indented when on next line. */
336    private int arrayInitIndent = DEFAULT_INDENTATION;
337
338    /** Specify how far continuation line should be indented when line-wrapping is present. */
339    private int lineWrappingIndentation = DEFAULT_INDENTATION;
340
341    /**
342     * Force strict indent level in line wrapping case. If value is true, line wrap indent
343     * have to be same as lineWrappingIndentation parameter. If value is false, line wrap indent
344     * could be bigger on any value user would like.
345     */
346    private boolean forceStrictCondition;
347
348    /**
349     * Getter to query strict indent level in line wrapping case. If value is true, line wrap indent
350     * have to be same as lineWrappingIndentation parameter. If value is false, line wrap indent
351     * could be bigger on any value user would like.
352     *
353     * @return forceStrictCondition value.
354     */
355    public boolean isForceStrictCondition() {
356        return forceStrictCondition;
357    }
358
359    /**
360     * Setter to force strict indent level in line wrapping case. If value is true, line wrap indent
361     * have to be same as lineWrappingIndentation parameter. If value is false, line wrap indent
362     * could be bigger on any value user would like.
363     *
364     * @param value user's value of forceStrictCondition.
365     */
366    public void setForceStrictCondition(boolean value) {
367        forceStrictCondition = value;
368    }
369
370    /**
371     * Setter to specify how far new indentation level should be indented when on the next line.
372     *
373     * @param basicOffset   the number of tabs or spaces to indent
374     */
375    public void setBasicOffset(int basicOffset) {
376        this.basicOffset = basicOffset;
377    }
378
379    /**
380     * Getter to query how far new indentation level should be indented when on the next line.
381     *
382     * @return the number of tabs or spaces to indent
383     */
384    public int getBasicOffset() {
385        return basicOffset;
386    }
387
388    /**
389     * Setter to specify how far a braces should be indented when on the next line.
390     *
391     * @param adjustmentAmount   the brace offset
392     */
393    public void setBraceAdjustment(int adjustmentAmount) {
394        braceAdjustment = adjustmentAmount;
395    }
396
397    /**
398     * Getter to query how far a braces should be indented when on the next line.
399     *
400     * @return the positive offset to adjust braces
401     */
402    public int getBraceAdjustment() {
403        return braceAdjustment;
404    }
405
406    /**
407     * Setter to specify how far a case label should be indented when on next line.
408     *
409     * @param amount   the case indentation level
410     */
411    public void setCaseIndent(int amount) {
412        caseIndent = amount;
413    }
414
415    /**
416     * Getter to query how far a case label should be indented when on next line.
417     *
418     * @return the case indentation level
419     */
420    public int getCaseIndent() {
421        return caseIndent;
422    }
423
424    /**
425     * Setter to specify how far a throws clause should be indented when on next line.
426     *
427     * @param throwsIndent the throws indentation level
428     */
429    public void setThrowsIndent(int throwsIndent) {
430        this.throwsIndent = throwsIndent;
431    }
432
433    /**
434     * Getter to query how far a throws clause should be indented when on next line.
435     *
436     * @return the throws indentation level
437     */
438    public int getThrowsIndent() {
439        return throwsIndent;
440    }
441
442    /**
443     * Setter to specify how far an array initialisation should be indented when on next line.
444     *
445     * @param arrayInitIndent the array initialisation indentation level
446     */
447    public void setArrayInitIndent(int arrayInitIndent) {
448        this.arrayInitIndent = arrayInitIndent;
449    }
450
451    /**
452     * Getter to query how far an array initialisation should be indented when on next line.
453     *
454     * @return the initialisation indentation level
455     */
456    public int getArrayInitIndent() {
457        return arrayInitIndent;
458    }
459
460    /**
461     * Getter to query how far continuation line should be indented when line-wrapping is present.
462     *
463     * @return the line-wrapping indentation level
464     */
465    public int getLineWrappingIndentation() {
466        return lineWrappingIndentation;
467    }
468
469    /**
470     * Setter to specify how far continuation line should be indented when line-wrapping is present.
471     *
472     * @param lineWrappingIndentation the line-wrapping indentation level
473     */
474    public void setLineWrappingIndentation(int lineWrappingIndentation) {
475        this.lineWrappingIndentation = lineWrappingIndentation;
476    }
477
478    /**
479     * Log a violation message.
480     *
481     * @param  ast the ast for which error to be logged
482     * @param key the message that describes the violation
483     * @param args the details of the message
484     *
485     * @see java.text.MessageFormat
486     */
487    public void indentationLog(DetailAST ast, String key, Object... args) {
488        if (!incorrectIndentationLines.contains(ast.getLineNo())) {
489            incorrectIndentationLines.add(ast.getLineNo());
490            log(ast, key, args);
491        }
492    }
493
494    /**
495     * Get the width of a tab.
496     *
497     * @return the width of a tab
498     */
499    public int getIndentationTabWidth() {
500        return getTabWidth();
501    }
502
503    @Override
504    public int[] getDefaultTokens() {
505        return getRequiredTokens();
506    }
507
508    @Override
509    public int[] getAcceptableTokens() {
510        return getRequiredTokens();
511    }
512
513    @Override
514    public int[] getRequiredTokens() {
515        return handlerFactory.getHandledTypes();
516    }
517
518    @Override
519    public void beginTree(DetailAST ast) {
520        handlerFactory.clearCreatedHandlers();
521        handlers.clear();
522        final PrimordialHandler primordialHandler = new PrimordialHandler(this);
523        handlers.push(primordialHandler);
524        primordialHandler.checkIndentation();
525        incorrectIndentationLines = new HashSet<>();
526    }
527
528    @Override
529    public void visitToken(DetailAST ast) {
530        final AbstractExpressionHandler handler = handlerFactory.getHandler(this, ast,
531            handlers.peek());
532        handlers.push(handler);
533        handler.checkIndentation();
534    }
535
536    @Override
537    public void leaveToken(DetailAST ast) {
538        handlers.pop();
539    }
540
541    /**
542     * Accessor for the line wrapping handler.
543     *
544     * @return the line wrapping handler
545     */
546    public LineWrappingHandler getLineWrappingHandler() {
547        return lineWrappingHandler;
548    }
549
550    /**
551     * Accessor for the handler factory.
552     *
553     * @return the handler factory
554     */
555    public final HandlerFactory getHandlerFactory() {
556        return handlerFactory;
557    }
558
559}