Coverage Report

Created: 2020-10-24 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Lex/DependencyDirectivesSourceMinimizer.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- DependencyDirectivesSourceMinimizer.cpp -  -------------------------===//
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 is the implementation for minimizing header and source files to the
11
/// minimum necessary preprocessor directives for evaluating includes. It
12
/// reduces the source down to #define, #include, #import, @import, and any
13
/// conditional preprocessor logic that contains one of those.
14
///
15
//===----------------------------------------------------------------------===//
16
17
#include "clang/Lex/DependencyDirectivesSourceMinimizer.h"
18
#include "clang/Basic/CharInfo.h"
19
#include "clang/Basic/Diagnostic.h"
20
#include "clang/Lex/LexDiagnostic.h"
21
#include "llvm/ADT/StringMap.h"
22
#include "llvm/ADT/StringSwitch.h"
23
#include "llvm/Support/MemoryBuffer.h"
24
25
using namespace llvm;
26
using namespace clang;
27
using namespace clang::minimize_source_to_dependency_directives;
28
29
namespace {
30
31
struct Minimizer {
32
  /// Minimized output.
33
  SmallVectorImpl<char> &Out;
34
  /// The known tokens encountered during the minimization.
35
  SmallVectorImpl<Token> &Tokens;
36
37
  Minimizer(SmallVectorImpl<char> &Out, SmallVectorImpl<Token> &Tokens,
38
            StringRef Input, DiagnosticsEngine *Diags,
39
            SourceLocation InputSourceLoc)
40
      : Out(Out), Tokens(Tokens), Input(Input), Diags(Diags),
41
165
        InputSourceLoc(InputSourceLoc) {}
42
43
  /// Lex the provided source and emit the minimized output.
44
  ///
45
  /// \returns True on error.
46
  bool minimize();
47
48
private:
49
  struct IdInfo {
50
    const char *Last;
51
    StringRef Name;
52
  };
53
54
  /// Lex an identifier.
55
  ///
56
  /// \pre First points at a valid identifier head.
57
  LLVM_NODISCARD IdInfo lexIdentifier(const char *First, const char *const End);
58
  LLVM_NODISCARD bool isNextIdentifier(StringRef Id, const char *&First,
59
                                       const char *const End);
60
  LLVM_NODISCARD bool minimizeImpl(const char *First, const char *const End);
61
  LLVM_NODISCARD bool lexPPLine(const char *&First, const char *const End);
62
  LLVM_NODISCARD bool lexAt(const char *&First, const char *const End);
63
  LLVM_NODISCARD bool lexModule(const char *&First, const char *const End);
64
  LLVM_NODISCARD bool lexDefine(const char *&First, const char *const End);
65
  LLVM_NODISCARD bool lexPragma(const char *&First, const char *const End);
66
  LLVM_NODISCARD bool lexEndif(const char *&First, const char *const End);
67
  LLVM_NODISCARD bool lexDefault(TokenKind Kind, StringRef Directive,
68
                                 const char *&First, const char *const End);
69
455
  Token &makeToken(TokenKind K) {
70
455
    Tokens.emplace_back(K, Out.size());
71
455
    return Tokens.back();
72
455
  }
73
3
  void popToken() {
74
3
    Out.resize(Tokens.back().Offset);
75
3
    Tokens.pop_back();
76
3
  }
77
188
  TokenKind top() const { return Tokens.empty() ? 
pp_none0
: Tokens.back().K; }
78
79
756
  Minimizer &put(char Byte) {
80
756
    Out.push_back(Byte);
81
756
    return *this;
82
756
  }
83
376
  Minimizer &append(StringRef S) { return append(S.begin(), S.end()); }
84
610
  Minimizer &append(const char *First, const char *Last) {
85
610
    Out.append(First, Last);
86
610
    return *this;
87
610
  }
88
89
  void printToNewline(const char *&First, const char *const End);
90
  void printAdjacentModuleNameParts(const char *&First, const char *const End);
91
  LLVM_NODISCARD bool printAtImportBody(const char *&First,
92
                                        const char *const End);
93
  void printDirectiveBody(const char *&First, const char *const End);
94
  void printAdjacentMacroArgs(const char *&First, const char *const End);
95
  LLVM_NODISCARD bool printMacroArgs(const char *&First, const char *const End);
96
97
  /// Reports a diagnostic if the diagnostic engine is provided. Always returns
98
  /// true at the end.
99
  bool reportError(const char *CurPtr, unsigned Err);
100
101
  StringMap<char> SplitIds;
102
  StringRef Input;
103
  DiagnosticsEngine *Diags;
104
  SourceLocation InputSourceLoc;
105
};
106
107
} // end anonymous namespace
108
109
8
bool Minimizer::reportError(const char *CurPtr, unsigned Err) {
110
8
  if (!Diags)
111
5
    return true;
112
3
  assert(CurPtr >= Input.data() && "invalid buffer ptr");
113
3
  Diags->Report(InputSourceLoc.getLocWithOffset(CurPtr - Input.data()), Err);
114
3
  return true;
115
3
}
116
117
2.46k
static void skipOverSpaces(const char *&First, const char *const End) {
118
3.20k
  while (First != End && 
isHorizontalWhitespace(*First)3.19k
)
119
743
    ++First;
120
2.46k
}
121
122
LLVM_NODISCARD static bool isRawStringLiteral(const char *First,
123
99
                                              const char *Current) {
124
99
  assert(First <= Current);
125
126
  // Check if we can even back up.
127
99
  if (*Current != '"' || 
First == Current68
)
128
92
    return false;
129
130
  // Check for an "R".
131
7
  --Current;
132
7
  if (*Current != 'R')
133
4
    return false;
134
3
  if (First == Current || 
!isIdentifierBody(*--Current)2
)
135
3
    return true;
136
137
  // Check for a prefix of "u", "U", or "L".
138
0
  if (*Current == 'u' || *Current == 'U' || *Current == 'L')
139
0
    return First == Current || !isIdentifierBody(*--Current);
140
141
  // Check for a prefix of "u8".
142
0
  if (*Current != '8' || First == Current || *Current-- != 'u')
143
0
    return false;
144
0
  return First == Current || !isIdentifierBody(*--Current);
145
0
}
146
147
3
static void skipRawString(const char *&First, const char *const End) {
148
3
  assert(First[0] == '"');
149
3
  assert(First[-1] == 'R');
150
151
3
  const char *Last = ++First;
152
6
  while (Last != End && *Last != '(')
153
3
    ++Last;
154
3
  if (Last == End) {
155
0
    First = Last; // Hit the end... just give up.
156
0
    return;
157
0
  }
158
159
3
  StringRef Terminator(First, Last - First);
160
3
  for (;;) {
161
    // Move First to just past the next ")".
162
3
    First = Last;
163
46
    while (First != End && *First != ')')
164
43
      ++First;
165
3
    if (First == End)
166
0
      return;
167
3
    ++First;
168
169
    // Look ahead for the terminator sequence.
170
3
    Last = First;
171
6
    while (Last != End && size_t(Last - First) < Terminator.size() &&
172
3
           Terminator[Last - First] == *Last)
173
3
      ++Last;
174
175
    // Check if we hit it (or the end of the file).
176
3
    if (Last == End) {
177
0
      First = Last;
178
0
      return;
179
0
    }
180
3
    if (size_t(Last - First) < Terminator.size())
181
0
      continue;
182
3
    if (*Last != '"')
183
0
      continue;
184
3
    First = Last + 1;
185
3
    return;
186
3
  }
187
3
}
188
189
// Returns the length of EOL, either 0 (no end-of-line), 1 (\n) or 2 (\r\n)
190
49.3k
static unsigned isEOL(const char *First, const char *const End) {
191
49.3k
  if (First == End)
192
0
    return 0;
193
49.3k
  if (End - First > 1 && 
isVerticalWhitespace(First[0])49.2k
&&
194
2.54k
      isVerticalWhitespace(First[1]) && 
First[0] != First[1]208
)
195
20
    return 2;
196
49.3k
  return !!isVerticalWhitespace(First[0]);
197
49.3k
}
198
199
96
static void skipString(const char *&First, const char *const End) {
200
96
  assert(*First == '\'' || *First == '"' || *First == '<');
201
72
  const char Terminator = *First == '<' ? 
'>'24
: *First;
202
852
  for (++First; First != End && *First != Terminator; 
++First756
) {
203
    // String and character literals don't extend past the end of the line.
204
759
    if (isVerticalWhitespace(*First))
205
3
      return;
206
756
    if (*First != '\\')
207
753
      continue;
208
    // Skip past backslash to the next character. This ensures that the
209
    // character right after it is skipped as well, which matters if it's
210
    // the terminator.
211
3
    if (++First == End)
212
0
      return;
213
3
    if (!isWhitespace(*First))
214
0
      continue;
215
    // Whitespace after the backslash might indicate a line continuation.
216
3
    const char *FirstAfterBackslashPastSpace = First;
217
3
    skipOverSpaces(FirstAfterBackslashPastSpace, End);
218
3
    if (unsigned NLSize = isEOL(FirstAfterBackslashPastSpace, End)) {
219
      // Advance the character pointer to the next line for the next
220
      // iteration.
221
3
      First = FirstAfterBackslashPastSpace + NLSize - 1;
222
3
    }
223
3
  }
224
93
  if (First != End)
225
93
    ++First; // Finish off the string.
226
93
}
227
228
// Returns the length of the skipped newline
229
1.55k
static unsigned skipNewline(const char *&First, const char *End) {
230
1.55k
  if (First == End)
231
12
    return 0;
232
1.53k
  assert(isVerticalWhitespace(*First));
233
1.53k
  unsigned Len = isEOL(First, End);
234
1.53k
  assert(Len && "expected newline");
235
1.53k
  First += Len;
236
1.53k
  return Len;
237
1.53k
}
238
239
28
static bool wasLineContinuation(const char *First, unsigned EOLLen) {
240
28
  return *(First - (int)EOLLen - 1) == '\\';
241
28
}
242
243
1.09k
static void skipToNewlineRaw(const char *&First, const char *const End) {
244
1.19k
  for (;;) {
245
1.19k
    if (First == End)
246
0
      return;
247
248
1.19k
    unsigned Len = isEOL(First, End);
249
1.19k
    if (Len)
250
61
      return;
251
252
47.2k
    
do 1.13k
{
253
47.2k
      if (++First == End)
254
0
        return;
255
47.2k
      Len = isEOL(First, End);
256
47.2k
    } while (!Len);
257
258
1.13k
    if (First[-1] != '\\')
259
1.02k
      return;
260
261
105
    First += Len;
262
    // Keep skipping lines...
263
105
  }
264
1.09k
}
265
266
212
static const char *findLastNonSpace(const char *First, const char *Last) {
267
212
  assert(First <= Last);
268
257
  while (First != Last && 
isHorizontalWhitespace(Last[-1])256
)
269
45
    --Last;
270
212
  return Last;
271
212
}
272
273
static const char *findFirstTrailingSpace(const char *First,
274
8
                                          const char *Last) {
275
8
  const char *LastNonSpace = findLastNonSpace(First, Last);
276
8
  if (Last == LastNonSpace)
277
1
    return Last;
278
7
  assert(isHorizontalWhitespace(LastNonSpace[0]));
279
7
  return LastNonSpace + 1;
280
7
}
281
282
1.07k
static void skipLineComment(const char *&First, const char *const End) {
283
1.07k
  assert(First[0] == '/' && First[1] == '/');
284
1.07k
  First += 2;
285
1.07k
  skipToNewlineRaw(First, End);
286
1.07k
}
287
288
8
static void skipBlockComment(const char *&First, const char *const End) {
289
8
  assert(First[0] == '/' && First[1] == '*');
290
8
  if (End - First < 4) {
291
0
    First = End;
292
0
    return;
293
0
  }
294
67
  
for (First += 3; 8
First != End;
++First59
)
295
67
    if (First[-1] == '*' && 
First[0] == '/'11
) {
296
8
      ++First;
297
8
      return;
298
8
    }
299
8
}
300
301
/// \returns True if the current single quotation mark character is a C++ 14
302
/// digit separator.
303
static bool isQuoteCppDigitSeparator(const char *const Start,
304
                                     const char *const Cur,
305
9
                                     const char *const End) {
306
9
  assert(*Cur == '\'' && "expected quotation character");
307
  // skipLine called in places where we don't expect a valid number
308
  // body before `start` on the same line, so always return false at the start.
309
9
  if (Start == Cur)
310
0
    return false;
311
  // The previous character must be a valid PP number character.
312
  // Make sure that the L, u, U, u8 prefixes don't get marked as a
313
  // separator though.
314
9
  char Prev = *(Cur - 1);
315
9
  if (Prev == 'L' || 
Prev == 'U'8
||
Prev == 'u'7
)
316
3
    return false;
317
6
  if (Prev == '8' && 
(Cur - 1 != Start)2
&&
*(Cur - 2) == 'u'2
)
318
1
    return false;
319
5
  if (!isPreprocessingNumberBody(Prev))
320
1
    return false;
321
  // The next character should be a valid identifier body character.
322
4
  return (Cur + 1) < End && isIdentifierBody(*(Cur + 1));
323
4
}
324
325
1.32k
static void skipLine(const char *&First, const char *const End) {
326
1.33k
  for (;;) {
327
1.33k
    assert(First <= End);
328
1.33k
    if (First == End)
329
1
      return;
330
331
1.33k
    if (isVerticalWhitespace(*First)) {
332
1.29k
      skipNewline(First, End);
333
1.29k
      return;
334
1.29k
    }
335
40
    const char *Start = First;
336
438
    while (First != End && 
!isVerticalWhitespace(*First)426
) {
337
      // Iterate over strings correctly to avoid comments and newlines.
338
398
      if (*First == '"' ||
339
395
          (*First == '\'' && 
!isQuoteCppDigitSeparator(Start, First, End)9
)) {
340
8
        if (isRawStringLiteral(Start, First))
341
3
          skipRawString(First, End);
342
5
        else
343
5
          skipString(First, End);
344
8
        continue;
345
8
      }
346
347
      // Iterate over comments correctly.
348
390
      if (*First != '/' || 
End - First < 20
) {
349
390
        ++First;
350
390
        continue;
351
390
      }
352
353
0
      if (First[1] == '/') {
354
        // "//...".
355
0
        skipLineComment(First, End);
356
0
        continue;
357
0
      }
358
359
0
      if (First[1] != '*') {
360
0
        ++First;
361
0
        continue;
362
0
      }
363
364
      // "/*...*/".
365
0
      skipBlockComment(First, End);
366
0
    }
367
40
    if (First == End)
368
12
      return;
369
370
    // Skip over the newline.
371
28
    unsigned Len = skipNewline(First, End);
372
28
    if (!wasLineContinuation(First, Len)) // Continue past line-continuations.
373
27
      break;
374
28
  }
375
1.32k
}
376
377
static void skipDirective(StringRef Name, const char *&First,
378
18
                          const char *const End) {
379
18
  if (llvm::StringSwitch<bool>(Name)
380
18
          .Case("warning", true)
381
18
          .Case("error", true)
382
18
          .Default(false))
383
    // Do not process quotes or comments.
384
18
    skipToNewlineRaw(First, End);
385
0
  else
386
0
    skipLine(First, End);
387
18
}
388
389
270
void Minimizer::printToNewline(const char *&First, const char *const End) {
390
277
  while (First != End && !isVerticalWhitespace(*First)) {
391
204
    const char *Last = First;
392
951
    do {
393
      // Iterate over strings correctly to avoid comments and newlines.
394
951
      if (*Last == '"' || 
*Last == '\''886
||
395
884
          (*Last == '<' && 
top() == pp_include32
)) {
396
91
        if (LLVM_UNLIKELY(isRawStringLiteral(First, Last)))
397
0
          skipRawString(Last, End);
398
91
        else
399
91
          skipString(Last, End);
400
91
        continue;
401
91
      }
402
860
      if (*Last != '/' || 
End - Last < 21
) {
403
859
        ++Last;
404
859
        continue; // Gather the rest up to print verbatim.
405
859
      }
406
407
1
      if (Last[1] != '/' && Last[1] != '*') {
408
0
        ++Last;
409
0
        continue;
410
0
      }
411
412
      // Deal with "//..." and "/*...*/".
413
1
      append(First, findFirstTrailingSpace(First, Last));
414
1
      First = Last;
415
416
1
      if (Last[1] == '/') {
417
0
        skipLineComment(First, End);
418
0
        return;
419
0
      }
420
421
1
      put(' ');
422
1
      skipBlockComment(First, End);
423
1
      skipOverSpaces(First, End);
424
1
      Last = First;
425
951
    } while (Last != End && 
!isVerticalWhitespace(*Last)939
);
426
427
    // Print out the string.
428
204
    const char *LastBeforeTrailingSpace = findLastNonSpace(First, Last);
429
204
    if (Last == End || 
LastBeforeTrailingSpace == First192
||
430
197
        
LastBeforeTrailingSpace[-1] != '\\'191
) {
431
197
      append(First, LastBeforeTrailingSpace);
432
197
      First = Last;
433
197
      skipNewline(First, End);
434
197
      return;
435
197
    }
436
437
    // Print up to the backslash, backing up over spaces. Preserve at least one
438
    // space, as the space matters when tokens are separated by a line
439
    // continuation.
440
7
    append(First, findFirstTrailingSpace(
441
7
                      First, LastBeforeTrailingSpace - 1));
442
443
7
    First = Last;
444
7
    skipNewline(First, End);
445
7
    skipOverSpaces(First, End);
446
7
  }
447
270
}
448
449
2.42k
static void skipWhitespace(const char *&First, const char *const End) {
450
2.44k
  for (;;) {
451
2.44k
    assert(First <= End);
452
2.44k
    skipOverSpaces(First, End);
453
454
2.44k
    if (End - First < 2)
455
107
      return;
456
457
2.34k
    if (First[0] == '\\' && 
isVerticalWhitespace(First[1])14
) {
458
14
      skipNewline(++First, End);
459
14
      continue;
460
14
    }
461
462
    // Check for a non-comment character.
463
2.32k
    if (First[0] != '/')
464
1.25k
      return;
465
466
    // "// ...".
467
1.07k
    if (First[1] == '/') {
468
1.07k
      skipLineComment(First, End);
469
1.07k
      return;
470
1.07k
    }
471
472
    // Cannot be a comment.
473
2
    if (First[1] != '*')
474
0
      return;
475
476
    // "/*...*/".
477
2
    skipBlockComment(First, End);
478
2
  }
479
2.42k
}
480
481
void Minimizer::printAdjacentModuleNameParts(const char *&First,
482
12
                                             const char *const End) {
483
  // Skip over parts of the body.
484
12
  const char *Last = First;
485
12
  do
486
18
    ++Last;
487
18
  while (Last != End && (isIdentifierBody(*Last) || 
*Last == '.'13
));
488
12
  append(First, Last);
489
12
  First = Last;
490
12
}
491
492
11
bool Minimizer::printAtImportBody(const char *&First, const char *const End) {
493
27
  for (;;) {
494
27
    skipWhitespace(First, End);
495
27
    if (First == End)
496
2
      return true;
497
498
25
    if (isVerticalWhitespace(*First)) {
499
4
      skipNewline(First, End);
500
4
      continue;
501
4
    }
502
503
    // Found a semicolon.
504
21
    if (*First == ';') {
505
7
      put(*First++).put('\n');
506
7
      return false;
507
7
    }
508
509
    // Don't handle macro expansions inside @import for now.
510
14
    if (!isIdentifierBody(*First) && 
*First != '.'3
)
511
2
      return true;
512
513
12
    printAdjacentModuleNameParts(First, End);
514
12
  }
515
11
}
516
517
260
void Minimizer::printDirectiveBody(const char *&First, const char *const End) {
518
260
  skipWhitespace(First, End); // Skip initial whitespace.
519
260
  printToNewline(First, End);
520
317
  while (Out.back() == ' ')
521
57
    Out.pop_back();
522
260
  put('\n');
523
260
}
524
525
LLVM_NODISCARD static const char *lexRawIdentifier(const char *First,
526
412
                                                   const char *const End) {
527
412
  assert(isIdentifierBody(*First) && "invalid identifer");
528
412
  const char *Last = First + 1;
529
2.26k
  while (Last != End && 
isIdentifierBody(*Last)2.26k
)
530
1.84k
    ++Last;
531
412
  return Last;
532
412
}
533
534
LLVM_NODISCARD static const char *
535
412
getIdentifierContinuation(const char *First, const char *const End) {
536
412
  if (End - First < 3 || 
First[0] != '\\'366
||
!isVerticalWhitespace(First[1])6
)
537
406
    return nullptr;
538
539
6
  ++First;
540
6
  skipNewline(First, End);
541
6
  if (First == End)
542
0
    return nullptr;
543
6
  return isIdentifierBody(First[0]) ? 
First4
:
nullptr2
;
544
6
}
545
546
Minimizer::IdInfo Minimizer::lexIdentifier(const char *First,
547
408
                                           const char *const End) {
548
408
  const char *Last = lexRawIdentifier(First, End);
549
408
  const char *Next = getIdentifierContinuation(Last, End);
550
408
  if (LLVM_LIKELY(!Next))
551
404
    return IdInfo{Last, StringRef(First, Last - First)};
552
553
  // Slow path, where identifiers are split over lines.
554
4
  SmallVector<char, 64> Id(First, Last);
555
8
  while (Next) {
556
4
    Last = lexRawIdentifier(Next, End);
557
4
    Id.append(Next, Last);
558
4
    Next = getIdentifierContinuation(Last, End);
559
4
  }
560
4
  return IdInfo{
561
4
      Last,
562
4
      SplitIds.try_emplace(StringRef(Id.begin(), Id.size()), 0).first->first()};
563
4
}
564
565
void Minimizer::printAdjacentMacroArgs(const char *&First,
566
17
                                       const char *const End) {
567
  // Skip over parts of the body.
568
17
  const char *Last = First;
569
17
  do
570
37
    ++Last;
571
37
  while (Last != End &&
572
37
         (isIdentifierBody(*Last) || 
*Last == '.'32
||
*Last == ','25
));
573
17
  append(First, Last);
574
17
  First = Last;
575
17
}
576
577
17
bool Minimizer::printMacroArgs(const char *&First, const char *const End) {
578
17
  assert(*First == '(');
579
17
  put(*First++);
580
34
  for (;;) {
581
34
    skipWhitespace(First, End);
582
34
    if (First == End)
583
1
      return true;
584
585
33
    if (*First == ')') {
586
14
      put(*First++);
587
14
      return false;
588
14
    }
589
590
    // This is intentionally fairly liberal.
591
19
    if (!(isIdentifierBody(*First) || 
*First == '.'4
||
*First == ','2
))
592
2
      return true;
593
594
17
    printAdjacentMacroArgs(First, End);
595
17
  }
596
17
}
597
598
/// Looks for an identifier starting from Last.
599
///
600
/// Updates "First" to just past the next identifier, if any.  Returns true iff
601
/// the identifier matches "Id".
602
bool Minimizer::isNextIdentifier(StringRef Id, const char *&First,
603
20
                                 const char *const End) {
604
20
  skipWhitespace(First, End);
605
20
  if (First == End || !isIdentifierHead(*First))
606
2
    return false;
607
608
18
  IdInfo FoundId = lexIdentifier(First, End);
609
18
  First = FoundId.Last;
610
18
  return FoundId.Name == Id;
611
18
}
612
613
11
bool Minimizer::lexAt(const char *&First, const char *const End) {
614
  // Handle "@import".
615
11
  const char *ImportLoc = First++;
616
11
  if (!isNextIdentifier("import", First, End)) {
617
0
    skipLine(First, End);
618
0
    return false;
619
0
  }
620
11
  makeToken(decl_at_import);
621
11
  append("@import ");
622
11
  if (printAtImportBody(First, End))
623
4
    return reportError(
624
4
        ImportLoc, diag::err_dep_source_minimizer_missing_sema_after_at_import);
625
7
  skipWhitespace(First, End);
626
7
  if (First == End)
627
2
    return false;
628
5
  if (!isVerticalWhitespace(*First))
629
1
    return reportError(
630
1
        ImportLoc, diag::err_dep_source_minimizer_unexpected_tokens_at_import);
631
4
  skipNewline(First, End);
632
4
  return false;
633
4
}
634
635
24
bool Minimizer::lexModule(const char *&First, const char *const End) {
636
24
  IdInfo Id = lexIdentifier(First, End);
637
24
  First = Id.Last;
638
24
  bool Export = false;
639
24
  if (Id.Name == "export") {
640
4
    Export = true;
641
4
    skipWhitespace(First, End);
642
4
    if (!isIdentifierBody(*First)) {
643
0
      skipLine(First, End);
644
0
      return false;
645
0
    }
646
4
    Id = lexIdentifier(First, End);
647
4
    First = Id.Last;
648
4
  }
649
650
24
  if (Id.Name != "module" && 
Id.Name != "import"21
) {
651
8
    skipLine(First, End);
652
8
    return false;
653
8
  }
654
655
16
  skipWhitespace(First, End);
656
657
  // Ignore this as a module directive if the next character can't be part of
658
  // an import.
659
660
16
  switch (*First) {
661
2
  case ':':
662
2
  case '<':
663
2
  case '"':
664
2
    break;
665
14
  default:
666
14
    if (!isIdentifierBody(*First)) {
667
6
      skipLine(First, End);
668
6
      return false;
669
6
    }
670
10
  }
671
672
10
  if (Export) {
673
3
    makeToken(cxx_export_decl);
674
3
    append("export ");
675
3
  }
676
677
10
  if (Id.Name == "module")
678
2
    makeToken(cxx_module_decl);
679
8
  else
680
8
    makeToken(cxx_import_decl);
681
10
  append(Id.Name);
682
10
  append(" ");
683
10
  printToNewline(First, End);
684
10
  append("\n");
685
10
  return false;
686
10
}
687
688
60
bool Minimizer::lexDefine(const char *&First, const char *const End) {
689
60
  makeToken(pp_define);
690
60
  append("#define ");
691
60
  skipWhitespace(First, End);
692
693
60
  if (!isIdentifierHead(*First))
694
3
    return reportError(First, diag::err_pp_macro_not_identifier);
695
696
57
  IdInfo Id = lexIdentifier(First, End);
697
57
  const char *Last = Id.Last;
698
57
  append(Id.Name);
699
57
  if (Last == End)
700
1
    return false;
701
56
  if (*Last == '(') {
702
17
    size_t Size = Out.size();
703
17
    if (printMacroArgs(Last, End)) {
704
      // Be robust to bad macro arguments, since they can show up in disabled
705
      // code.
706
3
      Out.resize(Size);
707
3
      append("(/* invalid */\n");
708
3
      skipLine(Last, End);
709
3
      return false;
710
3
    }
711
53
  }
712
53
  skipWhitespace(Last, End);
713
53
  if (Last == End)
714
3
    return false;
715
50
  if (!isVerticalWhitespace(*Last))
716
33
    put(' ');
717
50
  printDirectiveBody(Last, End);
718
50
  First = Last;
719
50
  return false;
720
50
}
721
722
8
bool Minimizer::lexPragma(const char *&First, const char *const End) {
723
  // #pragma.
724
8
  skipWhitespace(First, End);
725
8
  if (First == End || !isIdentifierHead(*First))
726
0
    return false;
727
728
8
  IdInfo FoundId = lexIdentifier(First, End);
729
8
  First = FoundId.Last;
730
8
  if (FoundId.Name == "once") {
731
    // #pragma once
732
2
    skipLine(First, End);
733
2
    makeToken(pp_pragma_once);
734
2
    append("#pragma once\n");
735
2
    return false;
736
2
  }
737
738
6
  if (FoundId.Name != "clang") {
739
1
    skipLine(First, End);
740
1
    return false;
741
1
  }
742
743
  // #pragma clang.
744
5
  if (!isNextIdentifier("module", First, End)) {
745
1
    skipLine(First, End);
746
1
    return false;
747
1
  }
748
749
  // #pragma clang module.
750
4
  if (!isNextIdentifier("import", First, End)) {
751
2
    skipLine(First, End);
752
2
    return false;
753
2
  }
754
755
  // #pragma clang module import.
756
2
  makeToken(pp_pragma_import);
757
2
  append("#pragma clang module import ");
758
2
  printDirectiveBody(First, End);
759
2
  return false;
760
2
}
761
762
52
bool Minimizer::lexEndif(const char *&First, const char *const End) {
763
  // Strip out "#else" if it's empty.
764
52
  if (top() == pp_else)
765
2
    popToken();
766
767
  // If "#ifdef" is empty, strip it and skip the "#endif".
768
  //
769
  // FIXME: Once/if Clang starts disallowing __has_include in macro expansions,
770
  // we can skip empty `#if` and `#elif` blocks as well after scanning for a
771
  // literal __has_include in the condition.  Even without that rule we could
772
  // drop the tokens if we scan for identifiers in the condition and find none.
773
52
  if (top() == pp_ifdef || top() == pp_ifndef) {
774
1
    popToken();
775
1
    skipLine(First, End);
776
1
    return false;
777
1
  }
778
779
51
  return lexDefault(pp_endif, "endif", First, End);
780
51
}
781
782
bool Minimizer::lexDefault(TokenKind Kind, StringRef Directive,
783
210
                           const char *&First, const char *const End) {
784
210
  makeToken(Kind);
785
210
  put('#').append(Directive).put(' ');
786
210
  printDirectiveBody(First, End);
787
210
  return false;
788
210
}
789
790
1.63k
static bool isStartOfRelevantLine(char First) {
791
1.63k
  switch (First) {
792
332
  case '#':
793
332
  case '@':
794
332
  case 'i':
795
332
  case 'e':
796
332
  case 'm':
797
332
    return true;
798
1.30k
  }
799
1.30k
  return false;
800
1.30k
}
801
802
1.64k
bool Minimizer::lexPPLine(const char *&First, const char *const End) {
803
1.64k
  assert(First != End);
804
805
1.64k
  skipWhitespace(First, End);
806
1.64k
  assert(First <= End);
807
1.64k
  if (First == End)
808
3
    return false;
809
810
1.63k
  if (!isStartOfRelevantLine(*First)) {
811
1.30k
    skipLine(First, End);
812
1.30k
    assert(First <= End);
813
1.30k
    return false;
814
1.30k
  }
815
816
  // Handle "@import".
817
334
  if (*First == '@')
818
11
    return lexAt(First, End);
819
820
323
  if (*First == 'i' || 
*First == 'e'302
||
*First == 'm'298
)
821
24
    return lexModule(First, End);
822
823
  // Handle preprocessing directives.
824
299
  ++First; // Skip over '#'.
825
299
  skipWhitespace(First, End);
826
827
299
  if (First == End)
828
0
    return reportError(First, diag::err_pp_expected_eol);
829
830
299
  if (!isIdentifierHead(*First)) {
831
0
    skipLine(First, End);
832
0
    return false;
833
0
  }
834
835
  // Figure out the token.
836
299
  IdInfo Id = lexIdentifier(First, End);
837
299
  First = Id.Last;
838
299
  auto Kind = llvm::StringSwitch<TokenKind>(Id.Name)
839
299
                  .Case("include", pp_include)
840
299
                  .Case("__include_macros", pp___include_macros)
841
299
                  .Case("define", pp_define)
842
299
                  .Case("undef", pp_undef)
843
299
                  .Case("import", pp_import)
844
299
                  .Case("include_next", pp_include_next)
845
299
                  .Case("if", pp_if)
846
299
                  .Case("ifdef", pp_ifdef)
847
299
                  .Case("ifndef", pp_ifndef)
848
299
                  .Case("elif", pp_elif)
849
299
                  .Case("else", pp_else)
850
299
                  .Case("endif", pp_endif)
851
299
                  .Case("pragma", pp_pragma_import)
852
299
                  .Default(pp_none);
853
299
  if (Kind == pp_none) {
854
18
    skipDirective(Id.Name, First, End);
855
18
    return false;
856
18
  }
857
858
281
  if (Kind == pp_endif)
859
52
    return lexEndif(First, End);
860
861
229
  if (Kind == pp_define)
862
60
    return lexDefine(First, End);
863
864
169
  if (Kind == pp_pragma_import)
865
8
    return lexPragma(First, End);
866
867
  // Everything else.
868
161
  return lexDefault(Kind, Id.Name, First, End);
869
161
}
870
871
164
static void skipUTF8ByteOrderMark(const char *&First, const char *const End) {
872
164
  if ((End - First) >= 3 && 
First[0] == '\xef'163
&&
First[1] == '\xbb'1
&&
873
1
      First[2] == '\xbf')
874
1
    First += 3;
875
164
}
876
877
164
bool Minimizer::minimizeImpl(const char *First, const char *const End) {
878
164
  skipUTF8ByteOrderMark(First, End);
879
1.79k
  while (First != End)
880
1.64k
    if (lexPPLine(First, End))
881
8
      return true;
882
156
  return false;
883
164
}
884
885
164
bool Minimizer::minimize() {
886
164
  bool Error = minimizeImpl(Input.begin(), Input.end());
887
888
164
  if (!Error) {
889
    // Add a trailing newline and an EOF on success.
890
157
    if (!Out.empty() && 
Out.back() != '\n'138
)
891
4
      Out.push_back('\n');
892
157
    makeToken(pp_eof);
893
157
  }
894
895
  // Null-terminate the output. This way the memory buffer that's passed to
896
  // Clang will not have to worry about the terminating '\0'.
897
164
  Out.push_back(0);
898
164
  Out.pop_back();
899
164
  return Error;
900
164
}
901
902
bool clang::minimize_source_to_dependency_directives::computeSkippedRanges(
903
69
    ArrayRef<Token> Input, llvm::SmallVectorImpl<SkippedRange> &Range) {
904
69
  struct Directive {
905
69
    enum DirectiveKind {
906
69
      If,  // if/ifdef/ifndef
907
69
      Else // elif,else
908
69
    };
909
69
    int Offset;
910
69
    DirectiveKind Kind;
911
69
  };
912
69
  llvm::SmallVector<Directive, 32> Offsets;
913
204
  for (const Token &T : Input) {
914
204
    switch (T.K) {
915
31
    case pp_if:
916
31
    case pp_ifdef:
917
31
    case pp_ifndef:
918
31
      Offsets.push_back({T.Offset, Directive::If});
919
31
      break;
920
921
4
    case pp_elif:
922
4
    case pp_else: {
923
4
      if (Offsets.empty())
924
0
        return true;
925
4
      int PreviousOffset = Offsets.back().Offset;
926
4
      Range.push_back({PreviousOffset, T.Offset - PreviousOffset});
927
4
      Offsets.push_back({T.Offset, Directive::Else});
928
4
      break;
929
4
    }
930
931
31
    case pp_endif: {
932
31
      if (Offsets.empty())
933
0
        return true;
934
31
      int PreviousOffset = Offsets.back().Offset;
935
31
      Range.push_back({PreviousOffset, T.Offset - PreviousOffset});
936
35
      do {
937
35
        Directive::DirectiveKind Kind = Offsets.pop_back_val().Kind;
938
35
        if (Kind == Directive::If)
939
31
          break;
940
4
      } while (!Offsets.empty());
941
31
      break;
942
31
    }
943
138
    default:
944
138
      break;
945
204
    }
946
204
  }
947
69
  return false;
948
69
}
949
950
bool clang::minimizeSourceToDependencyDirectives(
951
    StringRef Input, SmallVectorImpl<char> &Output,
952
    SmallVectorImpl<Token> &Tokens, DiagnosticsEngine *Diags,
953
164
    SourceLocation InputSourceLoc) {
954
164
  Output.clear();
955
164
  Tokens.clear();
956
164
  return Minimizer(Output, Tokens, Input, Diags, InputSourceLoc).minimize();
957
164
}