2012-12-04 02:12:45 +08:00
|
|
|
//===--- Format.cpp - Format C++ code -------------------------------------===//
|
|
|
|
//
|
|
|
|
// The LLVM Compiler Infrastructure
|
|
|
|
//
|
|
|
|
// This file is distributed under the University of Illinois Open Source
|
|
|
|
// License. See LICENSE.TXT for details.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
///
|
|
|
|
/// \file
|
|
|
|
/// \brief This file implements functions declared in Format.h. This will be
|
|
|
|
/// split into separate files as we go.
|
|
|
|
///
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2013-01-16 22:55:28 +08:00
|
|
|
#define DEBUG_TYPE "format-formatter"
|
|
|
|
|
2013-01-30 05:01:14 +08:00
|
|
|
#include "TokenAnnotator.h"
|
2012-12-04 17:13:33 +08:00
|
|
|
#include "UnwrappedLineParser.h"
|
2013-01-10 23:05:09 +08:00
|
|
|
#include "clang/Basic/Diagnostic.h"
|
2012-12-21 18:20:02 +08:00
|
|
|
#include "clang/Basic/OperatorPrecedence.h"
|
2013-01-02 18:28:36 +08:00
|
|
|
#include "clang/Basic/SourceManager.h"
|
2013-01-16 22:55:28 +08:00
|
|
|
#include "clang/Format/Format.h"
|
2013-01-10 23:05:09 +08:00
|
|
|
#include "clang/Frontend/TextDiagnosticPrinter.h"
|
2012-12-04 02:12:45 +08:00
|
|
|
#include "clang/Lex/Lexer.h"
|
2013-03-27 19:52:18 +08:00
|
|
|
#include "llvm/ADT/STLExtras.h"
|
2013-02-13 18:46:36 +08:00
|
|
|
#include "llvm/Support/Allocator.h"
|
2013-01-16 22:55:28 +08:00
|
|
|
#include "llvm/Support/Debug.h"
|
2013-02-13 18:46:36 +08:00
|
|
|
#include <queue>
|
2012-12-04 21:02:32 +08:00
|
|
|
#include <string>
|
|
|
|
|
2012-12-04 02:12:45 +08:00
|
|
|
namespace clang {
|
|
|
|
namespace format {
|
|
|
|
|
|
|
|
FormatStyle getLLVMStyle() {
|
|
|
|
FormatStyle LLVMStyle;
|
|
|
|
LLVMStyle.ColumnLimit = 80;
|
|
|
|
LLVMStyle.MaxEmptyLinesToKeep = 1;
|
2013-02-06 22:22:40 +08:00
|
|
|
LLVMStyle.PointerBindsToType = false;
|
|
|
|
LLVMStyle.DerivePointerBinding = false;
|
2012-12-04 02:12:45 +08:00
|
|
|
LLVMStyle.AccessModifierOffset = -2;
|
2013-02-06 22:22:40 +08:00
|
|
|
LLVMStyle.Standard = FormatStyle::LS_Cpp03;
|
2012-12-07 02:03:27 +08:00
|
|
|
LLVMStyle.IndentCaseLabels = false;
|
2013-01-07 19:09:06 +08:00
|
|
|
LLVMStyle.SpacesBeforeTrailingComments = 1;
|
2013-01-16 22:59:02 +08:00
|
|
|
LLVMStyle.BinPackParameters = true;
|
2013-01-30 00:03:49 +08:00
|
|
|
LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
|
2013-01-11 19:37:55 +08:00
|
|
|
LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
|
2013-01-15 00:24:39 +08:00
|
|
|
LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
|
2013-01-11 04:12:55 +08:00
|
|
|
LLVMStyle.ObjCSpaceBeforeProtocolList = true;
|
2013-02-04 15:21:18 +08:00
|
|
|
LLVMStyle.PenaltyExcessCharacter = 1000000;
|
2013-02-14 04:33:44 +08:00
|
|
|
LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 5;
|
2012-12-04 02:12:45 +08:00
|
|
|
return LLVMStyle;
|
|
|
|
}
|
|
|
|
|
|
|
|
FormatStyle getGoogleStyle() {
|
|
|
|
FormatStyle GoogleStyle;
|
|
|
|
GoogleStyle.ColumnLimit = 80;
|
|
|
|
GoogleStyle.MaxEmptyLinesToKeep = 1;
|
2013-02-06 22:22:40 +08:00
|
|
|
GoogleStyle.PointerBindsToType = true;
|
|
|
|
GoogleStyle.DerivePointerBinding = true;
|
2012-12-04 02:12:45 +08:00
|
|
|
GoogleStyle.AccessModifierOffset = -1;
|
2013-02-06 22:22:40 +08:00
|
|
|
GoogleStyle.Standard = FormatStyle::LS_Auto;
|
2012-12-07 02:03:27 +08:00
|
|
|
GoogleStyle.IndentCaseLabels = true;
|
2013-01-07 19:09:06 +08:00
|
|
|
GoogleStyle.SpacesBeforeTrailingComments = 2;
|
2013-02-27 17:47:53 +08:00
|
|
|
GoogleStyle.BinPackParameters = true;
|
2013-01-30 00:03:49 +08:00
|
|
|
GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
|
2013-01-11 19:37:55 +08:00
|
|
|
GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
|
2013-01-16 23:44:34 +08:00
|
|
|
GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
|
2013-01-11 04:12:55 +08:00
|
|
|
GoogleStyle.ObjCSpaceBeforeProtocolList = false;
|
2013-02-04 15:21:18 +08:00
|
|
|
GoogleStyle.PenaltyExcessCharacter = 1000000;
|
2013-02-14 04:33:44 +08:00
|
|
|
GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 100;
|
2012-12-04 02:12:45 +08:00
|
|
|
return GoogleStyle;
|
|
|
|
}
|
|
|
|
|
2013-01-15 00:24:39 +08:00
|
|
|
FormatStyle getChromiumStyle() {
|
|
|
|
FormatStyle ChromiumStyle = getGoogleStyle();
|
2013-01-30 00:03:49 +08:00
|
|
|
ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
|
2013-02-27 17:47:53 +08:00
|
|
|
ChromiumStyle.BinPackParameters = false;
|
2013-02-06 22:22:40 +08:00
|
|
|
ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
|
|
|
|
ChromiumStyle.DerivePointerBinding = false;
|
2013-01-15 00:24:39 +08:00
|
|
|
return ChromiumStyle;
|
|
|
|
}
|
|
|
|
|
2013-02-07 04:07:35 +08:00
|
|
|
static bool isTrailingComment(const AnnotatedToken &Tok) {
|
|
|
|
return Tok.is(tok::comment) &&
|
|
|
|
(Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
|
|
|
|
}
|
|
|
|
|
2013-03-20 20:37:50 +08:00
|
|
|
static bool isComparison(const AnnotatedToken &Tok) {
|
|
|
|
prec::Level Precedence = getPrecedence(Tok);
|
|
|
|
return Tok.Type == TT_BinaryOperator &&
|
|
|
|
(Precedence == prec::Equality || Precedence == prec::Relational);
|
|
|
|
}
|
|
|
|
|
2013-02-08 16:22:00 +08:00
|
|
|
// Returns the length of everything up to the first possible line break after
|
|
|
|
// the ), ], } or > matching \c Tok.
|
|
|
|
static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
|
|
|
|
if (Tok.MatchingParen == NULL)
|
|
|
|
return 0;
|
|
|
|
AnnotatedToken *End = Tok.MatchingParen;
|
|
|
|
while (!End->Children.empty() && !End->Children[0].CanBreakBefore) {
|
|
|
|
End = &End->Children[0];
|
|
|
|
}
|
|
|
|
return End->TotalLength - Tok.TotalLength + 1;
|
|
|
|
}
|
|
|
|
|
2013-03-27 19:52:18 +08:00
|
|
|
static size_t
|
|
|
|
calculateColumnLimit(const FormatStyle &Style, bool InPPDirective) {
|
|
|
|
// In preprocessor directives reserve two chars for trailing " \"
|
|
|
|
return Style.ColumnLimit - (InPPDirective ? 2 : 0);
|
|
|
|
}
|
|
|
|
|
2013-01-18 16:44:07 +08:00
|
|
|
/// \brief Manages the whitespaces around tokens and their replacements.
|
2013-01-11 02:45:26 +08:00
|
|
|
///
|
2013-01-18 16:44:07 +08:00
|
|
|
/// This includes special handling for certain constructs, e.g. the alignment of
|
|
|
|
/// trailing line comments.
|
|
|
|
class WhitespaceManager {
|
|
|
|
public:
|
2013-03-20 01:41:36 +08:00
|
|
|
WhitespaceManager(SourceManager &SourceMgr, const FormatStyle &Style)
|
|
|
|
: SourceMgr(SourceMgr), Style(Style) {}
|
2013-01-18 16:44:07 +08:00
|
|
|
|
|
|
|
/// \brief Replaces the whitespace in front of \p Tok. Only call once for
|
|
|
|
/// each \c AnnotatedToken.
|
|
|
|
void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
|
2013-03-20 01:41:36 +08:00
|
|
|
unsigned Spaces, unsigned WhitespaceStartColumn) {
|
2013-01-22 06:49:20 +08:00
|
|
|
// 2+ newlines mean an empty line separating logic scopes.
|
|
|
|
if (NewLines >= 2)
|
|
|
|
alignComments();
|
|
|
|
|
2013-03-27 19:52:18 +08:00
|
|
|
SourceLocation TokenLoc = Tok.FormatTok.Tok.getLocation();
|
|
|
|
bool LineExceedsColumnLimit = Spaces + WhitespaceStartColumn +
|
|
|
|
Tok.FormatTok.TokenLength > Style.ColumnLimit;
|
|
|
|
|
2013-01-22 06:49:20 +08:00
|
|
|
// Align line comments if they are trailing or if they continue other
|
|
|
|
// trailing comments.
|
2013-03-02 00:45:59 +08:00
|
|
|
if (isTrailingComment(Tok)) {
|
|
|
|
// Remove the comment's trailing whitespace.
|
|
|
|
if (Tok.FormatTok.Tok.getLength() != Tok.FormatTok.TokenLength)
|
|
|
|
Replaces.insert(tooling::Replacement(
|
2013-03-27 19:52:18 +08:00
|
|
|
SourceMgr, TokenLoc.getLocWithOffset(Tok.FormatTok.TokenLength),
|
2013-03-02 00:45:59 +08:00
|
|
|
Tok.FormatTok.Tok.getLength() - Tok.FormatTok.TokenLength, ""));
|
|
|
|
|
|
|
|
// Align comment with other comments.
|
2013-03-27 19:52:18 +08:00
|
|
|
if ((Tok.Parent != NULL || !Comments.empty()) &&
|
|
|
|
!LineExceedsColumnLimit) {
|
|
|
|
StoredComment Comment;
|
|
|
|
Comment.Tok = Tok.FormatTok;
|
|
|
|
Comment.Spaces = Spaces;
|
|
|
|
Comment.NewLines = NewLines;
|
|
|
|
Comment.MinColumn =
|
|
|
|
NewLines > 0 ? Spaces : WhitespaceStartColumn + Spaces;
|
|
|
|
Comment.MaxColumn = Style.ColumnLimit - Tok.FormatTok.TokenLength;
|
|
|
|
Comment.Untouchable = false;
|
|
|
|
Comments.push_back(Comment);
|
|
|
|
return;
|
2013-01-18 16:44:07 +08:00
|
|
|
}
|
|
|
|
}
|
2013-01-22 06:49:20 +08:00
|
|
|
|
|
|
|
// If this line does not have a trailing comment, align the stored comments.
|
2013-02-07 04:07:35 +08:00
|
|
|
if (Tok.Children.empty() && !isTrailingComment(Tok))
|
2013-01-22 06:49:20 +08:00
|
|
|
alignComments();
|
2013-03-15 00:10:54 +08:00
|
|
|
|
2013-03-27 19:52:18 +08:00
|
|
|
if (Tok.Type == TT_BlockComment) {
|
2013-03-21 20:28:10 +08:00
|
|
|
indentBlockComment(Tok, Spaces, WhitespaceStartColumn, NewLines, false);
|
2013-03-27 19:52:18 +08:00
|
|
|
} else if (Tok.Type == TT_LineComment && LineExceedsColumnLimit) {
|
|
|
|
StringRef Line(SourceMgr.getCharacterData(TokenLoc),
|
|
|
|
Tok.FormatTok.TokenLength);
|
|
|
|
int StartColumn = Spaces + (NewLines == 0 ? WhitespaceStartColumn : 0);
|
|
|
|
StringRef Prefix = getLineCommentPrefix(Line);
|
|
|
|
std::string NewPrefix = std::string(StartColumn, ' ') + Prefix.str();
|
|
|
|
splitLineInComment(Tok.FormatTok, Line.substr(Prefix.size()),
|
|
|
|
StartColumn + Prefix.size(), NewPrefix,
|
|
|
|
/*InPPDirective=*/ false,
|
|
|
|
/*CommentHasMoreLines=*/ false);
|
|
|
|
}
|
2013-03-15 00:10:54 +08:00
|
|
|
|
2013-02-20 18:15:13 +08:00
|
|
|
storeReplacement(Tok.FormatTok, getNewLineText(NewLines, Spaces));
|
2013-01-18 16:44:07 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// \brief Like \c replaceWhitespace, but additionally adds right-aligned
|
|
|
|
/// backslashes to escape newlines inside a preprocessor directive.
|
|
|
|
///
|
|
|
|
/// This function and \c replaceWhitespace have the same behavior if
|
|
|
|
/// \c Newlines == 0.
|
|
|
|
void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
|
2013-03-20 01:41:36 +08:00
|
|
|
unsigned Spaces, unsigned WhitespaceStartColumn) {
|
|
|
|
if (Tok.Type == TT_BlockComment)
|
2013-03-21 20:28:10 +08:00
|
|
|
indentBlockComment(Tok, Spaces, WhitespaceStartColumn, NewLines, true);
|
2013-03-20 01:41:36 +08:00
|
|
|
|
|
|
|
storeReplacement(Tok.FormatTok,
|
|
|
|
getNewLineText(NewLines, Spaces, WhitespaceStartColumn));
|
2013-02-20 18:15:13 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// \brief Inserts a line break into the middle of a token.
|
|
|
|
///
|
|
|
|
/// Will break at \p Offset inside \p Tok, putting \p Prefix before the line
|
|
|
|
/// break and \p Postfix before the rest of the token starts in the next line.
|
|
|
|
///
|
|
|
|
/// \p InPPDirective, \p Spaces, \p WhitespaceStartColumn and \p Style are
|
|
|
|
/// used to generate the correct line break.
|
2013-03-20 01:41:36 +08:00
|
|
|
void breakToken(const FormatToken &Tok, unsigned Offset,
|
|
|
|
unsigned ReplaceChars, StringRef Prefix, StringRef Postfix,
|
|
|
|
bool InPPDirective, unsigned Spaces,
|
|
|
|
unsigned WhitespaceStartColumn) {
|
2013-02-20 18:15:13 +08:00
|
|
|
std::string NewLineText;
|
|
|
|
if (!InPPDirective)
|
|
|
|
NewLineText = getNewLineText(1, Spaces);
|
|
|
|
else
|
2013-03-20 01:41:36 +08:00
|
|
|
NewLineText = getNewLineText(1, Spaces, WhitespaceStartColumn);
|
2013-02-20 18:15:13 +08:00
|
|
|
std::string ReplacementText = (Prefix + NewLineText + Postfix).str();
|
2013-03-20 01:41:36 +08:00
|
|
|
SourceLocation Location = Tok.Tok.getLocation().getLocWithOffset(Offset);
|
|
|
|
Replaces.insert(tooling::Replacement(SourceMgr, Location, ReplaceChars,
|
|
|
|
ReplacementText));
|
2013-02-20 18:15:13 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// \brief Returns all the \c Replacements created during formatting.
|
|
|
|
const tooling::Replacements &generateReplacements() {
|
|
|
|
alignComments();
|
|
|
|
return Replaces;
|
|
|
|
}
|
|
|
|
|
2013-03-23 00:25:51 +08:00
|
|
|
void addUntouchableComment(unsigned Column) {
|
|
|
|
StoredComment Comment;
|
|
|
|
Comment.MinColumn = Column;
|
|
|
|
Comment.MaxColumn = Column;
|
|
|
|
Comment.Untouchable = true;
|
|
|
|
Comments.push_back(Comment);
|
|
|
|
}
|
|
|
|
|
2013-02-20 18:15:13 +08:00
|
|
|
private:
|
2013-03-27 19:52:18 +08:00
|
|
|
static StringRef getLineCommentPrefix(StringRef Comment) {
|
|
|
|
const char *KnownPrefixes[] = { "/// ", "///", "// ", "//" };
|
|
|
|
for (size_t i = 0; i < llvm::array_lengthof(KnownPrefixes); ++i)
|
|
|
|
if (Comment.startswith(KnownPrefixes[i]))
|
|
|
|
return KnownPrefixes[i];
|
|
|
|
return "";
|
|
|
|
}
|
|
|
|
|
2013-03-20 01:41:36 +08:00
|
|
|
/// \brief Finds a common prefix of lines of a block comment to properly
|
|
|
|
/// indent (and possibly decorate with '*'s) added lines.
|
|
|
|
///
|
2013-03-21 20:28:10 +08:00
|
|
|
/// The first line is ignored (it's special and starts with /*). The number of
|
|
|
|
/// lines should be more than one.
|
2013-03-20 01:41:36 +08:00
|
|
|
static StringRef findCommentLinesPrefix(ArrayRef<StringRef> Lines,
|
|
|
|
const char *PrefixChars = " *") {
|
2013-03-21 20:28:10 +08:00
|
|
|
assert(Lines.size() > 1);
|
2013-03-20 01:41:36 +08:00
|
|
|
StringRef Prefix(Lines[1].data(), Lines[1].find_first_not_of(PrefixChars));
|
|
|
|
for (size_t i = 2; i < Lines.size(); ++i) {
|
|
|
|
for (size_t j = 0; j < Prefix.size() && j < Lines[i].size(); ++j) {
|
|
|
|
if (Prefix[j] != Lines[i][j]) {
|
|
|
|
Prefix = Prefix.substr(0, j);
|
|
|
|
break;
|
|
|
|
}
|
2013-03-15 00:10:54 +08:00
|
|
|
}
|
|
|
|
}
|
2013-03-20 01:41:36 +08:00
|
|
|
return Prefix;
|
|
|
|
}
|
|
|
|
|
2013-03-27 19:52:18 +08:00
|
|
|
/// \brief Splits one line in a line or block comment, if it doesn't fit to
|
|
|
|
/// provided column limit. Removes trailing whitespace in each line.
|
|
|
|
///
|
|
|
|
/// \param Line points to the line contents without leading // or /*.
|
|
|
|
///
|
|
|
|
/// \param StartColumn is the column where the first character of Line will be
|
|
|
|
/// located after formatting.
|
|
|
|
///
|
|
|
|
/// \param LinePrefix is inserted after each line break.
|
|
|
|
///
|
|
|
|
/// When \param InPPDirective is true, each line break will be preceded by a
|
|
|
|
/// backslash in the last column to make line breaks inside the comment
|
|
|
|
/// visually consistent with line breaks outside the comment. This only makes
|
|
|
|
/// sense for block comments.
|
|
|
|
///
|
|
|
|
/// When \param CommentHasMoreLines is false, no line breaks/trailing
|
|
|
|
/// backslashes will be inserted after it.
|
2013-03-20 01:41:36 +08:00
|
|
|
void splitLineInComment(const FormatToken &Tok, StringRef Line,
|
|
|
|
size_t StartColumn, StringRef LinePrefix,
|
|
|
|
bool InPPDirective, bool CommentHasMoreLines,
|
|
|
|
const char *WhiteSpaceChars = " ") {
|
2013-03-27 19:52:18 +08:00
|
|
|
size_t ColumnLimit = calculateColumnLimit(Style, InPPDirective);
|
2013-03-20 01:41:36 +08:00
|
|
|
const char *TokenStart = SourceMgr.getCharacterData(Tok.Tok.getLocation());
|
2013-03-27 19:52:18 +08:00
|
|
|
|
|
|
|
StringRef TrimmedLine = Line.rtrim();
|
|
|
|
int TrailingSpaceLength = Line.size() - TrimmedLine.size();
|
|
|
|
|
|
|
|
// Don't touch leading whitespace.
|
|
|
|
Line = TrimmedLine.ltrim();
|
|
|
|
StartColumn += TrimmedLine.size() - Line.size();
|
|
|
|
|
|
|
|
while (Line.size() + StartColumn > ColumnLimit) {
|
2013-03-20 01:41:36 +08:00
|
|
|
// Try to break at the last whitespace before the column limit.
|
2013-03-21 20:28:10 +08:00
|
|
|
size_t SpacePos =
|
|
|
|
Line.find_last_of(WhiteSpaceChars, ColumnLimit - StartColumn + 1);
|
2013-03-20 01:41:36 +08:00
|
|
|
if (SpacePos == StringRef::npos) {
|
|
|
|
// Try to find any whitespace in the line.
|
|
|
|
SpacePos = Line.find_first_of(WhiteSpaceChars);
|
|
|
|
if (SpacePos == StringRef::npos) // No whitespace found, give up.
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
StringRef NextCut = Line.substr(0, SpacePos).rtrim();
|
|
|
|
StringRef RemainingLine = Line.substr(SpacePos).ltrim();
|
|
|
|
if (RemainingLine.empty())
|
|
|
|
break;
|
2013-03-21 20:28:10 +08:00
|
|
|
|
|
|
|
if (RemainingLine == "*/" && LinePrefix.endswith("* "))
|
|
|
|
LinePrefix = LinePrefix.substr(0, LinePrefix.size() - 2);
|
|
|
|
|
2013-03-20 01:41:36 +08:00
|
|
|
Line = RemainingLine;
|
|
|
|
|
|
|
|
size_t ReplaceChars = Line.begin() - NextCut.end();
|
|
|
|
breakToken(Tok, NextCut.end() - TokenStart, ReplaceChars, "", LinePrefix,
|
2013-03-27 19:52:18 +08:00
|
|
|
InPPDirective, 0, NextCut.size() + StartColumn);
|
2013-03-21 20:28:10 +08:00
|
|
|
StartColumn = LinePrefix.size();
|
2013-03-20 01:41:36 +08:00
|
|
|
}
|
|
|
|
|
2013-03-27 19:52:18 +08:00
|
|
|
if (TrailingSpaceLength > 0 || (InPPDirective && CommentHasMoreLines)) {
|
|
|
|
// Remove trailing whitespace/insert backslash. + 1 is for \n
|
|
|
|
breakToken(Tok, Line.end() - TokenStart, TrailingSpaceLength + 1, "", "",
|
|
|
|
InPPDirective, 0, Line.size() + StartColumn);
|
2013-03-20 01:41:36 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-03-27 19:52:18 +08:00
|
|
|
/// \brief Changes indentation of all lines in a block comment by Indent,
|
|
|
|
/// removes trailing whitespace from each line, splits lines that end up
|
|
|
|
/// exceeding the column limit.
|
2013-03-20 01:41:36 +08:00
|
|
|
void indentBlockComment(const AnnotatedToken &Tok, int Indent,
|
2013-03-21 20:28:10 +08:00
|
|
|
int WhitespaceStartColumn, int NewLines,
|
2013-03-20 01:41:36 +08:00
|
|
|
bool InPPDirective) {
|
2013-03-27 19:52:18 +08:00
|
|
|
assert(Tok.Type == TT_BlockComment);
|
|
|
|
int StartColumn = Indent + (NewLines == 0 ? WhitespaceStartColumn : 0);
|
2013-03-20 01:41:36 +08:00
|
|
|
const SourceLocation TokenLoc = Tok.FormatTok.Tok.getLocation();
|
|
|
|
const int CurrentIndent = SourceMgr.getSpellingColumnNumber(TokenLoc) - 1;
|
|
|
|
const int IndentDelta = Indent - CurrentIndent;
|
|
|
|
const StringRef Text(SourceMgr.getCharacterData(TokenLoc),
|
|
|
|
Tok.FormatTok.TokenLength);
|
|
|
|
assert(Text.startswith("/*") && Text.endswith("*/"));
|
|
|
|
|
|
|
|
SmallVector<StringRef, 16> Lines;
|
|
|
|
Text.split(Lines, "\n");
|
|
|
|
|
|
|
|
if (IndentDelta > 0) {
|
|
|
|
std::string WhiteSpace(IndentDelta, ' ');
|
|
|
|
for (size_t i = 1; i < Lines.size(); ++i) {
|
|
|
|
Replaces.insert(tooling::Replacement(
|
|
|
|
SourceMgr, TokenLoc.getLocWithOffset(Lines[i].data() - Text.data()),
|
|
|
|
0, WhiteSpace));
|
|
|
|
}
|
|
|
|
} else if (IndentDelta < 0) {
|
|
|
|
std::string WhiteSpace(-IndentDelta, ' ');
|
|
|
|
// Check that the line is indented enough.
|
|
|
|
for (size_t i = 1; i < Lines.size(); ++i) {
|
|
|
|
if (!Lines[i].startswith(WhiteSpace))
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
for (size_t i = 1; i < Lines.size(); ++i) {
|
|
|
|
Replaces.insert(tooling::Replacement(
|
|
|
|
SourceMgr, TokenLoc.getLocWithOffset(Lines[i].data() - Text.data()),
|
|
|
|
-IndentDelta, ""));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Split long lines in comments.
|
2013-03-27 19:52:18 +08:00
|
|
|
size_t OldPrefixSize = 0;
|
2013-03-21 20:28:10 +08:00
|
|
|
std::string NewPrefix;
|
|
|
|
if (Lines.size() > 1) {
|
|
|
|
StringRef CurrentPrefix = findCommentLinesPrefix(Lines);
|
2013-03-27 19:52:18 +08:00
|
|
|
OldPrefixSize = CurrentPrefix.size();
|
2013-03-21 20:28:10 +08:00
|
|
|
NewPrefix = (IndentDelta < 0)
|
|
|
|
? CurrentPrefix.substr(-IndentDelta).str()
|
|
|
|
: std::string(IndentDelta, ' ') + CurrentPrefix.str();
|
|
|
|
if (CurrentPrefix.endswith("*")) {
|
|
|
|
NewPrefix += " ";
|
2013-03-27 19:52:18 +08:00
|
|
|
++OldPrefixSize;
|
2013-03-21 20:28:10 +08:00
|
|
|
}
|
|
|
|
} else if (Tok.Parent == 0) {
|
|
|
|
NewPrefix = std::string(StartColumn, ' ') + " * ";
|
2013-03-20 01:41:36 +08:00
|
|
|
}
|
2013-03-15 21:42:02 +08:00
|
|
|
|
2013-03-21 20:28:10 +08:00
|
|
|
StartColumn += 2;
|
2013-03-20 01:41:36 +08:00
|
|
|
for (size_t i = 0; i < Lines.size(); ++i) {
|
2013-03-27 19:52:18 +08:00
|
|
|
StringRef Line = Lines[i].substr(i == 0 ? 2 : OldPrefixSize);
|
2013-03-20 01:41:36 +08:00
|
|
|
splitLineInComment(Tok.FormatTok, Line, StartColumn, NewPrefix,
|
|
|
|
InPPDirective, i != Lines.size() - 1);
|
2013-03-21 20:28:10 +08:00
|
|
|
StartColumn = NewPrefix.size();
|
2013-03-15 21:42:02 +08:00
|
|
|
}
|
2013-03-15 00:10:54 +08:00
|
|
|
}
|
|
|
|
|
2013-02-20 18:15:13 +08:00
|
|
|
std::string getNewLineText(unsigned NewLines, unsigned Spaces) {
|
|
|
|
return std::string(NewLines, '\n') + std::string(Spaces, ' ');
|
|
|
|
}
|
|
|
|
|
2013-03-20 01:41:36 +08:00
|
|
|
std::string getNewLineText(unsigned NewLines, unsigned Spaces,
|
|
|
|
unsigned WhitespaceStartColumn) {
|
2013-01-18 16:44:07 +08:00
|
|
|
std::string NewLineText;
|
|
|
|
if (NewLines > 0) {
|
2013-01-29 19:27:30 +08:00
|
|
|
unsigned Offset =
|
|
|
|
std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
|
2013-01-18 16:44:07 +08:00
|
|
|
for (unsigned i = 0; i < NewLines; ++i) {
|
|
|
|
NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
|
|
|
|
NewLineText += "\\\n";
|
|
|
|
Offset = 0;
|
|
|
|
}
|
|
|
|
}
|
2013-02-20 18:15:13 +08:00
|
|
|
return NewLineText + std::string(Spaces, ' ');
|
2013-01-18 16:44:07 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// \brief Structure to store a comment for later layout and alignment.
|
|
|
|
struct StoredComment {
|
|
|
|
FormatToken Tok;
|
|
|
|
unsigned MinColumn;
|
|
|
|
unsigned MaxColumn;
|
|
|
|
unsigned NewLines;
|
|
|
|
unsigned Spaces;
|
2013-03-23 00:25:51 +08:00
|
|
|
bool Untouchable;
|
2013-01-18 16:44:07 +08:00
|
|
|
};
|
|
|
|
SmallVector<StoredComment, 16> Comments;
|
|
|
|
typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
|
|
|
|
|
|
|
|
/// \brief Try to align all stashed comments.
|
|
|
|
void alignComments() {
|
|
|
|
unsigned MinColumn = 0;
|
|
|
|
unsigned MaxColumn = UINT_MAX;
|
|
|
|
comment_iterator Start = Comments.begin();
|
2013-03-15 00:10:54 +08:00
|
|
|
for (comment_iterator I = Start, E = Comments.end(); I != E; ++I) {
|
2013-01-18 16:44:07 +08:00
|
|
|
if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
|
|
|
|
alignComments(Start, I, MinColumn);
|
|
|
|
MinColumn = I->MinColumn;
|
|
|
|
MaxColumn = I->MaxColumn;
|
|
|
|
Start = I;
|
|
|
|
} else {
|
|
|
|
MinColumn = std::max(MinColumn, I->MinColumn);
|
|
|
|
MaxColumn = std::min(MaxColumn, I->MaxColumn);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
alignComments(Start, Comments.end(), MinColumn);
|
|
|
|
Comments.clear();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// \brief Put all the comments between \p I and \p E into \p Column.
|
|
|
|
void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
|
|
|
|
while (I != E) {
|
2013-03-23 00:25:51 +08:00
|
|
|
if (!I->Untouchable) {
|
|
|
|
unsigned Spaces = I->Spaces + Column - I->MinColumn;
|
2013-03-28 01:08:02 +08:00
|
|
|
storeReplacement(I->Tok, getNewLineText(I->NewLines, Spaces));
|
2013-03-23 00:25:51 +08:00
|
|
|
}
|
2013-01-18 16:44:07 +08:00
|
|
|
++I;
|
2013-01-11 02:45:26 +08:00
|
|
|
}
|
|
|
|
}
|
2013-01-18 16:44:07 +08:00
|
|
|
|
|
|
|
/// \brief Stores \p Text as the replacement for the whitespace in front of
|
|
|
|
/// \p Tok.
|
|
|
|
void storeReplacement(const FormatToken &Tok, const std::string Text) {
|
2013-01-30 17:46:12 +08:00
|
|
|
// Don't create a replacement, if it does not change anything.
|
|
|
|
if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
|
|
|
|
Tok.WhiteSpaceLength) == Text)
|
|
|
|
return;
|
|
|
|
|
2013-01-18 16:44:07 +08:00
|
|
|
Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
|
|
|
|
Tok.WhiteSpaceLength, Text));
|
|
|
|
}
|
|
|
|
|
|
|
|
SourceManager &SourceMgr;
|
|
|
|
tooling::Replacements Replaces;
|
2013-03-20 01:41:36 +08:00
|
|
|
const FormatStyle &Style;
|
2013-01-18 16:44:07 +08:00
|
|
|
};
|
2013-01-11 02:45:26 +08:00
|
|
|
|
2012-12-04 02:12:45 +08:00
|
|
|
class UnwrappedLineFormatter {
|
|
|
|
public:
|
2013-01-11 03:17:33 +08:00
|
|
|
UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
|
2013-01-14 21:08:07 +08:00
|
|
|
const AnnotatedLine &Line, unsigned FirstIndent,
|
2013-01-16 18:41:46 +08:00
|
|
|
const AnnotatedToken &RootToken,
|
2013-01-18 16:44:07 +08:00
|
|
|
WhitespaceManager &Whitespaces, bool StructuralError)
|
2012-12-19 05:05:13 +08:00
|
|
|
: Style(Style), SourceMgr(SourceMgr), Line(Line),
|
2013-01-18 16:44:07 +08:00
|
|
|
FirstIndent(FirstIndent), RootToken(RootToken),
|
2013-02-22 05:33:55 +08:00
|
|
|
Whitespaces(Whitespaces), Count(0) {}
|
2012-12-04 02:12:45 +08:00
|
|
|
|
2013-01-05 07:34:14 +08:00
|
|
|
/// \brief Formats an \c UnwrappedLine.
|
|
|
|
///
|
|
|
|
/// \returns The column after the last token in the last line of the
|
|
|
|
/// \c UnwrappedLine.
|
2013-02-28 19:05:57 +08:00
|
|
|
unsigned format(const AnnotatedLine *NextLine) {
|
2012-12-06 17:56:08 +08:00
|
|
|
// Initialize state dependent on indent.
|
2013-01-11 18:22:12 +08:00
|
|
|
LineState State;
|
2013-01-11 02:45:26 +08:00
|
|
|
State.Column = FirstIndent;
|
2013-01-08 22:56:18 +08:00
|
|
|
State.NextToken = &RootToken;
|
2013-03-13 15:49:51 +08:00
|
|
|
State.Stack.push_back(
|
2013-04-02 22:33:13 +08:00
|
|
|
ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
|
2013-03-13 15:49:51 +08:00
|
|
|
/*HasMultiParameterLine=*/ false));
|
2013-01-29 19:21:01 +08:00
|
|
|
State.VariablePos = 0;
|
2012-12-21 22:37:20 +08:00
|
|
|
State.LineContainsContinuedForLoopSection = false;
|
2013-02-08 23:28:42 +08:00
|
|
|
State.ParenLevel = 0;
|
2013-02-20 23:25:48 +08:00
|
|
|
State.StartOfStringLiteral = 0;
|
2013-02-18 19:05:07 +08:00
|
|
|
State.StartOfLineLevel = State.ParenLevel;
|
2012-12-06 17:56:08 +08:00
|
|
|
|
2013-01-16 22:55:28 +08:00
|
|
|
DEBUG({
|
|
|
|
DebugTokenState(*State.NextToken);
|
|
|
|
});
|
|
|
|
|
2012-12-06 17:56:08 +08:00
|
|
|
// The first token has already been indented and thus consumed.
|
2013-02-20 18:15:13 +08:00
|
|
|
moveStateToNextToken(State, /*DryRun=*/ false);
|
2012-12-04 02:12:45 +08:00
|
|
|
|
2013-02-01 19:00:45 +08:00
|
|
|
// If everything fits on a single line, just put it there.
|
2013-02-28 19:05:57 +08:00
|
|
|
unsigned ColumnLimit = Style.ColumnLimit;
|
|
|
|
if (NextLine && NextLine->InPPDirective &&
|
|
|
|
!NextLine->First.FormatTok.HasUnescapedNewline)
|
|
|
|
ColumnLimit = getColumnLimit();
|
|
|
|
if (Line.Last->TotalLength <= ColumnLimit - FirstIndent) {
|
2013-02-01 19:00:45 +08:00
|
|
|
while (State.NextToken != NULL) {
|
2012-12-19 05:05:13 +08:00
|
|
|
addTokenToState(false, false, State);
|
|
|
|
}
|
2013-02-01 19:00:45 +08:00
|
|
|
return State.Column;
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
2013-02-01 19:00:45 +08:00
|
|
|
|
2013-02-08 16:22:00 +08:00
|
|
|
// If the ObjC method declaration does not fit on a line, we should format
|
|
|
|
// it with one arg per line.
|
|
|
|
if (Line.Type == LT_ObjCMethodDecl)
|
|
|
|
State.Stack.back().BreakBeforeParameter = true;
|
|
|
|
|
2013-02-01 19:00:45 +08:00
|
|
|
// Find best solution in solution space.
|
|
|
|
return analyzeSolutionSpace(State);
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2013-01-16 22:55:28 +08:00
|
|
|
void DebugTokenState(const AnnotatedToken &AnnotatedTok) {
|
|
|
|
const Token &Tok = AnnotatedTok.FormatTok.Tok;
|
2013-01-29 19:27:30 +08:00
|
|
|
llvm::errs() << StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
|
|
|
|
Tok.getLength());
|
2013-01-16 22:55:28 +08:00
|
|
|
llvm::errs();
|
|
|
|
}
|
|
|
|
|
2013-01-11 18:22:12 +08:00
|
|
|
struct ParenState {
|
Fix some linebreak decisions in Google format.
Before:
f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa +
aaaaaaaaaaaaaaaaaaaa);
aaaaaaa(aaaaaaaaaaaaa, aaaaaaaaaaaaa, aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa,
aaaaaaaaaaaaaaaa));
After:
f(aaaaaaaaaaaaaaaaaaaa,
aaaaaaaaaaaaaaaaaaaa,
aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);
aaaaaaa(aaaaaaaaaaaaa,
aaaaaaaaaaaaa,
aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));
llvm-svn: 174363
2013-02-05 17:41:21 +08:00
|
|
|
ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
|
|
|
|
bool HasMultiParameterLine)
|
2013-02-08 23:28:42 +08:00
|
|
|
: Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
|
|
|
|
BreakBeforeClosingBrace(false), QuestionColumn(0),
|
2013-02-08 16:22:00 +08:00
|
|
|
AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
|
2013-03-02 00:48:32 +08:00
|
|
|
HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
|
2013-04-02 22:33:13 +08:00
|
|
|
StartOfFunctionCall(0), NestedNameSpecifierContinuation(0),
|
|
|
|
CallContinuation(0) {}
|
2012-12-25 00:43:00 +08:00
|
|
|
|
2012-12-04 02:12:45 +08:00
|
|
|
/// \brief The position to which a specific parenthesis level needs to be
|
|
|
|
/// indented.
|
2013-01-11 18:22:12 +08:00
|
|
|
unsigned Indent;
|
2012-12-04 02:12:45 +08:00
|
|
|
|
2012-12-06 17:56:08 +08:00
|
|
|
/// \brief The position of the last space on each level.
|
|
|
|
///
|
|
|
|
/// Used e.g. to break like:
|
|
|
|
/// functionCall(Parameter, otherCall(
|
|
|
|
/// OtherParameter));
|
2013-01-11 18:22:12 +08:00
|
|
|
unsigned LastSpace;
|
2012-12-04 02:12:45 +08:00
|
|
|
|
2012-12-06 17:56:08 +08:00
|
|
|
/// \brief The position the first "<<" operator encountered on each level.
|
|
|
|
///
|
|
|
|
/// Used to align "<<" operators. 0 if no such operator has been encountered
|
|
|
|
/// on a level.
|
2013-01-11 18:22:12 +08:00
|
|
|
unsigned FirstLessLess;
|
2012-12-06 17:56:08 +08:00
|
|
|
|
Fixes layout of right braces.
We now decide whether a newline should go before the closing brace
depending on whether a newline was inserted after the opening brace.
For example, we now insert a newline before '};' in:
static SomeClass WithALoooooooooooooooooooongName = {
100000000, \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"
};
... while not inserting a newline here:
static SomeClass = { a, b, c, d, e, f, g, h, i, j,
looooooooooooooooooooooooooooooooooongname,
looooooooooooooooooooooooooooooong };
Also fixes the formating of (column limit 25):
int x = {
avariable,
b(alongervariable)
};
llvm-svn: 172076
2013-01-10 23:58:26 +08:00
|
|
|
/// \brief Whether a newline needs to be inserted before the block's closing
|
|
|
|
/// brace.
|
|
|
|
///
|
|
|
|
/// We only want to insert a newline before the closing brace if there also
|
|
|
|
/// was a newline after the beginning left brace.
|
2013-01-11 18:22:12 +08:00
|
|
|
bool BreakBeforeClosingBrace;
|
|
|
|
|
2013-01-28 20:45:14 +08:00
|
|
|
/// \brief The column of a \c ? in a conditional expression;
|
|
|
|
unsigned QuestionColumn;
|
|
|
|
|
2013-01-31 22:59:26 +08:00
|
|
|
/// \brief Avoid bin packing, i.e. multiple parameters/elements on multiple
|
|
|
|
/// lines, in this context.
|
|
|
|
bool AvoidBinPacking;
|
|
|
|
|
|
|
|
/// \brief Break after the next comma (or all the commas in this context if
|
|
|
|
/// \c AvoidBinPacking is \c true).
|
2013-02-08 16:22:00 +08:00
|
|
|
bool BreakBeforeParameter;
|
2013-01-31 22:59:26 +08:00
|
|
|
|
|
|
|
/// \brief This context already has a line with more than one parameter.
|
2013-01-16 22:59:02 +08:00
|
|
|
bool HasMultiParameterLine;
|
2013-01-11 19:37:55 +08:00
|
|
|
|
2013-02-05 18:07:47 +08:00
|
|
|
/// \brief The position of the colon in an ObjC method declaration/call.
|
|
|
|
unsigned ColonPos;
|
2013-02-20 20:56:39 +08:00
|
|
|
|
2013-03-02 00:48:32 +08:00
|
|
|
/// \brief The start of the most recent function in a builder-type call.
|
|
|
|
unsigned StartOfFunctionCall;
|
|
|
|
|
2013-04-02 22:33:13 +08:00
|
|
|
/// \brief If a nested name specifier was broken over multiple lines, this
|
|
|
|
/// contains the start column of the second line. Otherwise 0.
|
|
|
|
unsigned NestedNameSpecifierContinuation;
|
|
|
|
|
|
|
|
/// \brief If a call expression was broken over multiple lines, this
|
|
|
|
/// contains the start column of the second line. Otherwise 0.
|
|
|
|
unsigned CallContinuation;
|
|
|
|
|
2013-01-11 18:22:12 +08:00
|
|
|
bool operator<(const ParenState &Other) const {
|
|
|
|
if (Indent != Other.Indent)
|
2013-01-11 22:23:32 +08:00
|
|
|
return Indent < Other.Indent;
|
2013-01-11 18:22:12 +08:00
|
|
|
if (LastSpace != Other.LastSpace)
|
|
|
|
return LastSpace < Other.LastSpace;
|
|
|
|
if (FirstLessLess != Other.FirstLessLess)
|
|
|
|
return FirstLessLess < Other.FirstLessLess;
|
2013-01-11 19:37:55 +08:00
|
|
|
if (BreakBeforeClosingBrace != Other.BreakBeforeClosingBrace)
|
|
|
|
return BreakBeforeClosingBrace;
|
2013-01-28 20:45:14 +08:00
|
|
|
if (QuestionColumn != Other.QuestionColumn)
|
|
|
|
return QuestionColumn < Other.QuestionColumn;
|
2013-01-31 22:59:26 +08:00
|
|
|
if (AvoidBinPacking != Other.AvoidBinPacking)
|
|
|
|
return AvoidBinPacking;
|
2013-02-08 16:22:00 +08:00
|
|
|
if (BreakBeforeParameter != Other.BreakBeforeParameter)
|
|
|
|
return BreakBeforeParameter;
|
2013-01-16 22:59:02 +08:00
|
|
|
if (HasMultiParameterLine != Other.HasMultiParameterLine)
|
|
|
|
return HasMultiParameterLine;
|
2013-02-05 18:07:47 +08:00
|
|
|
if (ColonPos != Other.ColonPos)
|
|
|
|
return ColonPos < Other.ColonPos;
|
2013-03-02 00:48:32 +08:00
|
|
|
if (StartOfFunctionCall != Other.StartOfFunctionCall)
|
|
|
|
return StartOfFunctionCall < Other.StartOfFunctionCall;
|
2013-04-02 22:33:13 +08:00
|
|
|
if (NestedNameSpecifierContinuation !=
|
|
|
|
Other.NestedNameSpecifierContinuation)
|
|
|
|
return NestedNameSpecifierContinuation <
|
|
|
|
Other.NestedNameSpecifierContinuation;
|
|
|
|
if (CallContinuation != Other.CallContinuation)
|
|
|
|
return CallContinuation < Other.CallContinuation;
|
2013-01-12 15:36:22 +08:00
|
|
|
return false;
|
2013-01-11 18:22:12 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
/// \brief The current state when indenting a unwrapped line.
|
|
|
|
///
|
|
|
|
/// As the indenting tries different combinations this is copied by value.
|
|
|
|
struct LineState {
|
|
|
|
/// \brief The number of used columns in the current line.
|
|
|
|
unsigned Column;
|
|
|
|
|
|
|
|
/// \brief The token that needs to be next formatted.
|
|
|
|
const AnnotatedToken *NextToken;
|
|
|
|
|
2013-01-29 19:27:30 +08:00
|
|
|
/// \brief The column of the first variable name in a variable declaration.
|
2012-12-21 22:37:20 +08:00
|
|
|
///
|
2013-01-29 19:27:30 +08:00
|
|
|
/// Used to align further variables if necessary.
|
2013-01-29 19:21:01 +08:00
|
|
|
unsigned VariablePos;
|
2012-12-21 22:37:20 +08:00
|
|
|
|
|
|
|
/// \brief \c true if this line contains a continued for-loop section.
|
|
|
|
bool LineContainsContinuedForLoopSection;
|
|
|
|
|
2013-02-08 23:28:42 +08:00
|
|
|
/// \brief The level of nesting inside (), [], <> and {}.
|
|
|
|
unsigned ParenLevel;
|
|
|
|
|
2013-02-18 19:05:07 +08:00
|
|
|
/// \brief The \c ParenLevel at the start of this line.
|
|
|
|
unsigned StartOfLineLevel;
|
|
|
|
|
2013-02-20 23:25:48 +08:00
|
|
|
/// \brief The start column of the string literal, if we're in a string
|
|
|
|
/// literal sequence, 0 otherwise.
|
|
|
|
unsigned StartOfStringLiteral;
|
|
|
|
|
2013-01-11 18:22:12 +08:00
|
|
|
/// \brief A stack keeping track of properties applying to parenthesis
|
|
|
|
/// levels.
|
|
|
|
std::vector<ParenState> Stack;
|
|
|
|
|
|
|
|
/// \brief Comparison operator to be able to used \c LineState in \c map.
|
|
|
|
bool operator<(const LineState &Other) const {
|
2013-02-19 17:28:55 +08:00
|
|
|
if (NextToken != Other.NextToken)
|
|
|
|
return NextToken < Other.NextToken;
|
|
|
|
if (Column != Other.Column)
|
|
|
|
return Column < Other.Column;
|
|
|
|
if (VariablePos != Other.VariablePos)
|
|
|
|
return VariablePos < Other.VariablePos;
|
|
|
|
if (LineContainsContinuedForLoopSection !=
|
2013-03-20 20:37:50 +08:00
|
|
|
Other.LineContainsContinuedForLoopSection)
|
2012-12-21 22:37:20 +08:00
|
|
|
return LineContainsContinuedForLoopSection;
|
2013-02-19 17:28:55 +08:00
|
|
|
if (ParenLevel != Other.ParenLevel)
|
|
|
|
return ParenLevel < Other.ParenLevel;
|
|
|
|
if (StartOfLineLevel != Other.StartOfLineLevel)
|
|
|
|
return StartOfLineLevel < Other.StartOfLineLevel;
|
2013-02-20 23:25:48 +08:00
|
|
|
if (StartOfStringLiteral != Other.StartOfStringLiteral)
|
|
|
|
return StartOfStringLiteral < Other.StartOfStringLiteral;
|
2013-02-19 17:28:55 +08:00
|
|
|
return Stack < Other.Stack;
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2012-12-04 22:54:30 +08:00
|
|
|
/// \brief Appends the next token to \p State and updates information
|
|
|
|
/// necessary for indentation.
|
|
|
|
///
|
|
|
|
/// Puts the token on the current line if \p Newline is \c true and adds a
|
|
|
|
/// line break and necessary indentation otherwise.
|
|
|
|
///
|
|
|
|
/// If \p DryRun is \c false, also creates and stores the required
|
|
|
|
/// \c Replacement.
|
2013-02-20 18:15:13 +08:00
|
|
|
unsigned addTokenToState(bool Newline, bool DryRun, LineState &State) {
|
2013-01-09 15:06:56 +08:00
|
|
|
const AnnotatedToken &Current = *State.NextToken;
|
|
|
|
const AnnotatedToken &Previous = *State.NextToken->Parent;
|
2012-12-04 02:12:45 +08:00
|
|
|
|
2013-03-20 23:58:10 +08:00
|
|
|
if (State.Stack.size() == 0 || Current.Type == TT_ImplicitStringLiteral) {
|
2013-02-01 19:00:45 +08:00
|
|
|
State.Column += State.NextToken->FormatTok.WhiteSpaceLength +
|
|
|
|
State.NextToken->FormatTok.TokenLength;
|
|
|
|
if (State.NextToken->Children.empty())
|
|
|
|
State.NextToken = NULL;
|
|
|
|
else
|
|
|
|
State.NextToken = &State.NextToken->Children[0];
|
2013-02-20 18:15:13 +08:00
|
|
|
return 0;
|
2013-02-01 19:00:45 +08:00
|
|
|
}
|
|
|
|
|
2013-04-02 22:33:13 +08:00
|
|
|
unsigned IndentedFurther =
|
|
|
|
std::max(State.Stack.back().LastSpace, State.Stack.back().Indent) + 4;
|
2012-12-04 02:12:45 +08:00
|
|
|
if (Newline) {
|
2013-01-03 02:33:23 +08:00
|
|
|
unsigned WhitespaceStartColumn = State.Column;
|
2013-01-10 19:52:21 +08:00
|
|
|
if (Current.is(tok::r_brace)) {
|
|
|
|
State.Column = Line.Level * 2;
|
2013-01-09 15:06:56 +08:00
|
|
|
} else if (Current.is(tok::string_literal) &&
|
2013-02-20 23:25:48 +08:00
|
|
|
State.StartOfStringLiteral != 0) {
|
|
|
|
State.Column = State.StartOfStringLiteral;
|
2013-02-18 19:59:17 +08:00
|
|
|
State.Stack.back().BreakBeforeParameter = true;
|
2013-01-09 15:06:56 +08:00
|
|
|
} else if (Current.is(tok::lessless) &&
|
2013-02-08 23:28:42 +08:00
|
|
|
State.Stack.back().FirstLessLess != 0) {
|
|
|
|
State.Column = State.Stack.back().FirstLessLess;
|
2013-04-02 22:33:13 +08:00
|
|
|
} else if (Previous.is(tok::coloncolon)) {
|
|
|
|
State.Column = IndentedFurther;
|
|
|
|
if (State.Stack.back().NestedNameSpecifierContinuation == 0)
|
|
|
|
State.Stack.back().NestedNameSpecifierContinuation = State.Column;
|
|
|
|
State.Column = State.Stack.back().NestedNameSpecifierContinuation;
|
|
|
|
} else if (Current.isOneOf(tok::period, tok::arrow)) {
|
|
|
|
State.Column = IndentedFurther;
|
|
|
|
if (State.Stack.back().CallContinuation == 0)
|
|
|
|
State.Stack.back().CallContinuation = State.Column;
|
|
|
|
State.Column = State.Stack.back().CallContinuation;
|
2013-01-28 20:45:14 +08:00
|
|
|
} else if (Current.Type == TT_ConditionalExpr) {
|
|
|
|
State.Column = State.Stack.back().QuestionColumn;
|
2013-01-29 19:21:01 +08:00
|
|
|
} else if (Previous.is(tok::comma) && State.VariablePos != 0 &&
|
2013-02-08 23:28:42 +08:00
|
|
|
((RootToken.is(tok::kw_for) && State.ParenLevel == 1) ||
|
|
|
|
State.ParenLevel == 0)) {
|
2013-01-29 19:21:01 +08:00
|
|
|
State.Column = State.VariablePos;
|
Allow breaking between a type and name in variable declarations.
This fixes llvm.org/PR14967 and is generall necessary to avoid
situations where the column limit is exceeded. The challenge is
restricting such lines splits, otherwise clang-format suddenly starts
breaking at bad places.
Before:
ReallyLongReturnType<TemplateParam1, TemplateParam2>
ReallyReallyLongFunctionName(
const std::string &SomeParameter,
const SomeType<string,
SomeOtherTemplateParameter> &ReallyReallyLongParameterName,
const SomeType<string,
SomeOtherTemplateParameter> &AnotherLongParameterName) {}
After:
ReallyLongReturnType<TemplateParam1, TemplateParam2>
ReallyReallyLongFunctionName(
const std::string &SomeParameter,
const SomeType<string, SomeOtherTemplateParameter> &
ReallyReallyLongParameterName,
const SomeType<string, SomeOtherTemplateParameter> &
AnotherLongParameterName) {}
llvm-svn: 175999
2013-02-25 02:54:32 +08:00
|
|
|
} else if (Previous.ClosesTemplateDeclaration ||
|
|
|
|
(Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
|
2013-04-02 22:33:13 +08:00
|
|
|
State.Column = State.Stack.back().Indent;
|
2013-02-05 18:07:47 +08:00
|
|
|
} else if (Current.Type == TT_ObjCSelectorName) {
|
|
|
|
if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
|
|
|
|
State.Column =
|
|
|
|
State.Stack.back().ColonPos - Current.FormatTok.TokenLength;
|
|
|
|
} else {
|
|
|
|
State.Column = State.Stack.back().Indent;
|
|
|
|
State.Stack.back().ColonPos =
|
|
|
|
State.Column + Current.FormatTok.TokenLength;
|
|
|
|
}
|
2013-04-02 22:33:13 +08:00
|
|
|
} else if (Current.Type == TT_StartOfName || Current.is(tok::question) ||
|
|
|
|
Previous.is(tok::equal) || isComparison(Previous) ||
|
|
|
|
Previous.Type == TT_ObjCMethodExpr) {
|
|
|
|
// Indent and extra 4 spaces if the current expression is continued.
|
|
|
|
State.Column = IndentedFurther;
|
2012-12-21 22:37:20 +08:00
|
|
|
} else {
|
2013-02-08 23:28:42 +08:00
|
|
|
State.Column = State.Stack.back().Indent;
|
2013-04-02 22:33:13 +08:00
|
|
|
if (State.Column == FirstIndent)
|
|
|
|
State.Column += 4;
|
2012-12-21 22:37:20 +08:00
|
|
|
}
|
|
|
|
|
2013-02-15 19:07:25 +08:00
|
|
|
if (Current.is(tok::question))
|
2013-02-24 05:01:55 +08:00
|
|
|
State.Stack.back().BreakBeforeParameter = true;
|
2013-03-13 22:41:29 +08:00
|
|
|
if (Previous.isOneOf(tok::comma, tok::semi) &&
|
2013-02-24 05:01:55 +08:00
|
|
|
!State.Stack.back().AvoidBinPacking)
|
2013-02-08 16:22:00 +08:00
|
|
|
State.Stack.back().BreakBeforeParameter = false;
|
2013-01-31 22:59:26 +08:00
|
|
|
|
2013-01-03 02:33:23 +08:00
|
|
|
if (!DryRun) {
|
2013-02-26 21:10:34 +08:00
|
|
|
unsigned NewLines = 1;
|
|
|
|
if (Current.Type == TT_LineComment)
|
|
|
|
NewLines =
|
|
|
|
std::max(NewLines, std::min(Current.FormatTok.NewlinesBefore,
|
|
|
|
Style.MaxEmptyLinesToKeep + 1));
|
2013-01-03 02:33:23 +08:00
|
|
|
if (!Line.InPPDirective)
|
2013-02-20 20:56:39 +08:00
|
|
|
Whitespaces.replaceWhitespace(Current, NewLines, State.Column,
|
2013-03-20 01:41:36 +08:00
|
|
|
WhitespaceStartColumn);
|
2013-01-03 02:33:23 +08:00
|
|
|
else
|
2013-02-20 20:56:39 +08:00
|
|
|
Whitespaces.replacePPWhitespace(Current, NewLines, State.Column,
|
2013-03-20 01:41:36 +08:00
|
|
|
WhitespaceStartColumn);
|
2013-01-03 02:33:23 +08:00
|
|
|
}
|
2012-12-04 02:12:45 +08:00
|
|
|
|
2013-02-08 23:28:42 +08:00
|
|
|
State.Stack.back().LastSpace = State.Column;
|
2013-02-18 19:05:07 +08:00
|
|
|
State.StartOfLineLevel = State.ParenLevel;
|
2013-02-24 05:01:55 +08:00
|
|
|
|
|
|
|
// Any break on this level means that the parent level has been broken
|
|
|
|
// and we need to avoid bin packing there.
|
|
|
|
for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
|
|
|
|
State.Stack[i].BreakBeforeParameter = true;
|
|
|
|
}
|
2013-03-13 22:41:29 +08:00
|
|
|
if (Current.isOneOf(tok::period, tok::arrow))
|
2013-02-27 17:47:53 +08:00
|
|
|
State.Stack.back().BreakBeforeParameter = true;
|
|
|
|
|
2013-02-24 05:01:55 +08:00
|
|
|
// If we break after {, we should also break before the corresponding }.
|
|
|
|
if (Previous.is(tok::l_brace))
|
|
|
|
State.Stack.back().BreakBeforeClosingBrace = true;
|
|
|
|
|
|
|
|
if (State.Stack.back().AvoidBinPacking) {
|
|
|
|
// If we are breaking after '(', '{', '<', this is not bin packing
|
|
|
|
// unless AllowAllParametersOfDeclarationOnNextLine is false.
|
Allow breaking between a type and name in variable declarations.
This fixes llvm.org/PR14967 and is generall necessary to avoid
situations where the column limit is exceeded. The challenge is
restricting such lines splits, otherwise clang-format suddenly starts
breaking at bad places.
Before:
ReallyLongReturnType<TemplateParam1, TemplateParam2>
ReallyReallyLongFunctionName(
const std::string &SomeParameter,
const SomeType<string,
SomeOtherTemplateParameter> &ReallyReallyLongParameterName,
const SomeType<string,
SomeOtherTemplateParameter> &AnotherLongParameterName) {}
After:
ReallyLongReturnType<TemplateParam1, TemplateParam2>
ReallyReallyLongFunctionName(
const std::string &SomeParameter,
const SomeType<string, SomeOtherTemplateParameter> &
ReallyReallyLongParameterName,
const SomeType<string, SomeOtherTemplateParameter> &
AnotherLongParameterName) {}
llvm-svn: 175999
2013-02-25 02:54:32 +08:00
|
|
|
if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
|
2013-02-24 05:01:55 +08:00
|
|
|
(!Style.AllowAllParametersOfDeclarationOnNextLine &&
|
|
|
|
Line.MustBeDeclaration))
|
|
|
|
State.Stack.back().BreakBeforeParameter = true;
|
|
|
|
}
|
2012-12-04 02:12:45 +08:00
|
|
|
} else {
|
2013-02-25 23:59:54 +08:00
|
|
|
// FIXME: Put VariablePos into ParenState and remove second part of if().
|
|
|
|
if (Current.is(tok::equal) &&
|
|
|
|
(RootToken.is(tok::kw_for) || State.ParenLevel == 0))
|
2013-01-29 19:21:01 +08:00
|
|
|
State.VariablePos = State.Column - Previous.FormatTok.TokenLength;
|
2012-12-21 22:37:20 +08:00
|
|
|
|
2013-02-11 20:36:37 +08:00
|
|
|
unsigned Spaces = State.NextToken->SpacesRequiredBefore;
|
2012-12-04 22:54:30 +08:00
|
|
|
|
2012-12-04 02:12:45 +08:00
|
|
|
if (!DryRun)
|
2013-03-20 01:41:36 +08:00
|
|
|
Whitespaces.replaceWhitespace(Current, 0, Spaces, State.Column);
|
2012-12-04 22:54:30 +08:00
|
|
|
|
2013-02-05 18:07:47 +08:00
|
|
|
if (Current.Type == TT_ObjCSelectorName &&
|
|
|
|
State.Stack.back().ColonPos == 0) {
|
|
|
|
if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
|
2013-03-20 20:37:50 +08:00
|
|
|
State.Column + Spaces + Current.FormatTok.TokenLength)
|
2013-02-05 18:07:47 +08:00
|
|
|
State.Stack.back().ColonPos =
|
|
|
|
State.Stack.back().Indent + Current.LongestObjCSelectorName;
|
|
|
|
else
|
|
|
|
State.Stack.back().ColonPos =
|
2013-02-07 00:00:26 +08:00
|
|
|
State.Column + Spaces + Current.FormatTok.TokenLength;
|
2013-02-05 18:07:47 +08:00
|
|
|
}
|
|
|
|
|
2013-01-30 03:41:55 +08:00
|
|
|
if (Current.Type != TT_LineComment &&
|
2013-03-13 22:41:29 +08:00
|
|
|
(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
|
2013-01-30 03:41:55 +08:00
|
|
|
State.NextToken->Parent->Type == TT_TemplateOpener))
|
2013-02-08 23:28:42 +08:00
|
|
|
State.Stack.back().Indent = State.Column + Spaces;
|
2013-02-04 16:34:57 +08:00
|
|
|
if (Previous.is(tok::comma) && !isTrailingComment(Current))
|
2013-02-08 23:28:42 +08:00
|
|
|
State.Stack.back().HasMultiParameterLine = true;
|
2013-01-16 22:59:02 +08:00
|
|
|
|
2012-12-06 17:56:08 +08:00
|
|
|
State.Column += Spaces;
|
2013-01-24 04:41:06 +08:00
|
|
|
if (Current.is(tok::l_paren) && Previous.is(tok::kw_if))
|
|
|
|
// Treat the condition inside an if as if it was a second function
|
|
|
|
// parameter, i.e. let nested calls have an indent of 4.
|
|
|
|
State.Stack.back().LastSpace = State.Column + 1; // 1 is length of "(".
|
2013-03-20 20:37:50 +08:00
|
|
|
else if (Previous.is(tok::comma))
|
2013-01-24 04:41:06 +08:00
|
|
|
State.Stack.back().LastSpace = State.Column;
|
2013-01-28 20:45:14 +08:00
|
|
|
else if ((Previous.Type == TT_BinaryOperator ||
|
2013-01-28 21:31:35 +08:00
|
|
|
Previous.Type == TT_ConditionalExpr ||
|
|
|
|
Previous.Type == TT_CtorInitializerColon) &&
|
2013-01-28 17:35:24 +08:00
|
|
|
getPrecedence(Previous) != prec::Assignment)
|
|
|
|
State.Stack.back().LastSpace = State.Column;
|
2013-02-14 16:42:54 +08:00
|
|
|
else if (Previous.Type == TT_InheritanceColon)
|
|
|
|
State.Stack.back().Indent = State.Column;
|
2013-01-28 15:35:34 +08:00
|
|
|
else if (Previous.ParameterCount > 1 &&
|
2013-03-13 22:41:29 +08:00
|
|
|
(Previous.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
|
2013-01-28 15:35:34 +08:00
|
|
|
Previous.Type == TT_TemplateOpener))
|
|
|
|
// If this function has multiple parameters, indent nested calls from
|
|
|
|
// the start of the first parameter.
|
|
|
|
State.Stack.back().LastSpace = State.Column;
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
2013-01-16 22:59:02 +08:00
|
|
|
|
2013-02-20 18:15:13 +08:00
|
|
|
return moveStateToNextToken(State, DryRun);
|
2012-12-04 22:54:30 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// \brief Mark the next token as consumed in \p State and modify its stacks
|
|
|
|
/// accordingly.
|
2013-02-20 18:15:13 +08:00
|
|
|
unsigned moveStateToNextToken(LineState &State, bool DryRun) {
|
2013-01-08 22:56:18 +08:00
|
|
|
const AnnotatedToken &Current = *State.NextToken;
|
2013-01-11 18:22:12 +08:00
|
|
|
assert(State.Stack.size());
|
2012-12-06 17:56:08 +08:00
|
|
|
|
2013-02-14 16:42:54 +08:00
|
|
|
if (Current.Type == TT_InheritanceColon)
|
|
|
|
State.Stack.back().AvoidBinPacking = true;
|
2013-01-11 18:22:12 +08:00
|
|
|
if (Current.is(tok::lessless) && State.Stack.back().FirstLessLess == 0)
|
|
|
|
State.Stack.back().FirstLessLess = State.Column;
|
2013-01-28 20:45:14 +08:00
|
|
|
if (Current.is(tok::question))
|
|
|
|
State.Stack.back().QuestionColumn = State.Column;
|
2013-03-13 22:41:29 +08:00
|
|
|
if (Current.isOneOf(tok::period, tok::arrow) &&
|
2013-03-02 00:48:32 +08:00
|
|
|
Line.Type == LT_BuilderTypeCall && State.ParenLevel == 0)
|
|
|
|
State.Stack.back().StartOfFunctionCall =
|
|
|
|
Current.LastInChainOfCalls ? 0 : State.Column;
|
Allow breaking between type and name in for loops.
This fixes llvm.org/PR15033.
Also: Always break before a parameter, if the previous parameter was
split over multiple lines. This was necessary to make the right
decisions in for-loops, almost always makes the code more readable and
also fixes llvm.org/PR14873.
Before:
for (llvm::ArrayRef<NamedDecl *>::iterator I = FD->getDeclsInPrototypeScope()
.begin(), E = FD->getDeclsInPrototypeScope().end();
I != E; ++I) {
}
foo(bar(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,
ccccccccccccccccccccccccccccc), d, bar(e, f));
After:
for (llvm::ArrayRef<NamedDecl *>::iterator
I = FD->getDeclsInPrototypeScope().begin(),
E = FD->getDeclsInPrototypeScope().end();
I != E; ++I) {
}
foo(bar(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,
ccccccccccccccccccccccccccccc),
d, bar(e, f));
llvm-svn: 175741
2013-02-21 23:00:29 +08:00
|
|
|
if (Current.Type == TT_CtorInitializerColon) {
|
|
|
|
if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
|
|
|
|
State.Stack.back().AvoidBinPacking = true;
|
|
|
|
State.Stack.back().BreakBeforeParameter = false;
|
2013-01-31 22:59:26 +08:00
|
|
|
}
|
2013-04-02 22:33:13 +08:00
|
|
|
if (Current.Type == TT_ObjCMethodSpecifier)
|
|
|
|
State.Stack.back().Indent += 4;
|
2012-12-06 17:56:08 +08:00
|
|
|
|
2013-02-08 23:28:42 +08:00
|
|
|
// Insert scopes created by fake parenthesis.
|
|
|
|
for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
|
|
|
|
ParenState NewParenState = State.Stack.back();
|
|
|
|
NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
|
2013-02-24 05:01:55 +08:00
|
|
|
NewParenState.BreakBeforeParameter = false;
|
2013-02-08 23:28:42 +08:00
|
|
|
State.Stack.push_back(NewParenState);
|
|
|
|
}
|
|
|
|
|
2012-12-24 21:43:52 +08:00
|
|
|
// If we encounter an opening (, [, { or <, we add a level to our stacks to
|
2012-12-04 22:54:30 +08:00
|
|
|
// prepare for the following tokens.
|
2013-03-13 22:41:29 +08:00
|
|
|
if (Current.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
|
2013-01-08 22:56:18 +08:00
|
|
|
State.NextToken->Type == TT_TemplateOpener) {
|
2013-01-11 18:22:12 +08:00
|
|
|
unsigned NewIndent;
|
2013-01-31 22:59:26 +08:00
|
|
|
bool AvoidBinPacking;
|
2013-01-10 22:36:46 +08:00
|
|
|
if (Current.is(tok::l_brace)) {
|
2013-01-31 22:59:26 +08:00
|
|
|
NewIndent = 2 + State.Stack.back().LastSpace;
|
|
|
|
AvoidBinPacking = false;
|
2013-01-10 22:36:46 +08:00
|
|
|
} else {
|
2013-03-02 00:48:32 +08:00
|
|
|
NewIndent = 4 + std::max(State.Stack.back().LastSpace,
|
|
|
|
State.Stack.back().StartOfFunctionCall);
|
2013-02-28 17:39:12 +08:00
|
|
|
AvoidBinPacking =
|
|
|
|
!Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
|
2013-01-10 22:36:46 +08:00
|
|
|
}
|
Fix some linebreak decisions in Google format.
Before:
f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa +
aaaaaaaaaaaaaaaaaaaa);
aaaaaaa(aaaaaaaaaaaaa, aaaaaaaaaaaaa, aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa,
aaaaaaaaaaaaaaaa));
After:
f(aaaaaaaaaaaaaaaaaaaa,
aaaaaaaaaaaaaaaaaaaa,
aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);
aaaaaaa(aaaaaaaaaaaaa,
aaaaaaaaaaaaa,
aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));
llvm-svn: 174363
2013-02-05 17:41:21 +08:00
|
|
|
State.Stack.push_back(
|
|
|
|
ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
|
|
|
|
State.Stack.back().HasMultiParameterLine));
|
2013-02-08 23:28:42 +08:00
|
|
|
++State.ParenLevel;
|
2012-12-04 22:54:30 +08:00
|
|
|
}
|
2012-12-04 02:12:45 +08:00
|
|
|
|
2013-02-08 16:22:00 +08:00
|
|
|
// If this '[' opens an ObjC call, determine whether all parameters fit into
|
|
|
|
// one line and put one per line if they don't.
|
|
|
|
if (Current.is(tok::l_square) && Current.Type == TT_ObjCMethodExpr &&
|
|
|
|
Current.MatchingParen != NULL) {
|
|
|
|
if (getLengthToMatchingParen(Current) + State.Column > getColumnLimit())
|
|
|
|
State.Stack.back().BreakBeforeParameter = true;
|
|
|
|
}
|
|
|
|
|
2012-12-24 21:43:52 +08:00
|
|
|
// If we encounter a closing ), ], } or >, we can remove a level from our
|
2012-12-04 22:54:30 +08:00
|
|
|
// stacks.
|
2013-03-13 22:41:29 +08:00
|
|
|
if (Current.isOneOf(tok::r_paren, tok::r_square) ||
|
2013-01-08 22:56:18 +08:00
|
|
|
(Current.is(tok::r_brace) && State.NextToken != &RootToken) ||
|
|
|
|
State.NextToken->Type == TT_TemplateCloser) {
|
2013-01-11 18:22:12 +08:00
|
|
|
State.Stack.pop_back();
|
2013-02-08 23:28:42 +08:00
|
|
|
--State.ParenLevel;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Remove scopes created by fake parenthesis.
|
|
|
|
for (unsigned i = 0, e = Current.FakeRParens; i != e; ++i) {
|
|
|
|
State.Stack.pop_back();
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
2013-01-10 22:36:46 +08:00
|
|
|
|
2013-02-20 23:32:58 +08:00
|
|
|
if (Current.is(tok::string_literal)) {
|
2013-02-20 23:25:48 +08:00
|
|
|
State.StartOfStringLiteral = State.Column;
|
|
|
|
} else if (Current.isNot(tok::comment)) {
|
|
|
|
State.StartOfStringLiteral = 0;
|
|
|
|
}
|
|
|
|
|
2013-02-20 18:15:13 +08:00
|
|
|
State.Column += Current.FormatTok.TokenLength;
|
|
|
|
|
2013-01-08 22:56:18 +08:00
|
|
|
if (State.NextToken->Children.empty())
|
|
|
|
State.NextToken = NULL;
|
|
|
|
else
|
|
|
|
State.NextToken = &State.NextToken->Children[0];
|
2013-01-10 22:36:46 +08:00
|
|
|
|
2013-02-20 18:15:13 +08:00
|
|
|
return breakProtrudingToken(Current, State, DryRun);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// \brief If the current token sticks out over the end of the line, break
|
|
|
|
/// it if possible.
|
|
|
|
unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
|
|
|
|
bool DryRun) {
|
|
|
|
if (Current.isNot(tok::string_literal))
|
|
|
|
return 0;
|
2013-03-09 02:59:48 +08:00
|
|
|
// Only break up default narrow strings.
|
2013-03-20 01:41:36 +08:00
|
|
|
const char *LiteralData = Current.FormatTok.Tok.getLiteralData();
|
|
|
|
if (!LiteralData || *LiteralData != '"')
|
2013-03-09 02:59:48 +08:00
|
|
|
return 0;
|
2013-02-20 18:15:13 +08:00
|
|
|
|
|
|
|
unsigned Penalty = 0;
|
|
|
|
unsigned TailOffset = 0;
|
|
|
|
unsigned TailLength = Current.FormatTok.TokenLength;
|
|
|
|
unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
|
|
|
|
unsigned OffsetFromStart = 0;
|
|
|
|
while (StartColumn + TailLength > getColumnLimit()) {
|
2013-03-20 01:41:36 +08:00
|
|
|
StringRef Text = StringRef(LiteralData + TailOffset, TailLength);
|
2013-03-01 21:29:19 +08:00
|
|
|
if (StartColumn + OffsetFromStart + 1 > getColumnLimit())
|
2013-03-01 21:14:08 +08:00
|
|
|
break;
|
2013-03-01 21:29:19 +08:00
|
|
|
StringRef::size_type SplitPoint = getSplitPoint(
|
|
|
|
Text, getColumnLimit() - StartColumn - OffsetFromStart - 1);
|
2013-02-20 18:15:13 +08:00
|
|
|
if (SplitPoint == StringRef::npos)
|
|
|
|
break;
|
|
|
|
assert(SplitPoint != 0);
|
|
|
|
// +2, because 'Text' starts after the opening quotes, and does not
|
|
|
|
// include the closing quote we need to insert.
|
|
|
|
unsigned WhitespaceStartColumn =
|
|
|
|
StartColumn + OffsetFromStart + SplitPoint + 2;
|
|
|
|
State.Stack.back().LastSpace = StartColumn;
|
|
|
|
if (!DryRun) {
|
2013-03-20 01:41:36 +08:00
|
|
|
Whitespaces.breakToken(Current.FormatTok, TailOffset + SplitPoint + 1,
|
|
|
|
0, "\"", "\"", Line.InPPDirective, StartColumn,
|
|
|
|
WhitespaceStartColumn);
|
2013-02-20 18:15:13 +08:00
|
|
|
}
|
|
|
|
TailOffset += SplitPoint + 1;
|
|
|
|
TailLength -= SplitPoint + 1;
|
|
|
|
OffsetFromStart = 1;
|
2013-02-26 20:52:34 +08:00
|
|
|
Penalty += Style.PenaltyExcessCharacter;
|
2013-02-27 17:47:53 +08:00
|
|
|
for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
|
|
|
|
State.Stack[i].BreakBeforeParameter = true;
|
2013-02-20 18:15:13 +08:00
|
|
|
}
|
|
|
|
State.Column = StartColumn + TailLength;
|
|
|
|
return Penalty;
|
|
|
|
}
|
|
|
|
|
|
|
|
StringRef::size_type
|
|
|
|
getSplitPoint(StringRef Text, StringRef::size_type Offset) {
|
2013-03-01 21:14:08 +08:00
|
|
|
StringRef::size_type SpaceOffset = Text.rfind(' ', Offset);
|
2013-03-05 04:03:38 +08:00
|
|
|
if (SpaceOffset != StringRef::npos && SpaceOffset != 0)
|
2013-03-01 21:29:19 +08:00
|
|
|
return SpaceOffset;
|
|
|
|
StringRef::size_type SlashOffset = Text.rfind('/', Offset);
|
2013-03-05 04:03:38 +08:00
|
|
|
if (SlashOffset != StringRef::npos && SlashOffset != 0)
|
2013-03-01 21:29:19 +08:00
|
|
|
return SlashOffset;
|
2013-03-09 02:59:48 +08:00
|
|
|
StringRef::size_type Split = getStartOfCharacter(Text, Offset);
|
|
|
|
if (Split != StringRef::npos && Split > 1)
|
2013-03-01 21:29:19 +08:00
|
|
|
// Do not split at 0.
|
2013-03-09 02:59:48 +08:00
|
|
|
return Split - 1;
|
2013-03-01 21:29:19 +08:00
|
|
|
return StringRef::npos;
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
|
|
|
|
2013-03-09 02:59:48 +08:00
|
|
|
StringRef::size_type
|
|
|
|
getStartOfCharacter(StringRef Text, StringRef::size_type Offset) {
|
|
|
|
StringRef::size_type NextEscape = Text.find('\\');
|
|
|
|
while (NextEscape != StringRef::npos && NextEscape < Offset) {
|
|
|
|
StringRef::size_type SequenceLength =
|
|
|
|
getEscapeSequenceLength(Text.substr(NextEscape));
|
|
|
|
if (Offset < NextEscape + SequenceLength)
|
|
|
|
return NextEscape;
|
|
|
|
NextEscape = Text.find('\\', NextEscape + SequenceLength);
|
|
|
|
}
|
|
|
|
return Offset;
|
|
|
|
}
|
|
|
|
|
|
|
|
unsigned getEscapeSequenceLength(StringRef Text) {
|
|
|
|
assert(Text[0] == '\\');
|
|
|
|
if (Text.size() < 2)
|
|
|
|
return 1;
|
|
|
|
|
|
|
|
switch (Text[1]) {
|
|
|
|
case 'u':
|
|
|
|
return 6;
|
|
|
|
case 'U':
|
|
|
|
return 10;
|
|
|
|
case 'x':
|
|
|
|
return getHexLength(Text);
|
|
|
|
default:
|
|
|
|
if (Text[1] >= '0' && Text[1] <= '7')
|
|
|
|
return getOctalLength(Text);
|
|
|
|
return 2;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
unsigned getHexLength(StringRef Text) {
|
|
|
|
unsigned I = 2; // Point after '\x'.
|
|
|
|
while (I < Text.size() && ((Text[I] >= '0' && Text[I] <= '9') ||
|
|
|
|
(Text[I] >= 'a' && Text[I] <= 'f') ||
|
|
|
|
(Text[I] >= 'A' && Text[I] <= 'F'))) {
|
|
|
|
++I;
|
|
|
|
}
|
|
|
|
return I;
|
|
|
|
}
|
|
|
|
|
|
|
|
unsigned getOctalLength(StringRef Text) {
|
|
|
|
unsigned I = 1;
|
|
|
|
while (I < Text.size() && I < 4 && (Text[I] >= '0' && Text[I] <= '7')) {
|
|
|
|
++I;
|
|
|
|
}
|
|
|
|
return I;
|
|
|
|
}
|
|
|
|
|
2013-01-09 18:16:05 +08:00
|
|
|
unsigned getColumnLimit() {
|
2013-03-27 19:52:18 +08:00
|
|
|
return calculateColumnLimit(Style, Line.InPPDirective);
|
2013-01-09 18:16:05 +08:00
|
|
|
}
|
|
|
|
|
2013-02-13 18:46:36 +08:00
|
|
|
/// \brief 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)
|
2013-02-22 05:33:55 +08:00
|
|
|
: State(State), NewLine(NewLine), Previous(Previous) {}
|
2013-02-13 18:46:36 +08:00
|
|
|
LineState State;
|
|
|
|
bool NewLine;
|
|
|
|
StateNode *Previous;
|
|
|
|
};
|
|
|
|
|
|
|
|
/// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
|
|
|
|
///
|
|
|
|
/// In case of equal penalties, we want to prefer states that were inserted
|
|
|
|
/// first. During state generation we make sure that we insert states first
|
|
|
|
/// that break the line as late as possible.
|
|
|
|
typedef std::pair<unsigned, unsigned> OrderedPenalty;
|
2013-02-01 19:00:45 +08:00
|
|
|
|
2013-02-13 18:46:36 +08:00
|
|
|
/// \brief An item in the prioritized BFS search queue. The \c StateNode's
|
|
|
|
/// \c State has the given \c OrderedPenalty.
|
|
|
|
typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
|
|
|
|
|
|
|
|
/// \brief The BFS queue type.
|
|
|
|
typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
|
|
|
|
std::greater<QueueItem> > QueueType;
|
2013-02-01 19:00:45 +08:00
|
|
|
|
|
|
|
/// \brief Analyze the entire solution space starting from \p InitialState.
|
2012-12-04 02:12:45 +08:00
|
|
|
///
|
2013-02-01 19:00:45 +08:00
|
|
|
/// This implements a variant of Dijkstra's algorithm on the graph that spans
|
|
|
|
/// the solution space (\c LineStates are the nodes). The algorithm tries to
|
|
|
|
/// find the shortest path (the one with lowest penalty) from \p InitialState
|
|
|
|
/// to a state where all tokens are placed.
|
2013-02-13 18:46:36 +08:00
|
|
|
unsigned analyzeSolutionSpace(LineState &InitialState) {
|
|
|
|
std::set<LineState> Seen;
|
|
|
|
|
2013-02-01 19:00:45 +08:00
|
|
|
// Insert start element into queue.
|
2013-02-14 22:26:07 +08:00
|
|
|
StateNode *Node =
|
2013-02-13 18:46:36 +08:00
|
|
|
new (Allocator.Allocate()) StateNode(InitialState, false, NULL);
|
|
|
|
Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
|
|
|
|
++Count;
|
2013-02-01 19:00:45 +08:00
|
|
|
|
|
|
|
// While not empty, take first element and follow edges.
|
|
|
|
while (!Queue.empty()) {
|
2013-02-13 18:46:36 +08:00
|
|
|
unsigned Penalty = Queue.top().first.first;
|
2013-02-14 22:26:07 +08:00
|
|
|
StateNode *Node = Queue.top().second;
|
2013-02-13 18:46:36 +08:00
|
|
|
if (Node->State.NextToken == NULL) {
|
2013-02-04 15:21:18 +08:00
|
|
|
DEBUG(llvm::errs() << "\n---\nPenalty for line: " << Penalty << "\n");
|
2013-02-01 19:00:45 +08:00
|
|
|
break;
|
2013-02-04 15:21:18 +08:00
|
|
|
}
|
2013-02-13 18:46:36 +08:00
|
|
|
Queue.pop();
|
2013-02-01 19:00:45 +08:00
|
|
|
|
2013-02-13 18:46:36 +08:00
|
|
|
if (!Seen.insert(Node->State).second)
|
|
|
|
// State already examined with lower penalty.
|
|
|
|
continue;
|
2013-02-01 19:00:45 +08:00
|
|
|
|
2013-02-13 18:54:19 +08:00
|
|
|
addNextStateToQueue(Penalty, Node, /*NewLine=*/ false);
|
|
|
|
addNextStateToQueue(Penalty, Node, /*NewLine=*/ true);
|
2013-02-01 19:00:45 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
if (Queue.empty())
|
|
|
|
// We were unable to find a solution, do nothing.
|
|
|
|
// FIXME: Add diagnostic?
|
2012-12-04 02:12:45 +08:00
|
|
|
return 0;
|
|
|
|
|
2013-02-01 19:00:45 +08:00
|
|
|
// Reconstruct the solution.
|
2013-02-13 18:46:36 +08:00
|
|
|
reconstructPath(InitialState, Queue.top().second);
|
2013-02-04 15:21:18 +08:00
|
|
|
DEBUG(llvm::errs() << "---\n");
|
2012-12-04 02:12:45 +08:00
|
|
|
|
2013-02-01 19:00:45 +08:00
|
|
|
// Return the column after the last token of the solution.
|
2013-02-13 18:46:36 +08:00
|
|
|
return Queue.top().second->State.Column;
|
|
|
|
}
|
|
|
|
|
|
|
|
void reconstructPath(LineState &State, StateNode *Current) {
|
|
|
|
// FIXME: This recursive implementation limits the possible number
|
|
|
|
// of tokens per line if compiled into a binary with small stack space.
|
|
|
|
// To become more independent of stack frame limitations we would need
|
|
|
|
// to also change the TokenAnnotator.
|
|
|
|
if (Current->Previous == NULL)
|
|
|
|
return;
|
|
|
|
reconstructPath(State, Current->Previous);
|
|
|
|
DEBUG({
|
|
|
|
if (Current->NewLine) {
|
2013-02-14 04:33:44 +08:00
|
|
|
llvm::errs()
|
|
|
|
<< "Penalty for splitting before "
|
|
|
|
<< Current->Previous->State.NextToken->FormatTok.Tok.getName()
|
|
|
|
<< ": " << Current->Previous->State.NextToken->SplitPenalty << "\n";
|
2013-02-13 18:46:36 +08:00
|
|
|
}
|
|
|
|
});
|
|
|
|
addTokenToState(Current->NewLine, false, State);
|
2013-02-01 19:00:45 +08:00
|
|
|
}
|
2012-12-04 02:12:45 +08:00
|
|
|
|
2013-02-13 18:54:19 +08:00
|
|
|
/// \brief Add the following state to the analysis queue \c Queue.
|
2013-02-01 19:00:45 +08:00
|
|
|
///
|
2013-02-13 18:54:19 +08:00
|
|
|
/// Assume the current state is \p PreviousNode and has been reached with a
|
2013-02-01 19:00:45 +08:00
|
|
|
/// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
|
2013-02-13 18:54:19 +08:00
|
|
|
void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
|
|
|
|
bool NewLine) {
|
2013-02-13 18:46:36 +08:00
|
|
|
if (NewLine && !canBreak(PreviousNode->State))
|
2013-02-01 19:00:45 +08:00
|
|
|
return;
|
2013-02-13 18:46:36 +08:00
|
|
|
if (!NewLine && mustBreak(PreviousNode->State))
|
2013-02-01 19:00:45 +08:00
|
|
|
return;
|
|
|
|
if (NewLine)
|
2013-02-13 18:46:36 +08:00
|
|
|
Penalty += PreviousNode->State.NextToken->SplitPenalty;
|
|
|
|
|
|
|
|
StateNode *Node = new (Allocator.Allocate())
|
|
|
|
StateNode(PreviousNode->State, NewLine, PreviousNode);
|
2013-02-20 18:15:13 +08:00
|
|
|
Penalty += addTokenToState(NewLine, true, Node->State);
|
2013-02-13 18:46:36 +08:00
|
|
|
if (Node->State.Column > getColumnLimit()) {
|
|
|
|
unsigned ExcessCharacters = Node->State.Column - getColumnLimit();
|
2013-02-04 15:21:18 +08:00
|
|
|
Penalty += Style.PenaltyExcessCharacter * ExcessCharacters;
|
2012-12-05 22:57:28 +08:00
|
|
|
}
|
2013-02-13 18:46:36 +08:00
|
|
|
|
|
|
|
Queue.push(QueueItem(OrderedPenalty(Penalty, Count), Node));
|
|
|
|
++Count;
|
2013-02-01 19:00:45 +08:00
|
|
|
}
|
2012-12-04 02:12:45 +08:00
|
|
|
|
2013-02-01 19:00:45 +08:00
|
|
|
/// \brief Returns \c true, if a line break after \p State is allowed.
|
|
|
|
bool canBreak(const LineState &State) {
|
|
|
|
if (!State.NextToken->CanBreakBefore &&
|
|
|
|
!(State.NextToken->is(tok::r_brace) &&
|
|
|
|
State.Stack.back().BreakBeforeClosingBrace))
|
|
|
|
return false;
|
|
|
|
// Trying to insert a parameter on a new line if there are already more than
|
|
|
|
// one parameter on the current line is bin packing.
|
Fix some linebreak decisions in Google format.
Before:
f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa +
aaaaaaaaaaaaaaaaaaaa);
aaaaaaa(aaaaaaaaaaaaa, aaaaaaaaaaaaa, aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa,
aaaaaaaaaaaaaaaa));
After:
f(aaaaaaaaaaaaaaaaaaaa,
aaaaaaaaaaaaaaaaaaaa,
aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);
aaaaaaa(aaaaaaaaaaaaa,
aaaaaaaaaaaaa,
aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));
llvm-svn: 174363
2013-02-05 17:41:21 +08:00
|
|
|
if (State.Stack.back().HasMultiParameterLine &&
|
2013-02-01 19:00:45 +08:00
|
|
|
State.Stack.back().AvoidBinPacking)
|
|
|
|
return false;
|
|
|
|
return true;
|
|
|
|
}
|
2012-12-17 22:34:14 +08:00
|
|
|
|
2013-02-01 19:00:45 +08:00
|
|
|
/// \brief Returns \c true, if a line break after \p State is mandatory.
|
|
|
|
bool mustBreak(const LineState &State) {
|
|
|
|
if (State.NextToken->MustBreakBefore)
|
|
|
|
return true;
|
|
|
|
if (State.NextToken->is(tok::r_brace) &&
|
|
|
|
State.Stack.back().BreakBeforeClosingBrace)
|
|
|
|
return true;
|
|
|
|
if (State.NextToken->Parent->is(tok::semi) &&
|
|
|
|
State.LineContainsContinuedForLoopSection)
|
|
|
|
return true;
|
2013-03-13 22:41:29 +08:00
|
|
|
if ((State.NextToken->Parent->isOneOf(tok::comma, tok::semi) ||
|
2013-02-24 05:01:55 +08:00
|
|
|
State.NextToken->is(tok::question) ||
|
|
|
|
State.NextToken->Type == TT_ConditionalExpr) &&
|
2013-02-08 16:22:00 +08:00
|
|
|
State.Stack.back().BreakBeforeParameter &&
|
2013-02-14 17:19:04 +08:00
|
|
|
!isTrailingComment(*State.NextToken) &&
|
Allow breaking between type and name in for loops.
This fixes llvm.org/PR15033.
Also: Always break before a parameter, if the previous parameter was
split over multiple lines. This was necessary to make the right
decisions in for-loops, almost always makes the code more readable and
also fixes llvm.org/PR14873.
Before:
for (llvm::ArrayRef<NamedDecl *>::iterator I = FD->getDeclsInPrototypeScope()
.begin(), E = FD->getDeclsInPrototypeScope().end();
I != E; ++I) {
}
foo(bar(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,
ccccccccccccccccccccccccccccc), d, bar(e, f));
After:
for (llvm::ArrayRef<NamedDecl *>::iterator
I = FD->getDeclsInPrototypeScope().begin(),
E = FD->getDeclsInPrototypeScope().end();
I != E; ++I) {
}
foo(bar(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,
ccccccccccccccccccccccccccccc),
d, bar(e, f));
llvm-svn: 175741
2013-02-21 23:00:29 +08:00
|
|
|
State.NextToken->isNot(tok::r_paren) &&
|
|
|
|
State.NextToken->isNot(tok::r_brace))
|
2013-02-01 19:00:45 +08:00
|
|
|
return true;
|
2013-02-08 16:22:00 +08:00
|
|
|
// FIXME: Comparing LongestObjCSelectorName to 0 is a hacky way of finding
|
|
|
|
// out whether it is the first parameter. Clean this up.
|
2013-02-05 18:07:47 +08:00
|
|
|
if (State.NextToken->Type == TT_ObjCSelectorName &&
|
2013-02-08 16:22:00 +08:00
|
|
|
State.NextToken->LongestObjCSelectorName == 0 &&
|
|
|
|
State.Stack.back().BreakBeforeParameter)
|
2013-02-05 18:07:47 +08:00
|
|
|
return true;
|
2013-02-01 19:00:45 +08:00
|
|
|
if ((State.NextToken->Type == TT_CtorInitializerColon ||
|
|
|
|
(State.NextToken->Parent->ClosesTemplateDeclaration &&
|
2013-02-08 23:28:42 +08:00
|
|
|
State.ParenLevel == 0)))
|
2013-02-01 19:00:45 +08:00
|
|
|
return true;
|
2013-03-14 21:45:21 +08:00
|
|
|
if (State.NextToken->Type == TT_InlineASMColon)
|
|
|
|
return true;
|
2013-03-15 22:57:30 +08:00
|
|
|
// This prevents breaks like:
|
|
|
|
// ...
|
|
|
|
// SomeParameter, OtherParameter).DoSomething(
|
|
|
|
// ...
|
|
|
|
// As they hide "DoSomething" and generally bad for readability.
|
|
|
|
if (State.NextToken->isOneOf(tok::period, tok::arrow) &&
|
|
|
|
getRemainingLength(State) + State.Column > getColumnLimit() &&
|
|
|
|
State.ParenLevel < State.StartOfLineLevel)
|
|
|
|
return true;
|
2013-02-01 19:00:45 +08:00
|
|
|
return false;
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
|
|
|
|
2013-03-15 22:57:30 +08:00
|
|
|
// Returns the total number of columns required for the remaining tokens.
|
|
|
|
unsigned getRemainingLength(const LineState &State) {
|
|
|
|
if (State.NextToken && State.NextToken->Parent)
|
|
|
|
return Line.Last->TotalLength - State.NextToken->Parent->TotalLength;
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2012-12-04 02:12:45 +08:00
|
|
|
FormatStyle Style;
|
|
|
|
SourceManager &SourceMgr;
|
2013-01-14 21:08:07 +08:00
|
|
|
const AnnotatedLine &Line;
|
2013-01-11 02:45:26 +08:00
|
|
|
const unsigned FirstIndent;
|
2013-01-08 22:56:18 +08:00
|
|
|
const AnnotatedToken &RootToken;
|
2013-01-18 16:44:07 +08:00
|
|
|
WhitespaceManager &Whitespaces;
|
2013-02-13 18:54:19 +08:00
|
|
|
|
|
|
|
llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
|
|
|
|
QueueType Queue;
|
|
|
|
// Increasing count of \c StateNode items we have created. This is used
|
|
|
|
// to create a deterministic order independent of the container.
|
|
|
|
unsigned Count;
|
2012-12-04 02:12:45 +08:00
|
|
|
};
|
|
|
|
|
2012-12-08 00:15:44 +08:00
|
|
|
class LexerBasedFormatTokenSource : public FormatTokenSource {
|
|
|
|
public:
|
|
|
|
LexerBasedFormatTokenSource(Lexer &Lex, SourceManager &SourceMgr)
|
2012-12-19 05:05:13 +08:00
|
|
|
: GreaterStashed(false), Lex(Lex), SourceMgr(SourceMgr),
|
2012-12-08 00:15:44 +08:00
|
|
|
IdentTable(Lex.getLangOpts()) {
|
|
|
|
Lex.SetKeepWhitespaceMode(true);
|
|
|
|
}
|
|
|
|
|
|
|
|
virtual FormatToken getNextToken() {
|
|
|
|
if (GreaterStashed) {
|
|
|
|
FormatTok.NewlinesBefore = 0;
|
|
|
|
FormatTok.WhiteSpaceStart =
|
|
|
|
FormatTok.Tok.getLocation().getLocWithOffset(1);
|
|
|
|
FormatTok.WhiteSpaceLength = 0;
|
|
|
|
GreaterStashed = false;
|
|
|
|
return FormatTok;
|
|
|
|
}
|
|
|
|
|
|
|
|
FormatTok = FormatToken();
|
|
|
|
Lex.LexFromRawLexer(FormatTok.Tok);
|
2013-01-07 15:56:50 +08:00
|
|
|
StringRef Text = rawTokenText(FormatTok.Tok);
|
2012-12-08 00:15:44 +08:00
|
|
|
FormatTok.WhiteSpaceStart = FormatTok.Tok.getLocation();
|
2013-01-06 06:56:06 +08:00
|
|
|
if (SourceMgr.getFileOffset(FormatTok.WhiteSpaceStart) == 0)
|
|
|
|
FormatTok.IsFirst = true;
|
2012-12-08 00:15:44 +08:00
|
|
|
|
|
|
|
// Consume and record whitespace until we find a significant token.
|
|
|
|
while (FormatTok.Tok.is(tok::unknown)) {
|
2013-02-11 20:33:24 +08:00
|
|
|
unsigned Newlines = Text.count('\n');
|
2013-03-04 21:43:19 +08:00
|
|
|
if (Newlines > 0)
|
|
|
|
FormatTok.LastNewlineOffset =
|
|
|
|
FormatTok.WhiteSpaceLength + Text.rfind('\n') + 1;
|
2013-02-11 20:33:24 +08:00
|
|
|
unsigned EscapedNewlines = Text.count("\\\n");
|
|
|
|
FormatTok.NewlinesBefore += Newlines;
|
|
|
|
FormatTok.HasUnescapedNewline |= EscapedNewlines != Newlines;
|
2012-12-08 00:15:44 +08:00
|
|
|
FormatTok.WhiteSpaceLength += FormatTok.Tok.getLength();
|
|
|
|
|
|
|
|
if (FormatTok.Tok.is(tok::eof))
|
|
|
|
return FormatTok;
|
|
|
|
Lex.LexFromRawLexer(FormatTok.Tok);
|
2013-01-07 15:56:50 +08:00
|
|
|
Text = rawTokenText(FormatTok.Tok);
|
2013-01-05 07:34:14 +08:00
|
|
|
}
|
2013-01-07 15:56:50 +08:00
|
|
|
|
|
|
|
// Now FormatTok is the next non-whitespace token.
|
|
|
|
FormatTok.TokenLength = Text.size();
|
|
|
|
|
2013-01-05 07:34:14 +08:00
|
|
|
// In case the token starts with escaped newlines, we want to
|
|
|
|
// take them into account as whitespace - this pattern is quite frequent
|
|
|
|
// in macro definitions.
|
|
|
|
// FIXME: What do we want to do with other escaped spaces, and escaped
|
|
|
|
// spaces or newlines in the middle of tokens?
|
|
|
|
// FIXME: Add a more explicit test.
|
|
|
|
unsigned i = 0;
|
2013-01-07 18:48:50 +08:00
|
|
|
while (i + 1 < Text.size() && Text[i] == '\\' && Text[i + 1] == '\n') {
|
2013-01-23 00:31:55 +08:00
|
|
|
// FIXME: ++FormatTok.NewlinesBefore is missing...
|
2013-01-05 07:34:14 +08:00
|
|
|
FormatTok.WhiteSpaceLength += 2;
|
2013-01-07 15:56:50 +08:00
|
|
|
FormatTok.TokenLength -= 2;
|
2013-01-05 07:34:14 +08:00
|
|
|
i += 2;
|
2012-12-08 00:15:44 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
if (FormatTok.Tok.is(tok::raw_identifier)) {
|
2013-01-05 07:34:14 +08:00
|
|
|
IdentifierInfo &Info = IdentTable.get(Text);
|
2012-12-22 01:58:39 +08:00
|
|
|
FormatTok.Tok.setIdentifierInfo(&Info);
|
2012-12-08 00:15:44 +08:00
|
|
|
FormatTok.Tok.setKind(Info.getTokenID());
|
|
|
|
}
|
|
|
|
|
|
|
|
if (FormatTok.Tok.is(tok::greatergreater)) {
|
|
|
|
FormatTok.Tok.setKind(tok::greater);
|
2013-02-28 18:06:05 +08:00
|
|
|
FormatTok.TokenLength = 1;
|
2012-12-08 00:15:44 +08:00
|
|
|
GreaterStashed = true;
|
|
|
|
}
|
|
|
|
|
2013-03-02 00:45:59 +08:00
|
|
|
// If we reformat comments, we remove trailing whitespace. Update the length
|
|
|
|
// accordingly.
|
|
|
|
if (FormatTok.Tok.is(tok::comment))
|
|
|
|
FormatTok.TokenLength = Text.rtrim().size();
|
|
|
|
|
2012-12-08 00:15:44 +08:00
|
|
|
return FormatTok;
|
|
|
|
}
|
|
|
|
|
2013-02-11 23:32:15 +08:00
|
|
|
IdentifierTable &getIdentTable() { return IdentTable; }
|
|
|
|
|
2012-12-08 00:15:44 +08:00
|
|
|
private:
|
|
|
|
FormatToken FormatTok;
|
|
|
|
bool GreaterStashed;
|
|
|
|
Lexer &Lex;
|
|
|
|
SourceManager &SourceMgr;
|
|
|
|
IdentifierTable IdentTable;
|
|
|
|
|
|
|
|
/// Returns the text of \c FormatTok.
|
2013-01-07 15:56:50 +08:00
|
|
|
StringRef rawTokenText(Token &Tok) {
|
2012-12-08 00:15:44 +08:00
|
|
|
return StringRef(SourceMgr.getCharacterData(Tok.getLocation()),
|
|
|
|
Tok.getLength());
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2012-12-04 02:12:45 +08:00
|
|
|
class Formatter : public UnwrappedLineConsumer {
|
|
|
|
public:
|
2013-01-14 22:14:23 +08:00
|
|
|
Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
|
|
|
|
SourceManager &SourceMgr,
|
2012-12-04 02:12:45 +08:00
|
|
|
const std::vector<CharSourceRange> &Ranges)
|
2013-01-10 23:05:09 +08:00
|
|
|
: Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
|
2013-03-20 01:41:36 +08:00
|
|
|
Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
|
2012-12-04 02:12:45 +08:00
|
|
|
|
2013-01-11 22:23:32 +08:00
|
|
|
virtual ~Formatter() {}
|
2012-12-05 05:05:31 +08:00
|
|
|
|
2012-12-04 02:12:45 +08:00
|
|
|
tooling::Replacements format() {
|
2012-12-08 00:15:44 +08:00
|
|
|
LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
|
2013-01-10 23:05:09 +08:00
|
|
|
UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
|
2012-12-05 01:27:50 +08:00
|
|
|
StructuralError = Parser.parse();
|
2013-01-05 07:34:14 +08:00
|
|
|
unsigned PreviousEndOfLineColumn = 0;
|
2013-02-11 23:32:15 +08:00
|
|
|
TokenAnnotator Annotator(Style, SourceMgr, Lex,
|
|
|
|
Tokens.getIdentTable().get("in"));
|
2013-02-06 22:22:40 +08:00
|
|
|
for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
|
|
|
|
Annotator.annotate(AnnotatedLines[i]);
|
|
|
|
}
|
|
|
|
deriveLocalStyle();
|
2013-01-14 21:08:07 +08:00
|
|
|
for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
|
2013-02-06 22:22:40 +08:00
|
|
|
Annotator.calculateFormattingInformation(AnnotatedLines[i]);
|
2013-03-13 23:53:12 +08:00
|
|
|
|
|
|
|
// Adapt level to the next line if this is a comment.
|
|
|
|
// FIXME: Can/should this be done in the UnwrappedLineParser?
|
|
|
|
if (i + 1 != e && AnnotatedLines[i].First.is(tok::comment) &&
|
|
|
|
AnnotatedLines[i].First.Children.empty() &&
|
|
|
|
AnnotatedLines[i + 1].First.isNot(tok::r_brace))
|
|
|
|
AnnotatedLines[i].Level = AnnotatedLines[i + 1].Level;
|
2013-01-14 21:08:07 +08:00
|
|
|
}
|
2013-02-09 01:38:27 +08:00
|
|
|
std::vector<int> IndentForLevel;
|
2013-02-14 17:58:41 +08:00
|
|
|
bool PreviousLineWasTouched = false;
|
2013-03-28 01:08:02 +08:00
|
|
|
const AnnotatedToken *PreviousLineLastToken = 0;
|
2013-01-14 21:08:07 +08:00
|
|
|
for (std::vector<AnnotatedLine>::iterator I = AnnotatedLines.begin(),
|
|
|
|
E = AnnotatedLines.end();
|
2013-01-11 03:49:59 +08:00
|
|
|
I != E; ++I) {
|
2013-01-14 21:08:07 +08:00
|
|
|
const AnnotatedLine &TheLine = *I;
|
2013-03-13 22:41:29 +08:00
|
|
|
const FormatToken &FirstTok = TheLine.First.FormatTok;
|
2013-02-14 17:58:41 +08:00
|
|
|
int Offset = getIndentOffset(TheLine.First);
|
2013-02-09 01:38:27 +08:00
|
|
|
while (IndentForLevel.size() <= TheLine.Level)
|
|
|
|
IndentForLevel.push_back(-1);
|
|
|
|
IndentForLevel.resize(TheLine.Level + 1);
|
2013-03-20 20:37:50 +08:00
|
|
|
bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
|
2013-03-02 02:11:39 +08:00
|
|
|
if (TheLine.First.is(tok::eof)) {
|
|
|
|
if (PreviousLineWasTouched) {
|
2013-03-13 22:41:29 +08:00
|
|
|
unsigned NewLines = std::min(FirstTok.NewlinesBefore, 1u);
|
2013-03-02 02:11:39 +08:00
|
|
|
Whitespaces.replaceWhitespace(TheLine.First, NewLines, /*Indent*/ 0,
|
2013-03-20 01:41:36 +08:00
|
|
|
/*WhitespaceStartColumn*/ 0);
|
2013-03-02 02:11:39 +08:00
|
|
|
}
|
|
|
|
} else if (TheLine.Type != LT_Invalid &&
|
2013-03-08 04:50:00 +08:00
|
|
|
(WasMoved || touchesLine(TheLine))) {
|
2013-02-14 17:58:41 +08:00
|
|
|
unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
|
2013-02-09 01:38:27 +08:00
|
|
|
unsigned Indent = LevelIndent;
|
|
|
|
if (static_cast<int>(Indent) + Offset >= 0)
|
|
|
|
Indent += Offset;
|
2013-03-13 22:41:29 +08:00
|
|
|
if (!FirstTok.WhiteSpaceStart.isValid() || StructuralError) {
|
2013-03-20 20:37:50 +08:00
|
|
|
Indent = LevelIndent =
|
|
|
|
SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
|
2013-02-09 01:38:27 +08:00
|
|
|
} else {
|
2013-03-28 01:08:02 +08:00
|
|
|
formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
|
|
|
|
TheLine.InPPDirective, PreviousEndOfLineColumn);
|
2013-02-09 01:38:27 +08:00
|
|
|
}
|
2013-01-16 18:41:46 +08:00
|
|
|
tryFitMultipleLinesInOne(Indent, I, E);
|
2013-01-14 21:08:07 +08:00
|
|
|
UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
|
2013-01-18 16:44:07 +08:00
|
|
|
TheLine.First, Whitespaces,
|
2013-01-14 21:08:07 +08:00
|
|
|
StructuralError);
|
2013-02-28 19:05:57 +08:00
|
|
|
PreviousEndOfLineColumn =
|
|
|
|
Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
|
2013-02-09 01:38:27 +08:00
|
|
|
IndentForLevel[TheLine.Level] = LevelIndent;
|
2013-02-14 17:58:41 +08:00
|
|
|
PreviousLineWasTouched = true;
|
2013-01-11 03:49:59 +08:00
|
|
|
} else {
|
2013-03-13 22:41:29 +08:00
|
|
|
if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
|
|
|
|
unsigned Indent =
|
|
|
|
SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
|
2013-02-13 00:51:23 +08:00
|
|
|
unsigned LevelIndent = Indent;
|
|
|
|
if (static_cast<int>(LevelIndent) - Offset >= 0)
|
|
|
|
LevelIndent -= Offset;
|
2013-03-20 22:31:47 +08:00
|
|
|
if (TheLine.First.isNot(tok::comment))
|
|
|
|
IndentForLevel[TheLine.Level] = LevelIndent;
|
2013-02-14 17:58:41 +08:00
|
|
|
|
|
|
|
// Remove trailing whitespace of the previous line if it was touched.
|
2013-03-08 04:50:00 +08:00
|
|
|
if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
|
2013-03-28 01:08:02 +08:00
|
|
|
formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
|
|
|
|
TheLine.InPPDirective, PreviousEndOfLineColumn);
|
2013-02-13 00:51:23 +08:00
|
|
|
}
|
2013-02-14 17:58:41 +08:00
|
|
|
// If we did not reformat this unwrapped line, the column at the end of
|
|
|
|
// the last token is unchanged - thus, we can calculate the end of the
|
|
|
|
// last token.
|
2013-03-13 22:41:29 +08:00
|
|
|
SourceLocation LastLoc = TheLine.Last->FormatTok.Tok.getLocation();
|
2013-02-14 17:58:41 +08:00
|
|
|
PreviousEndOfLineColumn =
|
2013-03-13 22:41:29 +08:00
|
|
|
SourceMgr.getSpellingColumnNumber(LastLoc) +
|
|
|
|
Lex.MeasureTokenLength(LastLoc, SourceMgr, Lex.getLangOpts()) - 1;
|
2013-02-14 17:58:41 +08:00
|
|
|
PreviousLineWasTouched = false;
|
2013-03-23 00:25:51 +08:00
|
|
|
if (TheLine.Last->is(tok::comment))
|
|
|
|
Whitespaces.addUntouchableComment(SourceMgr.getSpellingColumnNumber(
|
|
|
|
TheLine.Last->FormatTok.Tok.getLocation()) - 1);
|
2013-01-11 03:49:59 +08:00
|
|
|
}
|
2013-03-28 01:08:02 +08:00
|
|
|
PreviousLineLastToken = I->Last;
|
2013-01-11 03:49:59 +08:00
|
|
|
}
|
2013-01-18 16:44:07 +08:00
|
|
|
return Whitespaces.generateReplacements();
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2013-03-13 22:41:29 +08:00
|
|
|
void deriveLocalStyle() {
|
|
|
|
unsigned CountBoundToVariable = 0;
|
|
|
|
unsigned CountBoundToType = 0;
|
|
|
|
bool HasCpp03IncompatibleFormat = false;
|
|
|
|
for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
|
|
|
|
if (AnnotatedLines[i].First.Children.empty())
|
|
|
|
continue;
|
|
|
|
AnnotatedToken *Tok = &AnnotatedLines[i].First.Children[0];
|
|
|
|
while (!Tok->Children.empty()) {
|
|
|
|
if (Tok->Type == TT_PointerOrReference) {
|
|
|
|
bool SpacesBefore = Tok->FormatTok.WhiteSpaceLength > 0;
|
|
|
|
bool SpacesAfter = Tok->Children[0].FormatTok.WhiteSpaceLength > 0;
|
|
|
|
if (SpacesBefore && !SpacesAfter)
|
|
|
|
++CountBoundToVariable;
|
|
|
|
else if (!SpacesBefore && SpacesAfter)
|
|
|
|
++CountBoundToType;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Tok->Type == TT_TemplateCloser &&
|
|
|
|
Tok->Parent->Type == TT_TemplateCloser &&
|
|
|
|
Tok->FormatTok.WhiteSpaceLength == 0)
|
|
|
|
HasCpp03IncompatibleFormat = true;
|
|
|
|
Tok = &Tok->Children[0];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (Style.DerivePointerBinding) {
|
|
|
|
if (CountBoundToType > CountBoundToVariable)
|
|
|
|
Style.PointerBindsToType = true;
|
|
|
|
else if (CountBoundToType < CountBoundToVariable)
|
|
|
|
Style.PointerBindsToType = false;
|
|
|
|
}
|
|
|
|
if (Style.Standard == FormatStyle::LS_Auto) {
|
|
|
|
Style.Standard = HasCpp03IncompatibleFormat ? FormatStyle::LS_Cpp11
|
|
|
|
: FormatStyle::LS_Cpp03;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-02-09 01:38:27 +08:00
|
|
|
/// \brief Get the indent of \p Level from \p IndentForLevel.
|
|
|
|
///
|
|
|
|
/// \p IndentForLevel must contain the indent for the level \c l
|
|
|
|
/// at \p IndentForLevel[l], or a value < 0 if the indent for
|
|
|
|
/// that level is unknown.
|
2013-02-14 22:26:07 +08:00
|
|
|
unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
|
2013-02-09 01:38:27 +08:00
|
|
|
if (IndentForLevel[Level] != -1)
|
|
|
|
return IndentForLevel[Level];
|
2013-02-09 03:53:32 +08:00
|
|
|
if (Level == 0)
|
|
|
|
return 0;
|
2013-02-14 17:58:41 +08:00
|
|
|
return getIndent(IndentForLevel, Level - 1) + 2;
|
2013-02-09 01:38:27 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// \brief Get the offset of the line relatively to the level.
|
|
|
|
///
|
|
|
|
/// For example, 'public:' labels in classes are offset by 1 or 2
|
|
|
|
/// characters to the left from their level.
|
2013-02-14 17:58:41 +08:00
|
|
|
int getIndentOffset(const AnnotatedToken &RootToken) {
|
2013-03-28 01:08:02 +08:00
|
|
|
if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
|
2013-02-09 01:38:27 +08:00
|
|
|
return Style.AccessModifierOffset;
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2013-01-12 01:54:10 +08:00
|
|
|
/// \brief Tries to merge lines into one.
|
|
|
|
///
|
|
|
|
/// This will change \c Line and \c AnnotatedLine to contain the merged line,
|
|
|
|
/// if possible; note that \c I will be incremented when lines are merged.
|
|
|
|
///
|
|
|
|
/// Returns whether the resulting \c Line can fit in a single line.
|
2013-01-16 18:41:46 +08:00
|
|
|
void tryFitMultipleLinesInOne(unsigned Indent,
|
2013-01-14 21:08:07 +08:00
|
|
|
std::vector<AnnotatedLine>::iterator &I,
|
|
|
|
std::vector<AnnotatedLine>::iterator E) {
|
2013-01-16 18:41:46 +08:00
|
|
|
// We can never merge stuff if there are trailing line comments.
|
|
|
|
if (I->Last->Type == TT_LineComment)
|
|
|
|
return;
|
|
|
|
|
2013-02-28 19:05:57 +08:00
|
|
|
unsigned Limit = Style.ColumnLimit - Indent;
|
2013-02-22 05:33:55 +08:00
|
|
|
// If we already exceed the column limit, we set 'Limit' to 0. The different
|
|
|
|
// tryMerge..() functions can then decide whether to still do merging.
|
|
|
|
Limit = I->Last->TotalLength > Limit ? 0 : Limit - I->Last->TotalLength;
|
2013-01-16 15:02:34 +08:00
|
|
|
|
2013-01-21 22:18:28 +08:00
|
|
|
if (I + 1 == E || (I + 1)->Type == LT_Invalid)
|
2013-01-16 18:41:46 +08:00
|
|
|
return;
|
2013-01-14 22:14:23 +08:00
|
|
|
|
|
|
|
if (I->Last->is(tok::l_brace)) {
|
|
|
|
tryMergeSimpleBlock(I, E, Limit);
|
|
|
|
} else if (I->First.is(tok::kw_if)) {
|
|
|
|
tryMergeSimpleIf(I, E, Limit);
|
2013-01-14 23:40:57 +08:00
|
|
|
} else if (I->InPPDirective && (I->First.FormatTok.HasUnescapedNewline ||
|
|
|
|
I->First.FormatTok.IsFirst)) {
|
|
|
|
tryMergeSimplePPDirective(I, E, Limit);
|
2013-01-14 22:14:23 +08:00
|
|
|
}
|
2013-01-16 18:41:46 +08:00
|
|
|
return;
|
2013-01-14 22:14:23 +08:00
|
|
|
}
|
2013-01-12 01:54:10 +08:00
|
|
|
|
2013-01-14 23:40:57 +08:00
|
|
|
void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
|
|
|
|
std::vector<AnnotatedLine>::iterator E,
|
|
|
|
unsigned Limit) {
|
2013-02-22 05:33:55 +08:00
|
|
|
if (Limit == 0)
|
|
|
|
return;
|
2013-01-14 23:40:57 +08:00
|
|
|
AnnotatedLine &Line = *I;
|
2013-01-14 23:52:06 +08:00
|
|
|
if (!(I + 1)->InPPDirective || (I + 1)->First.FormatTok.HasUnescapedNewline)
|
|
|
|
return;
|
2013-01-14 23:40:57 +08:00
|
|
|
if (I + 2 != E && (I + 2)->InPPDirective &&
|
|
|
|
!(I + 2)->First.FormatTok.HasUnescapedNewline)
|
|
|
|
return;
|
2013-01-22 00:42:44 +08:00
|
|
|
if (1 + (I + 1)->Last->TotalLength > Limit)
|
2013-01-16 18:41:46 +08:00
|
|
|
return;
|
2013-01-14 23:40:57 +08:00
|
|
|
join(Line, *(++I));
|
|
|
|
}
|
|
|
|
|
2013-01-14 22:14:23 +08:00
|
|
|
void tryMergeSimpleIf(std::vector<AnnotatedLine>::iterator &I,
|
|
|
|
std::vector<AnnotatedLine>::iterator E,
|
|
|
|
unsigned Limit) {
|
2013-02-22 05:33:55 +08:00
|
|
|
if (Limit == 0)
|
|
|
|
return;
|
2013-01-15 00:24:39 +08:00
|
|
|
if (!Style.AllowShortIfStatementsOnASingleLine)
|
|
|
|
return;
|
2013-01-18 22:46:43 +08:00
|
|
|
if ((I + 1)->InPPDirective != I->InPPDirective ||
|
|
|
|
((I + 1)->InPPDirective &&
|
|
|
|
(I + 1)->First.FormatTok.HasUnescapedNewline))
|
|
|
|
return;
|
2013-01-14 22:14:23 +08:00
|
|
|
AnnotatedLine &Line = *I;
|
2013-01-16 15:02:34 +08:00
|
|
|
if (Line.Last->isNot(tok::r_paren))
|
|
|
|
return;
|
2013-01-22 00:42:44 +08:00
|
|
|
if (1 + (I + 1)->Last->TotalLength > Limit)
|
2013-01-14 22:14:23 +08:00
|
|
|
return;
|
|
|
|
if ((I + 1)->First.is(tok::kw_if) || (I + 1)->First.Type == TT_LineComment)
|
|
|
|
return;
|
|
|
|
// Only inline simple if's (no nested if or else).
|
|
|
|
if (I + 2 != E && (I + 2)->First.is(tok::kw_else))
|
|
|
|
return;
|
|
|
|
join(Line, *(++I));
|
|
|
|
}
|
|
|
|
|
|
|
|
void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
|
2013-01-29 19:27:30 +08:00
|
|
|
std::vector<AnnotatedLine>::iterator E,
|
|
|
|
unsigned Limit) {
|
2013-01-12 01:54:10 +08:00
|
|
|
// First, check that the current line allows merging. This is the case if
|
|
|
|
// we're not in a control flow statement and the last token is an opening
|
|
|
|
// brace.
|
2013-01-14 22:14:23 +08:00
|
|
|
AnnotatedLine &Line = *I;
|
2013-03-13 22:41:29 +08:00
|
|
|
if (Line.First.isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::r_brace,
|
|
|
|
tok::kw_else, tok::kw_try, tok::kw_catch,
|
|
|
|
tok::kw_for,
|
|
|
|
// This gets rid of all ObjC @ keywords and methods.
|
|
|
|
tok::at, tok::minus, tok::plus))
|
2013-01-14 22:14:23 +08:00
|
|
|
return;
|
2013-01-12 01:54:10 +08:00
|
|
|
|
2013-01-22 00:42:44 +08:00
|
|
|
AnnotatedToken *Tok = &(I + 1)->First;
|
|
|
|
if (Tok->Children.empty() && Tok->is(tok::r_brace) &&
|
2013-02-22 05:33:55 +08:00
|
|
|
!Tok->MustBreakBefore) {
|
|
|
|
// We merge empty blocks even if the line exceeds the column limit.
|
2013-02-11 20:36:37 +08:00
|
|
|
Tok->SpacesRequiredBefore = 0;
|
2013-02-22 05:33:55 +08:00
|
|
|
Tok->CanBreakBefore = true;
|
2013-01-22 00:42:44 +08:00
|
|
|
join(Line, *(I + 1));
|
|
|
|
I += 1;
|
2013-02-22 05:33:55 +08:00
|
|
|
} else if (Limit != 0) {
|
2013-01-22 00:42:44 +08:00
|
|
|
// Check that we still have three lines and they fit into the limit.
|
|
|
|
if (I + 2 == E || (I + 2)->Type == LT_Invalid ||
|
|
|
|
!nextTwoLinesFitInto(I, Limit))
|
2013-01-14 22:14:23 +08:00
|
|
|
return;
|
2013-01-12 01:54:10 +08:00
|
|
|
|
2013-01-22 00:42:44 +08:00
|
|
|
// Second, check that the next line does not contain any braces - if it
|
|
|
|
// does, readability declines when putting it into a single line.
|
|
|
|
if ((I + 1)->Last->Type == TT_LineComment || Tok->MustBreakBefore)
|
|
|
|
return;
|
|
|
|
do {
|
2013-03-13 22:41:29 +08:00
|
|
|
if (Tok->isOneOf(tok::l_brace, tok::r_brace))
|
2013-01-22 00:42:44 +08:00
|
|
|
return;
|
|
|
|
Tok = Tok->Children.empty() ? NULL : &Tok->Children.back();
|
|
|
|
} while (Tok != NULL);
|
|
|
|
|
|
|
|
// Last, check that the third line contains a single closing brace.
|
|
|
|
Tok = &(I + 2)->First;
|
|
|
|
if (!Tok->Children.empty() || Tok->isNot(tok::r_brace) ||
|
|
|
|
Tok->MustBreakBefore)
|
|
|
|
return;
|
2013-01-14 21:08:07 +08:00
|
|
|
|
2013-01-22 00:42:44 +08:00
|
|
|
join(Line, *(I + 1));
|
|
|
|
join(Line, *(I + 2));
|
|
|
|
I += 2;
|
2013-01-12 01:54:10 +08:00
|
|
|
}
|
2013-01-14 22:14:23 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
bool nextTwoLinesFitInto(std::vector<AnnotatedLine>::iterator I,
|
|
|
|
unsigned Limit) {
|
2013-01-22 00:42:44 +08:00
|
|
|
return 1 + (I + 1)->Last->TotalLength + 1 + (I + 2)->Last->TotalLength <=
|
|
|
|
Limit;
|
2013-01-12 01:54:10 +08:00
|
|
|
}
|
|
|
|
|
2013-01-14 21:08:07 +08:00
|
|
|
void join(AnnotatedLine &A, const AnnotatedLine &B) {
|
2013-02-22 05:33:55 +08:00
|
|
|
unsigned LengthA = A.Last->TotalLength + B.First.SpacesRequiredBefore;
|
2013-01-14 21:08:07 +08:00
|
|
|
A.Last->Children.push_back(B.First);
|
|
|
|
while (!A.Last->Children.empty()) {
|
|
|
|
A.Last->Children[0].Parent = A.Last;
|
2013-02-22 05:33:55 +08:00
|
|
|
A.Last->Children[0].TotalLength += LengthA;
|
2013-01-14 21:08:07 +08:00
|
|
|
A.Last = &A.Last->Children[0];
|
|
|
|
}
|
2012-12-05 01:27:50 +08:00
|
|
|
}
|
|
|
|
|
2013-03-13 15:49:51 +08:00
|
|
|
bool touchesRanges(const CharSourceRange &Range) {
|
2012-12-04 02:12:45 +08:00
|
|
|
for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
|
2013-03-08 04:50:00 +08:00
|
|
|
if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),
|
2013-01-11 03:49:59 +08:00
|
|
|
Ranges[i].getBegin()) &&
|
|
|
|
!SourceMgr.isBeforeInTranslationUnit(Ranges[i].getEnd(),
|
2013-03-08 04:50:00 +08:00
|
|
|
Range.getBegin()))
|
2013-01-11 03:49:59 +08:00
|
|
|
return true;
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
2013-01-11 03:49:59 +08:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2013-03-08 04:50:00 +08:00
|
|
|
bool touchesLine(const AnnotatedLine &TheLine) {
|
|
|
|
const FormatToken *First = &TheLine.First.FormatTok;
|
|
|
|
const FormatToken *Last = &TheLine.Last->FormatTok;
|
|
|
|
CharSourceRange LineRange = CharSourceRange::getTokenRange(
|
|
|
|
First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
|
|
|
|
Last->Tok.getLocation());
|
|
|
|
return touchesRanges(LineRange);
|
|
|
|
}
|
|
|
|
|
|
|
|
bool touchesEmptyLineBefore(const AnnotatedLine &TheLine) {
|
|
|
|
const FormatToken *First = &TheLine.First.FormatTok;
|
|
|
|
CharSourceRange LineRange = CharSourceRange::getCharRange(
|
|
|
|
First->WhiteSpaceStart,
|
|
|
|
First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset));
|
|
|
|
return touchesRanges(LineRange);
|
|
|
|
}
|
|
|
|
|
2013-01-11 03:49:59 +08:00
|
|
|
virtual void consumeUnwrappedLine(const UnwrappedLine &TheLine) {
|
2013-01-16 17:10:19 +08:00
|
|
|
AnnotatedLines.push_back(AnnotatedLine(TheLine));
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
|
|
|
|
2013-01-11 02:45:26 +08:00
|
|
|
/// \brief Add a new line and the required indent before the first Token
|
|
|
|
/// of the \c UnwrappedLine if there was no structural parsing error.
|
|
|
|
/// Returns the indent level of the \c UnwrappedLine.
|
2013-03-28 01:08:02 +08:00
|
|
|
void formatFirstToken(const AnnotatedToken &RootToken,
|
|
|
|
const AnnotatedToken *PreviousToken, unsigned Indent,
|
2013-02-09 01:38:27 +08:00
|
|
|
bool InPPDirective, unsigned PreviousEndOfLineColumn) {
|
2013-01-11 22:23:32 +08:00
|
|
|
const FormatToken &Tok = RootToken.FormatTok;
|
2013-01-11 02:45:26 +08:00
|
|
|
|
2013-01-29 19:27:30 +08:00
|
|
|
unsigned Newlines =
|
|
|
|
std::min(Tok.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
|
2013-01-11 02:45:26 +08:00
|
|
|
if (Newlines == 0 && !Tok.IsFirst)
|
|
|
|
Newlines = 1;
|
|
|
|
|
|
|
|
if (!InPPDirective || Tok.HasUnescapedNewline) {
|
2013-03-28 01:08:02 +08:00
|
|
|
// Insert extra new line before access specifiers.
|
|
|
|
if (PreviousToken && PreviousToken->isOneOf(tok::semi, tok::r_brace) &&
|
|
|
|
RootToken.isAccessSpecifier() && Tok.NewlinesBefore == 1)
|
|
|
|
++Newlines;
|
|
|
|
|
2013-03-20 01:41:36 +08:00
|
|
|
Whitespaces.replaceWhitespace(RootToken, Newlines, Indent, 0);
|
2013-01-11 02:45:26 +08:00
|
|
|
} else {
|
2013-01-18 16:44:07 +08:00
|
|
|
Whitespaces.replacePPWhitespace(RootToken, Newlines, Indent,
|
2013-03-20 01:41:36 +08:00
|
|
|
PreviousEndOfLineColumn);
|
2013-01-11 02:45:26 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-01-14 19:34:14 +08:00
|
|
|
DiagnosticsEngine &Diag;
|
2012-12-04 02:12:45 +08:00
|
|
|
FormatStyle Style;
|
|
|
|
Lexer &Lex;
|
|
|
|
SourceManager &SourceMgr;
|
2013-01-18 16:44:07 +08:00
|
|
|
WhitespaceManager Whitespaces;
|
2012-12-04 02:12:45 +08:00
|
|
|
std::vector<CharSourceRange> Ranges;
|
2013-01-14 21:08:07 +08:00
|
|
|
std::vector<AnnotatedLine> AnnotatedLines;
|
2012-12-05 01:27:50 +08:00
|
|
|
bool StructuralError;
|
2012-12-04 02:12:45 +08:00
|
|
|
};
|
|
|
|
|
2013-01-29 19:27:30 +08:00
|
|
|
tooling::Replacements
|
|
|
|
reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
|
|
|
|
std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
|
2013-01-10 23:05:09 +08:00
|
|
|
IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
|
2013-01-14 19:34:14 +08:00
|
|
|
OwningPtr<DiagnosticConsumer> DiagPrinter;
|
|
|
|
if (DiagClient == 0) {
|
|
|
|
DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
|
|
|
|
DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
|
|
|
|
DiagClient = DiagPrinter.get();
|
|
|
|
}
|
2013-01-10 23:05:09 +08:00
|
|
|
DiagnosticsEngine Diagnostics(
|
2013-01-13 03:30:44 +08:00
|
|
|
IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
|
2013-01-14 19:34:14 +08:00
|
|
|
DiagClient, false);
|
2013-01-10 23:05:09 +08:00
|
|
|
Diagnostics.setSourceManager(&SourceMgr);
|
|
|
|
Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
|
2012-12-04 02:12:45 +08:00
|
|
|
return formatter.format();
|
|
|
|
}
|
|
|
|
|
2013-01-10 21:08:12 +08:00
|
|
|
LangOptions getFormattingLangOpts() {
|
|
|
|
LangOptions LangOpts;
|
|
|
|
LangOpts.CPlusPlus = 1;
|
|
|
|
LangOpts.CPlusPlus11 = 1;
|
2013-03-22 18:01:29 +08:00
|
|
|
LangOpts.LineComment = 1;
|
2013-01-10 21:08:12 +08:00
|
|
|
LangOpts.Bool = 1;
|
|
|
|
LangOpts.ObjC1 = 1;
|
|
|
|
LangOpts.ObjC2 = 1;
|
|
|
|
return LangOpts;
|
|
|
|
}
|
|
|
|
|
2013-01-07 21:26:07 +08:00
|
|
|
} // namespace format
|
|
|
|
} // namespace clang
|