1 //===--- WhitespaceManager.h - Format C++ code ------------------*- 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 /// WhitespaceManager class manages whitespace around tokens and their 11 /// replacements. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #ifndef LLVM_CLANG_LIB_FORMAT_WHITESPACEMANAGER_H 16 #define LLVM_CLANG_LIB_FORMAT_WHITESPACEMANAGER_H 17 18 #include "TokenAnnotator.h" 19 #include "clang/Basic/SourceManager.h" 20 #include "clang/Format/Format.h" 21 #include <string> 22 23 namespace clang { 24 namespace format { 25 26 /// Manages the whitespaces around tokens and their replacements. 27 /// 28 /// This includes special handling for certain constructs, e.g. the alignment of 29 /// trailing line comments. 30 /// 31 /// To guarantee correctness of alignment operations, the \c WhitespaceManager 32 /// must be informed about every token in the source file; for each token, there 33 /// must be exactly one call to either \c replaceWhitespace or 34 /// \c addUntouchableToken. 35 /// 36 /// There may be multiple calls to \c breakToken for a given token. 37 class WhitespaceManager { 38 public: 39 WhitespaceManager(const SourceManager &SourceMgr, const FormatStyle &Style, 40 bool UseCRLF) 41 : SourceMgr(SourceMgr), Style(Style), UseCRLF(UseCRLF) {} 42 43 bool useCRLF() const { return UseCRLF; } 44 45 /// Replaces the whitespace in front of \p Tok. Only call once for 46 /// each \c AnnotatedToken. 47 /// 48 /// \p StartOfTokenColumn is the column at which the token will start after 49 /// this replacement. It is needed for determining how \p Spaces is turned 50 /// into tabs and spaces for some format styles. 51 void replaceWhitespace(FormatToken &Tok, unsigned Newlines, unsigned Spaces, 52 unsigned StartOfTokenColumn, bool isAligned = false, 53 bool InPPDirective = false); 54 55 /// Adds information about an unchangeable token's whitespace. 56 /// 57 /// Needs to be called for every token for which \c replaceWhitespace 58 /// was not called. 59 void addUntouchableToken(const FormatToken &Tok, bool InPPDirective); 60 61 llvm::Error addReplacement(const tooling::Replacement &Replacement); 62 63 /// Inserts or replaces whitespace in the middle of a token. 64 /// 65 /// Inserts \p PreviousPostfix, \p Newlines, \p Spaces and \p CurrentPrefix 66 /// (in this order) at \p Offset inside \p Tok, replacing \p ReplaceChars 67 /// characters. 68 /// 69 /// Note: \p Spaces can be negative to retain information about initial 70 /// relative column offset between a line of a block comment and the start of 71 /// the comment. This negative offset may be compensated by trailing comment 72 /// alignment here. In all other cases negative \p Spaces will be truncated to 73 /// 0. 74 /// 75 /// When \p InPPDirective is true, escaped newlines are inserted. \p Spaces is 76 /// used to align backslashes correctly. 77 void replaceWhitespaceInToken(const FormatToken &Tok, unsigned Offset, 78 unsigned ReplaceChars, 79 StringRef PreviousPostfix, 80 StringRef CurrentPrefix, bool InPPDirective, 81 unsigned Newlines, int Spaces); 82 83 /// Returns all the \c Replacements created during formatting. 84 const tooling::Replacements &generateReplacements(); 85 86 /// Represents a change before a token, a break inside a token, 87 /// or the layout of an unchanged token (or whitespace within). 88 struct Change { 89 /// Functor to sort changes in original source order. 90 class IsBeforeInFile { 91 public: 92 IsBeforeInFile(const SourceManager &SourceMgr) : SourceMgr(SourceMgr) {} 93 bool operator()(const Change &C1, const Change &C2) const; 94 95 private: 96 const SourceManager &SourceMgr; 97 }; 98 99 /// Creates a \c Change. 100 /// 101 /// The generated \c Change will replace the characters at 102 /// \p OriginalWhitespaceRange with a concatenation of 103 /// \p PreviousLinePostfix, \p NewlinesBefore line breaks, \p Spaces spaces 104 /// and \p CurrentLinePrefix. 105 /// 106 /// \p StartOfTokenColumn and \p InPPDirective will be used to lay out 107 /// trailing comments and escaped newlines. 108 Change(const FormatToken &Tok, bool CreateReplacement, 109 SourceRange OriginalWhitespaceRange, int Spaces, 110 unsigned StartOfTokenColumn, unsigned NewlinesBefore, 111 StringRef PreviousLinePostfix, StringRef CurrentLinePrefix, 112 bool IsAligned, bool ContinuesPPDirective, bool IsInsideToken); 113 114 // The kind of the token whose whitespace this change replaces, or in which 115 // this change inserts whitespace. 116 // FIXME: Currently this is not set correctly for breaks inside comments, as 117 // the \c BreakableToken is still doing its own alignment. 118 const FormatToken *Tok; 119 120 bool CreateReplacement; 121 // Changes might be in the middle of a token, so we cannot just keep the 122 // FormatToken around to query its information. 123 SourceRange OriginalWhitespaceRange; 124 unsigned StartOfTokenColumn; 125 unsigned NewlinesBefore; 126 std::string PreviousLinePostfix; 127 std::string CurrentLinePrefix; 128 bool IsAligned; 129 bool ContinuesPPDirective; 130 131 // The number of spaces in front of the token or broken part of the token. 132 // This will be adapted when aligning tokens. 133 // Can be negative to retain information about the initial relative offset 134 // of the lines in a block comment. This is used when aligning trailing 135 // comments. Uncompensated negative offset is truncated to 0. 136 int Spaces; 137 138 // If this change is inside of a token but not at the start of the token or 139 // directly after a newline. 140 bool IsInsideToken; 141 142 // \c IsTrailingComment, \c TokenLength, \c PreviousEndOfTokenColumn and 143 // \c EscapedNewlineColumn will be calculated in 144 // \c calculateLineBreakInformation. 145 bool IsTrailingComment; 146 unsigned TokenLength; 147 unsigned PreviousEndOfTokenColumn; 148 unsigned EscapedNewlineColumn; 149 150 // These fields are used to retain correct relative line indentation in a 151 // block comment when aligning trailing comments. 152 // 153 // If this Change represents a continuation of a block comment, 154 // \c StartOfBlockComment is pointer to the first Change in the block 155 // comment. \c IndentationOffset is a relative column offset to this 156 // change, so that the correct column can be reconstructed at the end of 157 // the alignment process. 158 const Change *StartOfBlockComment; 159 int IndentationOffset; 160 161 // A combination of indent level and nesting level, which are used in 162 // tandem to compute lexical scope, for the purposes of deciding 163 // when to stop consecutive alignment runs. 164 std::pair<unsigned, unsigned> indentAndNestingLevel() const { 165 return std::make_pair(Tok->IndentLevel, Tok->NestingLevel); 166 } 167 }; 168 169 private: 170 /// Calculate \c IsTrailingComment, \c TokenLength for the last tokens 171 /// or token parts in a line and \c PreviousEndOfTokenColumn and 172 /// \c EscapedNewlineColumn for the first tokens or token parts in a line. 173 void calculateLineBreakInformation(); 174 175 /// \brief Align consecutive C/C++ preprocessor macros over all \c Changes. 176 void alignConsecutiveMacros(); 177 178 /// Align consecutive assignments over all \c Changes. 179 void alignConsecutiveAssignments(); 180 181 /// Align consecutive declarations over all \c Changes. 182 void alignConsecutiveDeclarations(); 183 184 /// Align trailing comments over all \c Changes. 185 void alignTrailingComments(); 186 187 /// Align trailing comments from change \p Start to change \p End at 188 /// the specified \p Column. 189 void alignTrailingComments(unsigned Start, unsigned End, unsigned Column); 190 191 /// Align escaped newlines over all \c Changes. 192 void alignEscapedNewlines(); 193 194 /// Align escaped newlines from change \p Start to change \p End at 195 /// the specified \p Column. 196 void alignEscapedNewlines(unsigned Start, unsigned End, unsigned Column); 197 198 /// Fill \c Replaces with the replacements for all effective changes. 199 void generateChanges(); 200 201 /// Stores \p Text as the replacement for the whitespace in \p Range. 202 void storeReplacement(SourceRange Range, StringRef Text); 203 void appendNewlineText(std::string &Text, unsigned Newlines); 204 void appendEscapedNewlineText(std::string &Text, unsigned Newlines, 205 unsigned PreviousEndOfTokenColumn, 206 unsigned EscapedNewlineColumn); 207 void appendIndentText(std::string &Text, unsigned IndentLevel, 208 unsigned Spaces, unsigned WhitespaceStartColumn, 209 bool IsAligned); 210 unsigned appendTabIndent(std::string &Text, unsigned Spaces, 211 unsigned Indentation); 212 213 SmallVector<Change, 16> Changes; 214 const SourceManager &SourceMgr; 215 tooling::Replacements Replaces; 216 const FormatStyle &Style; 217 bool UseCRLF; 218 }; 219 220 } // namespace format 221 } // namespace clang 222 223 #endif 224