//===--- MyFirstCheckCheck.cpp - clang-tidy -------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "MyFirstCheckCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace gjb {

void MyFirstCheckCheck::registerMatchers(MatchFinder *Finder) {
  // FIXME: Add matchers.
  Finder->addMatcher(
functionDecl(isExpansionInMainFile(),
             anyOf(hasDescendant(compoundStmt().bind("cpd")),
                   unless(hasDescendant(compoundStmt().bind("cpd")))),
             anyOf(hasDescendant(returnStmt().bind("ret")),
                   unless(hasDescendant(returnStmt().bind("ret")))))
    .bind("func"),
this);
}

void MyFirstCheckCheck::check(const MatchFinder::MatchResult &Result) {
  // FIXME: Add callback implementation.

  /// get Node which we want to get
  if(const auto *MatchedDecl =
          Result.Nodes.getNodeAs<FunctionDecl>("func")){
    /// ReturnType is not 'void' or 'void *'
    if(MatchedDecl->getReturnType().getAsString() != "void"
        && MatchedDecl->getReturnType().getAsString() != "void *"
        /// Func Name is not "main"
        && MatchedDecl->getName() != "main"){
      /// Func has definition
      if(const auto *MatchedCpd =
              Result.Nodes.getNodeAs<CompoundStmt>("cpd")){
        /// Func has ReturnStmt
        if(const auto *MatchedStmt =
                Result.Nodes.getNodeAs<ReturnStmt>("ret")){
        }
        /// Func does not have ReturnStmt
        else{
          diag(MatchedDecl->getLocation(),
           "Function '%0' has no return") << MatchedDecl->getName();
        }
      }
    }
  }
}

} // namespace gjb
} // namespace tidy
} // namespace clang
