Menu

Howto write a Check for Tabspace present in Whitespace of Code

AbhishekKr
2014-03-12
2014-04-26
  • AbhishekKr

    AbhishekKr - 2014-03-12

    We were thinking of removing our usage requirement of Checkstyle tool and bring all those as custom rules in PMD which aren't already there.

    Having a hard time figuring out Tabspace presence in code as can't see it's occurence from AST (if possible let know).

    How can one do it? Is it possible by overriding some baseclass stuff, at least?

     
  • Andreas Dangel

    Andreas Dangel - 2014-04-26

    I don't think, it is possible with PMD right now, to check for tabs in files. This is a whitespace character, that is ignored by the lexer already, so you won't find it in the AST anymore.

    Checkstyle implements this by directly looking into the file without parsing it, see the FileTabCharacterCheck. The indentation checks are mapping the AST nodes to the source lines - each checkstyle check has access to the raw content of the source file.

    With PMD, you could do the same: RuleContext gives you the current file that is checked. You can open this file and check each line for tab characters.
    If you need to map the lines to AST nodes, you can use Node.getBeginLine() to get the begin line, end line, and the columns, if needed.
    If you just want to check for tab characters, you could write a minimal java rule:

    import java.io.FileInputStream;
    import java.io.IOException;
    
    import net.sourceforge.pmd.RuleContext;
    import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
    import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
    
    import org.apache.commons.io.IOUtils;
    
    public class TabRule extends AbstractJavaRule {
    
        public Object visit(ASTCompilationUnit node, Object data) {
            RuleContext ctx = (RuleContext)data;
            FileInputStream file = null;
            try {
                file = new FileInputStream(ctx.getSourceCodeFile());
                String source = IOUtils.toString(file, "UTF-8");
                if (source.indexOf("\t") != -1) {
                    addViolation(data, node);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                IOUtils.closeQuietly(file);
            }
            return data;
        }
    }
    
     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.