1 //===--- WhitespaceManager.h - Format C++ code ------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief WhitespaceManager class manages whitespace around tokens and their
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CLANG_LIB_FORMAT_WHITESPACEMANAGER_H
17 #define LLVM_CLANG_LIB_FORMAT_WHITESPACEMANAGER_H
19 #include "TokenAnnotator.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Format/Format.h"
27 /// \brief Manages the whitespaces around tokens and their replacements.
29 /// This includes special handling for certain constructs, e.g. the alignment of
30 /// trailing line comments.
32 /// To guarantee correctness of alignment operations, the \c WhitespaceManager
33 /// must be informed about every token in the source file; for each token, there
34 /// must be exactly one call to either \c replaceWhitespace or
35 /// \c addUntouchableToken.
37 /// There may be multiple calls to \c breakToken for a given token.
38 class WhitespaceManager {
40 WhitespaceManager(const SourceManager &SourceMgr, const FormatStyle &Style,
42 : SourceMgr(SourceMgr), Style(Style), UseCRLF(UseCRLF) {}
44 /// \brief Replaces the whitespace in front of \p Tok. Only call once for
45 /// each \c AnnotatedToken.
46 void replaceWhitespace(FormatToken &Tok, unsigned Newlines, unsigned Spaces,
47 unsigned StartOfTokenColumn,
48 bool InPPDirective = false);
50 /// \brief Adds information about an unchangeable token's whitespace.
52 /// Needs to be called for every token for which \c replaceWhitespace
54 void addUntouchableToken(const FormatToken &Tok, bool InPPDirective);
56 /// \brief Inserts or replaces whitespace in the middle of a token.
58 /// Inserts \p PreviousPostfix, \p Newlines, \p Spaces and \p CurrentPrefix
59 /// (in this order) at \p Offset inside \p Tok, replacing \p ReplaceChars
62 /// Note: \p Spaces can be negative to retain information about initial
63 /// relative column offset between a line of a block comment and the start of
64 /// the comment. This negative offset may be compensated by trailing comment
65 /// alignment here. In all other cases negative \p Spaces will be truncated to
68 /// When \p InPPDirective is true, escaped newlines are inserted. \p Spaces is
69 /// used to align backslashes correctly.
70 void replaceWhitespaceInToken(const FormatToken &Tok, unsigned Offset,
71 unsigned ReplaceChars,
72 StringRef PreviousPostfix,
73 StringRef CurrentPrefix, bool InPPDirective,
74 unsigned Newlines, int Spaces);
76 /// \brief Returns all the \c Replacements created during formatting.
77 const tooling::Replacements &generateReplacements();
79 /// \brief Represents a change before a token, a break inside a token,
80 /// or the layout of an unchanged token (or whitespace within).
82 /// \brief Functor to sort changes in original source order.
83 class IsBeforeInFile {
85 IsBeforeInFile(const SourceManager &SourceMgr) : SourceMgr(SourceMgr) {}
86 bool operator()(const Change &C1, const Change &C2) const;
89 const SourceManager &SourceMgr;
92 /// \brief Creates a \c Change.
94 /// The generated \c Change will replace the characters at
95 /// \p OriginalWhitespaceRange with a concatenation of
96 /// \p PreviousLinePostfix, \p NewlinesBefore line breaks, \p Spaces spaces
97 /// and \p CurrentLinePrefix.
99 /// \p StartOfTokenColumn and \p InPPDirective will be used to lay out
100 /// trailing comments and escaped newlines.
101 Change(const FormatToken &Tok, bool CreateReplacement,
102 SourceRange OriginalWhitespaceRange, int Spaces,
103 unsigned StartOfTokenColumn, unsigned NewlinesBefore,
104 StringRef PreviousLinePostfix, StringRef CurrentLinePrefix,
105 bool ContinuesPPDirective, bool IsInsideToken);
107 // The kind of the token whose whitespace this change replaces, or in which
108 // this change inserts whitespace.
109 // FIXME: Currently this is not set correctly for breaks inside comments, as
110 // the \c BreakableToken is still doing its own alignment.
111 const FormatToken *Tok;
113 bool CreateReplacement;
114 // Changes might be in the middle of a token, so we cannot just keep the
115 // FormatToken around to query its information.
116 SourceRange OriginalWhitespaceRange;
117 unsigned StartOfTokenColumn;
118 unsigned NewlinesBefore;
119 std::string PreviousLinePostfix;
120 std::string CurrentLinePrefix;
121 bool ContinuesPPDirective;
123 // The number of spaces in front of the token or broken part of the token.
124 // This will be adapted when aligning tokens.
125 // Can be negative to retain information about the initial relative offset
126 // of the lines in a block comment. This is used when aligning trailing
127 // comments. Uncompensated negative offset is truncated to 0.
130 // If this change is inside of a token but not at the start of the token or
131 // directly after a newline.
134 // \c IsTrailingComment, \c TokenLength, \c PreviousEndOfTokenColumn and
135 // \c EscapedNewlineColumn will be calculated in
136 // \c calculateLineBreakInformation.
137 bool IsTrailingComment;
138 unsigned TokenLength;
139 unsigned PreviousEndOfTokenColumn;
140 unsigned EscapedNewlineColumn;
142 // These fields are used to retain correct relative line indentation in a
143 // block comment when aligning trailing comments.
145 // If this Change represents a continuation of a block comment,
146 // \c StartOfBlockComment is pointer to the first Change in the block
147 // comment. \c IndentationOffset is a relative column offset to this
148 // change, so that the correct column can be reconstructed at the end of
149 // the alignment process.
150 const Change *StartOfBlockComment;
151 int IndentationOffset;
153 // A combination of nesting level and indent level, which are used in
154 // tandem to compute lexical scope, for the purposes of deciding
155 // when to stop consecutive alignment runs.
156 std::pair<unsigned, unsigned>
157 nestingAndIndentLevel() const {
158 return std::make_pair(Tok->NestingLevel, Tok->IndentLevel);
163 /// \brief Calculate \c IsTrailingComment, \c TokenLength for the last tokens
164 /// or token parts in a line and \c PreviousEndOfTokenColumn and
165 /// \c EscapedNewlineColumn for the first tokens or token parts in a line.
166 void calculateLineBreakInformation();
168 /// \brief Align consecutive assignments over all \c Changes.
169 void alignConsecutiveAssignments();
171 /// \brief Align consecutive declarations over all \c Changes.
172 void alignConsecutiveDeclarations();
174 /// \brief Align trailing comments over all \c Changes.
175 void alignTrailingComments();
177 /// \brief Align trailing comments from change \p Start to change \p End at
178 /// the specified \p Column.
179 void alignTrailingComments(unsigned Start, unsigned End, unsigned Column);
181 /// \brief Align escaped newlines over all \c Changes.
182 void alignEscapedNewlines();
184 /// \brief Align escaped newlines from change \p Start to change \p End at
185 /// the specified \p Column.
186 void alignEscapedNewlines(unsigned Start, unsigned End, unsigned Column);
188 /// \brief Fill \c Replaces with the replacements for all effective changes.
189 void generateChanges();
191 /// \brief Stores \p Text as the replacement for the whitespace in \p Range.
192 void storeReplacement(SourceRange Range, StringRef Text);
193 void appendNewlineText(std::string &Text, unsigned Newlines);
194 void appendNewlineText(std::string &Text, unsigned Newlines,
195 unsigned PreviousEndOfTokenColumn,
196 unsigned EscapedNewlineColumn);
197 void appendIndentText(std::string &Text, unsigned IndentLevel,
198 unsigned Spaces, unsigned WhitespaceStartColumn);
200 SmallVector<Change, 16> Changes;
201 const SourceManager &SourceMgr;
202 tooling::Replacements Replaces;
203 const FormatStyle &Style;
207 } // namespace format