Coverage Report

Created: 2022-05-17 06:19

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Format/DefinitionBlockSeparator.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- DefinitionBlockSeparator.cpp ---------------------------*- C++ -*-===//
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
/// \file
10
/// This file implements DefinitionBlockSeparator, a TokenAnalyzer that inserts
11
/// or removes empty lines separating definition blocks like classes, structs,
12
/// functions, enums, and namespaces in between.
13
///
14
//===----------------------------------------------------------------------===//
15
16
#include "DefinitionBlockSeparator.h"
17
#include "llvm/Support/Debug.h"
18
#define DEBUG_TYPE "definition-block-separator"
19
20
namespace clang {
21
namespace format {
22
std::pair<tooling::Replacements, unsigned> DefinitionBlockSeparator::analyze(
23
    TokenAnnotator &Annotator, SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
24
84
    FormatTokenLexer &Tokens) {
25
84
  assert(Style.SeparateDefinitionBlocks != FormatStyle::SDS_Leave);
26
0
  AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
27
84
  tooling::Replacements Result;
28
84
  separateBlocks(AnnotatedLines, Result, Tokens);
29
84
  return {Result, 0};
30
84
}
31
32
void DefinitionBlockSeparator::separateBlocks(
33
    SmallVectorImpl<AnnotatedLine *> &Lines, tooling::Replacements &Result,
34
84
    FormatTokenLexer &Tokens) {
35
84
  const bool IsNeverStyle =
36
84
      Style.SeparateDefinitionBlocks == FormatStyle::SDS_Never;
37
84
  const AdditionalKeywords &ExtraKeywords = Tokens.getKeywords();
38
6.52k
  auto GetBracketLevelChange = [](const FormatToken *Tok) {
39
6.52k
    if (Tok->isOneOf(tok::l_brace, tok::l_paren, tok::l_square))
40
626
      return 1;
41
5.90k
    if (Tok->isOneOf(tok::r_brace, tok::r_paren, tok::r_square))
42
698
      return -1;
43
5.20k
    return 0;
44
5.90k
  };
45
84
  auto LikelyDefinition = [&](const AnnotatedLine *Line,
46
1.33k
                              bool ExcludeEnum = false) {
47
1.33k
    if ((Line->MightBeFunctionDecl && 
Line->mightBeFunctionDefinition()394
) ||
48
1.33k
        
Line->startsWithNamespace()936
)
49
510
      return true;
50
820
    int BracketLevel = 0;
51
2.62k
    for (const FormatToken *CurrentToken = Line->First; CurrentToken;
52
2.03k
         
CurrentToken = CurrentToken->Next1.80k
) {
53
2.03k
      if (BracketLevel == 0) {
54
1.55k
        if ((CurrentToken->isOneOf(tok::kw_class, tok::kw_struct,
55
1.55k
                                   tok::kw_union) ||
56
1.55k
             
(1.48k
Style.isJavaScript()1.48k
&&
57
1.48k
              
CurrentToken->is(ExtraKeywords.kw_function)195
)))
58
94
          return true;
59
1.45k
        if (!ExcludeEnum && 
CurrentToken->is(tok::kw_enum)1.07k
)
60
133
          return true;
61
1.45k
      }
62
1.80k
      BracketLevel += GetBracketLevelChange(CurrentToken);
63
1.80k
    }
64
593
    return false;
65
820
  };
66
84
  unsigned NewlineCount =
67
84
      (Style.SeparateDefinitionBlocks == FormatStyle::SDS_Always ? 
151
:
033
) + 1;
68
84
  WhitespaceManager Whitespaces(
69
84
      Env.getSourceManager(), Style,
70
84
      Style.DeriveLineEnding
71
84
          ? WhitespaceManager::inputUsesCRLF(
72
84
                Env.getSourceManager().getBufferData(Env.getFileID()),
73
84
                Style.UseCRLF)
74
84
          : 
Style.UseCRLF0
);
75
1.47k
  for (unsigned I = 0; I < Lines.size(); 
++I1.39k
) {
76
1.39k
    const auto &CurrentLine = Lines[I];
77
1.39k
    if (CurrentLine->InPPDirective)
78
72
      continue;
79
1.32k
    FormatToken *TargetToken = nullptr;
80
1.32k
    AnnotatedLine *TargetLine;
81
1.32k
    auto OpeningLineIndex = CurrentLine->MatchingOpeningBlockLineIndex;
82
1.32k
    AnnotatedLine *OpeningLine = nullptr;
83
1.32k
    const auto IsAccessSpecifierToken = [](const FormatToken *Token) {
84
587
      return Token->isAccessSpecifier() || 
Token->isObjCAccessSpecifier()586
;
85
587
    };
86
1.32k
    const auto InsertReplacement = [&](const int NewlineToInsert) {
87
386
      assert(TargetLine);
88
0
      assert(TargetToken);
89
90
      // Do not handle EOF newlines.
91
386
      if (TargetToken->is(tok::eof))
92
82
        return;
93
304
      if (IsAccessSpecifierToken(TargetToken) ||
94
304
          (OpeningLineIndex > 0 &&
95
304
           
IsAccessSpecifierToken(Lines[OpeningLineIndex - 1]->First)283
))
96
1
        return;
97
303
      if (!TargetLine->Affected)
98
0
        return;
99
303
      Whitespaces.replaceWhitespace(*TargetToken, NewlineToInsert,
100
303
                                    TargetToken->OriginalColumn,
101
303
                                    TargetToken->OriginalColumn);
102
303
    };
103
1.32k
    const auto IsPPConditional = [&](const size_t LineIndex) {
104
549
      const auto &Line = Lines[LineIndex];
105
549
      return Line->First->is(tok::hash) && 
Line->First->Next72
&&
106
549
             Line->First->Next->isOneOf(tok::pp_if, tok::pp_ifdef, tok::pp_else,
107
72
                                        tok::pp_ifndef, tok::pp_elifndef,
108
72
                                        tok::pp_elifdef, tok::pp_elif,
109
72
                                        tok::pp_endif);
110
549
    };
111
1.32k
    const auto FollowingOtherOpening = [&]() {
112
344
      return OpeningLineIndex == 0 ||
113
344
             
Lines[OpeningLineIndex - 1]->Last->opensScope()286
||
114
344
             
IsPPConditional(OpeningLineIndex - 1)246
;
115
344
    };
116
1.32k
    const auto HasEnumOnLine = [&]() {
117
1.32k
      bool FoundEnumKeyword = false;
118
1.32k
      int BracketLevel = 0;
119
6.03k
      for (const FormatToken *CurrentToken = CurrentLine->First; CurrentToken;
120
4.81k
           
CurrentToken = CurrentToken->Next4.71k
) {
121
4.81k
        if (BracketLevel == 0) {
122
3.67k
          if (CurrentToken->is(tok::kw_enum))
123
95
            FoundEnumKeyword = true;
124
3.58k
          else if (FoundEnumKeyword && 
CurrentToken->is(tok::l_brace)190
)
125
95
            return true;
126
3.67k
        }
127
4.71k
        BracketLevel += GetBracketLevelChange(CurrentToken);
128
4.71k
      }
129
1.22k
      return FoundEnumKeyword && 
I + 1 < Lines.size()0
&&
130
1.22k
             
Lines[I + 1]->First->is(tok::l_brace)0
;
131
1.32k
    };
132
133
1.32k
    bool IsDefBlock = false;
134
1.32k
    const auto MayPrecedeDefinition = [&](const int Direction = -1) {
135
679
      assert(Direction >= -1);
136
0
      assert(Direction <= 1);
137
0
      const size_t OperateIndex = OpeningLineIndex + Direction;
138
679
      assert(OperateIndex < Lines.size());
139
0
      const auto &OperateLine = Lines[OperateIndex];
140
679
      if (LikelyDefinition(OperateLine))
141
304
        return false;
142
143
375
      if (OperateLine->First->is(tok::comment))
144
184
        return true;
145
146
      // A single line identifier that is not in the last line.
147
191
      if (OperateLine->First->is(tok::identifier) &&
148
191
          
OperateLine->First == OperateLine->Last12
&&
149
191
          
OperateIndex + 1 < Lines.size()6
) {
150
        // UnwrappedLineParser's recognition of free-standing macro like
151
        // Q_OBJECT may also recognize some uppercased type names that may be
152
        // used as return type as that kind of macros, which is a bit hard to
153
        // distinguish one from another purely from token patterns. Here, we
154
        // try not to add new lines below those identifiers.
155
6
        AnnotatedLine *NextLine = Lines[OperateIndex + 1];
156
6
        if (NextLine->MightBeFunctionDecl &&
157
6
            NextLine->mightBeFunctionDefinition() &&
158
6
            NextLine->First->NewlinesBefore == 1 &&
159
6
            OperateLine->First->is(TT_FunctionLikeOrFreestandingMacro))
160
6
          return true;
161
6
      }
162
163
185
      if ((Style.isCSharp() && 
OperateLine->First->is(TT_AttributeSquare)24
))
164
6
        return true;
165
179
      return false;
166
185
    };
167
168
1.32k
    if (HasEnumOnLine() &&
169
1.32k
        
!LikelyDefinition(CurrentLine, /*ExcludeEnum=*/true)95
) {
170
      // We have no scope opening/closing information for enum.
171
95
      IsDefBlock = true;
172
95
      OpeningLineIndex = I;
173
145
      while (OpeningLineIndex > 0 && 
MayPrecedeDefinition()133
)
174
50
        --OpeningLineIndex;
175
95
      OpeningLine = Lines[OpeningLineIndex];
176
95
      TargetLine = OpeningLine;
177
95
      TargetToken = TargetLine->First;
178
95
      if (!FollowingOtherOpening())
179
25
        InsertReplacement(NewlineCount);
180
70
      else if (IsNeverStyle)
181
32
        InsertReplacement(OpeningLineIndex != 0);
182
95
      TargetLine = CurrentLine;
183
95
      TargetToken = TargetLine->First;
184
653
      while (TargetToken && 
!TargetToken->is(tok::r_brace)644
)
185
558
        TargetToken = TargetToken->Next;
186
95
      if (!TargetToken)
187
42
        
while (9
I < Lines.size() && !Lines[I]->First->is(tok::r_brace))
188
33
          ++I;
189
1.22k
    } else if (CurrentLine->First->closesScope()) {
190
277
      if (OpeningLineIndex > Lines.size())
191
0
        continue;
192
      // Handling the case that opening brace has its own line, with checking
193
      // whether the last line already had an opening brace to guard against
194
      // misrecognition.
195
277
      if (OpeningLineIndex > 0 &&
196
277
          
Lines[OpeningLineIndex]->First->is(tok::l_brace)236
&&
197
277
          
Lines[OpeningLineIndex - 1]->Last->isNot(tok::l_brace)38
)
198
28
        --OpeningLineIndex;
199
277
      OpeningLine = Lines[OpeningLineIndex];
200
      // Closing a function definition.
201
277
      if (LikelyDefinition(OpeningLine)) {
202
249
        IsDefBlock = true;
203
314
        while (OpeningLineIndex > 0 && 
MayPrecedeDefinition()268
)
204
65
          --OpeningLineIndex;
205
249
        OpeningLine = Lines[OpeningLineIndex];
206
249
        TargetLine = OpeningLine;
207
249
        TargetToken = TargetLine->First;
208
249
        if (!FollowingOtherOpening()) {
209
          // Avoid duplicated replacement.
210
173
          if (TargetToken->isNot(tok::l_brace))
211
173
            InsertReplacement(NewlineCount);
212
173
        } else 
if (76
IsNeverStyle76
)
213
31
          InsertReplacement(OpeningLineIndex != 0);
214
249
      }
215
277
    }
216
217
    // Not the last token.
218
1.32k
    if (IsDefBlock && 
I + 1 < Lines.size()344
) {
219
344
      OpeningLineIndex = I + 1;
220
344
      TargetLine = Lines[OpeningLineIndex];
221
344
      TargetToken = TargetLine->First;
222
223
      // No empty line for continuously closing scopes. The token will be
224
      // handled in another case if the line following is opening a
225
      // definition.
226
344
      if (!TargetToken->closesScope() && 
!IsPPConditional(OpeningLineIndex)303
) {
227
        // Check whether current line may precede a definition line.
228
360
        while (OpeningLineIndex + 1 < Lines.size() &&
229
360
               
MayPrecedeDefinition(/*Direction=*/0)278
)
230
81
          ++OpeningLineIndex;
231
279
        TargetLine = Lines[OpeningLineIndex];
232
279
        if (!LikelyDefinition(TargetLine)) {
233
95
          OpeningLineIndex = I + 1;
234
95
          TargetLine = Lines[I + 1];
235
95
          TargetToken = TargetLine->First;
236
95
          InsertReplacement(NewlineCount);
237
95
        }
238
279
      } else 
if (65
IsNeverStyle65
)
239
30
        InsertReplacement(/*NewlineToInsert=*/1);
240
344
    }
241
1.32k
  }
242
84
  for (const auto &R : Whitespaces.generateReplacements())
243
    // The add method returns an Error instance which simulates program exit
244
    // code through overloading boolean operator, thus false here indicates
245
    // success.
246
157
    if (Result.add(R))
247
0
      return;
248
84
}
249
} // namespace format
250
} // namespace clang