1 //===--- DefaultArgumentsDeclarationsCheck.cpp - clang-tidy ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "DefaultArgumentsDeclarationsCheck.h"
10 #include "clang/Lex/Lexer.h"
11 
12 using namespace clang::ast_matchers;
13 
14 namespace clang {
15 namespace tidy {
16 namespace fuchsia {
17 
registerMatchers(MatchFinder * Finder)18 void DefaultArgumentsDeclarationsCheck::registerMatchers(MatchFinder *Finder) {
19   // Declaring default parameters is disallowed.
20   Finder->addMatcher(parmVarDecl(hasDefaultArgument()).bind("decl"), this);
21 }
22 
check(const MatchFinder::MatchResult & Result)23 void DefaultArgumentsDeclarationsCheck::check(
24     const MatchFinder::MatchResult &Result) {
25   const auto *D = Result.Nodes.getNodeAs<ParmVarDecl>("decl");
26   if (!D)
27     return;
28 
29   SourceRange DefaultArgRange = D->getDefaultArgRange();
30 
31   if (DefaultArgRange.getEnd() != D->getEndLoc())
32     return;
33 
34   if (DefaultArgRange.getBegin().isMacroID()) {
35     diag(D->getBeginLoc(),
36          "declaring a parameter with a default argument is disallowed");
37     return;
38   }
39 
40   SourceLocation StartLocation =
41       D->getName().empty() ? D->getBeginLoc() : D->getLocation();
42 
43   SourceRange RemovalRange(
44       Lexer::getLocForEndOfToken(StartLocation, 0, *Result.SourceManager,
45                                  Result.Context->getLangOpts()),
46       DefaultArgRange.getEnd());
47 
48   diag(D->getBeginLoc(),
49        "declaring a parameter with a default argument is disallowed")
50       << D << FixItHint::CreateRemoval(RemovalRange);
51 }
52 
53 } // namespace fuchsia
54 } // namespace tidy
55 } // namespace clang
56