Source code: com/puppycrawl/tools/checkstyle/checks/FinalParametersCheck.java
1 ////////////////////////////////////////////////////////////////////////////////
2 // checkstyle: Checks Java source code for adherence to a set of rules.
3 // Copyright (C) 2001-2003 Oliver Burn
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
14 //
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 ////////////////////////////////////////////////////////////////////////////////
19 package com.puppycrawl.tools.checkstyle.checks;
20
21 import com.puppycrawl.tools.checkstyle.api.Check;
22 import com.puppycrawl.tools.checkstyle.api.TokenTypes;
23 import com.puppycrawl.tools.checkstyle.api.DetailAST;
24
25 /**
26 * Check that method/constructor parameters are final.
27 * The user can set the token set to METHOD_DEF, CONSTRUCTOR_DEF, or both
28 * (default), to control the scope of this check.
29 *
30 * @author lkuehne
31 */
32 public class FinalParametersCheck extends Check
33 {
34 /** @see Check */
35 public int[] getDefaultTokens()
36 {
37 return new int[] {TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF};
38 }
39
40 /** @see Check */
41 public void visitToken(DetailAST aAST)
42 {
43 // don't flag interfaces
44 final DetailAST container = aAST.getParent().getParent();
45 if (container.getType() == TokenTypes.INTERFACE_DEF) {
46 return;
47 }
48
49 // exit on fast lane if there is nothing to check here
50 if (!aAST.branchContains(TokenTypes.PARAMETER_DEF)) {
51 return;
52 }
53
54 // we can now be sure that there is at least one parameter
55
56 DetailAST parameters = aAST.findFirstToken(TokenTypes.PARAMETERS);
57 DetailAST child = (DetailAST) parameters.getFirstChild();
58 while (child != null) {
59 // childs are PARAMETER_DEF and COMMA
60 if (child.getType() == TokenTypes.PARAMETER_DEF
61 && !child.branchContains(TokenTypes.FINAL))
62 {
63 DetailAST paramName = child.findFirstToken(TokenTypes.IDENT);
64 // TODO: i18n
65 log(child.getLineNo(), child.getColumnNo(),
66 "Parameter " + paramName.getText() + " should be final.");
67 }
68 child = (DetailAST) child.getNextSibling();
69 }
70
71
72 }
73 }