Exemplo n.º 1
0
  public static void main(String[] args) {
    CommandLineOptions opts = new CommandLineOptions(args);

    List files;
    if (opts.containsCommaSeparatedFileList()) {
      files = collectFromCommaDelimitedString(opts.getInputFileName());
    } else {
      files = collectFilesFromOneName(opts.getInputFileName());
    }

    PMD pmd;
    if (opts.jdk13()) {
      pmd = new PMD(new TargetJDK1_3());
    } else {
      pmd = new PMD();
    }

    RuleContext ctx = new RuleContext();
    ctx.setReport(new Report());

    try {
      RuleSetFactory ruleSetFactory = new RuleSetFactory();
      RuleSet rules = ruleSetFactory.createRuleSet(opts.getRulesets());
      for (Iterator i = files.iterator(); i.hasNext(); ) {
        File file = (File) i.next();
        ctx.setSourceCodeFilename(
            glomName(opts.shortNamesEnabled(), opts.getInputFileName(), file));
        try {
          pmd.processFile(new FileInputStream(file), opts.getEncoding(), rules, ctx);
        } catch (PMDException pmde) {
          if (opts.debugEnabled()) {
            pmde.getReason().printStackTrace();
          }
          ctx.getReport()
              .addError(
                  new Report.ProcessingError(
                      pmde.getMessage(),
                      glomName(opts.shortNamesEnabled(), opts.getInputFileName(), file)));
        }
      }
    } catch (FileNotFoundException fnfe) {
      System.out.println(opts.usage());
      fnfe.printStackTrace();
    } catch (RuleSetNotFoundException rsnfe) {
      System.out.println(opts.usage());
      rsnfe.printStackTrace();
    }

    try {
      Renderer r = opts.createRenderer();
      System.out.println(r.render(ctx.getReport()));
    } catch (Exception e) {
      System.out.println(e.getMessage());
      System.out.println(opts.usage());
      if (opts.debugEnabled()) {
        e.printStackTrace();
      }
    }
  }
  public Object visit(ASTMethodDeclaration node, Object data) {
    if (interfaceSkipper == true) { // skip methods in interfaces
      return super.visit(node, data);
    }
    ASTResultType rt = (ASTResultType) node.jjtGetChild(0);
    if (rt.isVoid() == true) {
      return super.visit(node, data);
    }
    ASTType t = (ASTType) rt.jjtGetChild(0);
    if (t.jjtGetNumChildren() == 0 || !(t.jjtGetChild(0) instanceof ASTName)) {
      return super.visit(node, data);
    }
    String returnVariableName = null;
    List finder = new ArrayList();
    GET_RETURN_VARIABLE_NAME:
    {
      node.findChildrenOfType(ASTReturnStatement.class, finder, true);
      if (finder.size() != 1) {
        return super.visit(node, data);
      }
      ASTReturnStatement rs =
          (ASTReturnStatement)
              finder.get(0); // EXPLODES IF THE CLASS IS AN INTERFACE SINCE NO RETURN

      finder.clear();
      rs.findChildrenOfType(ASTPrimaryExpression.class, finder, true);
      ASTPrimaryExpression ape = (ASTPrimaryExpression) finder.get(0);
      Node lastChild = ape.jjtGetChild(ape.jjtGetNumChildren() - 1);
      if (lastChild instanceof ASTPrimaryPrefix) {
        returnVariableName = getNameFromPrimaryPrefix((ASTPrimaryPrefix) lastChild);
      }
      if (returnVariableName == null) {
        return super.visit(node, data);
      }
    }
    CHECK_OUTER_IF:
    {
      finder.clear();
      node.findChildrenOfType(ASTIfStatement.class, finder, true);
      if (finder.size() == 2) {
        ASTIfStatement is = (ASTIfStatement) finder.get(0);
        if (ifVerify(is, returnVariableName)) {
          // find synchronized
          finder.clear();
          is.findChildrenOfType(ASTSynchronizedStatement.class, finder, true);
          if (finder.size() == 1) {
            ASTSynchronizedStatement ss = (ASTSynchronizedStatement) finder.get(0);
            finder.clear();
            ss.findChildrenOfType(ASTIfStatement.class, finder, true);
            if (finder.size() == 1) {
              ASTIfStatement is2 = (ASTIfStatement) finder.get(0);
              if (ifVerify(is2, returnVariableName)) {
                finder.clear();
                is2.findChildrenOfType(ASTStatementExpression.class, finder, true);
                if (finder.size() == 1) {
                  ASTStatementExpression se = (ASTStatementExpression) finder.get(0);
                  if (se.jjtGetNumChildren()
                      == 3) { // primaryExpression, AssignmentOperator, Expression
                    if (se.jjtGetChild(0) instanceof ASTPrimaryExpression) {
                      ASTPrimaryExpression pe = (ASTPrimaryExpression) se.jjtGetChild(0);
                      if (matchName(pe, returnVariableName)) {
                        if (se.jjtGetChild(1) instanceof ASTAssignmentOperator) {
                          RuleContext ctx = (RuleContext) data;
                          ctx.getReport()
                              .addRuleViolation(createRuleViolation(ctx, node.getBeginLine()));
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
    return super.visit(node, data);
  }
Exemplo n.º 3
0
 /**
  * Constructor which shares attributes and report listeners with the given RuleContext.
  *
  * @param ruleContext the context from which the values are shared
  */
 public RuleContext(RuleContext ruleContext) {
   this.attributes = ruleContext.attributes;
   this.report.addSynchronizedListeners(ruleContext.getReport().getSynchronizedListeners());
 }
Exemplo n.º 4
0
  private void updateMarkers(IFile file, RuleContext context, boolean fTask)
      throws CoreException, PropertiesException {

    Map<IFile, Set<MarkerInfo2>> accumulator = getAccumulator();
    Set<MarkerInfo2> markerSet = new HashSet<MarkerInfo2>();
    List<Review> reviewsList = findReviewedViolations(file);
    Review review = new Review();
    Iterator<RuleViolation> iter = context.getReport().iterator();
    //        final IPreferences preferences = PMDPlugin.getDefault().loadPreferences();
    //        final int maxViolationsPerFilePerRule = preferences.getMaxViolationsPerFilePerRule();
    Map<Rule, Integer> violationsByRule = new HashMap<Rule, Integer>();

    Rule rule = null;
    while (iter.hasNext()) {
      RuleViolation violation = iter.next();
      rule = violation.getRule();
      review.ruleName = rule.getName();
      review.lineNumber = violation.getBeginLine();

      if (reviewsList.contains(review)) {
        log.debug(
            "Ignoring violation of rule "
                + rule.getName()
                + " at line "
                + violation.getBeginLine()
                + " because of a review.");
        continue;
      }

      Integer count = violationsByRule.get(rule);
      if (count == null) {
        count = NumericConstants.ZERO;
        violationsByRule.put(rule, count);
      }

      int maxViolations = maxAllowableViolationsFor(rule);

      if (count.intValue() < maxViolations) {
        // Ryan Gustafson 02/16/2008 - Always use PMD_MARKER, as people get confused as to why PMD
        // problems don't always show up on Problems view like they do when you do build.
        // markerSet.add(getMarkerInfo(violation, fTask ? PMDRuntimeConstants.PMD_TASKMARKER :
        // PMDRuntimeConstants.PMD_MARKER));
        markerSet.add(getMarkerInfo(violation, markerTypeFor(violation)));
        /*
        if (isDfaEnabled && violation.getRule().usesDFA()) {
            markerSet.add(getMarkerInfo(violation, PMDRuntimeConstants.PMD_DFA_MARKER));
        } else {
             markerSet.add(getMarkerInfo(violation, fTask ? PMDRuntimeConstants.PMD_TASKMARKER : PMDRuntimeConstants.PMD_MARKER));
        }
         */
        violationsByRule.put(rule, Integer.valueOf(count.intValue() + 1));

        log.debug(
            "Adding a violation for rule "
                + rule.getName()
                + " at line "
                + violation.getBeginLine());
      } else {
        log.debug(
            "Ignoring violation of rule "
                + rule.getName()
                + " at line "
                + violation.getBeginLine()
                + " because maximum violations has been reached for file "
                + file.getName());
      }
    }

    if (accumulator != null) {
      log.debug("Adding markerSet to accumulator for file " + file.getName());
      accumulator.put(file, markerSet);
    }
  }