1 //===- DependencyDirectivesSourceMinimizer.cpp - -------------------------===//
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
7 //===----------------------------------------------------------------------===//
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.
15 //===----------------------------------------------------------------------===//
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/StringSwitch.h"
22 #include "llvm/Support/MemoryBuffer.h"
25 using namespace clang;
26 using namespace clang::minimize_source_to_dependency_directives;
32 SmallVectorImpl<char> &Out;
33 /// The known tokens encountered during the minimization.
34 SmallVectorImpl<Token> &Tokens;
36 Minimizer(SmallVectorImpl<char> &Out, SmallVectorImpl<Token> &Tokens,
37 StringRef Input, DiagnosticsEngine *Diags,
38 SourceLocation InputSourceLoc)
39 : Out(Out), Tokens(Tokens), Input(Input), Diags(Diags),
40 InputSourceLoc(InputSourceLoc) {}
42 /// Lex the provided source and emit the minimized output.
44 /// \returns True on error.
53 /// Lex an identifier.
55 /// \pre First points at a valid identifier head.
56 LLVM_NODISCARD IdInfo lexIdentifier(const char *First, const char *const End);
57 LLVM_NODISCARD bool isNextIdentifier(StringRef Id, const char *&First,
58 const char *const End);
59 LLVM_NODISCARD bool minimizeImpl(const char *First, const char *const End);
60 LLVM_NODISCARD bool lexPPLine(const char *&First, const char *const End);
61 LLVM_NODISCARD bool lexAt(const char *&First, const char *const End);
62 LLVM_NODISCARD bool lexDefine(const char *&First, const char *const End);
63 LLVM_NODISCARD bool lexPragma(const char *&First, const char *const End);
64 LLVM_NODISCARD bool lexEndif(const char *&First, const char *const End);
65 LLVM_NODISCARD bool lexDefault(TokenKind Kind, StringRef Directive,
66 const char *&First, const char *const End);
67 Token &makeToken(TokenKind K) {
68 Tokens.emplace_back(K, Out.size());
72 Out.resize(Tokens.back().Offset);
75 TokenKind top() const { return Tokens.empty() ? pp_none : Tokens.back().K; }
77 Minimizer &put(char Byte) {
81 Minimizer &append(StringRef S) { return append(S.begin(), S.end()); }
82 Minimizer &append(const char *First, const char *Last) {
83 Out.append(First, Last);
87 void printToNewline(const char *&First, const char *const End);
88 void printAdjacentModuleNameParts(const char *&First, const char *const End);
89 LLVM_NODISCARD bool printAtImportBody(const char *&First,
90 const char *const End);
91 void printDirectiveBody(const char *&First, const char *const End);
92 void printAdjacentMacroArgs(const char *&First, const char *const End);
93 LLVM_NODISCARD bool printMacroArgs(const char *&First, const char *const End);
95 /// Reports a diagnostic if the diagnostic engine is provided. Always returns
97 bool reportError(const char *CurPtr, unsigned Err);
99 StringMap<char> SplitIds;
101 DiagnosticsEngine *Diags;
102 SourceLocation InputSourceLoc;
105 } // end anonymous namespace
107 bool Minimizer::reportError(const char *CurPtr, unsigned Err) {
110 assert(CurPtr >= Input.data() && "invalid buffer ptr");
111 Diags->Report(InputSourceLoc.getLocWithOffset(CurPtr - Input.data()), Err);
115 static void skipOverSpaces(const char *&First, const char *const End) {
116 while (First != End && isHorizontalWhitespace(*First))
120 LLVM_NODISCARD static bool isRawStringLiteral(const char *First,
121 const char *Current) {
122 assert(First <= Current);
124 // Check if we can even back up.
125 if (*Current != '"' || First == Current)
132 if (First == Current || !isIdentifierBody(*--Current))
135 // Check for a prefix of "u", "U", or "L".
136 if (*Current == 'u' || *Current == 'U' || *Current == 'L')
137 return First == Current || !isIdentifierBody(*--Current);
139 // Check for a prefix of "u8".
140 if (*Current != '8' || First == Current || *Current-- != 'u')
142 return First == Current || !isIdentifierBody(*--Current);
145 static void skipRawString(const char *&First, const char *const End) {
146 assert(First[0] == '"');
147 assert(First[-1] == 'R');
149 const char *Last = ++First;
150 while (Last != End && *Last != '(')
153 First = Last; // Hit the end... just give up.
157 StringRef Terminator(First, Last - First);
159 // Move First to just past the next ")".
161 while (First != End && *First != ')')
167 // Look ahead for the terminator sequence.
169 while (Last != End && size_t(Last - First) < Terminator.size() &&
170 Terminator[Last - First] == *Last)
173 // Check if we hit it (or the end of the file).
178 if (size_t(Last - First) < Terminator.size())
187 static void skipString(const char *&First, const char *const End) {
188 assert(*First == '\'' || *First == '"');
189 const char Terminator = *First;
190 for (++First; First != End && *First != Terminator; ++First)
195 ++First; // Finish off the string.
198 static void skipNewline(const char *&First, const char *End) {
199 assert(isVerticalWhitespace(*First));
204 // Check for "\n\r" and "\r\n".
205 if (LLVM_UNLIKELY(isVerticalWhitespace(*First) && First[-1] != First[0]))
209 static void skipToNewlineRaw(const char *&First, const char *const End) {
214 if (isVerticalWhitespace(*First))
217 while (!isVerticalWhitespace(*First))
221 if (First[-1] != '\\')
224 ++First; // Keep going...
228 static const char *reverseOverSpaces(const char *First, const char *Last) {
229 assert(First <= Last);
230 while (First != Last && isHorizontalWhitespace(Last[-1]))
235 static void skipLineComment(const char *&First, const char *const End) {
236 assert(First[0] == '/' && First[1] == '/');
238 skipToNewlineRaw(First, End);
241 static void skipBlockComment(const char *&First, const char *const End) {
242 assert(First[0] == '/' && First[1] == '*');
243 if (End - First < 4) {
247 for (First += 3; First != End; ++First)
248 if (First[-1] == '*' && First[0] == '/') {
254 /// \returns True if the current single quotation mark character is a C++ 14
256 static bool isQuoteCppDigitSeparator(const char *const Start,
257 const char *const Cur,
258 const char *const End) {
259 assert(*Cur == '\'' && "expected quotation character");
260 // skipLine called in places where we don't expect a valid number
261 // body before `start` on the same line, so always return false at the start.
264 // The previous character must be a valid PP number character.
265 // Make sure that the L, u, U, u8 prefixes don't get marked as a
267 char Prev = *(Cur - 1);
268 if (Prev == 'L' || Prev == 'U' || Prev == 'u')
270 if (Prev == '8' && (Cur - 1 != Start) && *(Cur - 2) == 'u')
272 if (!isPreprocessingNumberBody(Prev))
274 // The next character should be a valid identifier body character.
275 return (Cur + 1) < End && isIdentifierBody(*(Cur + 1));
278 static void skipLine(const char *&First, const char *const End) {
280 assert(First <= End);
284 if (isVerticalWhitespace(*First)) {
285 skipNewline(First, End);
288 const char *Start = First;
289 while (First != End && !isVerticalWhitespace(*First)) {
290 // Iterate over strings correctly to avoid comments and newlines.
292 (*First == '\'' && !isQuoteCppDigitSeparator(Start, First, End))) {
293 if (isRawStringLiteral(Start, First))
294 skipRawString(First, End);
296 skipString(First, End);
300 // Iterate over comments correctly.
301 if (*First != '/' || End - First < 2) {
306 if (First[1] == '/') {
308 skipLineComment(First, End);
312 if (First[1] != '*') {
318 skipBlockComment(First, End);
323 // Skip over the newline.
324 assert(isVerticalWhitespace(*First));
325 skipNewline(First, End);
326 } while (First[-2] == '\\'); // Continue past line-continuations.
329 static void skipDirective(StringRef Name, const char *&First,
330 const char *const End) {
331 if (llvm::StringSwitch<bool>(Name)
332 .Case("warning", true)
335 // Do not process quotes or comments.
336 skipToNewlineRaw(First, End);
338 skipLine(First, End);
341 void Minimizer::printToNewline(const char *&First, const char *const End) {
342 while (First != End && !isVerticalWhitespace(*First)) {
343 const char *Last = First;
345 // Iterate over strings correctly to avoid comments and newlines.
346 if (*Last == '"' || *Last == '\'') {
347 if (LLVM_UNLIKELY(isRawStringLiteral(First, Last)))
348 skipRawString(Last, End);
350 skipString(Last, End);
353 if (*Last != '/' || End - Last < 2) {
355 continue; // Gather the rest up to print verbatim.
358 if (Last[1] != '/' && Last[1] != '*') {
363 // Deal with "//..." and "/*...*/".
364 append(First, reverseOverSpaces(First, Last));
367 if (Last[1] == '/') {
368 skipLineComment(First, End);
373 skipBlockComment(First, End);
374 skipOverSpaces(First, End);
376 } while (Last != End && !isVerticalWhitespace(*Last));
378 // Print out the string.
379 if (Last == End || Last == First || Last[-1] != '\\') {
380 append(First, reverseOverSpaces(First, Last));
384 // Print up to the backslash, backing up over spaces.
385 append(First, reverseOverSpaces(First, Last - 1));
388 skipNewline(First, End);
389 skipOverSpaces(First, End);
393 static void skipWhitespace(const char *&First, const char *const End) {
395 assert(First <= End);
396 skipOverSpaces(First, End);
401 if (First[0] == '\\' && isVerticalWhitespace(First[1])) {
402 skipNewline(++First, End);
406 // Check for a non-comment character.
411 if (First[1] == '/') {
412 skipLineComment(First, End);
416 // Cannot be a comment.
421 skipBlockComment(First, End);
425 void Minimizer::printAdjacentModuleNameParts(const char *&First,
426 const char *const End) {
427 // Skip over parts of the body.
428 const char *Last = First;
431 while (Last != End && (isIdentifierBody(*Last) || *Last == '.'));
436 bool Minimizer::printAtImportBody(const char *&First, const char *const End) {
438 skipWhitespace(First, End);
442 if (isVerticalWhitespace(*First)) {
443 skipNewline(First, End);
447 // Found a semicolon.
449 put(*First++).put('\n');
453 // Don't handle macro expansions inside @import for now.
454 if (!isIdentifierBody(*First) && *First != '.')
457 printAdjacentModuleNameParts(First, End);
461 void Minimizer::printDirectiveBody(const char *&First, const char *const End) {
462 skipWhitespace(First, End); // Skip initial whitespace.
463 printToNewline(First, End);
464 while (Out.back() == ' ')
469 LLVM_NODISCARD static const char *lexRawIdentifier(const char *First,
470 const char *const End) {
471 assert(isIdentifierBody(*First) && "invalid identifer");
472 const char *Last = First + 1;
473 while (Last != End && isIdentifierBody(*Last))
478 LLVM_NODISCARD static const char *
479 getIdentifierContinuation(const char *First, const char *const End) {
480 if (End - First < 3 || First[0] != '\\' || !isVerticalWhitespace(First[1]))
484 skipNewline(First, End);
487 return isIdentifierBody(First[0]) ? First : nullptr;
490 Minimizer::IdInfo Minimizer::lexIdentifier(const char *First,
491 const char *const End) {
492 const char *Last = lexRawIdentifier(First, End);
493 const char *Next = getIdentifierContinuation(Last, End);
494 if (LLVM_LIKELY(!Next))
495 return IdInfo{Last, StringRef(First, Last - First)};
497 // Slow path, where identifiers are split over lines.
498 SmallVector<char, 64> Id(First, Last);
500 Last = lexRawIdentifier(Next, End);
501 Id.append(Next, Last);
502 Next = getIdentifierContinuation(Last, End);
506 SplitIds.try_emplace(StringRef(Id.begin(), Id.size()), 0).first->first()};
509 void Minimizer::printAdjacentMacroArgs(const char *&First,
510 const char *const End) {
511 // Skip over parts of the body.
512 const char *Last = First;
515 while (Last != End &&
516 (isIdentifierBody(*Last) || *Last == '.' || *Last == ','));
521 bool Minimizer::printMacroArgs(const char *&First, const char *const End) {
522 assert(*First == '(');
525 skipWhitespace(First, End);
534 // This is intentionally fairly liberal.
535 if (!(isIdentifierBody(*First) || *First == '.' || *First == ','))
538 printAdjacentMacroArgs(First, End);
542 /// Looks for an identifier starting from Last.
544 /// Updates "First" to just past the next identifier, if any. Returns true iff
545 /// the identifier matches "Id".
546 bool Minimizer::isNextIdentifier(StringRef Id, const char *&First,
547 const char *const End) {
548 skipWhitespace(First, End);
549 if (First == End || !isIdentifierHead(*First))
552 IdInfo FoundId = lexIdentifier(First, End);
553 First = FoundId.Last;
554 return FoundId.Name == Id;
557 bool Minimizer::lexAt(const char *&First, const char *const End) {
559 const char *ImportLoc = First++;
560 if (!isNextIdentifier("import", First, End)) {
561 skipLine(First, End);
564 makeToken(decl_at_import);
566 if (printAtImportBody(First, End))
568 ImportLoc, diag::err_dep_source_minimizer_missing_sema_after_at_import);
569 skipWhitespace(First, End);
572 if (!isVerticalWhitespace(*First))
574 ImportLoc, diag::err_dep_source_minimizer_unexpected_tokens_at_import);
575 skipNewline(First, End);
579 bool Minimizer::lexDefine(const char *&First, const char *const End) {
580 makeToken(pp_define);
582 skipWhitespace(First, End);
584 if (!isIdentifierHead(*First))
585 return reportError(First, diag::err_pp_macro_not_identifier);
587 IdInfo Id = lexIdentifier(First, End);
588 const char *Last = Id.Last;
593 size_t Size = Out.size();
594 if (printMacroArgs(Last, End)) {
595 // Be robust to bad macro arguments, since they can show up in disabled
598 append("(/* invalid */\n");
603 skipWhitespace(Last, End);
606 if (!isVerticalWhitespace(*Last))
608 printDirectiveBody(Last, End);
613 bool Minimizer::lexPragma(const char *&First, const char *const End) {
615 if (!isNextIdentifier("clang", First, End)) {
616 skipLine(First, End);
621 if (!isNextIdentifier("module", First, End)) {
622 skipLine(First, End);
626 // #pragma clang module.
627 if (!isNextIdentifier("import", First, End)) {
628 skipLine(First, End);
632 // #pragma clang module import.
633 makeToken(pp_pragma_import);
634 append("#pragma clang module import ");
635 printDirectiveBody(First, End);
639 bool Minimizer::lexEndif(const char *&First, const char *const End) {
640 // Strip out "#else" if it's empty.
641 if (top() == pp_else)
644 // Strip out "#elif" if they're empty.
645 while (top() == pp_elif)
648 // If "#if" is empty, strip it and skip the "#endif".
649 if (top() == pp_if || top() == pp_ifdef || top() == pp_ifndef) {
651 skipLine(First, End);
655 return lexDefault(pp_endif, "endif", First, End);
658 bool Minimizer::lexDefault(TokenKind Kind, StringRef Directive,
659 const char *&First, const char *const End) {
661 put('#').append(Directive).put(' ');
662 printDirectiveBody(First, End);
666 bool Minimizer::lexPPLine(const char *&First, const char *const End) {
667 assert(First != End);
669 skipWhitespace(First, End);
670 assert(First <= End);
674 if (*First != '#' && *First != '@') {
675 skipLine(First, End);
676 assert(First <= End);
682 return lexAt(First, End);
684 // Handle preprocessing directives.
685 ++First; // Skip over '#'.
686 skipWhitespace(First, End);
689 return reportError(First, diag::err_pp_expected_eol);
691 if (!isIdentifierHead(*First)) {
692 skipLine(First, End);
696 // Figure out the token.
697 IdInfo Id = lexIdentifier(First, End);
699 auto Kind = llvm::StringSwitch<TokenKind>(Id.Name)
700 .Case("include", pp_include)
701 .Case("__include_macros", pp___include_macros)
702 .Case("define", pp_define)
703 .Case("undef", pp_undef)
704 .Case("import", pp_import)
705 .Case("include_next", pp_include_next)
707 .Case("ifdef", pp_ifdef)
708 .Case("ifndef", pp_ifndef)
709 .Case("elif", pp_elif)
710 .Case("else", pp_else)
711 .Case("endif", pp_endif)
712 .Case("pragma", pp_pragma_import)
714 if (Kind == pp_none) {
715 skipDirective(Id.Name, First, End);
719 if (Kind == pp_endif)
720 return lexEndif(First, End);
722 if (Kind == pp_define)
723 return lexDefine(First, End);
725 if (Kind == pp_pragma_import)
726 return lexPragma(First, End);
729 return lexDefault(Kind, Id.Name, First, End);
732 bool Minimizer::minimizeImpl(const char *First, const char *const End) {
734 if (lexPPLine(First, End))
739 bool Minimizer::minimize() {
740 bool Error = minimizeImpl(Input.begin(), Input.end());
743 // Add a trailing newline and an EOF on success.
744 if (!Out.empty() && Out.back() != '\n')
749 // Null-terminate the output. This way the memory buffer that's passed to
750 // Clang will not have to worry about the terminating '\0'.
756 bool clang::minimizeSourceToDependencyDirectives(
757 StringRef Input, SmallVectorImpl<char> &Output,
758 SmallVectorImpl<Token> &Tokens, DiagnosticsEngine *Diags,
759 SourceLocation InputSourceLoc) {
762 return Minimizer(Output, Tokens, Input, Diags, InputSourceLoc).minimize();