Added getAcceptableTokens to Check.

Prevent registration for tokens the Check is not
designed for
This commit is contained in:
Lars Kühne 2002-11-02 06:48:52 +00:00
parent 2effcfd0bc
commit a2fded8ed7
3 changed files with 45 additions and 1 deletions

View File

@ -30,6 +30,7 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Arrays;
/**
* Responsible for walking an abstract syntax tree and notifying interested
@ -73,9 +74,16 @@ class TreeWalker
aCheck.setMessages(mMessages);
aCheck.setTabWidth(mTabWidth);
if (!aConfig.getTokens().isEmpty()) {
int acceptableTokens[] = aCheck.getAcceptableTokens();
Arrays.sort(acceptableTokens);
final Iterator it = aConfig.getTokens().iterator();
while (it.hasNext()) {
registerCheck((String) it.next(), aCheck);
String token = (String) it.next();
int tokenId = TokenTypes.getTokenId(token);
if (Arrays.binarySearch(acceptableTokens, tokenId) >= 0) {
registerCheck(token, aCheck);
}
// TODO: else error message?
}
}
else {

View File

@ -19,6 +19,7 @@
package com.puppycrawl.tools.checkstyle.api;
import java.util.Map;
import java.util.Arrays;
/**
* The base class for checks.
@ -55,6 +56,27 @@ public abstract class Check
*/
public abstract int[] getDefaultTokens();
/**
* The token set this check is designed for. Used to protect Checks
* against malicious users who specify a meaningless token set in the
* config file.
* The default implementations returns the check's default tokens.
* @return the token set this check is designed for.
*/
public int[] getAcceptableTokens()
{
int[] defaultTokens = getDefaultTokens();
int[] copy = new int[defaultTokens.length];
System.arraycopy(defaultTokens, 0, copy, 0, defaultTokens.length);
return copy;
}
// TODO: oburn on checkstyle-dev: another method should be added
// to specify the tokens that a check must have. For some checks to
// work, they must be registered for some tokens.
/**
* Return the global context object for check. This context is valid for
* the lifetime of the check.

View File

@ -388,4 +388,18 @@ public class TokenTypes
}
return name;
}
/**
* Returns the ID of a token for a given name.
* @param aName the name of the token ID to get
* @return a token ID
*/
public static int getTokenId(String aName)
{
final Integer id = (Integer) TOKEN_NAME_TO_VALUE.get(aName);
if (id == null) {
throw new IllegalArgumentException("given name " + aName);
}
return id.intValue();
}
}