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 lexModule(const char *&First, const char *const End);
63 LLVM_NODISCARD bool lexDefine(const char *&First, const char *const End);
64 LLVM_NODISCARD bool lexPragma(const char *&First, const char *const End);
65 LLVM_NODISCARD bool lexEndif(const char *&First, const char *const End);
66 LLVM_NODISCARD bool lexDefault(TokenKind Kind, StringRef Directive,
67 const char *&First, const char *const End);
68 Token &makeToken(TokenKind K) {
69 Tokens.emplace_back(K, Out.size());
73 Out.resize(Tokens.back().Offset);
76 TokenKind top() const { return Tokens.empty() ? pp_none : Tokens.back().K; }
78 Minimizer &put(char Byte) {
82 Minimizer &append(StringRef S) { return append(S.begin(), S.end()); }
83 Minimizer &append(const char *First, const char *Last) {
84 Out.append(First, Last);
88 void printToNewline(const char *&First, const char *const End);
89 void printAdjacentModuleNameParts(const char *&First, const char *const End);
90 LLVM_NODISCARD bool printAtImportBody(const char *&First,
91 const char *const End);
92 void printDirectiveBody(const char *&First, const char *const End);
93 void printAdjacentMacroArgs(const char *&First, const char *const End);
94 LLVM_NODISCARD bool printMacroArgs(const char *&First, const char *const End);
96 /// Reports a diagnostic if the diagnostic engine is provided. Always returns
98 bool reportError(const char *CurPtr, unsigned Err);
100 StringMap<char> SplitIds;
102 DiagnosticsEngine *Diags;
103 SourceLocation InputSourceLoc;
106 } // end anonymous namespace
108 bool Minimizer::reportError(const char *CurPtr, unsigned Err) {
111 assert(CurPtr >= Input.data() && "invalid buffer ptr");
112 Diags->Report(InputSourceLoc.getLocWithOffset(CurPtr - Input.data()), Err);
116 static void skipOverSpaces(const char *&First, const char *const End) {
117 while (First != End && isHorizontalWhitespace(*First))
121 LLVM_NODISCARD static bool isRawStringLiteral(const char *First,
122 const char *Current) {
123 assert(First <= Current);
125 // Check if we can even back up.
126 if (*Current != '"' || First == Current)
133 if (First == Current || !isIdentifierBody(*--Current))
136 // Check for a prefix of "u", "U", or "L".
137 if (*Current == 'u' || *Current == 'U' || *Current == 'L')
138 return First == Current || !isIdentifierBody(*--Current);
140 // Check for a prefix of "u8".
141 if (*Current != '8' || First == Current || *Current-- != 'u')
143 return First == Current || !isIdentifierBody(*--Current);
146 static void skipRawString(const char *&First, const char *const End) {
147 assert(First[0] == '"');
148 assert(First[-1] == 'R');
150 const char *Last = ++First;
151 while (Last != End && *Last != '(')
154 First = Last; // Hit the end... just give up.
158 StringRef Terminator(First, Last - First);
160 // Move First to just past the next ")".
162 while (First != End && *First != ')')
168 // Look ahead for the terminator sequence.
170 while (Last != End && size_t(Last - First) < Terminator.size() &&
171 Terminator[Last - First] == *Last)
174 // Check if we hit it (or the end of the file).
179 if (size_t(Last - First) < Terminator.size())
188 // Returns the length of EOL, either 0 (no end-of-line), 1 (\n) or 2 (\r\n)
189 static unsigned isEOL(const char *First, const char *const End) {
192 if (End - First > 1 && isVerticalWhitespace(First[0]) &&
193 isVerticalWhitespace(First[1]) && First[0] != First[1])
195 return !!isVerticalWhitespace(First[0]);
198 static void skipString(const char *&First, const char *const End) {
199 assert(*First == '\'' || *First == '"' || *First == '<');
200 const char Terminator = *First == '<' ? '>' : *First;
201 for (++First; First != End && *First != Terminator; ++First) {
202 // String and character literals don't extend past the end of the line.
203 if (isVerticalWhitespace(*First))
207 // Skip past backslash to the next character. This ensures that the
208 // character right after it is skipped as well, which matters if it's
212 if (!isWhitespace(*First))
214 // Whitespace after the backslash might indicate a line continuation.
215 const char *FirstAfterBackslashPastSpace = First;
216 skipOverSpaces(FirstAfterBackslashPastSpace, End);
217 if (unsigned NLSize = isEOL(FirstAfterBackslashPastSpace, End)) {
218 // Advance the character pointer to the next line for the next
220 First = FirstAfterBackslashPastSpace + NLSize - 1;
224 ++First; // Finish off the string.
227 // Returns the length of the skipped newline
228 static unsigned skipNewline(const char *&First, const char *End) {
231 assert(isVerticalWhitespace(*First));
232 unsigned Len = isEOL(First, End);
233 assert(Len && "expected newline");
238 static bool wasLineContinuation(const char *First, unsigned EOLLen) {
239 return *(First - (int)EOLLen - 1) == '\\';
242 static void skipToNewlineRaw(const char *&First, const char *const End) {
247 unsigned Len = isEOL(First, End);
254 Len = isEOL(First, End);
257 if (First[-1] != '\\')
261 // Keep skipping lines...
265 static const char *findLastNonSpace(const char *First, const char *Last) {
266 assert(First <= Last);
267 while (First != Last && isHorizontalWhitespace(Last[-1]))
272 static const char *findFirstTrailingSpace(const char *First,
274 const char *LastNonSpace = findLastNonSpace(First, Last);
275 if (Last == LastNonSpace)
277 assert(isHorizontalWhitespace(LastNonSpace[0]));
278 return LastNonSpace + 1;
281 static void skipLineComment(const char *&First, const char *const End) {
282 assert(First[0] == '/' && First[1] == '/');
284 skipToNewlineRaw(First, End);
287 static void skipBlockComment(const char *&First, const char *const End) {
288 assert(First[0] == '/' && First[1] == '*');
289 if (End - First < 4) {
293 for (First += 3; First != End; ++First)
294 if (First[-1] == '*' && First[0] == '/') {
300 /// \returns True if the current single quotation mark character is a C++ 14
302 static bool isQuoteCppDigitSeparator(const char *const Start,
303 const char *const Cur,
304 const char *const End) {
305 assert(*Cur == '\'' && "expected quotation character");
306 // skipLine called in places where we don't expect a valid number
307 // body before `start` on the same line, so always return false at the start.
310 // The previous character must be a valid PP number character.
311 // Make sure that the L, u, U, u8 prefixes don't get marked as a
313 char Prev = *(Cur - 1);
314 if (Prev == 'L' || Prev == 'U' || Prev == 'u')
316 if (Prev == '8' && (Cur - 1 != Start) && *(Cur - 2) == 'u')
318 if (!isPreprocessingNumberBody(Prev))
320 // The next character should be a valid identifier body character.
321 return (Cur + 1) < End && isIdentifierBody(*(Cur + 1));
324 static void skipLine(const char *&First, const char *const End) {
326 assert(First <= End);
330 if (isVerticalWhitespace(*First)) {
331 skipNewline(First, End);
334 const char *Start = First;
335 while (First != End && !isVerticalWhitespace(*First)) {
336 // Iterate over strings correctly to avoid comments and newlines.
338 (*First == '\'' && !isQuoteCppDigitSeparator(Start, First, End))) {
339 if (isRawStringLiteral(Start, First))
340 skipRawString(First, End);
342 skipString(First, End);
346 // Iterate over comments correctly.
347 if (*First != '/' || End - First < 2) {
352 if (First[1] == '/') {
354 skipLineComment(First, End);
358 if (First[1] != '*') {
364 skipBlockComment(First, End);
369 // Skip over the newline.
370 unsigned Len = skipNewline(First, End);
371 if (!wasLineContinuation(First, Len)) // Continue past line-continuations.
376 static void skipDirective(StringRef Name, const char *&First,
377 const char *const End) {
378 if (llvm::StringSwitch<bool>(Name)
379 .Case("warning", true)
382 // Do not process quotes or comments.
383 skipToNewlineRaw(First, End);
385 skipLine(First, End);
388 void Minimizer::printToNewline(const char *&First, const char *const End) {
389 while (First != End && !isVerticalWhitespace(*First)) {
390 const char *Last = First;
392 // Iterate over strings correctly to avoid comments and newlines.
393 if (*Last == '"' || *Last == '\'' ||
394 (*Last == '<' && top() == pp_include)) {
395 if (LLVM_UNLIKELY(isRawStringLiteral(First, Last)))
396 skipRawString(Last, End);
398 skipString(Last, End);
401 if (*Last != '/' || End - Last < 2) {
403 continue; // Gather the rest up to print verbatim.
406 if (Last[1] != '/' && Last[1] != '*') {
411 // Deal with "//..." and "/*...*/".
412 append(First, findFirstTrailingSpace(First, Last));
415 if (Last[1] == '/') {
416 skipLineComment(First, End);
421 skipBlockComment(First, End);
422 skipOverSpaces(First, End);
424 } while (Last != End && !isVerticalWhitespace(*Last));
426 // Print out the string.
427 const char *LastBeforeTrailingSpace = findLastNonSpace(First, Last);
428 if (Last == End || LastBeforeTrailingSpace == First ||
429 LastBeforeTrailingSpace[-1] != '\\') {
430 append(First, LastBeforeTrailingSpace);
432 skipNewline(First, End);
436 // Print up to the backslash, backing up over spaces. Preserve at least one
437 // space, as the space matters when tokens are separated by a line
439 append(First, findFirstTrailingSpace(
440 First, LastBeforeTrailingSpace - 1));
443 skipNewline(First, End);
444 skipOverSpaces(First, End);
448 static void skipWhitespace(const char *&First, const char *const End) {
450 assert(First <= End);
451 skipOverSpaces(First, End);
456 if (First[0] == '\\' && isVerticalWhitespace(First[1])) {
457 skipNewline(++First, End);
461 // Check for a non-comment character.
466 if (First[1] == '/') {
467 skipLineComment(First, End);
471 // Cannot be a comment.
476 skipBlockComment(First, End);
480 void Minimizer::printAdjacentModuleNameParts(const char *&First,
481 const char *const End) {
482 // Skip over parts of the body.
483 const char *Last = First;
486 while (Last != End && (isIdentifierBody(*Last) || *Last == '.'));
491 bool Minimizer::printAtImportBody(const char *&First, const char *const End) {
493 skipWhitespace(First, End);
497 if (isVerticalWhitespace(*First)) {
498 skipNewline(First, End);
502 // Found a semicolon.
504 put(*First++).put('\n');
508 // Don't handle macro expansions inside @import for now.
509 if (!isIdentifierBody(*First) && *First != '.')
512 printAdjacentModuleNameParts(First, End);
516 void Minimizer::printDirectiveBody(const char *&First, const char *const End) {
517 skipWhitespace(First, End); // Skip initial whitespace.
518 printToNewline(First, End);
519 while (Out.back() == ' ')
524 LLVM_NODISCARD static const char *lexRawIdentifier(const char *First,
525 const char *const End) {
526 assert(isIdentifierBody(*First) && "invalid identifer");
527 const char *Last = First + 1;
528 while (Last != End && isIdentifierBody(*Last))
533 LLVM_NODISCARD static const char *
534 getIdentifierContinuation(const char *First, const char *const End) {
535 if (End - First < 3 || First[0] != '\\' || !isVerticalWhitespace(First[1]))
539 skipNewline(First, End);
542 return isIdentifierBody(First[0]) ? First : nullptr;
545 Minimizer::IdInfo Minimizer::lexIdentifier(const char *First,
546 const char *const End) {
547 const char *Last = lexRawIdentifier(First, End);
548 const char *Next = getIdentifierContinuation(Last, End);
549 if (LLVM_LIKELY(!Next))
550 return IdInfo{Last, StringRef(First, Last - First)};
552 // Slow path, where identifiers are split over lines.
553 SmallVector<char, 64> Id(First, Last);
555 Last = lexRawIdentifier(Next, End);
556 Id.append(Next, Last);
557 Next = getIdentifierContinuation(Last, End);
561 SplitIds.try_emplace(StringRef(Id.begin(), Id.size()), 0).first->first()};
564 void Minimizer::printAdjacentMacroArgs(const char *&First,
565 const char *const End) {
566 // Skip over parts of the body.
567 const char *Last = First;
570 while (Last != End &&
571 (isIdentifierBody(*Last) || *Last == '.' || *Last == ','));
576 bool Minimizer::printMacroArgs(const char *&First, const char *const End) {
577 assert(*First == '(');
580 skipWhitespace(First, End);
589 // This is intentionally fairly liberal.
590 if (!(isIdentifierBody(*First) || *First == '.' || *First == ','))
593 printAdjacentMacroArgs(First, End);
597 /// Looks for an identifier starting from Last.
599 /// Updates "First" to just past the next identifier, if any. Returns true iff
600 /// the identifier matches "Id".
601 bool Minimizer::isNextIdentifier(StringRef Id, const char *&First,
602 const char *const End) {
603 skipWhitespace(First, End);
604 if (First == End || !isIdentifierHead(*First))
607 IdInfo FoundId = lexIdentifier(First, End);
608 First = FoundId.Last;
609 return FoundId.Name == Id;
612 bool Minimizer::lexAt(const char *&First, const char *const End) {
614 const char *ImportLoc = First++;
615 if (!isNextIdentifier("import", First, End)) {
616 skipLine(First, End);
619 makeToken(decl_at_import);
621 if (printAtImportBody(First, End))
623 ImportLoc, diag::err_dep_source_minimizer_missing_sema_after_at_import);
624 skipWhitespace(First, End);
627 if (!isVerticalWhitespace(*First))
629 ImportLoc, diag::err_dep_source_minimizer_unexpected_tokens_at_import);
630 skipNewline(First, End);
634 bool Minimizer::lexModule(const char *&First, const char *const End) {
635 IdInfo Id = lexIdentifier(First, End);
638 if (Id.Name == "export") {
640 skipWhitespace(First, End);
641 if (!isIdentifierBody(*First)) {
642 skipLine(First, End);
645 Id = lexIdentifier(First, End);
649 if (Id.Name != "module" && Id.Name != "import") {
650 skipLine(First, End);
654 skipWhitespace(First, End);
656 // Ignore this as a module directive if the next character can't be part of
665 if (!isIdentifierBody(*First)) {
666 skipLine(First, End);
672 makeToken(cxx_export_decl);
676 if (Id.Name == "module")
677 makeToken(cxx_module_decl);
679 makeToken(cxx_import_decl);
682 printToNewline(First, End);
687 bool Minimizer::lexDefine(const char *&First, const char *const End) {
688 makeToken(pp_define);
690 skipWhitespace(First, End);
692 if (!isIdentifierHead(*First))
693 return reportError(First, diag::err_pp_macro_not_identifier);
695 IdInfo Id = lexIdentifier(First, End);
696 const char *Last = Id.Last;
701 size_t Size = Out.size();
702 if (printMacroArgs(Last, End)) {
703 // Be robust to bad macro arguments, since they can show up in disabled
706 append("(/* invalid */\n");
711 skipWhitespace(Last, End);
714 if (!isVerticalWhitespace(*Last))
716 printDirectiveBody(Last, End);
721 bool Minimizer::lexPragma(const char *&First, const char *const End) {
723 skipWhitespace(First, End);
724 if (First == End || !isIdentifierHead(*First))
727 IdInfo FoundId = lexIdentifier(First, End);
728 First = FoundId.Last;
729 if (FoundId.Name == "once") {
731 skipLine(First, End);
732 makeToken(pp_pragma_once);
733 append("#pragma once\n");
737 if (FoundId.Name != "clang") {
738 skipLine(First, End);
743 if (!isNextIdentifier("module", First, End)) {
744 skipLine(First, End);
748 // #pragma clang module.
749 if (!isNextIdentifier("import", First, End)) {
750 skipLine(First, End);
754 // #pragma clang module import.
755 makeToken(pp_pragma_import);
756 append("#pragma clang module import ");
757 printDirectiveBody(First, End);
761 bool Minimizer::lexEndif(const char *&First, const char *const End) {
762 // Strip out "#else" if it's empty.
763 if (top() == pp_else)
766 // Strip out "#elif" if they're empty.
767 while (top() == pp_elif)
770 // If "#if" is empty, strip it and skip the "#endif".
771 if (top() == pp_if || top() == pp_ifdef || top() == pp_ifndef) {
773 skipLine(First, End);
777 return lexDefault(pp_endif, "endif", First, End);
780 bool Minimizer::lexDefault(TokenKind Kind, StringRef Directive,
781 const char *&First, const char *const End) {
783 put('#').append(Directive).put(' ');
784 printDirectiveBody(First, End);
788 static bool isStartOfRelevantLine(char First) {
800 bool Minimizer::lexPPLine(const char *&First, const char *const End) {
801 assert(First != End);
803 skipWhitespace(First, End);
804 assert(First <= End);
808 if (!isStartOfRelevantLine(*First)) {
809 skipLine(First, End);
810 assert(First <= End);
816 return lexAt(First, End);
818 if (*First == 'i' || *First == 'e' || *First == 'm')
819 return lexModule(First, End);
821 // Handle preprocessing directives.
822 ++First; // Skip over '#'.
823 skipWhitespace(First, End);
826 return reportError(First, diag::err_pp_expected_eol);
828 if (!isIdentifierHead(*First)) {
829 skipLine(First, End);
833 // Figure out the token.
834 IdInfo Id = lexIdentifier(First, End);
836 auto Kind = llvm::StringSwitch<TokenKind>(Id.Name)
837 .Case("include", pp_include)
838 .Case("__include_macros", pp___include_macros)
839 .Case("define", pp_define)
840 .Case("undef", pp_undef)
841 .Case("import", pp_import)
842 .Case("include_next", pp_include_next)
844 .Case("ifdef", pp_ifdef)
845 .Case("ifndef", pp_ifndef)
846 .Case("elif", pp_elif)
847 .Case("else", pp_else)
848 .Case("endif", pp_endif)
849 .Case("pragma", pp_pragma_import)
851 if (Kind == pp_none) {
852 skipDirective(Id.Name, First, End);
856 if (Kind == pp_endif)
857 return lexEndif(First, End);
859 if (Kind == pp_define)
860 return lexDefine(First, End);
862 if (Kind == pp_pragma_import)
863 return lexPragma(First, End);
866 return lexDefault(Kind, Id.Name, First, End);
869 static void skipUTF8ByteOrderMark(const char *&First, const char *const End) {
870 if ((End - First) >= 3 && First[0] == '\xef' && First[1] == '\xbb' &&
875 bool Minimizer::minimizeImpl(const char *First, const char *const End) {
876 skipUTF8ByteOrderMark(First, End);
878 if (lexPPLine(First, End))
883 bool Minimizer::minimize() {
884 bool Error = minimizeImpl(Input.begin(), Input.end());
887 // Add a trailing newline and an EOF on success.
888 if (!Out.empty() && Out.back() != '\n')
893 // Null-terminate the output. This way the memory buffer that's passed to
894 // Clang will not have to worry about the terminating '\0'.
900 bool clang::minimize_source_to_dependency_directives::computeSkippedRanges(
901 ArrayRef<Token> Input, llvm::SmallVectorImpl<SkippedRange> &Range) {
904 If, // if/ifdef/ifndef
910 llvm::SmallVector<Directive, 32> Offsets;
911 for (const Token &T : Input) {
916 Offsets.push_back({T.Offset, Directive::If});
923 int PreviousOffset = Offsets.back().Offset;
924 Range.push_back({PreviousOffset, T.Offset - PreviousOffset});
925 Offsets.push_back({T.Offset, Directive::Else});
932 int PreviousOffset = Offsets.back().Offset;
933 Range.push_back({PreviousOffset, T.Offset - PreviousOffset});
935 Directive::DirectiveKind Kind = Offsets.pop_back_val().Kind;
936 if (Kind == Directive::If)
938 } while (!Offsets.empty());
948 bool clang::minimizeSourceToDependencyDirectives(
949 StringRef Input, SmallVectorImpl<char> &Output,
950 SmallVectorImpl<Token> &Tokens, DiagnosticsEngine *Diags,
951 SourceLocation InputSourceLoc) {
954 return Minimizer(Output, Tokens, Input, Diags, InputSourceLoc).minimize();