void MisleadingIndentationCheck::registerMatchers(MatchFinder *Finder) {
  Finder->addMatcher(ifStmt(hasElse(stmt())).bind("if"), this);
  Finder->addMatcher(
      compoundStmt(has(stmt(anyOf(ifStmt(), forStmt(), whileStmt()))))
          .bind("compound"),
      this);
}
void MultiwayPathsCoveredCheck::registerMatchers(MatchFinder *Finder) {
  Finder->addMatcher(
      switchStmt(
          hasCondition(allOf(
              // Match on switch statements that have either a bit-field or
              // an integer condition. The ordering in 'anyOf()' is
              // important because the last condition is the most general.
              anyOf(ignoringImpCasts(memberExpr(hasDeclaration(
                        fieldDecl(isBitField()).bind("bitfield")))),
                    ignoringImpCasts(declRefExpr().bind("non-enum-condition"))),
              // 'unless()' must be the last match here and must be bound,
              // otherwise the matcher does not work correctly, because it
              // will not explicitly ignore enum conditions.
              unless(ignoringImpCasts(
                  declRefExpr(hasType(enumType())).bind("enum-condition"))))))
          .bind("switch"),
      this);

  // This option is noisy, therefore matching is configurable.
  if (WarnOnMissingElse) {
    Finder->addMatcher(
        ifStmt(allOf(hasParent(ifStmt()), unless(hasElse(anything()))))
            .bind("else-if"),
        this);
  }
}
void DeleteNullPointerCheck::registerMatchers(MatchFinder *Finder) {
  const auto DeleteExpr =
      cxxDeleteExpr(has(castExpr(has(declRefExpr(
                        to(decl(equalsBoundNode("deletedPointer"))))))))
          .bind("deleteExpr");

  const auto DeleteMemberExpr =
      cxxDeleteExpr(has(castExpr(has(memberExpr(hasDeclaration(
                        fieldDecl(equalsBoundNode("deletedMemberPointer"))))))))
          .bind("deleteMemberExpr");

  const auto PointerExpr = ignoringImpCasts(anyOf(
      declRefExpr(to(decl().bind("deletedPointer"))),
      memberExpr(hasDeclaration(fieldDecl().bind("deletedMemberPointer")))));

  const auto PointerCondition = castExpr(hasCastKind(CK_PointerToBoolean),
                                         hasSourceExpression(PointerExpr));
  const auto BinaryPointerCheckCondition =
      binaryOperator(hasEitherOperand(castExpr(hasCastKind(CK_NullToPointer))),
                     hasEitherOperand(PointerExpr));

  Finder->addMatcher(
      ifStmt(hasCondition(anyOf(PointerCondition, BinaryPointerCheckCondition)),
             hasThen(anyOf(
                 DeleteExpr, DeleteMemberExpr,
                 compoundStmt(anyOf(has(DeleteExpr), has(DeleteMemberExpr)),
                              statementCountIs(1))
                     .bind("compound"))))
          .bind("ifWithDelete"),
      this);
}
void AssertSideEffectCheck::registerMatchers(MatchFinder *Finder) {
  auto ConditionWithSideEffect =
      hasCondition(hasDescendant(expr(hasSideEffect(CheckFunctionCalls))));
  Finder->addMatcher(
      stmt(anyOf(conditionalOperator(ConditionWithSideEffect),
                 ifStmt(ConditionWithSideEffect))).bind("condStmt"),
      this);
}
void ElseAfterReturnCheck::registerMatchers(MatchFinder *Finder) {
  // FIXME: Support continue, break and throw.
  Finder->addMatcher(
      ifStmt(
          hasThen(stmt(anyOf(returnStmt(), compoundStmt(has(returnStmt()))))),
          hasElse(stmt().bind("else"))).bind("if"),
      this);
}
Ejemplo n.º 6
0
    /*Conjunto de Construções*/
    void SyntaxAnalysis::expression() {

        Token::Token tokenTemp = vecToken[0];
        Token::Token recover;

        Tree::Tree * tempTree = subTree;
        setAndAdvance(EXPSTRING);

        switch (tokenTemp.getTokenType()) {

            case(Token::INTEGER): case(Token::FLOAT): case(Token::VOID):
                targetAdvance();
                variableDecStmt();
                break;

            case(Token::WRITE):
                writeStmt();
                break;

            case(Token::READ):
                readStmt();
                break;

            case(Token::RETURN):
                returnValue();
                break;

            case(Token::IDENTIFIER):
                recover = tokenTemp;
                tokenTemp = targetAdvance();
                switch (tokenTemp.getTokenType()) {

                    case(Token::ATTRIBUTION):
                        attributionStmt();
                        break;

                    case(Token::OPEN):
                        functionCallStmt();
                        break;

                    default: this->error.expressionError(recover);
                }
                break;

            case(Token::IF):
                ifStmt();
                break;

            case(Token::REPEAT):
                whileStmt();
                break;

            default: this->error.expressionError(tokenTemp);
        }

        subTree = tempTree;
    }
