Index: clang/lib/Format/AffectedRangeManager.h =================================================================== --- clang/lib/Format/AffectedRangeManager.h +++ clang/lib/Format/AffectedRangeManager.h @@ -24,8 +24,8 @@ class AffectedRangeManager { public: - AffectedRangeManager(const SourceManager &SourceMgr, - const ArrayRef Ranges) + AffectedRangeManager(SourceManager const &SourceMgr, + ArrayRef const Ranges) : SourceMgr(SourceMgr), Ranges(Ranges.begin(), Ranges.end()) {} // Determines which lines are affected by the SourceRanges given as input. @@ -34,17 +34,17 @@ bool computeAffectedLines(SmallVectorImpl &Lines); // Returns true if 'Range' intersects with one of the input ranges. - bool affectsCharSourceRange(const CharSourceRange &Range); + bool affectsCharSourceRange(CharSourceRange const &Range); private: // Returns true if the range from 'First' to 'Last' intersects with one of the // input ranges. - bool affectsTokenRange(const FormatToken &First, const FormatToken &Last, + bool affectsTokenRange(FormatToken const &First, FormatToken const &Last, bool IncludeLeadingNewlines); // Returns true if one of the input ranges intersect the leading empty lines // before 'Tok'. - bool affectsLeadingEmptyLines(const FormatToken &Tok); + bool affectsLeadingEmptyLines(FormatToken const &Tok); // Marks all lines between I and E as well as all their children as affected. void markAllAsAffected(SmallVectorImpl::iterator I, @@ -52,11 +52,11 @@ // Determines whether 'Line' is affected by the SourceRanges given as input. // Returns \c true if line or one if its children is affected. - bool nonPPLineAffected(AnnotatedLine *Line, const AnnotatedLine *PreviousLine, + bool nonPPLineAffected(AnnotatedLine *Line, AnnotatedLine const *PreviousLine, SmallVectorImpl &Lines); - const SourceManager &SourceMgr; - const SmallVector Ranges; + SourceManager const &SourceMgr; + SmallVector const Ranges; }; } // namespace format Index: clang/lib/Format/AffectedRangeManager.cpp =================================================================== --- clang/lib/Format/AffectedRangeManager.cpp +++ clang/lib/Format/AffectedRangeManager.cpp @@ -24,7 +24,7 @@ SmallVectorImpl::iterator I = Lines.begin(); SmallVectorImpl::iterator E = Lines.end(); bool SomeLineAffected = false; - const AnnotatedLine *PreviousLine = nullptr; + AnnotatedLine const *PreviousLine = nullptr; while (I != E) { AnnotatedLine *Line = *I; Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First); @@ -58,7 +58,7 @@ } bool AffectedRangeManager::affectsCharSourceRange( - const CharSourceRange &Range) { + CharSourceRange const &Range) { for (SmallVectorImpl::const_iterator I = Ranges.begin(), E = Ranges.end(); I != E; ++I) { @@ -69,8 +69,8 @@ return false; } -bool AffectedRangeManager::affectsTokenRange(const FormatToken &First, - const FormatToken &Last, +bool AffectedRangeManager::affectsTokenRange(FormatToken const &First, + FormatToken const &Last, bool IncludeLeadingNewlines) { SourceLocation Start = First.WhitespaceRange.getBegin(); if (!IncludeLeadingNewlines) @@ -81,7 +81,7 @@ return affectsCharSourceRange(Range); } -bool AffectedRangeManager::affectsLeadingEmptyLines(const FormatToken &Tok) { +bool AffectedRangeManager::affectsLeadingEmptyLines(FormatToken const &Tok) { CharSourceRange EmptyLineRange = CharSourceRange::getCharRange( Tok.WhitespaceRange.getBegin(), Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset)); @@ -99,7 +99,7 @@ } bool AffectedRangeManager::nonPPLineAffected( - AnnotatedLine *Line, const AnnotatedLine *PreviousLine, + AnnotatedLine *Line, AnnotatedLine const *PreviousLine, SmallVectorImpl &Lines) { bool SomeLineAffected = false; Line->ChildrenAffected = computeAffectedLines(Line->Children); Index: clang/lib/Format/BreakableToken.h =================================================================== --- clang/lib/Format/BreakableToken.h +++ clang/lib/Format/BreakableToken.h @@ -29,7 +29,7 @@ /// Checks if \p Token switches formatting, like /* clang-format off */. /// \p Token must be a comment. -bool switchesFormatting(const FormatToken &Token); +bool switchesFormatting(FormatToken const &Token); struct FormatStyle; @@ -155,7 +155,7 @@ /// file. virtual Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit, unsigned ContentStartColumn, - const llvm::Regex &CommentPragmasRegex) const = 0; + llvm::Regex const &CommentPragmasRegex) const = 0; /// Emits the previously retrieved \p Split via \p Whitespaces. virtual void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, @@ -190,7 +190,7 @@ /// If the split is not contained within one token, for example when reflowing /// line comments, returns (0, ). virtual Split getReflowSplit(unsigned LineIndex, - const llvm::Regex &CommentPragmasRegex) const { + llvm::Regex const &CommentPragmasRegex) const { return Split(StringRef::npos, 0); } @@ -231,15 +231,15 @@ virtual void updateNextToken(LineState &State) const {} protected: - BreakableToken(const FormatToken &Tok, bool InPPDirective, - encoding::Encoding Encoding, const FormatStyle &Style) + BreakableToken(FormatToken const &Tok, bool InPPDirective, + encoding::Encoding Encoding, FormatStyle const &Style) : Tok(Tok), InPPDirective(InPPDirective), Encoding(Encoding), Style(Style) {} - const FormatToken &Tok; - const bool InPPDirective; + FormatToken const &Tok; + bool const InPPDirective; const encoding::Encoding Encoding; - const FormatStyle &Style; + FormatStyle const &Style; }; class BreakableStringLiteral : public BreakableToken { @@ -248,14 +248,14 @@ /// /// \p StartColumn specifies the column in which the token will start /// after formatting. - BreakableStringLiteral(const FormatToken &Tok, unsigned StartColumn, + BreakableStringLiteral(FormatToken const &Tok, unsigned StartColumn, StringRef Prefix, StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective, - encoding::Encoding Encoding, const FormatStyle &Style); + encoding::Encoding Encoding, FormatStyle const &Style); Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit, unsigned ContentStartColumn, - const llvm::Regex &CommentPragmasRegex) const override; + llvm::Regex const &CommentPragmasRegex) const override; void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, unsigned ContentIndent, WhitespaceManager &Whitespaces) const override; @@ -289,27 +289,27 @@ /// /// \p StartColumn specifies the column in which the comment will start after /// formatting. - BreakableComment(const FormatToken &Token, unsigned StartColumn, + BreakableComment(FormatToken const &Token, unsigned StartColumn, bool InPPDirective, encoding::Encoding Encoding, - const FormatStyle &Style); + FormatStyle const &Style); public: bool supportsReflow() const override { return true; } unsigned getLineCount() const override; Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit, unsigned ContentStartColumn, - const llvm::Regex &CommentPragmasRegex) const override; + llvm::Regex const &CommentPragmasRegex) const override; void compressWhitespace(unsigned LineIndex, unsigned TailOffset, Split Split, WhitespaceManager &Whitespaces) const override; protected: // Returns the token containing the line at LineIndex. - const FormatToken &tokenAt(unsigned LineIndex) const; + FormatToken const &tokenAt(unsigned LineIndex) const; // Checks if the content of line LineIndex may be reflown with the previous // line. virtual bool mayReflow(unsigned LineIndex, - const llvm::Regex &CommentPragmasRegex) const = 0; + llvm::Regex const &CommentPragmasRegex) const = 0; // Contains the original text of the lines of the block comment. // @@ -356,14 +356,14 @@ class BreakableBlockComment : public BreakableComment { public: - BreakableBlockComment(const FormatToken &Token, unsigned StartColumn, + BreakableBlockComment(FormatToken const &Token, unsigned StartColumn, unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective, encoding::Encoding Encoding, - const FormatStyle &Style, bool UseCRLF); + FormatStyle const &Style, bool UseCRLF); Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit, unsigned ContentStartColumn, - const llvm::Regex &CommentPragmasRegex) const override; + llvm::Regex const &CommentPragmasRegex) const override; unsigned getRangeLength(unsigned LineIndex, unsigned Offset, StringRef::size_type Length, unsigned StartColumn) const override; @@ -375,7 +375,7 @@ unsigned ContentIndent, WhitespaceManager &Whitespaces) const override; Split getReflowSplit(unsigned LineIndex, - const llvm::Regex &CommentPragmasRegex) const override; + llvm::Regex const &CommentPragmasRegex) const override; void reflow(unsigned LineIndex, WhitespaceManager &Whitespaces) const override; bool introducesBreakBeforeToken() const override; @@ -384,7 +384,7 @@ Split getSplitAfterLastLine(unsigned TailOffset) const override; bool mayReflow(unsigned LineIndex, - const llvm::Regex &CommentPragmasRegex) const override; + llvm::Regex const &CommentPragmasRegex) const override; // Contains Javadoc annotations that require additional indent when continued // on multiple lines. @@ -435,9 +435,9 @@ class BreakableLineCommentSection : public BreakableComment { public: - BreakableLineCommentSection(const FormatToken &Token, unsigned StartColumn, + BreakableLineCommentSection(FormatToken const &Token, unsigned StartColumn, bool InPPDirective, encoding::Encoding Encoding, - const FormatStyle &Style); + FormatStyle const &Style); unsigned getRangeLength(unsigned LineIndex, unsigned Offset, StringRef::size_type Length, @@ -447,14 +447,14 @@ unsigned ContentIndent, WhitespaceManager &Whitespaces) const override; Split getReflowSplit(unsigned LineIndex, - const llvm::Regex &CommentPragmasRegex) const override; + llvm::Regex const &CommentPragmasRegex) const override; void reflow(unsigned LineIndex, WhitespaceManager &Whitespaces) const override; void adaptStartOfLine(unsigned LineIndex, WhitespaceManager &Whitespaces) const override; void updateNextToken(LineState &State) const override; bool mayReflow(unsigned LineIndex, - const llvm::Regex &CommentPragmasRegex) const override; + llvm::Regex const &CommentPragmasRegex) const override; private: // OriginalPrefix[i] contains the original prefix of line i, including Index: clang/lib/Format/BreakableToken.cpp =================================================================== --- clang/lib/Format/BreakableToken.cpp +++ clang/lib/Format/BreakableToken.cpp @@ -40,7 +40,7 @@ } static StringRef getLineCommentIndentPrefix(StringRef Comment, - const FormatStyle &Style) { + FormatStyle const &Style) { static constexpr StringRef KnownCStylePrefixes[] = {"///<", "//!<", "///", "//!", "//:", "//"}; static constexpr StringRef KnownTextProtoPrefixes[] = {"####", "###", "##", @@ -56,7 +56,7 @@ for (StringRef KnownPrefix : KnownPrefixes) { if (Comment.startswith(KnownPrefix)) { - const auto PrefixLength = + auto const PrefixLength = Comment.find_first_not_of(' ', KnownPrefix.size()); return Comment.substr(0, PrefixLength); } @@ -67,7 +67,7 @@ static BreakableToken::Split getCommentSplit(StringRef Text, unsigned ContentStartColumn, unsigned ColumnLimit, unsigned TabWidth, - encoding::Encoding Encoding, const FormatStyle &Style, + encoding::Encoding Encoding, FormatStyle const &Style, bool DecorationEndsWithStar = false) { LLVM_DEBUG(llvm::dbgs() << "Comment split: \"" << Text << "\", Column limit: " << ColumnLimit @@ -102,7 +102,7 @@ StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes); - static const auto kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\."); + static auto const kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\."); // Some spaces are unacceptable to break on, rewind past them. while (SpaceOffset != StringRef::npos) { // If a line-comment ends with `\`, the next line continues the comment, @@ -216,7 +216,7 @@ return BreakableToken::Split(StringRef::npos, 0); } -bool switchesFormatting(const FormatToken &Token) { +bool switchesFormatting(FormatToken const &Token) { assert((Token.is(TT_BlockComment) || Token.is(TT_LineComment)) && "formatting regions are switched by comment tokens"); StringRef Content = Token.TokenText.substr(2).ltrim(); @@ -265,9 +265,9 @@ } BreakableStringLiteral::BreakableStringLiteral( - const FormatToken &Tok, unsigned StartColumn, StringRef Prefix, + FormatToken const &Tok, unsigned StartColumn, StringRef Prefix, StringRef Postfix, unsigned UnbreakableTailLength, bool InPPDirective, - encoding::Encoding Encoding, const FormatStyle &Style) + encoding::Encoding Encoding, FormatStyle const &Style) : BreakableToken(Tok, InPPDirective, Encoding, Style), StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix), UnbreakableTailLength(UnbreakableTailLength) { @@ -278,7 +278,7 @@ BreakableToken::Split BreakableStringLiteral::getSplit( unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit, - unsigned ContentStartColumn, const llvm::Regex &CommentPragmasRegex) const { + unsigned ContentStartColumn, llvm::Regex const &CommentPragmasRegex) const { return getStringSplit(Line.substr(TailOffset), ContentStartColumn, ColumnLimit - Postfix.size(), Style.TabWidth, Encoding); } @@ -292,10 +292,10 @@ Prefix, InPPDirective, 1, StartColumn); } -BreakableComment::BreakableComment(const FormatToken &Token, +BreakableComment::BreakableComment(FormatToken const &Token, unsigned StartColumn, bool InPPDirective, encoding::Encoding Encoding, - const FormatStyle &Style) + FormatStyle const &Style) : BreakableToken(Token, InPPDirective, Encoding, Style), StartColumn(StartColumn) {} @@ -304,7 +304,7 @@ BreakableToken::Split BreakableComment::getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit, unsigned ContentStartColumn, - const llvm::Regex &CommentPragmasRegex) const { + llvm::Regex const &CommentPragmasRegex) const { // Don't break lines matching the comment pragmas regex. if (CommentPragmasRegex.match(Content[LineIndex])) return Split(StringRef::npos, 0); @@ -329,7 +329,7 @@ /*InPPDirective=*/false, /*Newlines=*/0, /*Spaces=*/1); } -const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const { +FormatToken const &BreakableComment::tokenAt(unsigned LineIndex) const { return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok; } @@ -349,7 +349,7 @@ // Numbered lists may also start with a number followed by '.' // To avoid issues if a line starts with a number which is actually the end // of a previous line, we only consider numbers with up to 2 digits. - static const auto kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\. "); + static auto const kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\. "); hasSpecialMeaningPrefix = hasSpecialMeaningPrefix || kNumberedListRegexp.match(Content); @@ -364,9 +364,9 @@ } BreakableBlockComment::BreakableBlockComment( - const FormatToken &Token, unsigned StartColumn, + FormatToken const &Token, unsigned StartColumn, unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective, - encoding::Encoding Encoding, const FormatStyle &Style, bool UseCRLF) + encoding::Encoding Encoding, FormatStyle const &Style, bool UseCRLF) : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style), DelimitersOnNewline(false), UnbreakableTailLength(Token.UnbreakableTailLength) { @@ -491,7 +491,7 @@ BreakableToken::Split BreakableBlockComment::getSplit( unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit, - unsigned ContentStartColumn, const llvm::Regex &CommentPragmasRegex) const { + unsigned ContentStartColumn, llvm::Regex const &CommentPragmasRegex) const { // Don't break lines matching the comment pragmas regex. if (CommentPragmasRegex.match(Content[LineIndex])) return Split(StringRef::npos, 0); @@ -630,7 +630,7 @@ } BreakableToken::Split BreakableBlockComment::getReflowSplit( - unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const { + unsigned LineIndex, llvm::Regex const &CommentPragmasRegex) const { if (!mayReflow(LineIndex, CommentPragmasRegex)) return Split(StringRef::npos, 0); @@ -738,7 +738,7 @@ } bool BreakableBlockComment::mayReflow( - unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const { + unsigned LineIndex, llvm::Regex const &CommentPragmasRegex) const { // Content[LineIndex] may exclude the indent after the '*' decoration. In that // case, we compute the start of the comment pragma manually. StringRef IndentContent = Content[LineIndex]; @@ -751,8 +751,8 @@ } BreakableLineCommentSection::BreakableLineCommentSection( - const FormatToken &Token, unsigned StartColumn, bool InPPDirective, - encoding::Encoding Encoding, const FormatStyle &Style) + FormatToken const &Token, unsigned StartColumn, bool InPPDirective, + encoding::Encoding Encoding, FormatStyle const &Style) : BreakableComment(Token, StartColumn, InPPDirective, Encoding, Style) { assert(Tok.is(TT_LineComment) && "line comment section must start with a line comment"); @@ -760,7 +760,7 @@ // How many spaces we changed in the first line of the section, this will be // applied in all following lines int FirstLineSpaceChange = 0; - for (const FormatToken *CurrentTok = &Tok; + for (FormatToken const *CurrentTok = &Tok; CurrentTok && CurrentTok->is(TT_LineComment); CurrentTok = CurrentTok->Next) { LastLineTok = LineTok; @@ -779,7 +779,7 @@ Lines[i] = Lines[i].ltrim(Blanks); StringRef IndentPrefix = getLineCommentIndentPrefix(Lines[i], Style); OriginalPrefix[i] = IndentPrefix; - const unsigned SpacesInPrefix = + unsigned const SpacesInPrefix = std::count(IndentPrefix.begin(), IndentPrefix.end(), ' '); // On the first line of the comment section we calculate how many spaces @@ -812,8 +812,8 @@ } assert(Lines[i].size() > IndentPrefix.size()); - const auto FirstNonSpace = Lines[i][IndentPrefix.size()]; - const auto AllowsSpaceChange = + auto const FirstNonSpace = Lines[i][IndentPrefix.size()]; + auto const AllowsSpaceChange = SpacesInPrefix != 0 || (isAlphanumeric(FirstNonSpace) || (FirstNonSpace == '}' && FirstLineSpaceChange != 0)); @@ -901,7 +901,7 @@ } BreakableComment::Split BreakableLineCommentSection::getReflowSplit( - unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const { + unsigned LineIndex, llvm::Regex const &CommentPragmasRegex) const { if (!mayReflow(LineIndex, CommentPragmasRegex)) return Split(StringRef::npos, 0); @@ -995,8 +995,8 @@ } if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) { // Adjust the prefix if necessary. - const auto SpacesToRemove = -std::min(PrefixSpaceChange[LineIndex], 0); - const auto SpacesToAdd = std::max(PrefixSpaceChange[LineIndex], 0); + auto const SpacesToRemove = -std::min(PrefixSpaceChange[LineIndex], 0); + auto const SpacesToAdd = std::max(PrefixSpaceChange[LineIndex], 0); Whitespaces.replaceWhitespaceInToken( tokenAt(LineIndex), OriginalPrefix[LineIndex].size() - SpacesToRemove, /*ReplaceChars=*/SpacesToRemove, "", "", /*InPPDirective=*/false, @@ -1011,7 +1011,7 @@ } bool BreakableLineCommentSection::mayReflow( - unsigned LineIndex, const llvm::Regex &CommentPragmasRegex) const { + unsigned LineIndex, llvm::Regex const &CommentPragmasRegex) const { // Line comments have the indent as part of the prefix, so we need to // recompute the start of the line. StringRef IndentContent = Content[LineIndex]; Index: clang/lib/Format/CMakeLists.txt =================================================================== --- clang/lib/Format/CMakeLists.txt +++ clang/lib/Format/CMakeLists.txt @@ -15,6 +15,7 @@ UnwrappedLineFormatter.cpp UnwrappedLineParser.cpp UsingDeclarationsSorter.cpp + EastWestConstFixer.cpp WhitespaceManager.cpp LINK_LIBS Index: clang/lib/Format/ContinuationIndenter.h =================================================================== --- clang/lib/Format/ContinuationIndenter.h +++ clang/lib/Format/ContinuationIndenter.h @@ -39,7 +39,7 @@ llvm::StringMap DelimiterStyle; llvm::StringMap EnclosingFunctionStyle; - RawStringFormatStyleManager(const FormatStyle &CodeStyle); + RawStringFormatStyleManager(FormatStyle const &CodeStyle); llvm::Optional getDelimiterStyle(StringRef Delimiter) const; @@ -51,9 +51,9 @@ public: /// Constructs a \c ContinuationIndenter to format \p Line starting in /// column \p FirstIndent. - ContinuationIndenter(const FormatStyle &Style, - const AdditionalKeywords &Keywords, - const SourceManager &SourceMgr, + ContinuationIndenter(FormatStyle const &Style, + AdditionalKeywords const &Keywords, + SourceManager const &SourceMgr, WhitespaceManager &Whitespaces, encoding::Encoding Encoding, bool BinPackInconclusiveFunctions); @@ -63,15 +63,15 @@ /// the case of formatting inside raw string literals, \p FirstStartColumn is /// the column at which the state of the parent formatter is. LineState getInitialState(unsigned FirstIndent, unsigned FirstStartColumn, - const AnnotatedLine *Line, bool DryRun); + AnnotatedLine const *Line, bool DryRun); // FIXME: canBreak and mustBreak aren't strictly indentation-related. Find a // better home. /// Returns \c true, if a line break after \p State is allowed. - bool canBreak(const LineState &State); + bool canBreak(LineState const &State); /// Returns \c true, if a line break after \p State is mandatory. - bool mustBreak(const LineState &State); + bool mustBreak(LineState const &State); /// Appends the next token to \p State and updates information /// necessary for indentation. @@ -86,7 +86,7 @@ /// Get the column limit for this line. This is the style's column /// limit, potentially reduced for preprocessor definitions. - unsigned getColumnLimit(const LineState &State) const; + unsigned getColumnLimit(LineState const &State) const; private: /// Mark the next token as consumed in \p State and modify its stacks @@ -108,20 +108,20 @@ /// Reformats a raw string literal. /// /// \returns An extra penalty induced by reformatting the token. - unsigned reformatRawStringLiteral(const FormatToken &Current, + unsigned reformatRawStringLiteral(FormatToken const &Current, LineState &State, - const FormatStyle &RawStringStyle, + FormatStyle const &RawStringStyle, bool DryRun, bool Newline); /// If the current token is at the end of the current line, handle /// the transition to the next line. - unsigned handleEndOfLine(const FormatToken &Current, LineState &State, + unsigned handleEndOfLine(FormatToken const &Current, LineState &State, bool DryRun, bool AllowBreak, bool Newline); /// If \p Current is a raw string that is configured to be reformatted, /// return the style to be used. - llvm::Optional getRawStringStyle(const FormatToken &Current, - const LineState &State); + llvm::Optional getRawStringStyle(FormatToken const &Current, + LineState const &State); /// If the current token sticks out over the end of the line, break /// it if possible. @@ -141,7 +141,7 @@ /// the column limit where possible; if false, words are allowed to protrude /// over the column limit as long as the penalty is less than the penalty /// of a break. - std::pair breakProtrudingToken(const FormatToken &Current, + std::pair breakProtrudingToken(FormatToken const &Current, LineState &State, bool AllowBreak, bool DryRun, bool Strict); @@ -149,7 +149,7 @@ /// Returns the \c BreakableToken starting at \p Current, or nullptr /// if the current token cannot be broken. std::unique_ptr - createBreakableToken(const FormatToken &Current, LineState &State, + createBreakableToken(FormatToken const &Current, LineState &State, bool AllowBreak); /// Appends the next token to \p State and updates information @@ -172,25 +172,25 @@ unsigned addTokenOnNewLine(LineState &State, bool DryRun); /// Calculate the new column for a line wrap before the next token. - unsigned getNewLineColumn(const LineState &State); + unsigned getNewLineColumn(LineState const &State); /// Adds a multiline token to the \p State. /// /// \returns Extra penalty for the first line of the literal: last line is /// handled in \c addNextStateToQueue, and the penalty for other lines doesn't /// matter, as we don't change them. - unsigned addMultilineToken(const FormatToken &Current, LineState &State); + unsigned addMultilineToken(FormatToken const &Current, LineState &State); /// Returns \c true if the next token starts a multiline string /// literal. /// /// This includes implicitly concatenated strings, strings that will be broken /// by clang-format and string literals with escaped newlines. - bool nextIsMultilineString(const LineState &State); + bool nextIsMultilineString(LineState const &State); FormatStyle Style; - const AdditionalKeywords &Keywords; - const SourceManager &SourceMgr; + AdditionalKeywords const &Keywords; + SourceManager const &SourceMgr; WhitespaceManager &Whitespaces; encoding::Encoding Encoding; bool BinPackInconclusiveFunctions; @@ -199,7 +199,7 @@ }; struct ParenState { - ParenState(const FormatToken *Tok, unsigned Indent, unsigned LastSpace, + ParenState(FormatToken const *Tok, unsigned Indent, unsigned LastSpace, bool AvoidBinPacking, bool NoLineBreak) : Tok(Tok), Indent(Indent), LastSpace(LastSpace), NestedBlockIndent(Indent), IsAligned(false), @@ -218,7 +218,7 @@ /// /// Not considered for memoization as it will always have the same value at /// the same token. - const FormatToken *Tok; + FormatToken const *Tok; /// The position to which a specific parenthesis level needs to be /// indented. @@ -349,7 +349,7 @@ /// operator. bool UnindentOperator : 1; - bool operator<(const ParenState &Other) const { + bool operator<(ParenState const &Other) const { if (Indent != Other.Indent) return Indent < Other.Indent; if (LastSpace != Other.LastSpace) @@ -451,10 +451,10 @@ /// The line that is being formatted. /// /// Does not need to be considered for memoization because it doesn't change. - const AnnotatedLine *Line; + AnnotatedLine const *Line; /// Comparison operator to be able to used \c LineState in \c map. - bool operator<(const LineState &Other) const { + bool operator<(LineState const &Other) const { if (NextToken != Other.NextToken) return NextToken < Other.NextToken; if (Column != Other.Column) Index: clang/lib/Format/ContinuationIndenter.cpp =================================================================== --- clang/lib/Format/ContinuationIndenter.cpp +++ clang/lib/Format/ContinuationIndenter.cpp @@ -27,15 +27,15 @@ // Returns true if a TT_SelectorName should be indented when wrapped, // false otherwise. -static bool shouldIndentWrappedSelectorName(const FormatStyle &Style, +static bool shouldIndentWrappedSelectorName(FormatStyle const &Style, LineType LineType) { return Style.IndentWrappedFunctionNames || LineType == LT_ObjCMethodDecl; } // Returns the length of everything up to the first possible line break after // the ), ], } or > matching \c Tok. -static unsigned getLengthToMatchingParen(const FormatToken &Tok, - const std::vector &Stack) { +static unsigned getLengthToMatchingParen(FormatToken const &Tok, + std::vector const &Stack) { // Normally whether or not a break before T is possible is calculated and // stored in T.CanBreakBefore. Braces, array initializers and text proto // messages like `key: < ... >` are an exception: a break is possible @@ -83,7 +83,7 @@ // corresponds. Returns either a pointer to the matching level or nullptr if // LParen is not found in the initial portion of the stack up to // MatchingStackIndex. - auto FindParenState = [&](const FormatToken *LBrace) -> const ParenState * { + auto FindParenState = [&](FormatToken const *LBrace) -> ParenState const * { while (MatchingStackIndex >= 0 && Stack[MatchingStackIndex].Tok != LBrace) --MatchingStackIndex; return MatchingStackIndex >= 0 ? &Stack[MatchingStackIndex] : nullptr; @@ -96,7 +96,7 @@ if (End->Next->MatchingParen && End->Next->MatchingParen->isOneOf( tok::l_brace, TT_ArrayInitializerLSquare, tok::less)) { - const ParenState *State = FindParenState(End->Next->MatchingParen); + ParenState const *State = FindParenState(End->Next->MatchingParen); if (State && State->BreakBeforeClosingBrace) break; } @@ -104,7 +104,7 @@ return End->TotalLength - Tok.TotalLength + 1; } -static unsigned getLengthToNextOperator(const FormatToken &Tok) { +static unsigned getLengthToNextOperator(FormatToken const &Tok) { if (!Tok.NextOperator) return 0; return Tok.NextOperator->TotalLength - Tok.TotalLength; @@ -112,14 +112,14 @@ // Returns \c true if \c Tok is the "." or "->" of a call and starts the next // segment of a builder type call. -static bool startsSegmentOfBuilderTypeCall(const FormatToken &Tok) { +static bool startsSegmentOfBuilderTypeCall(FormatToken const &Tok) { return Tok.isMemberAccess() && Tok.Previous && Tok.Previous->closesScope(); } // Returns \c true if \c Current starts a new parameter. -static bool startsNextParameter(const FormatToken &Current, - const FormatStyle &Style) { - const FormatToken &Previous = *Current.Previous; +static bool startsNextParameter(FormatToken const &Current, + FormatStyle const &Style) { + FormatToken const &Previous = *Current.Previous; if (Current.is(TT_CtorInitializerComma) && Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) return true; @@ -133,8 +133,8 @@ Style.BreakInheritanceList != FormatStyle::BILS_BeforeComma)); } -static bool opensProtoMessageField(const FormatToken &LessTok, - const FormatStyle &Style) { +static bool opensProtoMessageField(FormatToken const &LessTok, + FormatStyle const &Style) { if (LessTok.isNot(tok::less)) return false; return Style.Language == FormatStyle::LK_TextProto || @@ -171,9 +171,9 @@ // Returns the canonical delimiter for \p Language, or the empty string if no // canonical delimiter is specified. static StringRef -getCanonicalRawStringDelimiter(const FormatStyle &Style, +getCanonicalRawStringDelimiter(FormatStyle const &Style, FormatStyle::LanguageKind Language) { - for (const auto &Format : Style.RawStringFormats) { + for (auto const &Format : Style.RawStringFormats) { if (Format.Language == Language) return StringRef(Format.CanonicalDelimiter); } @@ -181,8 +181,8 @@ } RawStringFormatStyleManager::RawStringFormatStyleManager( - const FormatStyle &CodeStyle) { - for (const auto &RawStringFormat : CodeStyle.RawStringFormats) { + FormatStyle const &CodeStyle) { + for (auto const &RawStringFormat : CodeStyle.RawStringFormats) { llvm::Optional LanguageStyle = CodeStyle.GetLanguageStyle(RawStringFormat.Language); if (!LanguageStyle) { @@ -221,9 +221,9 @@ return It->second; } -ContinuationIndenter::ContinuationIndenter(const FormatStyle &Style, - const AdditionalKeywords &Keywords, - const SourceManager &SourceMgr, +ContinuationIndenter::ContinuationIndenter(FormatStyle const &Style, + AdditionalKeywords const &Keywords, + SourceManager const &SourceMgr, WhitespaceManager &Whitespaces, encoding::Encoding Encoding, bool BinPackInconclusiveFunctions) @@ -234,7 +234,7 @@ LineState ContinuationIndenter::getInitialState(unsigned FirstIndent, unsigned FirstStartColumn, - const AnnotatedLine *Line, + AnnotatedLine const *Line, bool DryRun) { LineState State; State.FirstIndent = FirstIndent; @@ -274,9 +274,9 @@ return State; } -bool ContinuationIndenter::canBreak(const LineState &State) { - const FormatToken &Current = *State.NextToken; - const FormatToken &Previous = *Current.Previous; +bool ContinuationIndenter::canBreak(LineState const &State) { + FormatToken const &Current = *State.NextToken; + FormatToken const &Previous = *Current.Previous; assert(&Previous == Current.Previous); if (!Current.CanBreakBefore && !(State.Stack.back().BreakBeforeClosingBrace && Current.closesBlockOrBlockTypeList(Style))) @@ -326,9 +326,9 @@ return !State.Stack.back().NoLineBreak; } -bool ContinuationIndenter::mustBreak(const LineState &State) { - const FormatToken &Current = *State.NextToken; - const FormatToken &Previous = *Current.Previous; +bool ContinuationIndenter::mustBreak(LineState const &State) { + FormatToken const &Current = *State.NextToken; + FormatToken const &Previous = *Current.Previous; if (Style.BraceWrapping.BeforeLambdaBody && Current.CanBreakBefore && Current.is(TT_LambdaLBrace) && Previous.isNot(TT_LineComment)) { auto LambdaBodyLength = getLengthToMatchingParen(Current, State.Stack); @@ -382,7 +382,7 @@ getColumnLimit(State)) return true; - const FormatToken &BreakConstructorInitializersToken = + FormatToken const &BreakConstructorInitializersToken = Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon ? Previous : Current; @@ -525,7 +525,7 @@ unsigned ContinuationIndenter::addTokenToState(LineState &State, bool Newline, bool DryRun, unsigned ExtraSpaces) { - const FormatToken &Current = *State.NextToken; + FormatToken const &Current = *State.NextToken; assert(!State.Stack.empty()); State.NoContinuation = false; @@ -562,13 +562,13 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState &State, bool DryRun, unsigned ExtraSpaces) { FormatToken &Current = *State.NextToken; - const FormatToken &Previous = *State.NextToken->Previous; + FormatToken const &Previous = *State.NextToken->Previous; if (Current.is(tok::equal) && (State.Line->First->is(tok::kw_for) || Current.NestingLevel == 0) && State.Stack.back().VariablePos == 0) { State.Stack.back().VariablePos = State.Column; // Move over * and & if they are bound to the variable name. - const FormatToken *Tok = &Previous; + FormatToken const *Tok = &Previous; while (Tok && State.Stack.back().VariablePos >= Tok->ColumnWidth) { State.Stack.back().VariablePos -= Tok->ColumnWidth; if (Tok->SpacesRequiredBefore != 0) @@ -677,7 +677,7 @@ // there is a line-break right after the operator. // Exclude relational operators, as there, it is always more desirable to // have the LHS 'left' of the RHS. - const FormatToken *P = Current.getPreviousNonComment(); + FormatToken const *P = Current.getPreviousNonComment(); if (!Current.is(tok::comment) && P && (P->isOneOf(TT_BinaryOperator, tok::comma) || (P->is(TT_ConditionalExpr) && P->is(tok::colon))) && @@ -744,7 +744,7 @@ // .SecondInnerFunctionCall(); bool HasTrailingCall = false; if (Previous.MatchingParen) { - const FormatToken *Next = Previous.MatchingParen->getNextNonComment(); + FormatToken const *Next = Previous.MatchingParen->getNextNonComment(); HasTrailingCall = Next && Next->isMemberAccess(); } if (HasTrailingCall && State.Stack.size() > 1 && @@ -756,14 +756,14 @@ unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State, bool DryRun) { FormatToken &Current = *State.NextToken; - const FormatToken &Previous = *State.NextToken->Previous; + FormatToken const &Previous = *State.NextToken->Previous; // Extra penalty that needs to be added because of the way certain line // breaks are chosen. unsigned Penalty = 0; - const FormatToken *PreviousNonComment = Current.getPreviousNonComment(); - const FormatToken *NextNonComment = Previous.getNextNonComment(); + FormatToken const *PreviousNonComment = Current.getPreviousNonComment(); + FormatToken const *NextNonComment = Previous.getNextNonComment(); if (!NextNonComment) NextNonComment = &Current; // The first line break on any NestingLevel causes an extra penalty in order @@ -959,7 +959,7 @@ return Penalty; } -unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) { +unsigned ContinuationIndenter::getNewLineColumn(LineState const &State) { if (!State.NextToken || !State.NextToken->Previous) return 0; @@ -969,13 +969,13 @@ Current.isNot(TT_CSharpGenericTypeConstraint)) return State.Stack.back().ColonPos + 2; - const FormatToken &Previous = *Current.Previous; + FormatToken const &Previous = *Current.Previous; // If we are continuing an expression, we want to use the continuation indent. unsigned ContinuationIndent = std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + Style.ContinuationIndentWidth; - const FormatToken *PreviousNonComment = Current.getPreviousNonComment(); - const FormatToken *NextNonComment = Previous.getNextNonComment(); + FormatToken const *PreviousNonComment = Current.getPreviousNonComment(); + FormatToken const *NextNonComment = Previous.getNextNonComment(); if (!NextNonComment) NextNonComment = &Current; @@ -1159,9 +1159,9 @@ return State.Stack.back().Indent; } -static bool hasNestedBlockInlined(const FormatToken *Previous, - const FormatToken &Current, - const FormatStyle &Style) { +static bool hasNestedBlockInlined(FormatToken const *Previous, + FormatToken const &Current, + FormatStyle const &Style) { if (Previous->isNot(tok::l_paren)) return true; if (Previous->ParameterCount > 1) @@ -1174,7 +1174,7 @@ unsigned ContinuationIndenter::moveStateToNextToken(LineState &State, bool DryRun, bool Newline) { assert(State.Stack.size()); - const FormatToken &Current = *State.NextToken; + FormatToken const &Current = *State.NextToken; if (Current.is(TT_CSharpGenericTypeConstraint)) State.Stack.back().IsCSharpGenericTypeConstraint = true; @@ -1204,7 +1204,7 @@ if (Style.BreakBeforeTernaryOperators && Current.is(tok::question)) State.Stack.back().QuestionColumn = State.Column; if (!Style.BreakBeforeTernaryOperators && Current.isNot(tok::colon)) { - const FormatToken *Previous = Current.Previous; + FormatToken const *Previous = Current.Previous; while (Previous && Previous->isTrailingComment()) Previous = Previous->Previous; if (Previous && Previous->is(tok::question)) @@ -1258,7 +1258,7 @@ State.Stack.back().LastSpace = State.Column; // Insert scopes created by fake parenthesis. - const FormatToken *Previous = Current.getPreviousNonComment(); + FormatToken const *Previous = Current.getPreviousNonComment(); // Add special behavior to support a format commonly used for JavaScript // closures: @@ -1321,8 +1321,8 @@ void ContinuationIndenter::moveStatePastFakeLParens(LineState &State, bool Newline) { - const FormatToken &Current = *State.NextToken; - const FormatToken *Previous = Current.getPreviousNonComment(); + FormatToken const &Current = *State.NextToken; + FormatToken const *Previous = Current.getPreviousNonComment(); // Don't add extra indentation for the first fake parenthesis after // 'return', assignments or opening <({[. The indentation for these cases @@ -1429,7 +1429,7 @@ void ContinuationIndenter::moveStatePastScopeOpener(LineState &State, bool Newline) { - const FormatToken &Current = *State.NextToken; + FormatToken const &Current = *State.NextToken; if (!Current.opensScope()) return; @@ -1457,7 +1457,7 @@ } else { NewIndent = State.Stack.back().LastSpace + Style.ContinuationIndentWidth; } - const FormatToken *NextNoComment = Current.getNextNonComment(); + FormatToken const *NextNoComment = Current.getNextNonComment(); bool EndsInComma = Current.MatchingParen && Current.MatchingParen->Previous && Current.MatchingParen->Previous->is(tok::comma); @@ -1521,7 +1521,7 @@ } else { // For ColumnLimit = 0, we have to figure out whether there is or has to // be a line break within this call. - for (const FormatToken *Tok = &Current; + for (FormatToken const *Tok = &Current; Tok && Tok != Current.MatchingParen; Tok = Tok->Next) { if (Tok->MustBreakBefore || (Tok->CanBreakBefore && Tok->NewlinesBefore > 0)) { @@ -1571,7 +1571,7 @@ } void ContinuationIndenter::moveStatePastScopeCloser(LineState &State) { - const FormatToken &Current = *State.NextToken; + FormatToken const &Current = *State.NextToken; if (!Current.closesScope()) return; @@ -1596,7 +1596,7 @@ // line). if (State.Stack.back().BreakBeforeParameter && Current.MatchingParen && Current.MatchingParen->Previous) { - const FormatToken &CurrentScopeOpener = *Current.MatchingParen->Previous; + FormatToken const &CurrentScopeOpener = *Current.MatchingParen->Previous; if (CurrentScopeOpener.is(TT_ObjCMethodExpr) && CurrentScopeOpener.MatchingParen) { int NecessarySpaceInLine = @@ -1610,7 +1610,7 @@ if (Current.is(tok::r_square)) { // If this ends the array subscript expr, reset the corresponding value. - const FormatToken *NextNonComment = Current.getNextNonComment(); + FormatToken const *NextNonComment = Current.getNextNonComment(); if (NextNonComment && NextNonComment->isNot(tok::l_square)) State.Stack.back().StartOfArraySubscripts = 0; } @@ -1645,8 +1645,8 @@ } unsigned ContinuationIndenter::reformatRawStringLiteral( - const FormatToken &Current, LineState &State, - const FormatStyle &RawStringStyle, bool DryRun, bool Newline) { + FormatToken const &Current, LineState &State, + FormatStyle const &RawStringStyle, bool DryRun, bool Newline) { unsigned StartColumn = State.Column - Current.ColumnWidth; StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText); StringRef NewDelimiter = @@ -1763,7 +1763,7 @@ } SourceLocation OriginLoc = Current.Tok.getLocation().getLocWithOffset(OldPrefixSize); - for (const tooling::Replacement &Fix : Fixes.first) { + for (tooling::Replacement const &Fix : Fixes.first) { auto Err = Whitespaces.addReplacement(tooling::Replacement( SourceMgr, OriginLoc.getLocWithOffset(Fix.getOffset()), Fix.getLength(), Fix.getReplacementText())); @@ -1793,7 +1793,7 @@ return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter; } -unsigned ContinuationIndenter::addMultilineToken(const FormatToken &Current, +unsigned ContinuationIndenter::addMultilineToken(FormatToken const &Current, LineState &State) { // Break before further function parameters on all levels. for (unsigned i = 0, e = State.Stack.size(); i != e; ++i) @@ -1809,7 +1809,7 @@ return 0; } -unsigned ContinuationIndenter::handleEndOfLine(const FormatToken &Current, +unsigned ContinuationIndenter::handleEndOfLine(FormatToken const &Current, LineState &State, bool DryRun, bool AllowBreak, bool Newline) { unsigned Penalty = 0; @@ -1865,7 +1865,7 @@ // Returns the enclosing function name of a token, or the empty string if not // found. -static StringRef getEnclosingFunctionName(const FormatToken &Current) { +static StringRef getEnclosingFunctionName(FormatToken const &Current) { // Look for: 'function(' or 'function(' before Current. auto Tok = Current.getPreviousNonComment(); if (!Tok || !Tok->is(tok::l_paren)) @@ -1884,8 +1884,8 @@ } llvm::Optional -ContinuationIndenter::getRawStringStyle(const FormatToken &Current, - const LineState &State) { +ContinuationIndenter::getRawStringStyle(FormatToken const &Current, + LineState const &State) { if (!Current.isStringLiteral()) return None; auto Delimiter = getRawStringDelimiter(Current.TokenText); @@ -1902,7 +1902,7 @@ } std::unique_ptr -ContinuationIndenter::createBreakableToken(const FormatToken &Current, +ContinuationIndenter::createBreakableToken(FormatToken const &Current, LineState &State, bool AllowBreak) { unsigned StartColumn = State.Column - Current.ColumnWidth; if (Current.isStringLiteral()) { @@ -1980,7 +1980,7 @@ } std::pair -ContinuationIndenter::breakProtrudingToken(const FormatToken &Current, +ContinuationIndenter::breakProtrudingToken(FormatToken const &Current, LineState &State, bool AllowBreak, bool DryRun, bool Strict) { std::unique_ptr Token = @@ -2358,13 +2358,13 @@ return {Penalty, Exceeded}; } -unsigned ContinuationIndenter::getColumnLimit(const LineState &State) const { +unsigned ContinuationIndenter::getColumnLimit(LineState const &State) const { // In preprocessor directives reserve two chars for trailing " \" return Style.ColumnLimit - (State.Line->InPPDirective ? 2 : 0); } -bool ContinuationIndenter::nextIsMultilineString(const LineState &State) { - const FormatToken &Current = *State.NextToken; +bool ContinuationIndenter::nextIsMultilineString(LineState const &State) { + FormatToken const &Current = *State.NextToken; if (!Current.isStringLiteral() || Current.is(TT_ImplicitStringLiteral)) return false; // We never consider raw string literals "multiline" for the purpose of Index: clang/lib/Format/Encoding.h =================================================================== --- clang/lib/Format/Encoding.h +++ clang/lib/Format/Encoding.h @@ -32,8 +32,8 @@ /// Detects encoding of the Text. If the Text can be decoded using UTF-8, /// it is considered UTF8, otherwise we treat it as some 8-bit encoding. inline Encoding detectEncoding(StringRef Text) { - const llvm::UTF8 *Ptr = reinterpret_cast(Text.begin()); - const llvm::UTF8 *BufEnd = reinterpret_cast(Text.end()); + llvm::UTF8 const *Ptr = reinterpret_cast(Text.begin()); + llvm::UTF8 const *BufEnd = reinterpret_cast(Text.end()); if (llvm::isLegalUTF8String(&Ptr, BufEnd)) return Encoding_UTF8; return Encoding_Unknown; Index: clang/lib/Format/Format.cpp =================================================================== --- clang/lib/Format/Format.cpp +++ clang/lib/Format/Format.cpp @@ -16,6 +16,7 @@ #include "AffectedRangeManager.h" #include "BreakableToken.h" #include "ContinuationIndenter.h" +#include "EastWestConstFixer.h" #include "FormatInternal.h" #include "FormatTokenLexer.h" #include "NamespaceEndCommentsFixer.h" @@ -126,6 +127,17 @@ } }; +template <> struct ScalarEnumerationTraits { + static void enumeration(IO &IO, FormatStyle::ConstPlacementStyle &Value) { + IO.enumCase(Value, "Leave", FormatStyle::CS_Leave); + IO.enumCase(Value, "West", FormatStyle::CS_West); + IO.enumCase(Value, "East", FormatStyle::CS_East); + + IO.enumCase(Value, "Left", FormatStyle::CS_West); + IO.enumCase(Value, "Right", FormatStyle::CS_East); + } +}; + template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) { IO.enumCase(Value, "None", FormatStyle::SFS_None); @@ -632,6 +644,7 @@ IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals); IO.mapOptional("ColumnLimit", Style.ColumnLimit); IO.mapOptional("CommentPragmas", Style.CommentPragmas); + IO.mapOptional("ConstPlacement", Style.ConstPlacement); IO.mapOptional("CompactNamespaces", Style.CompactNamespaces); IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine", Style.ConstructorInitializerAllOnOneLineOrOnePerLine); @@ -822,7 +835,7 @@ if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) { Template = Seq[0]; } else { - Template = *((const FormatStyle *)IO.getContext()); + Template = *((FormatStyle const *)IO.getContext()); Template.Language = FormatStyle::LK_None; } Seq.resize(Index + 1, Template); @@ -836,7 +849,7 @@ namespace clang { namespace format { -const std::error_category &getParseCategory() { +std::error_category const &getParseCategory() { static const ParseErrorCategory C{}; return C; } @@ -844,12 +857,12 @@ return std::error_code(static_cast(e), getParseCategory()); } -inline llvm::Error make_string_error(const llvm::Twine &Message) { +inline llvm::Error make_string_error(llvm::Twine const &Message) { return llvm::make_error(Message, llvm::inconvertibleErrorCode()); } -const char *ParseErrorCategory::name() const noexcept { +char const *ParseErrorCategory::name() const noexcept { return "clang-format.parse_error"; } @@ -867,7 +880,7 @@ llvm_unreachable("unexpected parse error"); } -static FormatStyle expandPresets(const FormatStyle &Style) { +static FormatStyle expandPresets(FormatStyle const &Style) { if (Style.BreakBeforeBraces == FormatStyle::BS_Custom) return Style; FormatStyle Expanded = Style; @@ -1033,6 +1046,7 @@ LLVMStyle.BreakStringLiterals = true; LLVMStyle.ColumnLimit = 80; LLVMStyle.CommentPragmas = "^ IWYU pragma:"; + LLVMStyle.ConstPlacement = FormatStyle::CS_Leave; LLVMStyle.CompactNamespaces = false; LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false; LLVMStyle.ConstructorInitializerIndentWidth = 4; @@ -1243,6 +1257,7 @@ // taze:, triple slash directives (`/// <...`), tslint:, and @see, which is // commonly followed by overlong URLs. GoogleStyle.CommentPragmas = "(taze:|^/[ \t]*<|tslint:|@see)"; + GoogleStyle.ConstPlacement = FormatStyle::CS_Leave; // TODO: enable once decided, in particular re disabling bin packing. // https://google.github.io/styleguide/jsguide.html#features-arrays-trailing-comma // GoogleStyle.InsertTrailingCommas = FormatStyle::TCS_Wrapped; @@ -1303,6 +1318,7 @@ // _prepend that with a comment_ to prevent it" before changing behavior. ChromiumStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Preserve; + ChromiumStyle.ConstPlacement = FormatStyle::CS_Leave; if (Language == FormatStyle::LK_Java) { ChromiumStyle.AllowShortIfStatementsOnASingleLine = @@ -1364,6 +1380,7 @@ MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200; MozillaStyle.PointerAlignment = FormatStyle::PAS_Left; MozillaStyle.SpaceAfterTemplateKeyword = false; + MozillaStyle.ConstPlacement = FormatStyle::CS_Leave; return MozillaStyle; } @@ -1387,6 +1404,7 @@ Style.PointerAlignment = FormatStyle::PAS_Left; Style.SpaceBeforeCpp11BracedList = true; Style.SpaceInEmptyBlock = true; + Style.ConstPlacement = FormatStyle::CS_Leave; return Style; } @@ -1402,6 +1420,7 @@ Style.FixNamespaceComments = false; Style.SpaceBeforeParens = FormatStyle::SBPO_Always; Style.Standard = FormatStyle::LS_Cpp03; + Style.ConstPlacement = FormatStyle::CS_Leave; return Style; } @@ -1432,6 +1451,7 @@ Style.AllowShortLoopsOnASingleLine = false; Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None; Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; + Style.ConstPlacement = FormatStyle::CS_Leave; return Style; } @@ -1440,6 +1460,7 @@ NoStyle.DisableFormat = true; NoStyle.SortIncludes = FormatStyle::SI_Never; NoStyle.SortUsingDeclarations = false; + NoStyle.ConstPlacement = FormatStyle::CS_Leave; return NoStyle; } @@ -1535,7 +1556,7 @@ return make_error_code(ParseError::Success); } -std::string configurationAsText(const FormatStyle &Style) { +std::string configurationAsText(FormatStyle const &Style) { std::string Text; llvm::raw_string_ostream Stream(Text); llvm::yaml::Output Output(Stream); @@ -1580,7 +1601,7 @@ class JavaScriptRequoter : public TokenAnalyzer { public: - JavaScriptRequoter(const Environment &Env, const FormatStyle &Style) + JavaScriptRequoter(Environment const &Env, FormatStyle const &Style) : TokenAnalyzer(Env, Style) {} std::pair @@ -1667,7 +1688,7 @@ class Formatter : public TokenAnalyzer { public: - Formatter(const Environment &Env, const FormatStyle &Style, + Formatter(Environment const &Env, FormatStyle const &Style, FormattingAttemptStatus *Status) : TokenAnalyzer(Env, Style), Status(Status) {} @@ -1703,7 +1724,7 @@ /*FirstStartColumn=*/Env.getFirstStartColumn(), /*NextStartColumn=*/Env.getNextStartColumn(), /*LastStartColumn=*/Env.getLastStartColumn()); - for (const auto &R : Whitespaces.generateReplacements()) + for (auto const &R : Whitespaces.generateReplacements()) if (Result.add(R)) return std::make_pair(Result, 0); return std::make_pair(Result, Penalty); @@ -1717,8 +1738,8 @@ } bool - hasCpp03IncompatibleFormat(const SmallVectorImpl &Lines) { - for (const AnnotatedLine *Line : Lines) { + hasCpp03IncompatibleFormat(SmallVectorImpl const &Lines) { + for (AnnotatedLine const *Line : Lines) { if (hasCpp03IncompatibleFormat(Line->Children)) return true; for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) { @@ -1734,9 +1755,9 @@ return false; } - int countVariableAlignments(const SmallVectorImpl &Lines) { + int countVariableAlignments(SmallVectorImpl const &Lines) { int AlignmentDiff = 0; - for (const AnnotatedLine *Line : Lines) { + for (AnnotatedLine const *Line : Lines) { AlignmentDiff += countVariableAlignments(Line->Children); for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) { if (!Tok->is(TT_PointerOrReference)) @@ -1755,7 +1776,7 @@ } void - deriveLocalStyle(const SmallVectorImpl &AnnotatedLines) { + deriveLocalStyle(SmallVectorImpl const &AnnotatedLines) { bool HasBinPackedFunction = false; bool HasOnePerLineFunction = false; for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { @@ -1802,7 +1823,7 @@ /// is conceptually incompatible with bin packing. class TrailingCommaInserter : public TokenAnalyzer { public: - TrailingCommaInserter(const Environment &Env, const FormatStyle &Style) + TrailingCommaInserter(Environment const &Env, FormatStyle const &Style) : TokenAnalyzer(Env, Style) {} std::pair @@ -1862,7 +1883,7 @@ // file. class Cleaner : public TokenAnalyzer { public: - Cleaner(const Environment &Env, const FormatStyle &Style) + Cleaner(Environment const &Env, FormatStyle const &Style) : TokenAnalyzer(Env, Style), DeletedTokens(FormatTokenLess(Env.getSourceManager())) {} @@ -1905,7 +1926,7 @@ } } - bool containsOnlyComments(const AnnotatedLine &Line) { + bool containsOnlyComments(AnnotatedLine const &Line) { for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) { if (Tok->isNot(tok::comment)) return false; @@ -1996,7 +2017,7 @@ template void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK, bool DeleteLeft) { - auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * { + auto NextNotDeleted = [this](FormatToken const &Tok) -> FormatToken * { for (auto *Res = Tok.Next; Res; Res = Res->Next) if (!Res->is(tok::comment) && DeletedTokens.find(Res) == DeletedTokens.end()) @@ -2072,13 +2093,13 @@ // We store tokens in the order they appear in the translation unit so that // we do not need to sort them in `generateFixes()`. struct FormatTokenLess { - FormatTokenLess(const SourceManager &SM) : SM(SM) {} + FormatTokenLess(SourceManager const &SM) : SM(SM) {} - bool operator()(const FormatToken *LHS, const FormatToken *RHS) const { + bool operator()(FormatToken const *LHS, FormatToken const *RHS) const { return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(), RHS->Tok.getLocation()); } - const SourceManager &SM; + SourceManager const &SM; }; // Tokens to be deleted. @@ -2087,7 +2108,7 @@ class ObjCHeaderStyleGuesser : public TokenAnalyzer { public: - ObjCHeaderStyleGuesser(const Environment &Env, const FormatStyle &Style) + ObjCHeaderStyleGuesser(Environment const &Env, FormatStyle const &Style) : TokenAnalyzer(Env, Style), IsObjC(false) {} std::pair @@ -2105,9 +2126,9 @@ private: static bool - guessIsObjC(const SourceManager &SourceManager, - const SmallVectorImpl &AnnotatedLines, - const AdditionalKeywords &Keywords) { + guessIsObjC(SourceManager const &SourceManager, + SmallVectorImpl const &AnnotatedLines, + AdditionalKeywords const &Keywords) { // Keep this array sorted, since we are binary searching over it. static constexpr llvm::StringLiteral FoundationIdentifiers[] = { "CGFloat", @@ -2187,7 +2208,7 @@ Line->First->TokenText == "__pragma" || Line->First->TokenText == "_Pragma")) continue; - for (const FormatToken *FormatTok = Line->First; FormatTok; + for (FormatToken const *FormatTok = Line->First; FormatTok; FormatTok = FormatTok->Next) { if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) && (FormatTok->Tok.getObjCKeywordID() != tok::objc_not_keyword || @@ -2258,8 +2279,8 @@ // its current line. // If `Cursor` is not on any #include, `Index` will be UINT_MAX. static std::pair -FindCursorIndex(const SmallVectorImpl &Includes, - const SmallVectorImpl &Indices, unsigned Cursor) { +FindCursorIndex(SmallVectorImpl const &Includes, + SmallVectorImpl const &Indices, unsigned Cursor) { unsigned CursorIndex = UINT_MAX; unsigned OffsetToEOL = 0; for (int i = 0, e = Includes.size(); i != e; ++i) { @@ -2279,7 +2300,7 @@ } // Replace all "\r\n" with "\n". -std::string replaceCRLF(const std::string &Code) { +std::string replaceCRLF(std::string const &Code) { std::string NewCode; size_t Pos = 0, LastPos = 0; @@ -2307,8 +2328,8 @@ // first #include in the duplicate #includes remains. If the `Cursor` is // provided and put on a deleted #include, it will be moved to the remaining // #include in the duplicate #includes. -static void sortCppIncludes(const FormatStyle &Style, - const SmallVectorImpl &Includes, +static void sortCppIncludes(FormatStyle const &Style, + SmallVectorImpl const &Includes, ArrayRef Ranges, StringRef FileName, StringRef Code, tooling::Replacements &Replaces, unsigned *Cursor) { @@ -2402,12 +2423,12 @@ namespace { -const char CppIncludeRegexPattern[] = +char const CppIncludeRegexPattern[] = R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))"; } // anonymous namespace -tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code, +tooling::Replacements sortCppIncludes(FormatStyle const &Style, StringRef Code, ArrayRef Ranges, StringRef FileName, tooling::Replacements &Replaces, @@ -2444,7 +2465,7 @@ Trimmed == "/* clang-format on */") FormattingOff = false; - const bool EmptyLineSkipped = + bool const EmptyLineSkipped = Trimmed.empty() && (Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Merge || Style.IncludeStyle.IncludeBlocks == @@ -2489,7 +2510,7 @@ // Returns group number to use as a first order sort on imports. Gives UINT_MAX // if the import does not match any given groups. -static unsigned findJavaImportGroup(const FormatStyle &Style, +static unsigned findJavaImportGroup(FormatStyle const &Style, StringRef ImportIdentifier) { unsigned LongestMatchIndex = UINT_MAX; unsigned LongestMatchLength = 0; @@ -2509,8 +2530,8 @@ // Import declarations with the same text will be deduplicated. Between each // import group, a newline is inserted, and within each import group, a // lexicographic sort based on ASCII value is performed. -static void sortJavaImports(const FormatStyle &Style, - const SmallVectorImpl &Imports, +static void sortJavaImports(FormatStyle const &Style, + SmallVectorImpl const &Imports, ArrayRef Ranges, StringRef FileName, StringRef Code, tooling::Replacements &Replaces) { unsigned ImportsBeginOffset = Imports.front().Offset; @@ -2583,12 +2604,12 @@ namespace { -const char JavaImportRegexPattern[] = +char const JavaImportRegexPattern[] = "^[\t ]*import[\t ]+(static[\t ]*)?([^\t ]*)[\t ]*;"; } // anonymous namespace -tooling::Replacements sortJavaImports(const FormatStyle &Style, StringRef Code, +tooling::Replacements sortJavaImports(FormatStyle const &Style, StringRef Code, ArrayRef Ranges, StringRef FileName, tooling::Replacements &Replaces) { @@ -2650,7 +2671,7 @@ bool isLikelyXml(StringRef Code) { return Code.ltrim().startswith("<"); } -tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code, +tooling::Replacements sortIncludes(FormatStyle const &Style, StringRef Code, ArrayRef Ranges, StringRef FileName, unsigned *Cursor) { tooling::Replacements Replaces; @@ -2672,8 +2693,8 @@ template static llvm::Expected processReplacements(T ProcessFunc, StringRef Code, - const tooling::Replacements &Replaces, - const FormatStyle &Style) { + tooling::Replacements const &Replaces, + FormatStyle const &Style) { if (Replaces.empty()) return tooling::Replacements(); @@ -2690,11 +2711,11 @@ } llvm::Expected -formatReplacements(StringRef Code, const tooling::Replacements &Replaces, - const FormatStyle &Style) { +formatReplacements(StringRef Code, tooling::Replacements const &Replaces, + FormatStyle const &Style) { // We need to use lambda function here since there are two versions of // `sortIncludes`. - auto SortIncludes = [](const FormatStyle &Style, StringRef Code, + auto SortIncludes = [](FormatStyle const &Style, StringRef Code, std::vector Ranges, StringRef FileName) -> tooling::Replacements { return sortIncludes(Style, Code, Ranges, FileName); @@ -2706,7 +2727,7 @@ // We need to use lambda function here since there are two versions of // `reformat`. - auto Reformat = [](const FormatStyle &Style, StringRef Code, + auto Reformat = [](FormatStyle const &Style, StringRef Code, std::vector Ranges, StringRef FileName) -> tooling::Replacements { return reformat(Style, Code, Ranges, FileName); @@ -2716,27 +2737,27 @@ namespace { -inline bool isHeaderInsertion(const tooling::Replacement &Replace) { +inline bool isHeaderInsertion(tooling::Replacement const &Replace) { return Replace.getOffset() == UINT_MAX && Replace.getLength() == 0 && llvm::Regex(CppIncludeRegexPattern) .match(Replace.getReplacementText()); } -inline bool isHeaderDeletion(const tooling::Replacement &Replace) { +inline bool isHeaderDeletion(tooling::Replacement const &Replace) { return Replace.getOffset() == UINT_MAX && Replace.getLength() == 1; } // FIXME: insert empty lines between newly created blocks. tooling::Replacements -fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces, - const FormatStyle &Style) { +fixCppIncludeInsertions(StringRef Code, tooling::Replacements const &Replaces, + FormatStyle const &Style) { if (!Style.isCpp()) return Replaces; tooling::Replacements HeaderInsertions; std::set HeadersToDelete; tooling::Replacements Result; - for (const auto &R : Replaces) { + for (auto const &R : Replaces) { if (isHeaderInsertion(R)) { // Replacements from \p Replaces must be conflict-free already, so we can // simply consume the error. @@ -2757,10 +2778,10 @@ StringRef FileName = Replaces.begin()->getFilePath(); tooling::HeaderIncludes Includes(FileName, Code, Style.IncludeStyle); - for (const auto &Header : HeadersToDelete) { + for (auto const &Header : HeadersToDelete) { tooling::Replacements Replaces = Includes.remove(Header.trim("\"<>"), Header.startswith("<")); - for (const auto &R : Replaces) { + for (auto const &R : Replaces) { auto Err = Result.add(R); if (Err) { // Ignore the deletion on conflict. @@ -2773,7 +2794,7 @@ llvm::Regex IncludeRegex = llvm::Regex(CppIncludeRegexPattern); llvm::SmallVector Matches; - for (const auto &R : HeaderInsertions) { + for (auto const &R : HeaderInsertions) { auto IncludeDirective = R.getReplacementText(); bool Matched = IncludeRegex.match(IncludeDirective, &Matches); assert(Matched && "Header insertion replacement must have replacement text " @@ -2800,11 +2821,11 @@ } // anonymous namespace llvm::Expected -cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces, - const FormatStyle &Style) { +cleanupAroundReplacements(StringRef Code, tooling::Replacements const &Replaces, + FormatStyle const &Style) { // We need to use lambda function here since there are two versions of // `cleanup`. - auto Cleanup = [](const FormatStyle &Style, StringRef Code, + auto Cleanup = [](FormatStyle const &Style, StringRef Code, std::vector Ranges, StringRef FileName) -> tooling::Replacements { return cleanup(Style, Code, Ranges, FileName); @@ -2817,7 +2838,7 @@ namespace internal { std::pair -reformat(const FormatStyle &Style, StringRef Code, +reformat(FormatStyle const &Style, StringRef Code, ArrayRef Ranges, unsigned FirstStartColumn, unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName, FormattingAttemptStatus *Status) { @@ -2849,35 +2870,40 @@ } typedef std::function( - const Environment &)> + Environment const &)> AnalyzerPass; SmallVector Passes; if (Style.Language == FormatStyle::LK_Cpp) { if (Style.FixNamespaceComments) - Passes.emplace_back([&](const Environment &Env) { + Passes.emplace_back([&](Environment const &Env) { return NamespaceEndCommentsFixer(Env, Expanded).process(); }); if (Style.SortUsingDeclarations) - Passes.emplace_back([&](const Environment &Env) { + Passes.emplace_back([&](Environment const &Env) { return UsingDeclarationsSorter(Env, Expanded).process(); }); } + if (Style.isCpp() && Style.ConstPlacement != FormatStyle::CS_Leave) + Passes.emplace_back([&](Environment const &Env) { + return EastWestConstFixer(Env, Expanded).process(); + }); + if (Style.Language == FormatStyle::LK_JavaScript && Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) - Passes.emplace_back([&](const Environment &Env) { + Passes.emplace_back([&](Environment const &Env) { return JavaScriptRequoter(Env, Expanded).process(); }); - Passes.emplace_back([&](const Environment &Env) { + Passes.emplace_back([&](Environment const &Env) { return Formatter(Env, Expanded, Status).process(); }); if (Style.Language == FormatStyle::LK_JavaScript && Style.InsertTrailingCommas == FormatStyle::TCS_Wrapped) - Passes.emplace_back([&](const Environment &Env) { + Passes.emplace_back([&](Environment const &Env) { return TrailingCommaInserter(Env, Expanded).process(); }); @@ -2908,7 +2934,7 @@ } } // namespace internal -tooling::Replacements reformat(const FormatStyle &Style, StringRef Code, +tooling::Replacements reformat(FormatStyle const &Style, StringRef Code, ArrayRef Ranges, StringRef FileName, FormattingAttemptStatus *Status) { @@ -2919,7 +2945,7 @@ .first; } -tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, +tooling::Replacements cleanup(FormatStyle const &Style, StringRef Code, ArrayRef Ranges, StringRef FileName) { // cleanups only apply to C++ (they mostly concern ctor commas etc.) @@ -2928,7 +2954,7 @@ return Cleaner(Environment(Code, FileName, Ranges), Style).process().first; } -tooling::Replacements reformat(const FormatStyle &Style, StringRef Code, +tooling::Replacements reformat(FormatStyle const &Style, StringRef Code, ArrayRef Ranges, StringRef FileName, bool *IncompleteFormat) { FormattingAttemptStatus Status; @@ -2938,7 +2964,7 @@ return Result; } -tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style, +tooling::Replacements fixNamespaceEndComments(FormatStyle const &Style, StringRef Code, ArrayRef Ranges, StringRef FileName) { @@ -2947,7 +2973,7 @@ .first; } -tooling::Replacements sortUsingDeclarations(const FormatStyle &Style, +tooling::Replacements sortUsingDeclarations(FormatStyle const &Style, StringRef Code, ArrayRef Ranges, StringRef FileName) { @@ -2956,7 +2982,7 @@ .first; } -LangOptions getFormattingLangOpts(const FormatStyle &Style) { +LangOptions getFormattingLangOpts(FormatStyle const &Style) { LangOptions LangOpts; FormatStyle::LanguageStandard LexingStd = Style.Standard; @@ -2982,7 +3008,7 @@ return LangOpts; } -const char *StyleOptionHelpDescription = +char const *StyleOptionHelpDescription = "Coding style, currently supports:\n" " LLVM, GNU, Google, Chromium, Microsoft, Mozilla, WebKit.\n" "Use -style=file to load style configuration from\n" @@ -3020,7 +3046,7 @@ } FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) { - const auto GuessedLanguage = getLanguageByFileName(FileName); + auto const GuessedLanguage = getLanguageByFileName(FileName); if (GuessedLanguage == FormatStyle::LK_Cpp) { auto Extension = llvm::sys::path::extension(FileName); // If there's no file extension (or it's .h), we need to check the contents @@ -3037,9 +3063,9 @@ return GuessedLanguage; } -const char *DefaultFormatStyle = "file"; +char const *DefaultFormatStyle = "file"; -const char *DefaultFallbackStyle = "LLVM"; +char const *DefaultFallbackStyle = "LLVM"; llvm::Expected getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyleName, @@ -3094,7 +3120,7 @@ FilesToLookFor.push_back(".clang-format"); FilesToLookFor.push_back("_clang-format"); - auto dropDiagnosticHandler = [](const llvm::SMDiagnostic &, void *) {}; + auto dropDiagnosticHandler = [](llvm::SMDiagnostic const &, void *) {}; for (StringRef Directory = Path; !Directory.empty(); Directory = llvm::sys::path::parent_path(Directory)) { @@ -3105,7 +3131,7 @@ continue; } - for (const auto &F : FilesToLookFor) { + for (auto const &F : FilesToLookFor) { SmallString<128> ConfigFile(Directory); llvm::sys::path::append(ConfigFile, F); @@ -3139,7 +3165,7 @@ LLVM_DEBUG(llvm::dbgs() << "Applying child configurations\n"); - for (const auto &MemBuf : llvm::reverse(ChildFormatTextToApply)) { + for (auto const &MemBuf : llvm::reverse(ChildFormatTextToApply)) { auto Ec = parseConfiguration(*MemBuf, &Style, AllowUnknownOptions, dropDiagnosticHandler); // It was already correctly parsed. Index: clang/lib/Format/FormatInternal.h =================================================================== --- clang/lib/Format/FormatInternal.h +++ clang/lib/Format/FormatInternal.h @@ -69,7 +69,7 @@ /// If ``Status`` is non-null, its value will be populated with the status of /// this formatting attempt. See \c FormattingAttemptStatus. std::pair -reformat(const FormatStyle &Style, StringRef Code, +reformat(FormatStyle const &Style, StringRef Code, ArrayRef Ranges, unsigned FirstStartColumn, unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName, FormattingAttemptStatus *Status); Index: clang/lib/Format/FormatToken.h =================================================================== --- clang/lib/Format/FormatToken.h +++ clang/lib/Format/FormatToken.h @@ -130,7 +130,7 @@ }; /// Determines the name of a token type. -const char *getTokenTypeName(TokenType Type); +char const *getTokenTypeName(TokenType Type); // Represents what type of block a set of braces open. enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit }; @@ -451,7 +451,7 @@ bool is(tok::TokenKind Kind) const { return Tok.is(Kind); } bool is(TokenType TT) const { return getType() == TT; } - bool is(const IdentifierInfo *II) const { + bool is(IdentifierInfo const *II) const { return II && II == Tok.getIdentifierInfo(); } bool is(tok::PPKeywordKind Kind) const { @@ -645,8 +645,8 @@ } /// Returns the next token ignoring comments. - const FormatToken *getNextNonComment() const { - const FormatToken *Tok = Next; + FormatToken const *getNextNonComment() const { + FormatToken const *Tok = Next; while (Tok && Tok->is(tok::comment)) Tok = Tok->Next; return Tok; @@ -654,7 +654,7 @@ /// Returns \c true if this tokens starts a block-type list, i.e. a /// list that should be indented with a block indent. - bool opensBlockOrBlockTypeList(const FormatStyle &Style) const { + bool opensBlockOrBlockTypeList(FormatStyle const &Style) const { // C# Does not indent object initialisers as continuations. if (is(tok::l_brace) && getBlockKind() == BK_BracedInit && Style.isCSharp()) return true; @@ -670,10 +670,10 @@ /// Returns whether the token is the left square bracket of a C++ /// structured binding declaration. - bool isCppStructuredBinding(const FormatStyle &Style) const { + bool isCppStructuredBinding(FormatStyle const &Style) const { if (!Style.isCpp() || isNot(tok::l_square)) return false; - const FormatToken *T = this; + FormatToken const *T = this; do { T = T->getPreviousNonComment(); } while (T && T->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp, @@ -682,7 +682,7 @@ } /// Same as opensBlockOrBlockTypeList, but for the closing token. - bool closesBlockOrBlockTypeList(const FormatStyle &Style) const { + bool closesBlockOrBlockTypeList(FormatStyle const &Style) const { if (is(TT_TemplateString) && closesScope()) return true; return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style); @@ -690,8 +690,8 @@ /// Return the actual namespace token, if this token starts a namespace /// block. - const FormatToken *getNamespaceToken() const { - const FormatToken *NamespaceTok = this; + FormatToken const *getNamespaceToken() const { + FormatToken const *NamespaceTok = this; if (is(tok::comment)) NamespaceTok = NamespaceTok->getNextNonComment(); // Detect "(inline|export)? namespace" in the beginning of a line. @@ -703,12 +703,12 @@ : nullptr; } - void copyFrom(const FormatToken &Tok) { *this = Tok; } + void copyFrom(FormatToken const &Tok) { *this = Tok; } private: // Only allow copying via the explicit copyFrom method. - FormatToken(const FormatToken &) = delete; - FormatToken &operator=(const FormatToken &) = default; + FormatToken(FormatToken const &) = delete; + FormatToken &operator=(FormatToken const &) = default; template bool startsSequenceInternal(A K1, Ts... Tokens) const { @@ -742,12 +742,12 @@ class TokenRole { public: - TokenRole(const FormatStyle &Style) : Style(Style) {} + TokenRole(FormatStyle const &Style) : Style(Style) {} virtual ~TokenRole(); /// After the \c TokenAnnotator has finished annotating all the tokens, /// this function precomputes required information for formatting. - virtual void precomputeFormattingInfos(const FormatToken *Token); + virtual void precomputeFormattingInfos(FormatToken const *Token); /// Apply the special formatting that the given role demands. /// @@ -770,20 +770,20 @@ } /// Notifies the \c Role that a comma was found. - virtual void CommaFound(const FormatToken *Token) {} + virtual void CommaFound(FormatToken const *Token) {} - virtual const FormatToken *lastComma() { return nullptr; } + virtual FormatToken const *lastComma() { return nullptr; } protected: - const FormatStyle &Style; + FormatStyle const &Style; }; class CommaSeparatedList : public TokenRole { public: - CommaSeparatedList(const FormatStyle &Style) + CommaSeparatedList(FormatStyle const &Style) : TokenRole(Style), HasNestedBracedList(false) {} - void precomputeFormattingInfos(const FormatToken *Token) override; + void precomputeFormattingInfos(FormatToken const *Token) override; unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter, bool DryRun) override; @@ -792,11 +792,11 @@ bool DryRun) override; /// Adds \p Token as the next comma to the \c CommaSeparated list. - void CommaFound(const FormatToken *Token) override { + void CommaFound(FormatToken const *Token) override { Commas.push_back(Token); } - const FormatToken *lastComma() override { + FormatToken const *lastComma() override { if (Commas.empty()) return nullptr; return Commas.back(); @@ -821,10 +821,10 @@ /// Calculate which \c ColumnFormat fits best into /// \p RemainingCharacters. - const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const; + ColumnFormat const *getColumnFormat(unsigned RemainingCharacters) const; /// The ordered \c FormatTokens making up the commas of this list. - SmallVector Commas; + SmallVector Commas; /// The length of each of the list's items in characters including the /// trailing comma. @@ -1057,7 +1057,7 @@ /// If \c AcceptIdentifierName is true, returns true not only for keywords, // but also for IdentifierName tokens (aka pseudo-keywords), such as // ``yield``. - bool IsJavaScriptIdentifier(const FormatToken &Tok, + bool IsJavaScriptIdentifier(FormatToken const &Tok, bool AcceptIdentifierName = true) const { // Based on the list of JavaScript & TypeScript keywords here: // https://github.com/microsoft/TypeScript/blob/master/src/compiler/scanner.ts#L74 @@ -1124,7 +1124,7 @@ /// Returns \c true if \p Tok is a C# keyword, returns /// \c false if it is a anything else. - bool isCSharpKeyword(const FormatToken &Tok) const { + bool isCSharpKeyword(FormatToken const &Tok) const { switch (Tok.Tok.getKind()) { case tok::kw_bool: case tok::kw_break: Index: clang/lib/Format/FormatToken.cpp =================================================================== --- clang/lib/Format/FormatToken.cpp +++ clang/lib/Format/FormatToken.cpp @@ -21,8 +21,8 @@ namespace clang { namespace format { -const char *getTokenTypeName(TokenType Type) { - static const char *const TokNames[] = { +char const *getTokenTypeName(TokenType Type) { + static char const *const TokNames[] = { #define TYPE(X) #X, LIST_TOKEN_TYPES #undef TYPE @@ -71,7 +71,7 @@ TokenRole::~TokenRole() {} -void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {} +void TokenRole::precomputeFormattingInfos(FormatToken const *Token) {} unsigned CommaSeparatedList::formatAfterToken(LineState &State, ContinuationIndenter *Indenter, @@ -83,7 +83,7 @@ return 0; // Handled by formatFromToken // Ensure that we start on the opening brace. - const FormatToken *LBrace = + FormatToken const *LBrace = State.NextToken->Previous->getPreviousNonComment(); if (!LBrace || !LBrace->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || LBrace->is(BK_Block) || LBrace->is(TT_DictLiteral) || @@ -96,7 +96,7 @@ Style.ColumnLimit - State.Column + State.NextToken->Previous->ColumnWidth; // Find the best ColumnFormat, i.e. the best number of columns to use. - const ColumnFormat *Format = getColumnFormat(RemainingCodePoints); + ColumnFormat const *Format = getColumnFormat(RemainingCodePoints); // If no ColumnFormat can be used, the braced list would generally be // bin-packed. Add a severe penalty to this so that column layouts are @@ -144,13 +144,13 @@ // Returns the lengths in code points between Begin and End (both included), // assuming that the entire sequence is put on a single line. -static unsigned CodePointsBetween(const FormatToken *Begin, - const FormatToken *End) { +static unsigned CodePointsBetween(FormatToken const *Begin, + FormatToken const *End) { assert(End->TotalLength >= Begin->TotalLength); return End->TotalLength - Begin->TotalLength + Begin->ColumnWidth; } -void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) { +void CommaSeparatedList::precomputeFormattingInfos(FormatToken const *Token) { // FIXME: At some point we might want to do this for other lists, too. if (!Token->MatchingParen || !Token->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)) @@ -193,10 +193,10 @@ MustBreakBeforeItem.push_back(ItemBegin->MustBreakBefore); if (ItemBegin->is(tok::l_brace)) HasNestedBracedList = true; - const FormatToken *ItemEnd = nullptr; + FormatToken const *ItemEnd = nullptr; if (i == Commas.size()) { ItemEnd = Token->MatchingParen; - const FormatToken *NonCommentEnd = ItemEnd->getPreviousNonComment(); + FormatToken const *NonCommentEnd = ItemEnd->getPreviousNonComment(); ItemLengths.push_back(CodePointsBetween(ItemBegin, NonCommentEnd)); if (Style.Cpp11BracedListStyle && !ItemEnd->Previous->isTrailingComment()) { @@ -288,9 +288,9 @@ } } -const CommaSeparatedList::ColumnFormat * +CommaSeparatedList::ColumnFormat const * CommaSeparatedList::getColumnFormat(unsigned RemainingCharacters) const { - const ColumnFormat *BestFormat = nullptr; + ColumnFormat const *BestFormat = nullptr; for (SmallVector::const_reverse_iterator I = Formats.rbegin(), E = Formats.rend(); Index: clang/lib/Format/FormatTokenLexer.h =================================================================== --- clang/lib/Format/FormatTokenLexer.h +++ clang/lib/Format/FormatTokenLexer.h @@ -37,14 +37,14 @@ class FormatTokenLexer { public: - FormatTokenLexer(const SourceManager &SourceMgr, FileID ID, unsigned Column, - const FormatStyle &Style, encoding::Encoding Encoding, + FormatTokenLexer(SourceManager const &SourceMgr, FileID ID, unsigned Column, + FormatStyle const &Style, encoding::Encoding Encoding, llvm::SpecificBumpPtrAllocator &Allocator, IdentifierTable &IdentTable); ArrayRef lex(); - const AdditionalKeywords &getKeywords() { return Keywords; } + AdditionalKeywords const &getKeywords() { return Keywords; } private: void tryMergePreviousTokens(); @@ -101,9 +101,9 @@ unsigned Column; unsigned TrailingWhitespace; std::unique_ptr Lex; - const SourceManager &SourceMgr; + SourceManager const &SourceMgr; FileID ID; - const FormatStyle &Style; + FormatStyle const &Style; IdentifierTable &IdentTable; AdditionalKeywords Keywords; encoding::Encoding Encoding; Index: clang/lib/Format/FormatTokenLexer.cpp =================================================================== --- clang/lib/Format/FormatTokenLexer.cpp +++ clang/lib/Format/FormatTokenLexer.cpp @@ -23,8 +23,8 @@ namespace format { FormatTokenLexer::FormatTokenLexer( - const SourceManager &SourceMgr, FileID ID, unsigned Column, - const FormatStyle &Style, encoding::Encoding Encoding, + SourceManager const &SourceMgr, FileID ID, unsigned Column, + FormatStyle const &Style, encoding::Encoding Encoding, llvm::SpecificBumpPtrAllocator &Allocator, IdentifierTable &IdentTable) : FormatTok(nullptr), IsFirstToken(true), StateStack({LexerState::NORMAL}), @@ -37,24 +37,24 @@ getFormattingLangOpts(Style))); Lex->SetKeepWhitespaceMode(true); - for (const std::string &ForEachMacro : Style.ForEachMacros) + for (std::string const &ForEachMacro : Style.ForEachMacros) Macros.insert({&IdentTable.get(ForEachMacro), TT_ForEachMacro}); - for (const std::string &IfMacro : Style.IfMacros) + for (std::string const &IfMacro : Style.IfMacros) Macros.insert({&IdentTable.get(IfMacro), TT_IfMacro}); - for (const std::string &AttributeMacro : Style.AttributeMacros) + for (std::string const &AttributeMacro : Style.AttributeMacros) Macros.insert({&IdentTable.get(AttributeMacro), TT_AttributeMacro}); - for (const std::string &StatementMacro : Style.StatementMacros) + for (std::string const &StatementMacro : Style.StatementMacros) Macros.insert({&IdentTable.get(StatementMacro), TT_StatementMacro}); - for (const std::string &TypenameMacro : Style.TypenameMacros) + for (std::string const &TypenameMacro : Style.TypenameMacros) Macros.insert({&IdentTable.get(TypenameMacro), TT_TypenameMacro}); - for (const std::string &NamespaceMacro : Style.NamespaceMacros) + for (std::string const &NamespaceMacro : Style.NamespaceMacros) Macros.insert({&IdentTable.get(NamespaceMacro), TT_NamespaceMacro}); - for (const std::string &WhitespaceSensitiveMacro : + for (std::string const &WhitespaceSensitiveMacro : Style.WhitespaceSensitiveMacros) { Macros.insert( {&IdentTable.get(WhitespaceSensitiveMacro), TT_UntouchableMacroFunc}); } - for (const std::string &StatementAttributeLikeMacro : + for (std::string const &StatementAttributeLikeMacro : Style.StatementAttributeLikeMacros) Macros.insert({&IdentTable.get(StatementAttributeLikeMacro), TT_StatementAttributeLikeMacro}); @@ -519,8 +519,8 @@ return; // 'Manually' lex ahead in the current file buffer. - const char *Offset = Lex->getBufferLocation(); - const char *RegexBegin = Offset - RegexToken->TokenText.size(); + char const *Offset = Lex->getBufferLocation(); + char const *RegexBegin = Offset - RegexToken->TokenText.size(); StringRef Buffer = Lex->getBuffer(); bool InCharacterClass = false; bool HaveClosingSlash = false; @@ -566,9 +566,9 @@ CSharpStringLiteral->TokenText.startswith(R"($@")"))) return; - const char *StrBegin = + char const *StrBegin = Lex->getBufferLocation() - CSharpStringLiteral->TokenText.size(); - const char *Offset = StrBegin; + char const *Offset = StrBegin; if (CSharpStringLiteral->TokenText.startswith(R"(@")")) Offset += 2; else // CSharpStringLiteral->TokenText.startswith(R"($@")") @@ -639,8 +639,8 @@ } // 'Manually' lex ahead in the current file buffer. - const char *Offset = Lex->getBufferLocation(); - const char *TmplBegin = Offset - BacktickToken->TokenText.size(); // at "`" + char const *Offset = Lex->getBufferLocation(); + char const *TmplBegin = Offset - BacktickToken->TokenText.size(); // at "`" for (; Offset != Lex->getBuffer().end(); ++Offset) { if (Offset[0] == '`') { StateStack.pop(); @@ -689,7 +689,7 @@ if (!HashToken->isOneOf(tok::hash, tok::hashhash)) return; // Turn the remainder of this line into a comment. - const char *CommentBegin = + char const *CommentBegin = Lex->getBufferLocation() - HashToken->TokenText.size(); // at "#" size_t From = CommentBegin - Lex->getBuffer().begin(); size_t To = Lex->getBuffer().find_first_of('\n', From); @@ -723,8 +723,8 @@ if (Macro->TokenText != "_T") return false; - const char *Start = Macro->TokenText.data(); - const char *End = Last->TokenText.data() + Last->TokenText.size(); + char const *Start = Macro->TokenText.data(); + char const *End = Last->TokenText.data() + Last->TokenText.size(); String->TokenText = StringRef(Start, End - Start); String->IsFirst = Macro->IsFirst; String->LastNewlineOffset = Macro->LastNewlineOffset; @@ -912,7 +912,7 @@ while (BackslashPos != StringRef::npos) { if (BackslashPos + 1 < FormatTok->TokenText.size() && FormatTok->TokenText[BackslashPos + 1] == '\n') { - const char *Offset = Lex->getBufferLocation(); + char const *Offset = Lex->getBufferLocation(); Offset -= FormatTok->TokenText.size(); Offset += BackslashPos + 1; resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset))); Index: clang/lib/Format/MacroExpander.cpp =================================================================== --- clang/lib/Format/MacroExpander.cpp +++ clang/lib/Format/MacroExpander.cpp @@ -120,26 +120,26 @@ }; MacroExpander::MacroExpander( - const std::vector &Macros, clang::SourceManager &SourceMgr, - const FormatStyle &Style, + std::vector const &Macros, clang::SourceManager &SourceMgr, + FormatStyle const &Style, llvm::SpecificBumpPtrAllocator &Allocator, IdentifierTable &IdentTable) : SourceMgr(SourceMgr), Style(Style), Allocator(Allocator), IdentTable(IdentTable) { - for (const std::string &Macro : Macros) { + for (std::string const &Macro : Macros) { parseDefinition(Macro); } } MacroExpander::~MacroExpander() = default; -void MacroExpander::parseDefinition(const std::string &Macro) { +void MacroExpander::parseDefinition(std::string const &Macro) { Buffers.push_back( llvm::MemoryBuffer::getMemBufferCopy(Macro, "")); clang::FileID FID = SourceMgr.createFileID(Buffers.back()->getMemBufferRef()); FormatTokenLexer Lex(SourceMgr, FID, 0, Style, encoding::Encoding_UTF8, Allocator, IdentTable); - const auto Tokens = Lex.lex(); + auto const Tokens = Lex.lex(); if (!Tokens.empty()) { DefinitionParser Parser(Tokens); auto Definition = Parser.parse(); @@ -159,7 +159,7 @@ ArgsList Args) const { assert(defined(ID->TokenText)); SmallVector Result; - const Definition &Def = Definitions.find(ID->TokenText)->second; + Definition const &Def = Definitions.find(ID->TokenText)->second; // Expand each argument at most once. llvm::StringSet<> ExpandedArgs; Index: clang/lib/Format/Macros.h =================================================================== --- clang/lib/Format/Macros.h +++ clang/lib/Format/Macros.h @@ -103,8 +103,8 @@ /// /// Macros that cannot be parsed will be silently discarded. /// - MacroExpander(const std::vector &Macros, - clang::SourceManager &SourceMgr, const FormatStyle &Style, + MacroExpander(std::vector const &Macros, + clang::SourceManager &SourceMgr, FormatStyle const &Style, llvm::SpecificBumpPtrAllocator &Allocator, IdentifierTable &IdentTable); ~MacroExpander(); @@ -125,10 +125,10 @@ struct Definition; class DefinitionParser; - void parseDefinition(const std::string &Macro); + void parseDefinition(std::string const &Macro); clang::SourceManager &SourceMgr; - const FormatStyle &Style; + FormatStyle const &Style; llvm::SpecificBumpPtrAllocator &Allocator; IdentifierTable &IdentTable; std::vector> Buffers; Index: clang/lib/Format/NamespaceEndCommentsFixer.h =================================================================== --- clang/lib/Format/NamespaceEndCommentsFixer.h +++ clang/lib/Format/NamespaceEndCommentsFixer.h @@ -26,13 +26,13 @@ // a preprocessor directive, the result will be the matching namespace token. // Otherwise returns null. // \p AnnotatedLines is the sequence of lines from which \p Line is a member of. -const FormatToken * -getNamespaceToken(const AnnotatedLine *Line, - const SmallVectorImpl &AnnotatedLines); +FormatToken const * +getNamespaceToken(AnnotatedLine const *Line, + SmallVectorImpl const &AnnotatedLines); class NamespaceEndCommentsFixer : public TokenAnalyzer { public: - NamespaceEndCommentsFixer(const Environment &Env, const FormatStyle &Style); + NamespaceEndCommentsFixer(Environment const &Env, FormatStyle const &Style); std::pair analyze(TokenAnnotator &Annotator, Index: clang/lib/Format/NamespaceEndCommentsFixer.cpp =================================================================== --- clang/lib/Format/NamespaceEndCommentsFixer.cpp +++ clang/lib/Format/NamespaceEndCommentsFixer.cpp @@ -24,12 +24,12 @@ namespace { // Computes the name of a namespace given the namespace token. // Returns "" for anonymous namespace. -std::string computeName(const FormatToken *NamespaceTok) { +std::string computeName(FormatToken const *NamespaceTok) { assert(NamespaceTok && NamespaceTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) && "expecting a namespace token"); std::string name = ""; - const FormatToken *Tok = NamespaceTok->getNextNonComment(); + FormatToken const *Tok = NamespaceTok->getNextNonComment(); if (NamespaceTok->is(TT_NamespaceMacro)) { // Collects all the non-comment tokens between opening parenthesis // and closing parenthesis or comma. @@ -44,7 +44,7 @@ // `namespace MACRO1 MACRO2 A::B::inline C {`, returns "A::B::inline C". // Peek for the first '::' (or '{') and then return all tokens from one // token before that up until the '{'. - const FormatToken *FirstNSTok = Tok; + FormatToken const *FirstNSTok = Tok; while (Tok && !Tok->is(tok::l_brace) && !Tok->is(tok::coloncolon)) { FirstNSTok = Tok; Tok = Tok->getNextNonComment(); @@ -62,7 +62,7 @@ } std::string computeEndCommentText(StringRef NamespaceName, bool AddNewline, - const FormatToken *NamespaceTok, + FormatToken const *NamespaceTok, unsigned SpacesToAdd) { std::string text = "//"; text.append(SpacesToAdd, ' '); @@ -79,14 +79,14 @@ return text; } -bool hasEndComment(const FormatToken *RBraceTok) { +bool hasEndComment(FormatToken const *RBraceTok) { return RBraceTok->Next && RBraceTok->Next->is(tok::comment); } -bool validEndComment(const FormatToken *RBraceTok, StringRef NamespaceName, - const FormatToken *NamespaceTok) { +bool validEndComment(FormatToken const *RBraceTok, StringRef NamespaceName, + FormatToken const *NamespaceTok) { assert(hasEndComment(RBraceTok)); - const FormatToken *Comment = RBraceTok->Next; + FormatToken const *Comment = RBraceTok->Next; // Matches a valid namespace end comment. // Valid namespace end comments don't need to be edited. @@ -140,8 +140,8 @@ return (NamespaceNameInComment == NamespaceName); } -void addEndComment(const FormatToken *RBraceTok, StringRef EndCommentText, - const SourceManager &SourceMgr, +void addEndComment(FormatToken const *RBraceTok, StringRef EndCommentText, + SourceManager const &SourceMgr, tooling::Replacements *Fixes) { auto EndLoc = RBraceTok->Tok.getEndLoc(); auto Range = CharSourceRange::getCharRange(EndLoc, EndLoc); @@ -152,11 +152,11 @@ } } -void updateEndComment(const FormatToken *RBraceTok, StringRef EndCommentText, - const SourceManager &SourceMgr, +void updateEndComment(FormatToken const *RBraceTok, StringRef EndCommentText, + SourceManager const &SourceMgr, tooling::Replacements *Fixes) { assert(hasEndComment(RBraceTok)); - const FormatToken *Comment = RBraceTok->Next; + FormatToken const *Comment = RBraceTok->Next; auto Range = CharSourceRange::getCharRange(Comment->getStartOfNonWhitespace(), Comment->Tok.getEndLoc()); auto Err = Fixes->add(tooling::Replacement(SourceMgr, Range, EndCommentText)); @@ -167,16 +167,16 @@ } } // namespace -const FormatToken * -getNamespaceToken(const AnnotatedLine *Line, - const SmallVectorImpl &AnnotatedLines) { +FormatToken const * +getNamespaceToken(AnnotatedLine const *Line, + SmallVectorImpl const &AnnotatedLines) { if (!Line->Affected || Line->InPPDirective || !Line->startsWith(tok::r_brace)) return nullptr; size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex; if (StartLineIndex == UnwrappedLine::kInvalidIndex) return nullptr; assert(StartLineIndex < AnnotatedLines.size()); - const FormatToken *NamespaceTok = AnnotatedLines[StartLineIndex]->First; + FormatToken const *NamespaceTok = AnnotatedLines[StartLineIndex]->First; if (NamespaceTok->is(tok::l_brace)) { // "namespace" keyword can be on the line preceding '{', e.g. in styles // where BraceWrapping.AfterNamespace is true. @@ -187,20 +187,20 @@ } StringRef -getNamespaceTokenText(const AnnotatedLine *Line, - const SmallVectorImpl &AnnotatedLines) { - const FormatToken *NamespaceTok = getNamespaceToken(Line, AnnotatedLines); +getNamespaceTokenText(AnnotatedLine const *Line, + SmallVectorImpl const &AnnotatedLines) { + FormatToken const *NamespaceTok = getNamespaceToken(Line, AnnotatedLines); return NamespaceTok ? NamespaceTok->TokenText : StringRef(); } -NamespaceEndCommentsFixer::NamespaceEndCommentsFixer(const Environment &Env, - const FormatStyle &Style) +NamespaceEndCommentsFixer::NamespaceEndCommentsFixer(Environment const &Env, + FormatStyle const &Style) : TokenAnalyzer(Env, Style) {} std::pair NamespaceEndCommentsFixer::analyze( TokenAnnotator &Annotator, SmallVectorImpl &AnnotatedLines, FormatTokenLexer &Tokens) { - const SourceManager &SourceMgr = Env.getSourceManager(); + SourceManager const &SourceMgr = Env.getSourceManager(); AffectedRangeMgr.computeAffectedLines(AnnotatedLines); tooling::Replacements Fixes; @@ -225,8 +225,8 @@ StringRef NamespaceTokenText; unsigned int CompactedNamespacesCount = 0; for (size_t I = 0, E = AnnotatedLines.size(); I != E; ++I) { - const AnnotatedLine *EndLine = AnnotatedLines[I]; - const FormatToken *NamespaceTok = + AnnotatedLine const *EndLine = AnnotatedLines[I]; + FormatToken const *NamespaceTok = getNamespaceToken(EndLine, AnnotatedLines); if (!NamespaceTok) continue; @@ -234,7 +234,7 @@ if (RBraceTok->Finalized) continue; RBraceTok->Finalized = true; - const FormatToken *EndCommentPrevTok = RBraceTok; + FormatToken const *EndCommentPrevTok = RBraceTok; // Namespaces often end with '};'. In that case, attach namespace end // comments to the semicolon tokens. if (RBraceTok->Next && RBraceTok->Next->is(tok::semi)) { @@ -267,7 +267,7 @@ // The next token in the token stream after the place where the end comment // token must be. This is either the next token on the current line or the // first token on the next line. - const FormatToken *EndCommentNextTok = EndCommentPrevTok->Next; + FormatToken const *EndCommentNextTok = EndCommentPrevTok->Next; if (EndCommentNextTok && EndCommentNextTok->is(tok::comment)) EndCommentNextTok = EndCommentNextTok->Next; if (!EndCommentNextTok && I + 1 < E) Index: clang/lib/Format/SortJavaScriptImports.h =================================================================== --- clang/lib/Format/SortJavaScriptImports.h +++ clang/lib/Format/SortJavaScriptImports.h @@ -24,7 +24,7 @@ // Sort JavaScript ES6 imports/exports in ``Code``. The generated replacements // only monotonically increase the length of the given code. -tooling::Replacements sortJavaScriptImports(const FormatStyle &Style, +tooling::Replacements sortJavaScriptImports(FormatStyle const &Style, StringRef Code, ArrayRef Ranges, StringRef FileName); Index: clang/lib/Format/SortJavaScriptImports.cpp =================================================================== --- clang/lib/Format/SortJavaScriptImports.cpp +++ clang/lib/Format/SortJavaScriptImports.cpp @@ -42,7 +42,7 @@ StringRef Alias; SourceRange Range; - bool operator==(const JsImportedSymbol &RHS) const { + bool operator==(JsImportedSymbol const &RHS) const { // Ignore Range for comparison, it is only used to stitch code together, // but imports at different code locations are still conceptually the same. return Symbol == RHS.Symbol && Alias == RHS.Alias; @@ -100,7 +100,7 @@ SourceRange Range; }; -bool operator<(const JsModuleReference &LHS, const JsModuleReference &RHS) { +bool operator<(JsModuleReference const &LHS, JsModuleReference const &RHS) { if (LHS.IsExport != RHS.IsExport) return LHS.IsExport < RHS.IsExport; if (LHS.Category != RHS.Category) @@ -128,7 +128,7 @@ // structure, making it messy to sort them using regular expressions. class JavaScriptImportSorter : public TokenAnalyzer { public: - JavaScriptImportSorter(const Environment &Env, const FormatStyle &Style) + JavaScriptImportSorter(Environment const &Env, FormatStyle const &Style) : TokenAnalyzer(Env, Style), FileContents(Env.getSourceManager().getBufferData(Env.getFileID())) {} @@ -139,7 +139,7 @@ tooling::Replacements Result; AffectedRangeMgr.computeAffectedLines(AnnotatedLines); - const AdditionalKeywords &Keywords = Tokens.getKeywords(); + AdditionalKeywords const &Keywords = Tokens.getKeywords(); SmallVector References; AnnotatedLine *FirstNonImportLine; std::tie(References, FirstNonImportLine) = @@ -239,7 +239,7 @@ } StringRef getSourceText(SourceLocation Begin, SourceLocation End) { - const SourceManager &SM = Env.getSourceManager(); + SourceManager const &SM = Env.getSourceManager(); return FileContents.substr(SM.getFileOffset(Begin), SM.getFileOffset(End) - SM.getFileOffset(Begin)); } @@ -249,12 +249,12 @@ // skips runs of "no-formatting" module references, and sorts/merges the // references that have formatting enabled in individual chunks. SmallVector - sortModuleReferences(const SmallVector &References) { + sortModuleReferences(SmallVector const &References) { // Sort module references. // Imports can have formatting disabled (FormattingOff), so the code below // skips runs of "no-formatting" module references, and sorts other // references per group. - const auto *Start = References.begin(); + auto const *Start = References.begin(); SmallVector ReferencesSorted; while (Start != References.end()) { while (Start != References.end() && Start->FormattingOff) { @@ -326,7 +326,7 @@ // E.g. `import {b, a} from 'x';` -> `import {a, b} from 'x';` SmallVector Symbols = Reference.Symbols; llvm::stable_sort( - Symbols, [&](const JsImportedSymbol &LHS, const JsImportedSymbol &RHS) { + Symbols, [&](JsImportedSymbol const &LHS, JsImportedSymbol const &RHS) { return LHS.Symbol.compare_insensitive(RHS.Symbol) < 0; }); if (!Reference.SymbolsMerged && Symbols == Reference.Symbols) { @@ -351,7 +351,7 @@ // and a pointer to the first "main code" line if that is adjacent to the // affected lines of module references, nullptr otherwise. std::pair, AnnotatedLine *> - parseModuleReferences(const AdditionalKeywords &Keywords, + parseModuleReferences(AdditionalKeywords const &Keywords, SmallVectorImpl &AnnotatedLines) { SmallVector References; SourceLocation Start; @@ -428,7 +428,7 @@ // Parses a JavaScript/ECMAScript 6 module reference. // See http://www.ecma-international.org/ecma-262/6.0/#sec-scripts-and-modules // for grammar EBNF (production ModuleItem). - bool parseModuleReference(const AdditionalKeywords &Keywords, + bool parseModuleReference(AdditionalKeywords const &Keywords, JsModuleReference &Reference) { if (!Current || !Current->isOneOf(Keywords.kw_import, tok::kw_export)) return false; @@ -468,14 +468,14 @@ return true; } - bool parseModuleBindings(const AdditionalKeywords &Keywords, + bool parseModuleBindings(AdditionalKeywords const &Keywords, JsModuleReference &Reference) { if (parseStarBinding(Keywords, Reference)) return true; return parseNamedBindings(Keywords, Reference); } - bool parseStarBinding(const AdditionalKeywords &Keywords, + bool parseStarBinding(AdditionalKeywords const &Keywords, JsModuleReference &Reference) { // * as prefix from '...'; if (Current->isNot(tok::star)) @@ -491,7 +491,7 @@ return true; } - bool parseNamedBindings(const AdditionalKeywords &Keywords, + bool parseNamedBindings(AdditionalKeywords const &Keywords, JsModuleReference &Reference) { // eat a potential "import X, " prefix. if (Current->is(tok::identifier)) { @@ -545,7 +545,7 @@ } }; -tooling::Replacements sortJavaScriptImports(const FormatStyle &Style, +tooling::Replacements sortJavaScriptImports(FormatStyle const &Style, StringRef Code, ArrayRef Ranges, StringRef FileName) { Index: clang/lib/Format/TokenAnalyzer.h =================================================================== --- clang/lib/Format/TokenAnalyzer.h +++ clang/lib/Format/TokenAnalyzer.h @@ -46,7 +46,7 @@ FileID getFileID() const { return ID; } - const SourceManager &getSourceManager() const { return SM; } + SourceManager const &getSourceManager() const { return SM; } ArrayRef getCharRanges() const { return CharRanges; } @@ -79,7 +79,7 @@ class TokenAnalyzer : public UnwrappedLineConsumer { public: - TokenAnalyzer(const Environment &Env, const FormatStyle &Style); + TokenAnalyzer(Environment const &Env, FormatStyle const &Style); std::pair process(); @@ -89,13 +89,13 @@ SmallVectorImpl &AnnotatedLines, FormatTokenLexer &Tokens) = 0; - void consumeUnwrappedLine(const UnwrappedLine &TheLine) override; + void consumeUnwrappedLine(UnwrappedLine const &TheLine) override; void finishRun() override; FormatStyle Style; // Stores Style, FileID and SourceManager etc. - const Environment &Env; + Environment const &Env; // AffectedRangeMgr stores ranges to be fixed. AffectedRangeManager AffectedRangeMgr; SmallVector, 2> UnwrappedLines; Index: clang/lib/Format/TokenAnalyzer.cpp =================================================================== --- clang/lib/Format/TokenAnalyzer.cpp +++ clang/lib/Format/TokenAnalyzer.cpp @@ -41,14 +41,14 @@ ID(VirtualSM->get().getMainFileID()), FirstStartColumn(FirstStartColumn), NextStartColumn(NextStartColumn), LastStartColumn(LastStartColumn) { SourceLocation StartOfFile = SM.getLocForStartOfFile(ID); - for (const tooling::Range &Range : Ranges) { + for (tooling::Range const &Range : Ranges) { SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset()); SourceLocation End = Start.getLocWithOffset(Range.getLength()); CharRanges.push_back(CharSourceRange::getCharRange(Start, End)); } } -TokenAnalyzer::TokenAnalyzer(const Environment &Env, const FormatStyle &Style) +TokenAnalyzer::TokenAnalyzer(Environment const &Env, FormatStyle const &Style) : Style(Style), Env(Env), AffectedRangeMgr(Env.getSourceManager(), Env.getCharRanges()), UnwrappedLines(1), @@ -103,7 +103,7 @@ } Penalty += RunResult.second; - for (const auto &R : RunResult.first) { + for (auto const &R : RunResult.first) { auto Err = Result.add(R); // FIXME: better error handling here. For now, simply return an empty // Replacements to indicate failure. @@ -116,7 +116,7 @@ return {Result, Penalty}; } -void TokenAnalyzer::consumeUnwrappedLine(const UnwrappedLine &TheLine) { +void TokenAnalyzer::consumeUnwrappedLine(UnwrappedLine const &TheLine) { assert(!UnwrappedLines.empty()); UnwrappedLines.back().push_back(TheLine); } Index: clang/lib/Format/TokenAnnotator.h =================================================================== --- clang/lib/Format/TokenAnnotator.h +++ clang/lib/Format/TokenAnnotator.h @@ -37,7 +37,7 @@ class AnnotatedLine { public: - AnnotatedLine(const UnwrappedLine &Line) + AnnotatedLine(UnwrappedLine const &Line) : First(Line.Tokens.front().Tok), Level(Line.Level), MatchingOpeningBlockLineIndex(Line.MatchingOpeningBlockLineIndex), MatchingClosingBlockLineIndex(Line.MatchingClosingBlockLineIndex), @@ -56,12 +56,12 @@ for (std::list::const_iterator I = ++Line.Tokens.begin(), E = Line.Tokens.end(); I != E; ++I) { - const UnwrappedLineNode &Node = *I; + UnwrappedLineNode const &Node = *I; Current->Next = I->Tok; I->Tok->Previous = Current; Current = Current->Next; Current->Children.clear(); - for (const auto &Child : Node.Children) { + for (auto const &Child : Node.Children) { Children.push_back(new AnnotatedLine(Child)); Current->Children.push_back(Children.back()); } @@ -149,15 +149,15 @@ private: // Disallow copying. - AnnotatedLine(const AnnotatedLine &) = delete; - void operator=(const AnnotatedLine &) = delete; + AnnotatedLine(AnnotatedLine const &) = delete; + void operator=(AnnotatedLine const &) = delete; }; /// Determines extra information about the tokens comprising an /// \c UnwrappedLine. class TokenAnnotator { public: - TokenAnnotator(const FormatStyle &Style, const AdditionalKeywords &Keywords) + TokenAnnotator(FormatStyle const &Style, AdditionalKeywords const &Keywords) : Style(Style), Keywords(Keywords) {} /// Adapts the indent levels of comment lines to the indent of the @@ -170,23 +170,23 @@ private: /// Calculate the penalty for splitting before \c Tok. - unsigned splitPenalty(const AnnotatedLine &Line, const FormatToken &Tok, + unsigned splitPenalty(AnnotatedLine const &Line, FormatToken const &Tok, bool InFunctionDecl); - bool spaceRequiredBeforeParens(const FormatToken &Right) const; + bool spaceRequiredBeforeParens(FormatToken const &Right) const; - bool spaceRequiredBetween(const AnnotatedLine &Line, const FormatToken &Left, - const FormatToken &Right); + bool spaceRequiredBetween(AnnotatedLine const &Line, FormatToken const &Left, + FormatToken const &Right); - bool spaceRequiredBefore(const AnnotatedLine &Line, const FormatToken &Right); + bool spaceRequiredBefore(AnnotatedLine const &Line, FormatToken const &Right); - bool mustBreakBefore(const AnnotatedLine &Line, const FormatToken &Right); + bool mustBreakBefore(AnnotatedLine const &Line, FormatToken const &Right); - bool canBreakBefore(const AnnotatedLine &Line, const FormatToken &Right); + bool canBreakBefore(AnnotatedLine const &Line, FormatToken const &Right); - bool mustBreakForReturnType(const AnnotatedLine &Line) const; + bool mustBreakForReturnType(AnnotatedLine const &Line) const; - void printDebugInfo(const AnnotatedLine &Line); + void printDebugInfo(AnnotatedLine const &Line); void calculateUnbreakableTailLengths(AnnotatedLine &Line); @@ -196,14 +196,14 @@ FormatToken *CurrentToken, unsigned Depth); FormatStyle::PointerAlignmentStyle - getTokenReferenceAlignment(const FormatToken &PointerOrReference); + getTokenReferenceAlignment(FormatToken const &PointerOrReference); FormatStyle::PointerAlignmentStyle - getTokenPointerOrReferenceAlignment(const FormatToken &PointerOrReference); + getTokenPointerOrReferenceAlignment(FormatToken const &PointerOrReference); - const FormatStyle &Style; + FormatStyle const &Style; - const AdditionalKeywords &Keywords; + AdditionalKeywords const &Keywords; }; } // end namespace format Index: clang/lib/Format/TokenAnnotator.cpp =================================================================== --- clang/lib/Format/TokenAnnotator.cpp +++ clang/lib/Format/TokenAnnotator.cpp @@ -37,13 +37,13 @@ /// are valid inside @selector(...) (or a macro which /// invokes @selector(...)). So, we allow treat any identifier or /// keyword as a potential Objective-C selector component. -static bool canBeObjCSelectorComponent(const FormatToken &Tok) { +static bool canBeObjCSelectorComponent(FormatToken const &Tok) { return Tok.Tok.getIdentifierInfo() != nullptr; } /// With `Left` being '(', check if we're at either `[...](` or /// `[...]<...>(`, where the [ opens a lambda capture list. -static bool isLambdaParameterList(const FormatToken *Left) { +static bool isLambdaParameterList(FormatToken const *Left) { // Skip <...> if present. if (Left->Previous && Left->Previous->is(tok::greater) && Left->Previous->MatchingParen && @@ -58,7 +58,7 @@ /// Returns \c true if the token is followed by a boolean condition, \c false /// otherwise. -static bool isKeywordWithCondition(const FormatToken &Tok) { +static bool isKeywordWithCondition(FormatToken const &Tok) { return Tok.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while, tok::kw_switch, tok::kw_constexpr, tok::kw_catch); } @@ -70,8 +70,8 @@ /// into template parameter lists. class AnnotatingParser { public: - AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line, - const AdditionalKeywords &Keywords) + AnnotatingParser(FormatStyle const &Style, AnnotatedLine &Line, + AdditionalKeywords const &Keywords) : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false), Keywords(Keywords) { Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false)); @@ -85,7 +85,7 @@ if (NonTemplateLess.count(CurrentToken->Previous)) return false; - const FormatToken &Previous = *CurrentToken->Previous; // The '<'. + FormatToken const &Previous = *CurrentToken->Previous; // The '<'. if (Previous.Previous) { if (Previous.Previous->Tok.isLiteral()) return false; @@ -443,7 +443,7 @@ return false; } - bool isCSharpAttributeSpecifier(const FormatToken &Tok) { + bool isCSharpAttributeSpecifier(FormatToken const &Tok) { if (!Style.isCSharp()) return false; @@ -458,7 +458,7 @@ return false; } - const FormatToken *AttrTok = Tok.Next; + FormatToken const *AttrTok = Tok.Next; if (!AttrTok) return false; @@ -494,14 +494,14 @@ return false; } - bool isCpp11AttributeSpecifier(const FormatToken &Tok) { + bool isCpp11AttributeSpecifier(FormatToken const &Tok) { if (!Style.isCpp() || !Tok.startsSequence(tok::l_square, tok::l_square)) return false; // The first square bracket is part of an ObjC array literal if (Tok.Previous && Tok.Previous->is(tok::at)) { return false; } - const FormatToken *AttrTok = Tok.Next->Next; + FormatToken const *AttrTok = Tok.Next->Next; if (!AttrTok) return false; // C++17 '[[using ns: foo, bar(baz, blech)]]' @@ -750,7 +750,7 @@ return false; // We want to back up no more then 2 context levels i.e. // . { { <- - const auto End = std::next(Contexts.rbegin(), 2); + auto const End = std::next(Contexts.rbegin(), 2); auto Last = Contexts.rbegin(); unsigned Depth = 0; for (; Last != End; ++Last) { @@ -913,7 +913,7 @@ } else if (Contexts.back().ColonIsObjCMethodExpr || Line.startsWith(TT_ObjCMethodSpecifier)) { Tok->setType(TT_ObjCMethodExpr); - const FormatToken *BeforePrevious = Tok->Previous->Previous; + FormatToken const *BeforePrevious = Tok->Previous->Previous; // Ensure we tag all identifiers in method declarations as // TT_SelectorName. bool UnknownIdentifierInMethodDeclaration = @@ -1379,7 +1379,7 @@ return LT_ObjCMethodDecl; } - for (const auto &ctx : Contexts) { + for (auto const &ctx : Contexts) { if (ctx.InStructArrayInitializer) { return LT_ArrayOfStructInitializer; } @@ -1389,7 +1389,7 @@ } private: - bool isClosureImportStatement(const FormatToken &Tok) { + bool isClosureImportStatement(FormatToken const &Tok) { // FIXME: Closure-library specific stuff should not be hard-coded but be // configurable. return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) && @@ -1488,7 +1488,7 @@ } }; - void modifyContext(const FormatToken &Current) { + void modifyContext(FormatToken const &Current) { if (Current.getPrecedence() == prec::Assignment && !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) && // Type aliases use `type X = ...;` in TypeScript and can be exported @@ -1787,8 +1787,8 @@ Current.Previous) { if (Current.Previous->is(tok::at) && Current.isNot(Keywords.kw_interface)) { - const FormatToken &AtToken = *Current.Previous; - const FormatToken *Previous = AtToken.getPreviousNonComment(); + FormatToken const &AtToken = *Current.Previous; + FormatToken const *Previous = AtToken.getPreviousNonComment(); if (!Previous || Previous->is(TT_LeadingJavaAnnotation)) Current.setType(TT_LeadingJavaAnnotation); else @@ -1806,7 +1806,7 @@ /// /// This is a heuristic based on whether \p Tok is an identifier following /// something that is likely a type. - bool isStartOfName(const FormatToken &Tok) { + bool isStartOfName(FormatToken const &Tok) { if (Tok.isNot(tok::identifier) || !Tok.Previous) return false; @@ -1846,7 +1846,7 @@ } /// Determine whether ')' is ending a cast. - bool rParenEndsCast(const FormatToken &Tok) { + bool rParenEndsCast(FormatToken const &Tok) { // C-style casts are only used in C++, C# and Java. if (!Style.isCSharp() && !Style.isCpp() && Style.Language != FormatStyle::LK_Java) @@ -1953,7 +1953,7 @@ // Certain token types inside the parentheses mean that this can't be a // cast. - for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok; + for (FormatToken const *Token = Tok.MatchingParen->Next; Token != &Tok; Token = Token->Next) if (Token->is(TT_BinaryOperator)) return false; @@ -1991,7 +1991,7 @@ } /// Return the type of the given token assuming it is * or &. - TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression, + TokenType determineStarAmpUsage(FormatToken const &Tok, bool IsExpression, bool InTemplateArgument) { if (Style.Language == FormatStyle::LK_JavaScript) return TT_BinaryOperator; @@ -2000,11 +2000,11 @@ if (Style.isCSharp() && Tok.is(tok::ampamp)) return TT_BinaryOperator; - const FormatToken *PrevToken = Tok.getPreviousNonComment(); + FormatToken const *PrevToken = Tok.getPreviousNonComment(); if (!PrevToken) return TT_UnaryOperator; - const FormatToken *NextToken = Tok.getNextNonComment(); + FormatToken const *NextToken = Tok.getNextNonComment(); if (!NextToken || NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_noexcept) || NextToken->canBePointerOrReferenceQualifier() || @@ -2052,7 +2052,7 @@ // This catches some cases where evaluation order is used as control flow: // aaa && aaa->f(); if (NextToken->Tok.isAnyIdentifier()) { - const FormatToken *NextNextToken = NextToken->getNextNonComment(); + FormatToken const *NextNextToken = NextToken->getNextNonComment(); if (NextNextToken && NextNextToken->is(tok::arrow)) return TT_BinaryOperator; } @@ -2065,8 +2065,8 @@ return TT_PointerOrReference; } - TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) { - const FormatToken *PrevToken = Tok.getPreviousNonComment(); + TokenType determinePlusMinusCaretUsage(FormatToken const &Tok) { + FormatToken const *PrevToken = Tok.getPreviousNonComment(); if (!PrevToken) return TT_UnaryOperator; @@ -2090,8 +2090,8 @@ } /// Determine whether ++/-- are pre- or post-increments/-decrements. - TokenType determineIncrementUsage(const FormatToken &Tok) { - const FormatToken *PrevToken = Tok.getPreviousNonComment(); + TokenType determineIncrementUsage(FormatToken const &Tok) { + FormatToken const *PrevToken = Tok.getPreviousNonComment(); if (!PrevToken || PrevToken->is(TT_CastRParen)) return TT_UnaryOperator; if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier)) @@ -2102,11 +2102,11 @@ SmallVector Contexts; - const FormatStyle &Style; + FormatStyle const &Style; AnnotatedLine &Line; FormatToken *CurrentToken; bool AutoFound; - const AdditionalKeywords &Keywords; + AdditionalKeywords const &Keywords; // Set of "<" tokens that do not open a template parameter list. If parseAngle // determines that a specific token can't be a template opener, it will make @@ -2115,14 +2115,14 @@ llvm::SmallPtrSet NonTemplateLess; }; -static const int PrecedenceUnaryOperator = prec::PointerToMember + 1; -static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2; +static int const PrecedenceUnaryOperator = prec::PointerToMember + 1; +static int const PrecedenceArrowAndPeriod = prec::PointerToMember + 2; /// Parses binary expressions by inserting fake parenthesis based on /// operator precedence. class ExpressionParser { public: - ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords, + ExpressionParser(FormatStyle const &Style, AdditionalKeywords const &Keywords, AnnotatedLine &Line) : Style(Style), Keywords(Keywords), Current(Line.First) {} @@ -2217,7 +2217,7 @@ /// and other tokens that we treat like binary operators. int getCurrentPrecedence() { if (Current) { - const FormatToken *NextNonComment = Current->getNextNonComment(); + FormatToken const *NextNonComment = Current->getNextNonComment(); if (Current->is(TT_ConditionalExpr)) return prec::Conditional; if (NextNonComment && Current->is(TT_SelectorName) && @@ -2312,8 +2312,8 @@ Current = Current->Next; } - const FormatStyle &Style; - const AdditionalKeywords &Keywords; + FormatStyle const &Style; + AdditionalKeywords const &Keywords; FormatToken *Current; }; @@ -2321,12 +2321,12 @@ void TokenAnnotator::setCommentLineLevels( SmallVectorImpl &Lines) { - const AnnotatedLine *NextNonCommentLine = nullptr; + AnnotatedLine const *NextNonCommentLine = nullptr; for (SmallVectorImpl::reverse_iterator I = Lines.rbegin(), E = Lines.rend(); I != E; ++I) { bool CommentLine = true; - for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) { + for (FormatToken const *Tok = (*I)->First; Tok; Tok = Tok->Next) { if (!Tok->is(tok::comment)) { CommentLine = false; break; @@ -2356,9 +2356,9 @@ } } -static unsigned maxNestingDepth(const AnnotatedLine &Line) { +static unsigned maxNestingDepth(AnnotatedLine const &Line) { unsigned Result = 0; - for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) + for (auto const *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) Result = std::max(Result, Tok->NestingLevel); return Result; } @@ -2398,9 +2398,9 @@ // This function heuristically determines whether 'Current' starts the name of a // function declaration. -static bool isFunctionDeclarationName(const FormatToken &Current, - const AnnotatedLine &Line) { - auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * { +static bool isFunctionDeclarationName(FormatToken const &Current, + AnnotatedLine const &Line) { + auto skipOperatorName = [](FormatToken const *Next) -> FormatToken const * { for (; Next; Next = Next->Next) { if (Next->is(TT_OverloadedOperatorLParen)) return Next; @@ -2435,7 +2435,7 @@ }; // Find parentheses of parameter list. - const FormatToken *Next = Current.Next; + FormatToken const *Next = Current.Next; if (Current.is(tok::kw_operator)) { if (Current.Previous && Current.Previous->is(tok::coloncolon)) return false; @@ -2476,7 +2476,7 @@ if (Next->MatchingParen->Next && Next->MatchingParen->Next->is(TT_PointerOrReference)) return true; - for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen; + for (FormatToken const *Tok = Next->Next; Tok && Tok != Next->MatchingParen; Tok = Tok->Next) { if (Tok->is(TT_TypeDeclarationParen)) return true; @@ -2494,7 +2494,7 @@ return false; } -bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const { +bool TokenAnnotator::mustBreakForReturnType(AnnotatedLine const &Line) const { assert(Line.MightBeFunctionDecl); if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel || @@ -2586,7 +2586,7 @@ ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit : LastOfChild.TotalLength + 1; } - const FormatToken *Prev = Current->Previous; + FormatToken const *Prev = Current->Previous; if (Current->MustBreakBefore || Prev->Children.size() > 1 || (Prev->Children.size() == 1 && Prev->Children[0]->First->MustBreakBefore) || @@ -2693,11 +2693,11 @@ return CurrentToken; } -unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line, - const FormatToken &Tok, +unsigned TokenAnnotator::splitPenalty(AnnotatedLine const &Line, + FormatToken const &Tok, bool InFunctionDecl) { - const FormatToken &Left = *Tok.Previous; - const FormatToken &Right = Tok; + FormatToken const &Left = *Tok.Previous; + FormatToken const &Right = Tok; if (Left.is(tok::semi)) return 0; @@ -2889,15 +2889,15 @@ return 3; } -bool TokenAnnotator::spaceRequiredBeforeParens(const FormatToken &Right) const { +bool TokenAnnotator::spaceRequiredBeforeParens(FormatToken const &Right) const { return Style.SpaceBeforeParens == FormatStyle::SBPO_Always || (Style.SpaceBeforeParens == FormatStyle::SBPO_NonEmptyParentheses && Right.ParameterCount > 0); } -bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line, - const FormatToken &Left, - const FormatToken &Right) { +bool TokenAnnotator::spaceRequiredBetween(AnnotatedLine const &Line, + FormatToken const &Left, + FormatToken const &Right) { if (Left.is(tok::kw_return) && Right.isNot(tok::semi)) return true; if (Style.isJson() && Left.is(tok::string_literal) && Right.is(tok::colon)) @@ -3033,7 +3033,7 @@ if (Left.is(tok::star) && Right.isOneOf(tok::star, tok::amp, tok::ampamp)) return false; if (Right.isOneOf(tok::star, tok::amp, tok::ampamp)) { - const FormatToken *Previous = &Left; + FormatToken const *Previous = &Left; while (Previous && !Previous->is(tok::kw_operator)) { if (Previous->is(tok::identifier) || Previous->isSimpleTypeSpecifier()) { Previous = Previous->getPreviousNonComment(); @@ -3071,8 +3071,8 @@ (Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both); } } - const auto SpaceRequiredForArrayInitializerLSquare = - [](const FormatToken &LSquareTok, const FormatStyle &Style) { + auto const SpaceRequiredForArrayInitializerLSquare = + [](FormatToken const &LSquareTok, FormatStyle const &Style) { return Style.SpacesInContainerLiterals || ((Style.Language == FormatStyle::LK_Proto || Style.Language == FormatStyle::LK_TextProto) && @@ -3190,9 +3190,9 @@ return true; } -bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, - const FormatToken &Right) { - const FormatToken &Left = *Right.Previous; +bool TokenAnnotator::spaceRequiredBefore(AnnotatedLine const &Line, + FormatToken const &Right) { + FormatToken const &Left = *Right.Previous; auto HasExistingWhitespace = [&Right]() { return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd(); }; @@ -3313,7 +3313,7 @@ return true; if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) && Right.MatchingParen) { - const FormatToken *Next = Right.MatchingParen->getNextNonComment(); + FormatToken const *Next = Right.MatchingParen->getNextNonComment(); // An async arrow function, for example: `x = async () => foo();`, // as opposed to calling a function called async: `x = async();` if (Next && Next->is(TT_FatArrow)) @@ -3567,31 +3567,31 @@ } // Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style. -static bool isAllmanBrace(const FormatToken &Tok) { +static bool isAllmanBrace(FormatToken const &Tok) { return Tok.is(tok::l_brace) && Tok.is(BK_Block) && !Tok.isOneOf(TT_ObjCBlockLBrace, TT_LambdaLBrace, TT_DictLiteral); } // Returns 'true' if 'Tok' is an function argument. -static bool IsFunctionArgument(const FormatToken &Tok) { +static bool IsFunctionArgument(FormatToken const &Tok) { return Tok.MatchingParen && Tok.MatchingParen->Next && Tok.MatchingParen->Next->isOneOf(tok::comma, tok::r_paren); } static bool -isItAnEmptyLambdaAllowed(const FormatToken &Tok, +isItAnEmptyLambdaAllowed(FormatToken const &Tok, FormatStyle::ShortLambdaStyle ShortLambdaOption) { return Tok.Children.empty() && ShortLambdaOption != FormatStyle::SLS_None; } -static bool isAllmanLambdaBrace(const FormatToken &Tok) { +static bool isAllmanLambdaBrace(FormatToken const &Tok) { return (Tok.is(tok::l_brace) && Tok.is(BK_Block) && !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral)); } -bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line, - const FormatToken &Right) { - const FormatToken &Left = *Right.Previous; +bool TokenAnnotator::mustBreakBefore(AnnotatedLine const &Line, + FormatToken const &Right) { + FormatToken const &Left = *Right.Previous; if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0) return true; @@ -3700,7 +3700,7 @@ // shuffling around entries easier. Import statements, especially in // JavaScript, can be an exception to this rule. if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) { - const FormatToken *BeforeClosingBrace = nullptr; + FormatToken const *BeforeClosingBrace = nullptr; if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || (Style.Language == FormatStyle::LK_JavaScript && Left.is(tok::l_paren))) && @@ -3920,9 +3920,9 @@ return false; } -bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line, - const FormatToken &Right) { - const FormatToken &Left = *Right.Previous; +bool TokenAnnotator::canBreakBefore(AnnotatedLine const &Line, + FormatToken const &Right) { + FormatToken const &Left = *Right.Previous; // Language-specific stuff. if (Style.isCSharp()) { if (Left.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon) || @@ -3943,7 +3943,7 @@ Keywords.kw_implements)) return true; } else if (Style.Language == FormatStyle::LK_JavaScript) { - const FormatToken *NonComment = Right.getPreviousNonComment(); + FormatToken const *NonComment = Right.getPreviousNonComment(); if (NonComment && NonComment->isOneOf( tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break, @@ -3971,7 +3971,7 @@ // function f(): a is B { ... } // Do not break before is in these cases. if (Right.is(Keywords.kw_is)) { - const FormatToken *Next = Right.getNextNonComment(); + FormatToken const *Next = Right.getNextNonComment(); // If `is` is followed by a colon, it's likely that it's a dict key, so // ignore it for this check. // For example this is common in Polymer: @@ -4219,9 +4219,9 @@ (Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser)); } -void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) { +void TokenAnnotator::printDebugInfo(AnnotatedLine const &Line) { llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n"; - const FormatToken *Tok = Line.First; + FormatToken const *Tok = Line.First; while (Tok) { llvm::errs() << " M=" << Tok->MustBreakBefore << " C=" << Tok->CanBreakBefore @@ -4244,7 +4244,7 @@ } FormatStyle::PointerAlignmentStyle -TokenAnnotator::getTokenReferenceAlignment(const FormatToken &Reference) { +TokenAnnotator::getTokenReferenceAlignment(FormatToken const &Reference) { assert(Reference.isOneOf(tok::amp, tok::ampamp)); switch (Style.ReferenceAlignment) { case FormatStyle::RAS_Pointer: @@ -4262,7 +4262,7 @@ FormatStyle::PointerAlignmentStyle TokenAnnotator::getTokenPointerOrReferenceAlignment( - const FormatToken &PointerOrReference) { + FormatToken const &PointerOrReference) { if (PointerOrReference.isOneOf(tok::amp, tok::ampamp)) { switch (Style.ReferenceAlignment) { case FormatStyle::RAS_Pointer: Index: clang/lib/Format/UnwrappedLineFormatter.h =================================================================== --- clang/lib/Format/UnwrappedLineFormatter.h +++ clang/lib/Format/UnwrappedLineFormatter.h @@ -29,15 +29,15 @@ public: UnwrappedLineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces, - const FormatStyle &Style, - const AdditionalKeywords &Keywords, - const SourceManager &SourceMgr, + FormatStyle const &Style, + AdditionalKeywords const &Keywords, + SourceManager const &SourceMgr, FormattingAttemptStatus *Status) : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style), Keywords(Keywords), SourceMgr(SourceMgr), Status(Status) {} /// Format the current block and return the penalty. - unsigned format(const SmallVectorImpl &Lines, + unsigned format(SmallVectorImpl const &Lines, bool DryRun = false, int AdditionalIndent = 0, bool FixBadIndentation = false, unsigned FirstStartColumn = 0, unsigned NextStartColumn = 0, unsigned LastStartColumn = 0); @@ -45,29 +45,29 @@ private: /// Add a new line and the required indent before the first Token /// of the \c UnwrappedLine if there was no structural parsing error. - void formatFirstToken(const AnnotatedLine &Line, - const AnnotatedLine *PreviousLine, - const AnnotatedLine *PrevPrevLine, - const SmallVectorImpl &Lines, + void formatFirstToken(AnnotatedLine const &Line, + AnnotatedLine const *PreviousLine, + AnnotatedLine const *PrevPrevLine, + SmallVectorImpl const &Lines, unsigned Indent, unsigned NewlineIndent); /// Returns the column limit for a line, taking into account whether we /// need an escaped newline due to a continued preprocessor directive. unsigned getColumnLimit(bool InPPDirective, - const AnnotatedLine *NextLine) const; + AnnotatedLine const *NextLine) const; // Cache to store the penalty of formatting a vector of AnnotatedLines // starting from a specific additional offset. Improves performance if there // are many nested blocks. - std::map *, unsigned>, + std::map const *, unsigned>, unsigned> PenaltyCache; ContinuationIndenter *Indenter; WhitespaceManager *Whitespaces; - const FormatStyle &Style; - const AdditionalKeywords &Keywords; - const SourceManager &SourceMgr; + FormatStyle const &Style; + AdditionalKeywords const &Keywords; + SourceManager const &SourceMgr; FormattingAttemptStatus *Status; }; } // end namespace format Index: clang/lib/Format/UnwrappedLineFormatter.cpp =================================================================== --- clang/lib/Format/UnwrappedLineFormatter.cpp +++ clang/lib/Format/UnwrappedLineFormatter.cpp @@ -19,9 +19,9 @@ namespace { -bool startsExternCBlock(const AnnotatedLine &Line) { - const FormatToken *Next = Line.First->getNextNonComment(); - const FormatToken *NextNext = Next ? Next->getNextNonComment() : nullptr; +bool startsExternCBlock(AnnotatedLine const &Line) { + FormatToken const *Next = Line.First->getNextNonComment(); + FormatToken const *NextNext = Next ? Next->getNextNonComment() : nullptr; return Line.startsWith(tok::kw_extern) && Next && Next->isStringLiteral() && NextNext && NextNext->is(tok::l_brace); } @@ -37,8 +37,8 @@ /// given line. class LevelIndentTracker { public: - LevelIndentTracker(const FormatStyle &Style, - const AdditionalKeywords &Keywords, unsigned StartLevel, + LevelIndentTracker(FormatStyle const &Style, + AdditionalKeywords const &Keywords, unsigned StartLevel, int AdditionalIndent) : Style(Style), Keywords(Keywords), AdditionalIndent(AdditionalIndent) { for (unsigned i = 0; i != StartLevel; ++i) @@ -50,7 +50,7 @@ /// Update the indent state given that \p Line is going to be formatted /// next. - void nextLine(const AnnotatedLine &Line) { + void nextLine(AnnotatedLine const &Line) { Offset = getIndentOffset(*Line.First); // Update the indent level cache size so that we can rely on it // having the right size in adjustToUnmodifiedline. @@ -72,7 +72,7 @@ /// Update the indent state given that \p Line indent should be /// skipped. - void skipLine(const AnnotatedLine &Line) { + void skipLine(AnnotatedLine const &Line) { while (IndentForLevel.size() <= Line.Level) IndentForLevel.push_back(Indent); } @@ -82,7 +82,7 @@ /// When a line is not formatted, we move the subsequent lines on the same /// level to the same indent. /// Note that \c nextLine must have been called before this method. - void adjustToUnmodifiedLine(const AnnotatedLine &Line) { + void adjustToUnmodifiedLine(AnnotatedLine const &Line) { unsigned LevelIndent = Line.First->OriginalColumn; if (static_cast(LevelIndent) - Offset >= 0) LevelIndent -= Offset; @@ -96,7 +96,7 @@ /// /// For example, 'public:' labels in classes are offset by 1 or 2 /// characters to the left from their level. - int getIndentOffset(const FormatToken &RootToken) { + int getIndentOffset(FormatToken const &RootToken) { if (Style.Language == FormatStyle::LK_Java || Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp()) return 0; @@ -126,9 +126,9 @@ return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth; } - const FormatStyle &Style; - const AdditionalKeywords &Keywords; - const unsigned AdditionalIndent; + FormatStyle const &Style; + AdditionalKeywords const &Keywords; + unsigned const AdditionalIndent; /// The indent in characters for each level. std::vector IndentForLevel; @@ -143,9 +143,9 @@ unsigned Indent = 0; }; -const FormatToken *getMatchingNamespaceToken( - const AnnotatedLine *Line, - const SmallVectorImpl &AnnotatedLines) { +FormatToken const *getMatchingNamespaceToken( + AnnotatedLine const *Line, + SmallVectorImpl const &AnnotatedLines) { if (!Line->startsWith(tok::r_brace)) return nullptr; size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex; @@ -155,32 +155,32 @@ return AnnotatedLines[StartLineIndex]->First->getNamespaceToken(); } -StringRef getNamespaceTokenText(const AnnotatedLine *Line) { - const FormatToken *NamespaceToken = Line->First->getNamespaceToken(); +StringRef getNamespaceTokenText(AnnotatedLine const *Line) { + FormatToken const *NamespaceToken = Line->First->getNamespaceToken(); return NamespaceToken ? NamespaceToken->TokenText : StringRef(); } StringRef getMatchingNamespaceTokenText( - const AnnotatedLine *Line, - const SmallVectorImpl &AnnotatedLines) { - const FormatToken *NamespaceToken = + AnnotatedLine const *Line, + SmallVectorImpl const &AnnotatedLines) { + FormatToken const *NamespaceToken = getMatchingNamespaceToken(Line, AnnotatedLines); return NamespaceToken ? NamespaceToken->TokenText : StringRef(); } class LineJoiner { public: - LineJoiner(const FormatStyle &Style, const AdditionalKeywords &Keywords, - const SmallVectorImpl &Lines) + LineJoiner(FormatStyle const &Style, AdditionalKeywords const &Keywords, + SmallVectorImpl const &Lines) : Style(Style), Keywords(Keywords), End(Lines.end()), Next(Lines.begin()), AnnotatedLines(Lines) {} /// Returns the next line, merging multiple lines into one if possible. - const AnnotatedLine *getNextMergedLine(bool DryRun, + AnnotatedLine const *getNextMergedLine(bool DryRun, LevelIndentTracker &IndentTracker) { if (Next == End) return nullptr; - const AnnotatedLine *Current = *Next; + AnnotatedLine const *Current = *Next; IndentTracker.nextLine(*Current); unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End); if (MergedLines > 0 && Style.ColumnLimit == 0) @@ -202,13 +202,13 @@ tryFitMultipleLinesInOne(LevelIndentTracker &IndentTracker, SmallVectorImpl::const_iterator I, SmallVectorImpl::const_iterator E) { - const unsigned Indent = IndentTracker.getIndent(); + unsigned const Indent = IndentTracker.getIndent(); // Can't join the last line with anything. if (I + 1 == E) return 0; // We can never merge stuff if there are trailing line comments. - const AnnotatedLine *TheLine = *I; + AnnotatedLine const *TheLine = *I; if (TheLine->Last->is(TT_LineComment)) return 0; if (I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore) @@ -239,7 +239,7 @@ I != AnnotatedLines.begin()) { bool EmptyBlock = I[1]->First->is(tok::r_brace); - const FormatToken *Tok = I[-1]->First; + FormatToken const *Tok = I[-1]->First; if (Tok && Tok->is(tok::comment)) Tok = Tok->getNextNonComment(); @@ -373,7 +373,7 @@ if (Style.BraceWrapping.SplitEmptyRecord && TheLine->Last->is(tok::l_brace) && I != AnnotatedLines.begin() && I[-1]->Last) { - const FormatToken *Previous = I[-1]->Last; + FormatToken const *Previous = I[-1]->Last; if (Previous) { if (Previous->is(tok::comment)) Previous = Previous->getPreviousNonComment(); @@ -381,7 +381,7 @@ if (Previous->is(tok::greater) && !I[-1]->InPPDirective) return 0; if (Previous->is(tok::identifier)) { - const FormatToken *PreviousPrevious = + FormatToken const *PreviousPrevious = Previous->getPreviousNonComment(); if (PreviousPrevious && PreviousPrevious->isOneOf(tok::kw_class, tok::kw_struct)) @@ -517,11 +517,11 @@ unsigned Length = 0; bool EndsWithComment = false; bool InPPDirective = I[0]->InPPDirective; - const unsigned Level = I[0]->Level; + unsigned const Level = I[0]->Level; for (; NumStmts < 3; ++NumStmts) { if (I + 1 + NumStmts == E) break; - const AnnotatedLine *Line = I[1 + NumStmts]; + AnnotatedLine const *Line = I[1 + NumStmts]; if (Line->InPPDirective != InPPDirective) break; if (Line->First->isOneOf(tok::kw_case, tok::kw_default, tok::r_brace)) @@ -574,7 +574,7 @@ return 0; // default: in switch statement if (Line.First->is(tok::kw_default)) { - const FormatToken *Tok = Line.First->getNextNonComment(); + FormatToken const *Tok = Line.First->getNextNonComment(); if (Tok && Tok->is(tok::colon)) return 0; } @@ -725,15 +725,15 @@ return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit; } - bool containsMustBreak(const AnnotatedLine *Line) { - for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) { + bool containsMustBreak(AnnotatedLine const *Line) { + for (FormatToken const *Tok = Line->First; Tok; Tok = Tok->Next) { if (Tok->MustBreakBefore) return true; } return false; } - void join(AnnotatedLine &A, const AnnotatedLine &B) { + void join(AnnotatedLine &A, AnnotatedLine const &B) { assert(!A.Last->Next); assert(!B.First->Previous); if (B.Affected) @@ -748,12 +748,12 @@ } } - const FormatStyle &Style; - const AdditionalKeywords &Keywords; - const SmallVectorImpl::const_iterator End; + FormatStyle const &Style; + AdditionalKeywords const &Keywords; + SmallVectorImpl::const_iterator const End; SmallVectorImpl::const_iterator Next; - const SmallVectorImpl &AnnotatedLines; + SmallVectorImpl const &AnnotatedLines; }; static void markFinalized(FormatToken *Tok) { @@ -765,9 +765,9 @@ } #ifndef NDEBUG -static void printLineState(const LineState &State) { +static void printLineState(LineState const &State) { llvm::dbgs() << "State: "; - for (const ParenState &P : State.Stack) { + for (ParenState const &P : State.Stack) { llvm::dbgs() << (P.Tok ? P.Tok->TokenText : "F") << "|" << P.Indent << "|" << P.LastSpace << "|" << P.NestedBlockIndent << " "; } @@ -779,7 +779,7 @@ class LineFormatter { public: LineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces, - const FormatStyle &Style, + FormatStyle const &Style, UnwrappedLineFormatter *BlockFormatter) : Indenter(Indenter), Whitespaces(Whitespaces), Style(Style), BlockFormatter(BlockFormatter) {} @@ -788,7 +788,7 @@ /// Formats an \c AnnotatedLine and returns the penalty. /// /// If \p DryRun is \c false, directly applies the changes. - virtual unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, + virtual unsigned formatLine(AnnotatedLine const &Line, unsigned FirstIndent, unsigned FirstStartColumn, bool DryRun) = 0; protected: @@ -814,7 +814,7 @@ /// break or don't break. bool formatChildren(LineState &State, bool NewLine, bool DryRun, unsigned &Penalty) { - const FormatToken *LBrace = State.NextToken->getPreviousNonComment(); + FormatToken const *LBrace = State.NextToken->getPreviousNonComment(); FormatToken &Previous = *State.NextToken->Previous; if (!LBrace || LBrace->isNot(tok::l_brace) || LBrace->isNot(BK_Block) || Previous.Children.size() == 0) @@ -823,7 +823,7 @@ return true; if (NewLine) { - const ParenState &P = State.Stack.back(); + ParenState const &P = State.Stack.back(); int AdditionalIndent = P.Indent - Previous.Children[0]->Level * Style.IndentWidth; @@ -855,7 +855,7 @@ if (Previous.Children.size() > 1) return false; - const AnnotatedLine *Child = Previous.Children[0]; + AnnotatedLine const *Child = Previous.Children[0]; // We can't put the closing "}" on a line with a trailing comment. if (Child->Last->isTrailingComment()) return false; @@ -883,7 +883,7 @@ private: WhitespaceManager *Whitespaces; - const FormatStyle &Style; + FormatStyle const &Style; UnwrappedLineFormatter *BlockFormatter; }; @@ -892,13 +892,13 @@ public: NoColumnLimitLineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces, - const FormatStyle &Style, + FormatStyle const &Style, UnwrappedLineFormatter *BlockFormatter) : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} /// Formats the line, simply keeping all of the input's line breaking /// decisions. - unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, + unsigned formatLine(AnnotatedLine const &Line, unsigned FirstIndent, unsigned FirstStartColumn, bool DryRun) override { assert(!DryRun); LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn, @@ -919,12 +919,12 @@ class NoLineBreakFormatter : public LineFormatter { public: NoLineBreakFormatter(ContinuationIndenter *Indenter, - WhitespaceManager *Whitespaces, const FormatStyle &Style, + WhitespaceManager *Whitespaces, FormatStyle const &Style, UnwrappedLineFormatter *BlockFormatter) : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} /// Puts all tokens into a single line. - unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, + unsigned formatLine(AnnotatedLine const &Line, unsigned FirstIndent, unsigned FirstStartColumn, bool DryRun) override { unsigned Penalty = 0; LineState State = @@ -943,13 +943,13 @@ public: OptimizingLineFormatter(ContinuationIndenter *Indenter, WhitespaceManager *Whitespaces, - const FormatStyle &Style, + FormatStyle const &Style, UnwrappedLineFormatter *BlockFormatter) : LineFormatter(Indenter, Whitespaces, Style, BlockFormatter) {} /// Formats the line by finding the best line breaks with line lengths /// below the column limit. - unsigned formatLine(const AnnotatedLine &Line, unsigned FirstIndent, + unsigned formatLine(AnnotatedLine const &Line, unsigned FirstIndent, unsigned FirstStartColumn, bool DryRun) override { LineState State = Indenter->getInitialState(FirstIndent, FirstStartColumn, &Line, DryRun); @@ -980,7 +980,7 @@ /// An edge in the solution space from \c Previous->State to \c State, /// inserting a newline dependent on the \c NewLine. struct StateNode { - StateNode(const LineState &State, bool NewLine, StateNode *Previous) + StateNode(LineState const &State, bool NewLine, StateNode *Previous) : State(State), NewLine(NewLine), Previous(Previous) {} LineState State; bool NewLine; @@ -1118,13 +1118,13 @@ } // anonymous namespace unsigned UnwrappedLineFormatter::format( - const SmallVectorImpl &Lines, bool DryRun, + SmallVectorImpl const &Lines, bool DryRun, int AdditionalIndent, bool FixBadIndentation, unsigned FirstStartColumn, unsigned NextStartColumn, unsigned LastStartColumn) { LineJoiner Joiner(Style, Keywords, Lines); // Try to look up already computed penalty in DryRun-mode. - std::pair *, unsigned> CacheKey( + std::pair const *, unsigned> CacheKey( &Lines, AdditionalIndent); auto CacheIt = PenaltyCache.find(CacheKey); if (DryRun && CacheIt != PenaltyCache.end()) @@ -1134,18 +1134,18 @@ unsigned Penalty = 0; LevelIndentTracker IndentTracker(Style, Keywords, Lines[0]->Level, AdditionalIndent); - const AnnotatedLine *PrevPrevLine = nullptr; - const AnnotatedLine *PreviousLine = nullptr; - const AnnotatedLine *NextLine = nullptr; + AnnotatedLine const *PrevPrevLine = nullptr; + AnnotatedLine const *PreviousLine = nullptr; + AnnotatedLine const *NextLine = nullptr; // The minimum level of consecutive lines that have been formatted. unsigned RangeMinLevel = UINT_MAX; bool FirstLine = true; - for (const AnnotatedLine *Line = + for (AnnotatedLine const *Line = Joiner.getNextMergedLine(DryRun, IndentTracker); Line; Line = NextLine, FirstLine = false) { - const AnnotatedLine &TheLine = *Line; + AnnotatedLine const &TheLine = *Line; unsigned Indent = IndentTracker.getIndent(); // We continue formatting unchanged lines to adjust their indent, e.g. if a @@ -1203,7 +1203,7 @@ // If no token in the current line is affected, we still need to format // affected children. if (TheLine.ChildrenAffected) - for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) + for (FormatToken const *Tok = TheLine.First; Tok; Tok = Tok->Next) if (!Tok->Children.empty()) format(Tok->Children, DryRun); @@ -1243,9 +1243,9 @@ } void UnwrappedLineFormatter::formatFirstToken( - const AnnotatedLine &Line, const AnnotatedLine *PreviousLine, - const AnnotatedLine *PrevPrevLine, - const SmallVectorImpl &Lines, unsigned Indent, + AnnotatedLine const &Line, AnnotatedLine const *PreviousLine, + AnnotatedLine const *PrevPrevLine, + SmallVectorImpl const &Lines, unsigned Indent, unsigned NewlineIndent) { FormatToken &RootToken = *Line.First; if (RootToken.is(tok::eof)) { @@ -1298,7 +1298,7 @@ Newlines = 1; // Previous is an access modifier remove all new lines. break; case FormatStyle::ELBAMS_Always: { - const FormatToken *previousToken; + FormatToken const *previousToken; if (PreviousLine->Last->is(tok::comment)) previousToken = PreviousLine->Last->getPreviousNonComment(); else @@ -1349,7 +1349,7 @@ unsigned UnwrappedLineFormatter::getColumnLimit(bool InPPDirective, - const AnnotatedLine *NextLine) const { + AnnotatedLine const *NextLine) const { // In preprocessor directives reserve two chars for trailing " \" if the // next line continues the preprocessor directive. bool ContinuesPPDirective = Index: clang/lib/Format/UnwrappedLineParser.h =================================================================== --- clang/lib/Format/UnwrappedLineParser.h +++ clang/lib/Format/UnwrappedLineParser.h @@ -66,7 +66,7 @@ class UnwrappedLineConsumer { public: virtual ~UnwrappedLineConsumer() {} - virtual void consumeUnwrappedLine(const UnwrappedLine &Line) = 0; + virtual void consumeUnwrappedLine(UnwrappedLine const &Line) = 0; virtual void finishRun() = 0; }; @@ -74,8 +74,8 @@ class UnwrappedLineParser { public: - UnwrappedLineParser(const FormatStyle &Style, - const AdditionalKeywords &Keywords, + UnwrappedLineParser(FormatStyle const &Style, + AdditionalKeywords const &Keywords, unsigned FirstStartColumn, ArrayRef Tokens, UnwrappedLineConsumer &Callback); @@ -166,8 +166,8 @@ // NextTok specifies the next token. A null pointer NextTok is supported, and // signifies either the absence of a next token, or that the next token // shouldn't be taken into accunt for the analysis. - void distributeComments(const SmallVectorImpl &Comments, - const FormatToken *NextTok); + void distributeComments(SmallVectorImpl const &Comments, + FormatToken const *NextTok); // Adds the comment preceding the next token to unwrapped lines. void flushComments(bool NewlineBeforeNext); @@ -183,7 +183,7 @@ void conditionalCompilationAlternative(); void conditionalCompilationEnd(); - bool isOnNewLine(const FormatToken &FormatTok); + bool isOnNewLine(FormatToken const &FormatTok); // Compute hash of the current preprocessor branch. // This is used to identify the different branches, and thus track if block @@ -221,8 +221,8 @@ // whether we are in a compound statement or not. std::vector DeclarationScopeStack; - const FormatStyle &Style; - const AdditionalKeywords &Keywords; + FormatStyle const &Style; + AdditionalKeywords const &Keywords; llvm::Regex CommentPragmasRegex; Index: clang/lib/Format/UnwrappedLineParser.cpp =================================================================== --- clang/lib/Format/UnwrappedLineParser.cpp +++ clang/lib/Format/UnwrappedLineParser.cpp @@ -57,16 +57,16 @@ std::vector &Stack; }; -static bool isLineComment(const FormatToken &FormatTok) { +static bool isLineComment(FormatToken const &FormatTok) { return FormatTok.is(tok::comment) && !FormatTok.TokenText.startswith("/*"); } // Checks if \p FormatTok is a line comment that continues the line comment // \p Previous. The original column of \p MinColumnToken is used to determine // whether \p FormatTok is indented enough to the right to continue \p Previous. -static bool continuesLineComment(const FormatToken &FormatTok, - const FormatToken *Previous, - const FormatToken *MinColumnToken) { +static bool continuesLineComment(FormatToken const &FormatTok, + FormatToken const *Previous, + FormatToken const *MinColumnToken) { if (!Previous || !MinColumnToken) return false; unsigned MinContinueColumn = @@ -172,7 +172,7 @@ class CompoundStatementIndenter { public: CompoundStatementIndenter(UnwrappedLineParser *Parser, - const FormatStyle &Style, unsigned &LineLevel) + FormatStyle const &Style, unsigned &LineLevel) : CompoundStatementIndenter(Parser, LineLevel, Style.BraceWrapping.AfterControlStatement, Style.BraceWrapping.IndentBraces) {} @@ -222,8 +222,8 @@ } // end anonymous namespace -UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style, - const AdditionalKeywords &Keywords, +UnwrappedLineParser::UnwrappedLineParser(FormatStyle const &Style, + AdditionalKeywords const &Keywords, unsigned FirstStartColumn, ArrayRef Tokens, UnwrappedLineConsumer &Callback) @@ -444,7 +444,7 @@ // definitions, too. unsigned StoredPosition = Tokens->getPosition(); FormatToken *Tok = FormatTok; - const FormatToken *PrevTok = Tok->Previous; + FormatToken const *PrevTok = Tok->Previous; // Keep a stack of positions of lbrace tokens. We will // update information about whether an lbrace starts a // braced init list or a different block during the loop. @@ -572,7 +572,7 @@ size_t UnwrappedLineParser::computePPHash() const { size_t h = 0; - for (const auto &i : PPStack) { + for (auto const &i : PPStack) { hash_combine(h, size_t(i.Kind)); hash_combine(h, i.Line); } @@ -584,7 +584,7 @@ bool UnindentWhitesmithsBraces) { assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) && "'{' or macro block token expected"); - const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin); + bool const MacroBlock = FormatTok->is(TT_MacroBlockBegin); FormatTok->setBlockKind(BK_Block); // For Whitesmiths mode, jump to the next level prior to skipping over the @@ -660,7 +660,7 @@ } } -static bool isGoogScope(const UnwrappedLine &Line) { +static bool isGoogScope(UnwrappedLine const &Line) { // FIXME: Closure-library specific stuff should not be hard-coded but be // configurable. if (Line.Tokens.size() < 4) @@ -678,8 +678,8 @@ return I->Tok->is(tok::l_paren); } -static bool isIIFE(const UnwrappedLine &Line, - const AdditionalKeywords &Keywords) { +static bool isIIFE(UnwrappedLine const &Line, + AdditionalKeywords const &Keywords) { // Look for the start of an immediately invoked anonymous function. // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression // This is commonly done in JavaScript to create a new, anonymous scope. @@ -696,8 +696,8 @@ return I->Tok->is(tok::l_paren); } -static bool ShouldBreakBeforeBrace(const FormatStyle &Style, - const FormatToken &InitialToken) { +static bool ShouldBreakBeforeBrace(FormatStyle const &Style, + FormatToken const &InitialToken) { if (InitialToken.isOneOf(tok::kw_namespace, TT_NamespaceMacro)) return Style.BraceWrapping.AfterNamespace; if (InitialToken.is(tok::kw_class)) @@ -925,7 +925,7 @@ // Here we exclude certain tokens that are not usually the first token in an // unwrapped line. This is used in attempt to distinguish macro calls without // trailing semicolons from other constructs split to several lines. -static bool tokenCanStartNewLine(const FormatToken &Tok) { +static bool tokenCanStartNewLine(FormatToken const &Tok) { // Semicolon can be a null-statement, l_square can be a start of a macro or // a C++11 attribute, but this doesn't seem to be common. return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) && @@ -951,8 +951,8 @@ Tok.isNot(tok::kw_noexcept); } -static bool mustBeJSIdent(const AdditionalKeywords &Keywords, - const FormatToken *FormatTok) { +static bool mustBeJSIdent(AdditionalKeywords const &Keywords, + FormatToken const *FormatTok) { // FIXME: This returns true for C/C++ keywords like 'struct'. return FormatTok->is(tok::identifier) && (FormatTok->Tok.getIdentifierInfo() == nullptr || @@ -966,8 +966,8 @@ Keywords.kw_from)); } -static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords, - const FormatToken *FormatTok) { +static bool mustBeJSIdentOrValue(AdditionalKeywords const &Keywords, + FormatToken const *FormatTok) { return FormatTok->Tok.isLiteral() || FormatTok->isOneOf(tok::kw_true, tok::kw_false) || mustBeJSIdent(Keywords, FormatTok); @@ -975,8 +975,8 @@ // isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement // when encountered after a value (see mustBeJSIdentOrValue). -static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords, - const FormatToken *FormatTok) { +static bool isJSDeclOrStmt(AdditionalKeywords const &Keywords, + FormatToken const *FormatTok) { return FormatTok->isOneOf( tok::kw_return, Keywords.kw_yield, // conditionals @@ -1219,7 +1219,7 @@ break; } do { - const FormatToken *Previous = FormatTok->Previous; + FormatToken const *Previous = FormatTok->Previous; switch (FormatTok->Tok.getKind()) { case tok::at: nextToken(); @@ -1713,7 +1713,7 @@ } bool UnwrappedLineParser::tryToParseLambdaIntroducer() { - const FormatToken *Previous = FormatTok->Previous; + FormatToken const *Previous = FormatTok->Previous; if (Previous && (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new, tok::kw_delete, tok::l_square) || @@ -2144,7 +2144,7 @@ assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) && "'namespace' expected"); - const FormatToken &InitialToken = *FormatTok; + FormatToken const &InitialToken = *FormatTok; nextToken(); if (InitialToken.is(TT_NamespaceMacro)) { parseParens(); @@ -2670,7 +2670,7 @@ } void UnwrappedLineParser::parseRecord(bool ParseAsExpr) { - const FormatToken &InitialToken = *FormatTok; + FormatToken const &InitialToken = *FormatTok; nextToken(); // The actual identifier can be a nested name specifier, and in macros @@ -2960,7 +2960,7 @@ addUnwrappedLine(); } -LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line, +LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(UnwrappedLine const &Line, StringRef Prefix = "") { llvm::dbgs() << Prefix << "Line(" << Line.Level << ", FSC=" << Line.FirstStartColumn << ")" @@ -2975,7 +2975,7 @@ for (std::list::const_iterator I = Line.Tokens.begin(), E = Line.Tokens.end(); I != E; ++I) { - const UnwrappedLineNode &Node = *I; + UnwrappedLineNode const &Node = *I; for (SmallVectorImpl::const_iterator I = Node.Children.begin(), E = Node.Children.end(); @@ -3021,7 +3021,7 @@ bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); } -bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) { +bool UnwrappedLineParser::isOnNewLine(FormatToken const &FormatTok) { return (Line->InPPDirective || FormatTok.HasUnescapedNewline) && FormatTok.NewlinesBefore > 0; } @@ -3029,9 +3029,9 @@ // Checks if \p FormatTok is a line comment that continues the line comment // section on \p Line. static bool -continuesLineCommentSection(const FormatToken &FormatTok, - const UnwrappedLine &Line, - const llvm::Regex &CommentPragmasRegex) { +continuesLineCommentSection(FormatToken const &FormatTok, + UnwrappedLine const &Line, + llvm::Regex const &CommentPragmasRegex) { if (Line.Tokens.empty()) return false; @@ -3108,12 +3108,12 @@ // a, // first line // // second line // }; - const FormatToken *MinColumnToken = Line.Tokens.front().Tok; + FormatToken const *MinColumnToken = Line.Tokens.front().Tok; // Scan for '{//'. If found, use the column of '{' as a min column for line // comment section continuation. - const FormatToken *PreviousToken = nullptr; - for (const UnwrappedLineNode &Node : Line.Tokens) { + FormatToken const *PreviousToken = nullptr; + for (UnwrappedLineNode const &Node : Line.Tokens) { if (PreviousToken && PreviousToken->is(tok::l_brace) && isLineComment(*Node.Tok)) { MinColumnToken = PreviousToken; @@ -3173,8 +3173,8 @@ } void UnwrappedLineParser::distributeComments( - const SmallVectorImpl &Comments, - const FormatToken *NextTok) { + SmallVectorImpl const &Comments, + FormatToken const *NextTok) { // Whether or not a line comment token continues a line is controlled by // the method continuesLineCommentSection, with the following caveat: // Index: clang/lib/Format/UsingDeclarationsSorter.h =================================================================== --- clang/lib/Format/UsingDeclarationsSorter.h +++ clang/lib/Format/UsingDeclarationsSorter.h @@ -22,7 +22,7 @@ class UsingDeclarationsSorter : public TokenAnalyzer { public: - UsingDeclarationsSorter(const Environment &Env, const FormatStyle &Style); + UsingDeclarationsSorter(Environment const &Env, FormatStyle const &Style); std::pair analyze(TokenAnnotator &Annotator, Index: clang/lib/Format/UsingDeclarationsSorter.cpp =================================================================== --- clang/lib/Format/UsingDeclarationsSorter.cpp +++ clang/lib/Format/UsingDeclarationsSorter.cpp @@ -65,13 +65,13 @@ } struct UsingDeclaration { - const AnnotatedLine *Line; + AnnotatedLine const *Line; std::string Label; - UsingDeclaration(const AnnotatedLine *Line, const std::string &Label) + UsingDeclaration(AnnotatedLine const *Line, std::string const &Label) : Line(Line), Label(Label) {} - bool operator<(const UsingDeclaration &Other) const { + bool operator<(UsingDeclaration const &Other) const { return compareLabels(Label, Other.Label) < 0; } }; @@ -84,10 +84,10 @@ /// and not type aliases, as in: /// using A = B::C; /// Type aliases are in general not safe to permute. -std::string computeUsingDeclarationLabel(const FormatToken *UsingTok) { +std::string computeUsingDeclarationLabel(FormatToken const *UsingTok) { assert(UsingTok && UsingTok->is(tok::kw_using) && "Expecting a using token"); std::string Label; - const FormatToken *Tok = UsingTok->Next; + FormatToken const *Tok = UsingTok->Next; if (Tok && Tok->is(tok::kw_typename)) { Label.append("typename "); Tok = Tok->Next; @@ -113,9 +113,9 @@ void endUsingDeclarationBlock( SmallVectorImpl *UsingDeclarations, - const SourceManager &SourceMgr, tooling::Replacements *Fixes) { + SourceManager const &SourceMgr, tooling::Replacements *Fixes) { bool BlockAffected = false; - for (const UsingDeclaration &Declaration : *UsingDeclarations) { + for (UsingDeclaration const &Declaration : *UsingDeclarations) { if (Declaration.Line->Affected) { BlockAffected = true; break; @@ -131,7 +131,7 @@ SortedUsingDeclarations.erase( std::unique(SortedUsingDeclarations.begin(), SortedUsingDeclarations.end(), - [](const UsingDeclaration &a, const UsingDeclaration &b) { + [](UsingDeclaration const &a, UsingDeclaration const &b) { return a.Label == b.Label; }), SortedUsingDeclarations.end()); @@ -177,19 +177,19 @@ } // namespace -UsingDeclarationsSorter::UsingDeclarationsSorter(const Environment &Env, - const FormatStyle &Style) +UsingDeclarationsSorter::UsingDeclarationsSorter(Environment const &Env, + FormatStyle const &Style) : TokenAnalyzer(Env, Style) {} std::pair UsingDeclarationsSorter::analyze( TokenAnnotator &Annotator, SmallVectorImpl &AnnotatedLines, FormatTokenLexer &Tokens) { - const SourceManager &SourceMgr = Env.getSourceManager(); + SourceManager const &SourceMgr = Env.getSourceManager(); AffectedRangeMgr.computeAffectedLines(AnnotatedLines); tooling::Replacements Fixes; SmallVector UsingDeclarations; for (size_t I = 0, E = AnnotatedLines.size(); I != E; ++I) { - const auto *FirstTok = AnnotatedLines[I]->First; + auto const *FirstTok = AnnotatedLines[I]->First; if (AnnotatedLines[I]->InPPDirective || !AnnotatedLines[I]->startsWith(tok::kw_using) || FirstTok->Finalized) { endUsingDeclarationBlock(&UsingDeclarations, SourceMgr, &Fixes); @@ -197,7 +197,7 @@ } if (FirstTok->NewlinesBefore > 1) endUsingDeclarationBlock(&UsingDeclarations, SourceMgr, &Fixes); - const auto *UsingTok = + auto const *UsingTok = FirstTok->is(tok::comment) ? FirstTok->getNextNonComment() : FirstTok; std::string Label = computeUsingDeclarationLabel(UsingTok); if (Label.empty()) { Index: clang/lib/Format/WhitespaceManager.h =================================================================== --- clang/lib/Format/WhitespaceManager.h +++ clang/lib/Format/WhitespaceManager.h @@ -39,7 +39,7 @@ /// There may be multiple calls to \c breakToken for a given token. class WhitespaceManager { public: - WhitespaceManager(const SourceManager &SourceMgr, const FormatStyle &Style, + WhitespaceManager(SourceManager const &SourceMgr, FormatStyle const &Style, bool UseCRLF) : SourceMgr(SourceMgr), Style(Style), UseCRLF(UseCRLF) {} @@ -59,9 +59,9 @@ /// /// Needs to be called for every token for which \c replaceWhitespace /// was not called. - void addUntouchableToken(const FormatToken &Tok, bool InPPDirective); + void addUntouchableToken(FormatToken const &Tok, bool InPPDirective); - llvm::Error addReplacement(const tooling::Replacement &Replacement); + llvm::Error addReplacement(tooling::Replacement const &Replacement); /// Inserts or replaces whitespace in the middle of a token. /// @@ -77,14 +77,14 @@ /// /// When \p InPPDirective is true, escaped newlines are inserted. \p Spaces is /// used to align backslashes correctly. - void replaceWhitespaceInToken(const FormatToken &Tok, unsigned Offset, + void replaceWhitespaceInToken(FormatToken const &Tok, unsigned Offset, unsigned ReplaceChars, StringRef PreviousPostfix, StringRef CurrentPrefix, bool InPPDirective, unsigned Newlines, int Spaces); /// Returns all the \c Replacements created during formatting. - const tooling::Replacements &generateReplacements(); + tooling::Replacements const &generateReplacements(); /// Represents a change before a token, a break inside a token, /// or the layout of an unchanged token (or whitespace within). @@ -92,11 +92,11 @@ /// Functor to sort changes in original source order. class IsBeforeInFile { public: - IsBeforeInFile(const SourceManager &SourceMgr) : SourceMgr(SourceMgr) {} - bool operator()(const Change &C1, const Change &C2) const; + IsBeforeInFile(SourceManager const &SourceMgr) : SourceMgr(SourceMgr) {} + bool operator()(Change const &C1, Change const &C2) const; private: - const SourceManager &SourceMgr; + SourceManager const &SourceMgr; }; /// Creates a \c Change. @@ -108,7 +108,7 @@ /// /// \p StartOfTokenColumn and \p InPPDirective will be used to lay out /// trailing comments and escaped newlines. - Change(const FormatToken &Tok, bool CreateReplacement, + Change(FormatToken const &Tok, bool CreateReplacement, SourceRange OriginalWhitespaceRange, int Spaces, unsigned StartOfTokenColumn, unsigned NewlinesBefore, StringRef PreviousLinePostfix, StringRef CurrentLinePrefix, @@ -118,7 +118,7 @@ // this change inserts whitespace. // FIXME: Currently this is not set correctly for breaks inside comments, as // the \c BreakableToken is still doing its own alignment. - const FormatToken *Tok; + FormatToken const *Tok; bool CreateReplacement; // Changes might be in the middle of a token, so we cannot just keep the @@ -158,7 +158,7 @@ // comment. \c IndentationOffset is a relative column offset to this // change, so that the correct column can be reconstructed at the end of // the alignment process. - const Change *StartOfBlockComment; + Change const *StartOfBlockComment; int IndentationOffset; // Depth of conditionals. Computed from tracking fake parenthesis, except @@ -182,11 +182,11 @@ bool HasSplit = false; CellDescription *NextColumnElement = nullptr; - constexpr bool operator==(const CellDescription &Other) const { + constexpr bool operator==(CellDescription const &Other) const { return Index == Other.Index && Cell == Other.Cell && EndIndex == Other.EndIndex; } - constexpr bool operator!=(const CellDescription &Other) const { + constexpr bool operator!=(CellDescription const &Other) const { return !(*this == Other); } }; @@ -255,7 +255,7 @@ CellDescriptions getCells(unsigned Start, unsigned End); /// Does this \p Cell contain a split element? - static bool isSplitCell(const CellDescription &Cell); + static bool isSplitCell(CellDescription const &Cell); /// Get the width of the preceeding cells from \p Start to \p End. template @@ -279,7 +279,7 @@ calculateCellWidth(CellIter->Index, CellIter->EndIndex, true); if (Changes[CellIter->Index].NewlinesBefore == 0) CellWidth += NetWidth; - for (const auto *Next = CellIter->NextColumnElement; Next != nullptr; + for (auto const *Next = CellIter->NextColumnElement; Next != nullptr; Next = Next->NextColumnElement) { auto ThisWidth = calculateCellWidth(Next->Index, Next->EndIndex, true); if (Changes[Next->Index].NewlinesBefore == 0) @@ -297,7 +297,7 @@ auto MaxNetWidth = getNetWidth(CellStart, CellStop, InitialSpaces); auto RowCount = 1U; auto Offset = std::distance(CellStart, CellStop); - for (const auto *Next = CellStop->NextColumnElement; Next != nullptr; + for (auto const *Next = CellStop->NextColumnElement; Next != nullptr; Next = Next->NextColumnElement) { auto Start = (CellStart + RowCount * CellCount); auto End = Start + Offset; @@ -330,9 +330,9 @@ unsigned Indentation); SmallVector Changes; - const SourceManager &SourceMgr; + SourceManager const &SourceMgr; tooling::Replacements Replaces; - const FormatStyle &Style; + FormatStyle const &Style; bool UseCRLF; }; Index: clang/lib/Format/WhitespaceManager.cpp =================================================================== --- clang/lib/Format/WhitespaceManager.cpp +++ clang/lib/Format/WhitespaceManager.cpp @@ -20,13 +20,13 @@ namespace format { bool WhitespaceManager::Change::IsBeforeInFile::operator()( - const Change &C1, const Change &C2) const { + Change const &C1, Change const &C2) const { return SourceMgr.isBeforeInTranslationUnit( C1.OriginalWhitespaceRange.getBegin(), C2.OriginalWhitespaceRange.getBegin()); } -WhitespaceManager::Change::Change(const FormatToken &Tok, +WhitespaceManager::Change::Change(FormatToken const &Tok, bool CreateReplacement, SourceRange OriginalWhitespaceRange, int Spaces, unsigned StartOfTokenColumn, @@ -58,7 +58,7 @@ /*IsInsideToken=*/false)); } -void WhitespaceManager::addUntouchableToken(const FormatToken &Tok, +void WhitespaceManager::addUntouchableToken(FormatToken const &Tok, bool InPPDirective) { if (Tok.Finalized) return; @@ -70,12 +70,12 @@ } llvm::Error -WhitespaceManager::addReplacement(const tooling::Replacement &Replacement) { +WhitespaceManager::addReplacement(tooling::Replacement const &Replacement) { return Replaces.add(Replacement); } void WhitespaceManager::replaceWhitespaceInToken( - const FormatToken &Tok, unsigned Offset, unsigned ReplaceChars, + FormatToken const &Tok, unsigned Offset, unsigned ReplaceChars, StringRef PreviousPostfix, StringRef CurrentPrefix, bool InPPDirective, unsigned Newlines, int Spaces) { if (Tok.Finalized) @@ -89,7 +89,7 @@ /*IsInsideToken=*/true)); } -const tooling::Replacements &WhitespaceManager::generateReplacements() { +tooling::Replacements const &WhitespaceManager::generateReplacements() { if (Changes.empty()) return Replaces; @@ -122,7 +122,7 @@ SourceMgr.getFileOffset(PreviousOriginalWhitespaceEnd); assert(PreviousOriginalWhitespaceEndOffset <= OriginalWhitespaceStartOffset); - const char *const PreviousOriginalWhitespaceEndData = + char const *const PreviousOriginalWhitespaceEndData = SourceMgr.getCharacterData(PreviousOriginalWhitespaceEnd); StringRef Text(PreviousOriginalWhitespaceEndData, SourceMgr.getCharacterData(OriginalWhitespaceStart) - @@ -211,7 +211,7 @@ Changes.back().TokenLength = 0; Changes.back().IsTrailingComment = Changes.back().Tok->is(tok::comment); - const WhitespaceManager::Change *LastBlockComment = nullptr; + WhitespaceManager::Change const *LastBlockComment = nullptr; for (auto &Change : Changes) { // Reset the IsTrailingComment flag for changes inside of trailing comments // so they don't get realigned later. Comment line breaks however still need @@ -265,7 +265,7 @@ // Align a single sequence of tokens, see AlignTokens below. template static void -AlignTokenSequence(const FormatStyle &Style, unsigned Start, unsigned End, +AlignTokenSequence(FormatStyle const &Style, unsigned Start, unsigned End, unsigned Column, F &&Matches, SmallVector &Changes) { bool FoundMatchOnLine = false; @@ -421,9 +421,9 @@ // that mentions "split function parameter alignment" for an example of this. template static unsigned AlignTokens( - const FormatStyle &Style, F &&Matches, + FormatStyle const &Style, F &&Matches, SmallVector &Changes, unsigned StartAt, - const FormatStyle::AlignConsecutiveStyle &ACS = FormatStyle::ACS_None) { + FormatStyle::AlignConsecutiveStyle const &ACS = FormatStyle::ACS_None) { unsigned MinColumn = 0; unsigned MaxColumn = UINT_MAX; @@ -567,7 +567,7 @@ static void AlignMacroSequence( unsigned &StartOfSequence, unsigned &EndOfSequence, unsigned &MinColumn, unsigned &MaxColumn, bool &FoundMatchOnLine, - std::function AlignMacrosMatches, + std::function AlignMacrosMatches, SmallVector &Changes) { if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) { @@ -606,7 +606,7 @@ if (Style.AlignConsecutiveMacros == FormatStyle::ACS_None) return; - auto AlignMacrosMatches = [](const Change &C) { + auto AlignMacrosMatches = [](Change const &C) { const FormatToken *Current = C.Tok; unsigned SpacesRequiredBefore = 1; @@ -711,7 +711,7 @@ AlignTokens( Style, - [&](const Change &C) { + [&](Change const &C) { // Do not align on equal signs that are first on a line. if (C.NewlinesBefore > 0) return false; @@ -1009,7 +1009,7 @@ // the spaces in front of the brace are enough. Changes[CellIter->Index].NewlinesBefore = 0; Changes[CellIter->Index].Spaces = 0; - for (const auto *Next = CellIter->NextColumnElement; Next != nullptr; + for (auto const *Next = CellIter->NextColumnElement; Next != nullptr; Next = Next->NextColumnElement) { Changes[Next->Index].Spaces = 0; Changes[Next->Index].NewlinesBefore = 0; @@ -1026,7 +1026,7 @@ Changes[CellIter->Index].Spaces = (MaxNetWidth - ThisNetWidth); auto RowCount = 1U; auto Offset = std::distance(Cells.begin(), CellIter); - for (const auto *Next = CellIter->NextColumnElement; Next != nullptr; + for (auto const *Next = CellIter->NextColumnElement; Next != nullptr; Next = Next->NextColumnElement) { auto *Start = (Cells.begin() + RowCount * CellDescs.CellCount); auto *End = Start + Offset; @@ -1045,7 +1045,7 @@ Changes[CellIter->Index].Spaces += (i > 0) ? 1 : 0; } alignToStartOfCell(CellIter->Index, CellIter->EndIndex); - for (const auto *Next = CellIter->NextColumnElement; Next != nullptr; + for (auto const *Next = CellIter->NextColumnElement; Next != nullptr; Next = Next->NextColumnElement) { ThisWidth = calculateCellWidth(Next->Index, Next->EndIndex, true) + NetWidth; @@ -1083,7 +1083,7 @@ } auto RowCount = 1U; auto Offset = std::distance(Cells.begin(), CellIter); - for (const auto *Next = CellIter->NextColumnElement; Next != nullptr; + for (auto const *Next = CellIter->NextColumnElement; Next != nullptr; Next = Next->NextColumnElement) { auto *Start = (Cells.begin() + RowCount * CellDescs.CellCount); auto *End = Start + Offset; @@ -1098,10 +1098,10 @@ } } -bool WhitespaceManager::isSplitCell(const CellDescription &Cell) { +bool WhitespaceManager::isSplitCell(CellDescription const &Cell) { if (Cell.HasSplit) return true; - for (const auto *Next = Cell.NextColumnElement; Next != nullptr; + for (auto const *Next = Cell.NextColumnElement; Next != nullptr; Next = Next->NextColumnElement) { if (Next->HasSplit) return true; @@ -1119,7 +1119,7 @@ unsigned InitialTokenLength = 0; unsigned EndSpaces = 0; SmallVector Cells; - const FormatToken *MatchingParen = nullptr; + FormatToken const *MatchingParen = nullptr; for (unsigned i = Start; i < End; ++i) { auto &C = Changes[i]; if (C.Tok->is(tok::l_brace)) @@ -1155,7 +1155,7 @@ Cells.push_back(CellDescription{i, ++Cell, i + 1, false, nullptr}); CellCount = Cell + 1; // Go to the next non-comment and ensure there is a break in front - const auto *NextNonComment = C.Tok->getNextNonComment(); + auto const *NextNonComment = C.Tok->getNextNonComment(); while (NextNonComment->is(tok::comma)) NextNonComment = NextNonComment->getNextNonComment(); auto j = i; @@ -1257,7 +1257,7 @@ void WhitespaceManager::generateChanges() { for (unsigned i = 0, e = Changes.size(); i != e; ++i) { - const Change &C = Changes[i]; + Change const &C = Changes[i]; if (i > 0) { assert(Changes[i - 1].OriginalWhitespaceRange.getBegin() != C.OriginalWhitespaceRange.getBegin() &&