Ejemplo n.º 7
0
void MustUseChecker::registerMatchers(MatchFinder *AstMatcher) {
  AstMatcher->addMatcher(switchCase().bind("switchcase"), this);
  AstMatcher->addMatcher(compoundStmt().bind("compound"), this);
  AstMatcher->addMatcher(ifStmt().bind("if"), this);
  AstMatcher->addMatcher(whileStmt().bind("while"), this);
  AstMatcher->addMatcher(doStmt().bind("do"), this);
  AstMatcher->addMatcher(forStmt().bind("for"), this);
  AstMatcher->addMatcher(binaryOperator(binaryCommaOperator()).bind("bin"),
                         this);
}
Ejemplo n.º 8
0
TEST_F(TestIRVisitor, TestWalker)
{
    IRTypes types;
    IRValue* condVar =
        new IRLocalVar("cond", types.GetBoolTy(), kIRUniform, NULL);
    IRStmt* thenStmt = MakeBlock(&types);
    IRStmt* elseStmt = MakeBlock(&types, true);
    IRIfStmt ifStmt(condVar, thenStmt, elseStmt, IRPos());
    Walker().Dispatch<void>(&ifStmt, 0);
}
Ejemplo n.º 9
0
void FunctionSizeCheck::registerMatchers(MatchFinder *Finder) {
  Finder->addMatcher(
      functionDecl(
          unless(isInstantiated()),
          forEachDescendant(
              stmt(unless(compoundStmt()),
                   hasParent(stmt(anyOf(compoundStmt(), ifStmt(),
                                        anyOf(whileStmt(), doStmt(),
                                              forRangeStmt(), forStmt())))))
                  .bind("stmt"))).bind("func"),
      this);
}
void ElseAfterReturnCheck::registerMatchers(MatchFinder *Finder) {
  const auto ControlFlowInterruptorMatcher =
      stmt(anyOf(returnStmt().bind("return"), continueStmt().bind("continue"),
                 breakStmt().bind("break"), cxxThrowExpr().bind("throw")));
  Finder->addMatcher(
      stmt(forEach(
          ifStmt(hasThen(stmt(
                     anyOf(ControlFlowInterruptorMatcher,
                           compoundStmt(has(ControlFlowInterruptorMatcher))))),
                 hasElse(stmt().bind("else")))
              .bind("if"))),
      this);
}
Ejemplo n.º 11
0
// }}}
// {{{ stmt
std::unique_ptr<Stmt> FlowParser::stmt()
{
	FNTRACE();

	switch (token()) {
		case FlowToken::If:
			return ifStmt();
		case FlowToken::Begin:
			return compoundStmt();
		case FlowToken::Ident:
			return callStmt();
		case FlowToken::Semicolon: {
			FlowLocation sloc(location());
			nextToken();
			return std::make_unique<CompoundStmt>(sloc.update(end()));
		}
		default:
			reportError("Unexpected token '%s'. Expected a statement instead.", token().c_str());
			return nullptr;
	}
}
Ejemplo n.º 12
0
ASTNode* Parser::statement()
{
	_stmtNum++;

	if (isKeyword("while")) {
		return whileStmt();
	}

	if (isKeyword("if")) {
		return ifStmt();
	}

	if (isKeyword("call")) {
		return callStmt();
	}

	if (isName()) {
		return assignStmt();
	}

	throw ParseException(_stmtNum, _token, "Unable to parse statement");
}
Ejemplo n.º 13
0
TEST_F(TestIRStmt, TestIfStmt)
{
    IRTypes types;
    IRValue* condVar =
        new IRLocalVar("cond", types.GetBoolTy(), kIRUniform, NULL);
    IRStmt* thenStmt = MakeBlock(&types);
    IRStmt* elseStmt = new IRSeq();
    IRIfStmt ifStmt(condVar, thenStmt, elseStmt, IRPos());
    std::cout << ifStmt;

    EXPECT_EQ(condVar, ifStmt.GetCond());
    EXPECT_EQ(thenStmt, ifStmt.GetThen());
    EXPECT_EQ(elseStmt, ifStmt.GetElse());

    // Test casting
    const IRStmt* s1 = UtStaticCast<const IRStmt*>(&ifStmt);
    const IRStmt* s2 = UtCast<const IRStmt*>(&ifStmt);
    EXPECT_TRUE(s2 != NULL);

    const IRStmt* s3 = UtStaticCast<const IRIfStmt*>(s1);
    const IRStmt* s4 = UtCast<const IRIfStmt*>(s2);
    EXPECT_TRUE(s4 != NULL);
}
Ejemplo n.º 14
0
ShPtr<Value> IfStmt::clone() {
	ShPtr<IfStmt> ifStmt(IfStmt::create(
		ucast<Expression>(ifClauseList.front().first->clone()),
		ucast<Statement>(ifClauseList.front().second->clone())));
	if (elseClause) {
		ifStmt->setElseClause(
			ucast<Statement>(elseClause->clone()));
	}

	// Clone all other clauses.
	for (const auto &clause : ifClauseList) {
		// The first clause has already been cloned, so skip it.
		if (clause == ifClauseList.front()) {
			continue;
		}
		ifStmt->addClause(
			ucast<Expression>(clause.first->clone()),
			ucast<Statement>(clause.second->clone()));
	}

	ifStmt->setMetadata(getMetadata());
	return ifStmt;
}
void SuspiciousStringCompareCheck::registerMatchers(MatchFinder *Finder) {
  // Match relational operators.
  const auto ComparisonUnaryOperator = unaryOperator(hasOperatorName("!"));
  const auto ComparisonBinaryOperator =
      binaryOperator(matchers::isComparisonOperator());
  const auto ComparisonOperator =
      expr(anyOf(ComparisonUnaryOperator, ComparisonBinaryOperator));

  // Add the list of known string compare-like functions and add user-defined
  // functions.
  std::vector<std::string> FunctionNames = utils::options::parseStringList(
      (llvm::Twine(KnownStringCompareFunctions) + StringCompareLikeFunctions)
          .str());

  // Match a call to a string compare functions.
  const auto FunctionCompareDecl =
      functionDecl(hasAnyName(std::vector<StringRef>(FunctionNames.begin(),
                                                     FunctionNames.end())))
          .bind("decl");
  const auto DirectStringCompareCallExpr =
      callExpr(hasDeclaration(FunctionCompareDecl)).bind("call");
  const auto MacroStringCompareCallExpr = conditionalOperator(anyOf(
      hasTrueExpression(ignoringParenImpCasts(DirectStringCompareCallExpr)),
      hasFalseExpression(ignoringParenImpCasts(DirectStringCompareCallExpr))));
  // The implicit cast is not present in C.
  const auto StringCompareCallExpr = ignoringParenImpCasts(
      anyOf(DirectStringCompareCallExpr, MacroStringCompareCallExpr));

  if (WarnOnImplicitComparison) {
    // Detect suspicious calls to string compare:
    //     'if (strcmp())'  ->  'if (strcmp() != 0)'
    Finder->addMatcher(
        stmt(anyOf(ifStmt(hasCondition(StringCompareCallExpr)),
                   whileStmt(hasCondition(StringCompareCallExpr)),
                   doStmt(hasCondition(StringCompareCallExpr)),
                   forStmt(hasCondition(StringCompareCallExpr)),
                   binaryOperator(
                       anyOf(hasOperatorName("&&"), hasOperatorName("||")),
                       hasEitherOperand(StringCompareCallExpr))))
            .bind("missing-comparison"),
        this);
  }

  if (WarnOnLogicalNotComparison) {
    // Detect suspicious calls to string compared with '!' operator:
    //     'if (!strcmp())'  ->  'if (strcmp() == 0)'
    Finder->addMatcher(unaryOperator(hasOperatorName("!"),
                                     hasUnaryOperand(ignoringParenImpCasts(
                                         StringCompareCallExpr)))
                           .bind("logical-not-comparison"),
                       this);
  }

  // Detect suspicious cast to an inconsistant type (i.e. not integer type).
  Finder->addMatcher(
      implicitCastExpr(unless(hasType(isInteger())),
                       hasSourceExpression(StringCompareCallExpr))
          .bind("invalid-conversion"),
      this);

  // Detect suspicious operator with string compare function as operand.
  Finder->addMatcher(
      binaryOperator(
          unless(anyOf(matchers::isComparisonOperator(), hasOperatorName("&&"),
                       hasOperatorName("||"), hasOperatorName("="))),
          hasEitherOperand(StringCompareCallExpr))
          .bind("suspicious-operator"),
      this);

  // Detect comparison to invalid constant: 'strcmp() == -1'.
  const auto InvalidLiteral = ignoringParenImpCasts(
      anyOf(integerLiteral(unless(equals(0))),
            unaryOperator(
                hasOperatorName("-"),
                has(ignoringParenImpCasts(integerLiteral(unless(equals(0)))))),
            characterLiteral(), cxxBoolLiteral()));

  Finder->addMatcher(binaryOperator(matchers::isComparisonOperator(),
                                    hasEitherOperand(StringCompareCallExpr),
                                    hasEitherOperand(InvalidLiteral))
                         .bind("invalid-comparison"),
                     this);
}
Ejemplo n.º 16
0
void Rule_6_4_2::registerMatchers(ast_matchers::MatchFinder *Finder) {
  Finder->addMatcher(
      ifStmt(hasElse(ifStmt(unless(hasElse(stmt()))).bind("if"))), this);
}