summaryrefslogtreecommitdiff
path: root/lib/Format
diff options
context:
space:
mode:
authorAbdoulaye Walsimou Gaye <awg@embtoolkit.org>2013-05-15 21:40:27 +0200
committerAbdoulaye Walsimou Gaye <awg@embtoolkit.org>2013-05-15 21:40:27 +0200
commitb0274c7c30af17c0255846bcd53cac4f7d76ddea (patch)
tree4243e33459039a96c26557de48f989e85c925a4c /lib/Format
parent38f7a3147aad1e25d0738356519cf9235f5c80b7 (diff)
parentcce70c7c5f0f4c1a41658fbed845f8b3a565c99c (diff)
downloadclang-embtk-support-master.tar.gz
clang-embtk-support-master.tar.bz2
clang-embtk-support-master.tar.xz
Merge branch 'master' into embtk-support-masterembtk-support-master
Signed-off-by: Abdoulaye Walsimou Gaye <awg@embtoolkit.org>
Diffstat (limited to 'lib/Format')
-rw-r--r--lib/Format/Format.cpp191
-rw-r--r--lib/Format/TokenAnnotator.cpp12
-rw-r--r--lib/Format/TokenAnnotator.h9
-rw-r--r--lib/Format/UnwrappedLineParser.cpp25
-rw-r--r--lib/Format/UnwrappedLineParser.h7
-rw-r--r--lib/Format/WhitespaceManager.cpp12
-rw-r--r--lib/Format/WhitespaceManager.h2
7 files changed, 163 insertions, 95 deletions
diff --git a/lib/Format/Format.cpp b/lib/Format/Format.cpp
index 9a320f94bd..9fd8ac6916 100644
--- a/lib/Format/Format.cpp
+++ b/lib/Format/Format.cpp
@@ -19,11 +19,9 @@
#include "TokenAnnotator.h"
#include "UnwrappedLineParser.h"
#include "WhitespaceManager.h"
-#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/OperatorPrecedence.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Format/Format.h"
-#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Lexer.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Allocator.h"
@@ -36,11 +34,21 @@ namespace llvm {
namespace yaml {
template <>
struct ScalarEnumerationTraits<clang::format::FormatStyle::LanguageStandard> {
- static void enumeration(IO &io,
- clang::format::FormatStyle::LanguageStandard &value) {
- io.enumCase(value, "C++03", clang::format::FormatStyle::LS_Cpp03);
- io.enumCase(value, "C++11", clang::format::FormatStyle::LS_Cpp11);
- io.enumCase(value, "Auto", clang::format::FormatStyle::LS_Auto);
+ static void enumeration(IO &IO,
+ clang::format::FormatStyle::LanguageStandard &Value) {
+ IO.enumCase(Value, "C++03", clang::format::FormatStyle::LS_Cpp03);
+ IO.enumCase(Value, "C++11", clang::format::FormatStyle::LS_Cpp11);
+ IO.enumCase(Value, "Auto", clang::format::FormatStyle::LS_Auto);
+ }
+};
+
+template <>
+struct ScalarEnumerationTraits<clang::format::FormatStyle::BraceBreakingStyle> {
+ static void
+ enumeration(IO &IO, clang::format::FormatStyle::BraceBreakingStyle &Value) {
+ IO.enumCase(Value, "Attach", clang::format::FormatStyle::BS_Attach);
+ IO.enumCase(Value, "Linux", clang::format::FormatStyle::BS_Linux);
+ IO.enumCase(Value, "Stroustrup", clang::format::FormatStyle::BS_Stroustrup);
}
};
@@ -85,6 +93,9 @@ template <> struct MappingTraits<clang::format::FormatStyle> {
IO.mapOptional("SpacesBeforeTrailingComments",
Style.SpacesBeforeTrailingComments);
IO.mapOptional("Standard", Style.Standard);
+ IO.mapOptional("IndentWidth", Style.IndentWidth);
+ IO.mapOptional("UseTab", Style.UseTab);
+ IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
}
};
}
@@ -111,6 +122,9 @@ FormatStyle getLLVMStyle() {
LLVMStyle.PointerBindsToType = false;
LLVMStyle.SpacesBeforeTrailingComments = 1;
LLVMStyle.Standard = FormatStyle::LS_Cpp03;
+ LLVMStyle.IndentWidth = 2;
+ LLVMStyle.UseTab = false;
+ LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
return LLVMStyle;
}
@@ -132,6 +146,9 @@ FormatStyle getGoogleStyle() {
GoogleStyle.PointerBindsToType = true;
GoogleStyle.SpacesBeforeTrailingComments = 2;
GoogleStyle.Standard = FormatStyle::LS_Auto;
+ GoogleStyle.IndentWidth = 2;
+ GoogleStyle.UseTab = false;
+ GoogleStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
return GoogleStyle;
}
@@ -185,7 +202,7 @@ std::string configurationAsText(const FormatStyle &Style) {
// reference here.
FormatStyle NonConstStyle = Style;
Output << NonConstStyle;
- return Text;
+ return Stream.str();
}
// Returns the length of everything up to the first possible line break after
@@ -267,7 +284,7 @@ private:
AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
NestedNameSpecifierContinuation(0), CallContinuation(0),
- VariablePos(0) {}
+ VariablePos(0), ForFakeParenthesis(false) {}
/// \brief The position to which a specific parenthesis level needs to be
/// indented.
@@ -326,6 +343,13 @@ private:
/// Used to align further variables if necessary.
unsigned VariablePos;
+ /// \brief \c true if this \c ParenState was created for a fake parenthesis.
+ ///
+ /// Does not need to be considered for memoization / the comparison function
+ /// as otherwise identical states will have the same fake/non-fake
+ /// \c ParenStates.
+ bool ForFakeParenthesis;
+
bool operator<(const ParenState &Other) const {
if (Indent != Other.Indent)
return Indent < Other.Indent;
@@ -429,7 +453,7 @@ private:
if (Newline) {
unsigned WhitespaceStartColumn = State.Column;
if (Current.is(tok::r_brace)) {
- State.Column = Line.Level * 2;
+ State.Column = Line.Level * Style.IndentWidth;
} else if (Current.is(tok::string_literal) &&
State.StartOfStringLiteral != 0) {
State.Column = State.StartOfStringLiteral;
@@ -480,6 +504,8 @@ private:
!State.Stack.back().AvoidBinPacking) ||
Previous.Type == TT_BinaryOperator)
State.Stack.back().BreakBeforeParameter = false;
+ if (Previous.Type == TT_TemplateCloser && State.ParenLevel == 0)
+ State.Stack.back().BreakBeforeParameter = false;
if (!DryRun) {
unsigned NewLines = 1;
@@ -507,6 +533,7 @@ private:
}
const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
+ TokenBefore->Type != TT_TemplateCloser &&
TokenBefore->Type != TT_BinaryOperator && !TokenBefore->opensScope())
State.Stack.back().BreakBeforeParameter = true;
@@ -517,7 +544,8 @@ private:
if (State.Stack.back().AvoidBinPacking) {
// If we are breaking after '(', '{', '<', this is not bin packing
// unless AllowAllParametersOfDeclarationOnNextLine is false.
- if ((Previous.isNot(tok::l_paren) && Previous.isNot(tok::l_brace)) ||
+ if (!(Previous.isOneOf(tok::l_paren, tok::l_brace) ||
+ Previous.Type == TT_BinaryOperator) ||
(!Style.AllowAllParametersOfDeclarationOnNextLine &&
Line.MustBeDeclaration))
State.Stack.back().BreakBeforeParameter = true;
@@ -604,6 +632,11 @@ private:
Current.LastInChainOfCalls ? 0 : State.Column +
Current.FormatTok.TokenLength;
if (Current.Type == TT_CtorInitializerColon) {
+ // Indent 2 from the column, so:
+ // SomeClass::SomeClass()
+ // : First(...), ...
+ // Next(...)
+ // ^ line up here.
State.Stack.back().Indent = State.Column + 2;
if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
State.Stack.back().AvoidBinPacking = true;
@@ -633,6 +666,7 @@ private:
E = Current.FakeLParens.rend();
I != E; ++I) {
ParenState NewParenState = State.Stack.back();
+ NewParenState.ForFakeParenthesis = true;
NewParenState.Indent =
std::max(std::max(State.Column, NewParenState.Indent),
State.Stack.back().LastSpace);
@@ -654,27 +688,31 @@ private:
// prepare for the following tokens.
if (Current.opensScope()) {
unsigned NewIndent;
+ unsigned LastSpace = State.Stack.back().LastSpace;
bool AvoidBinPacking;
if (Current.is(tok::l_brace)) {
- NewIndent = 2 + State.Stack.back().LastSpace;
+ NewIndent = Style.IndentWidth + LastSpace;
AvoidBinPacking = false;
} else {
- NewIndent = 4 + std::max(State.Stack.back().LastSpace,
- State.Stack.back().StartOfFunctionCall);
+ NewIndent =
+ 4 + std::max(LastSpace, State.Stack.back().StartOfFunctionCall);
AvoidBinPacking = !Style.BinPackParameters;
}
- State.Stack.push_back(
- ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
- State.Stack.back().NoLineBreak));
if (Current.NoMoreTokensOnLevel && Current.FakeLParens.empty()) {
// This parenthesis was the last token possibly making use of Indent and
- // LastSpace of the next higher ParenLevel. Thus, erase them to acieve
+ // LastSpace of the next higher ParenLevel. Thus, erase them to achieve
// better memoization results.
- State.Stack[State.Stack.size() - 2].Indent = 0;
- State.Stack[State.Stack.size() - 2].LastSpace = 0;
+ for (unsigned i = State.Stack.size() - 1; i > 0; --i) {
+ State.Stack[i].Indent = 0;
+ State.Stack[i].LastSpace = 0;
+ if (!State.Stack[i].ForFakeParenthesis)
+ break;
+ }
}
+ State.Stack.push_back(ParenState(NewIndent, LastSpace, AvoidBinPacking,
+ State.Stack.back().NoLineBreak));
++State.ParenLevel;
}
@@ -702,10 +740,10 @@ private:
State.Stack.back().VariablePos = VariablePos;
}
- if (Current.is(tok::string_literal)) {
+ if (Current.is(tok::string_literal) && State.StartOfStringLiteral == 0) {
State.StartOfStringLiteral = State.Column;
- } else if (Current.isNot(tok::comment)) {
- State.StartOfStringLiteral = 0;
+ } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash,
+ tok::string_literal)) {
}
State.Column += Current.FormatTok.TokenLength;
@@ -720,10 +758,18 @@ private:
/// \brief If the current token sticks out over the end of the line, break
/// it if possible.
+ ///
+ /// \returns An extra penalty if a token was broken, otherwise 0.
+ ///
+ /// Note that the penalty of the token protruding the allowed line length is
+ /// already handled in \c addNextStateToQueue; the returned penalty will only
+ /// cover the cost of the additional line breaks.
unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
- bool DryRun) {
+ bool DryRun,
+ unsigned UnbreakableTailLength = 0) {
llvm::OwningPtr<BreakableToken> Token;
- unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
+ unsigned StartColumn = State.Column - Current.FormatTok.TokenLength -
+ UnbreakableTailLength;
if (Current.is(tok::string_literal)) {
// Only break up default narrow strings.
const char *LiteralData = SourceMgr.getCharacterData(
@@ -744,42 +790,55 @@ private:
Current.Parent->Type != TT_ImplicitStringLiteral)) {
Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn));
} else {
- return 0;
+ // If a token that we cannot breaks protrudes, it means we were unable to
+ // break a sequence of tokens due to disallowed breaks between the tokens.
+ // Thus, we recursively search backwards to try to find a breakable token.
+ if (State.Column <= getColumnLimit() ||
+ Current.CanBreakBefore || !Current.Parent)
+ return 0;
+ return breakProtrudingToken(
+ *Current.Parent, State, DryRun,
+ UnbreakableTailLength + Current.FormatTok.TokenLength);
}
+ if (UnbreakableTailLength >= getColumnLimit())
+ return 0;
+ unsigned RemainingSpace = getColumnLimit() - UnbreakableTailLength;
bool BreakInserted = false;
unsigned Penalty = 0;
+ unsigned PositionAfterLastLineInToken = 0;
for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
++LineIndex) {
unsigned TailOffset = 0;
- unsigned RemainingLength =
+ unsigned RemainingTokenLength =
Token->getLineLengthAfterSplit(LineIndex, TailOffset);
- while (RemainingLength > getColumnLimit()) {
+ while (RemainingTokenLength > RemainingSpace) {
BreakableToken::Split Split =
- Token->getSplit(LineIndex, TailOffset, getColumnLimit());
+ Token->getSplit(LineIndex, TailOffset, RemainingSpace);
if (Split.first == StringRef::npos)
break;
assert(Split.first != 0);
- unsigned NewRemainingLength = Token->getLineLengthAfterSplit(
+ unsigned NewRemainingTokenLength = Token->getLineLengthAfterSplit(
LineIndex, TailOffset + Split.first + Split.second);
- if (NewRemainingLength >= RemainingLength)
+ if (NewRemainingTokenLength >= RemainingTokenLength)
break;
if (!DryRun) {
Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
Whitespaces);
}
TailOffset += Split.first + Split.second;
- RemainingLength = NewRemainingLength;
+ RemainingTokenLength = NewRemainingTokenLength;
Penalty += Style.PenaltyExcessCharacter;
BreakInserted = true;
}
- State.Column = RemainingLength;
+ PositionAfterLastLineInToken = RemainingTokenLength;
if (!DryRun) {
Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
}
}
if (BreakInserted) {
+ State.Column = PositionAfterLastLineInToken + UnbreakableTailLength;
for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
State.Stack[i].BreakBeforeParameter = true;
State.Stack.back().LastSpace = StartColumn;
@@ -961,6 +1020,10 @@ private:
getRemainingLength(State) + State.Column > getColumnLimit() &&
State.ParenLevel < State.StartOfLineLevel)
return true;
+
+ if (Current.Type == TT_StartOfName && Line.MightBeFunctionDecl &&
+ State.Stack.back().BreakBeforeParameter && State.ParenLevel == 0)
+ return true;
return false;
}
@@ -1082,17 +1145,16 @@ private:
class Formatter : public UnwrappedLineConsumer {
public:
- Formatter(DiagnosticsEngine &Diag, const FormatStyle &Style, Lexer &Lex,
- SourceManager &SourceMgr,
+ Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
const std::vector<CharSourceRange> &Ranges)
- : Diag(Diag), Style(Style), Lex(Lex), SourceMgr(SourceMgr),
+ : Style(Style), Lex(Lex), SourceMgr(SourceMgr),
Whitespaces(SourceMgr, Style), Ranges(Ranges) {}
virtual ~Formatter() {}
tooling::Replacements format() {
LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
- UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
+ UnwrappedLineParser Parser(Style, Tokens, *this);
bool StructuralError = Parser.parse();
unsigned PreviousEndOfLineColumn = 0;
TokenAnnotator Annotator(Style, SourceMgr, Lex,
@@ -1136,9 +1198,15 @@ public:
(touchesLine(TheLine) || touchesPPDirective(I + 1, E)))
FormatPPDirective = true;
+ // Determine indent and try to merge multiple unwrapped lines.
while (IndentForLevel.size() <= TheLine.Level)
IndentForLevel.push_back(-1);
IndentForLevel.resize(TheLine.Level + 1);
+ unsigned Indent = getIndent(IndentForLevel, TheLine.Level);
+ if (static_cast<int>(Indent) + Offset >= 0)
+ Indent += Offset;
+ tryFitMultipleLinesInOne(Indent, I, E);
+
bool WasMoved = PreviousLineWasTouched && FirstTok.NewlinesBefore == 0;
if (TheLine.First.is(tok::eof)) {
if (PreviousLineWasTouched) {
@@ -1149,9 +1217,6 @@ public:
} else if (TheLine.Type != LT_Invalid &&
(WasMoved || FormatPPDirective || touchesLine(TheLine))) {
unsigned LevelIndent = getIndent(IndentForLevel, TheLine.Level);
- unsigned Indent = LevelIndent;
- if (static_cast<int>(Indent) + Offset >= 0)
- Indent += Offset;
if (FirstTok.WhiteSpaceStart.isValid() &&
// Insert a break even if there is a structural error in case where
// we break apart a line consisting of multiple unwrapped lines.
@@ -1162,7 +1227,6 @@ public:
Indent = LevelIndent =
SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
}
- tryFitMultipleLinesInOne(Indent, I, E);
UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
TheLine.First, Whitespaces);
PreviousEndOfLineColumn =
@@ -1171,18 +1235,17 @@ public:
PreviousLineWasTouched = true;
} else {
if (FirstTok.NewlinesBefore > 0 || FirstTok.IsFirst) {
- unsigned Indent =
+ unsigned LevelIndent =
SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
- unsigned LevelIndent = Indent;
+ // Remove trailing whitespace of the previous line if it was touched.
+ if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
+ formatFirstToken(TheLine.First, PreviousLineLastToken, LevelIndent,
+ TheLine.InPPDirective, PreviousEndOfLineColumn);
+
if (static_cast<int>(LevelIndent) - Offset >= 0)
LevelIndent -= Offset;
if (TheLine.First.isNot(tok::comment))
IndentForLevel[TheLine.Level] = LevelIndent;
-
- // Remove trailing whitespace of the previous line if it was touched.
- if (PreviousLineWasTouched || touchesEmptyLineBefore(TheLine))
- formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
- TheLine.InPPDirective, PreviousEndOfLineColumn);
}
// 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
@@ -1253,7 +1316,7 @@ private:
return IndentForLevel[Level];
if (Level == 0)
return 0;
- return getIndent(IndentForLevel, Level - 1) + 2;
+ return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
}
/// \brief Get the offset of the line relatively to the level.
@@ -1270,8 +1333,6 @@ private:
///
/// 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.
void tryFitMultipleLinesInOne(unsigned Indent,
std::vector<AnnotatedLine>::iterator &I,
std::vector<AnnotatedLine>::iterator E) {
@@ -1295,7 +1356,6 @@ private:
I->First.FormatTok.IsFirst)) {
tryMergeSimplePPDirective(I, E, Limit);
}
- return;
}
void tryMergeSimplePPDirective(std::vector<AnnotatedLine>::iterator &I,
@@ -1341,13 +1401,17 @@ private:
void tryMergeSimpleBlock(std::vector<AnnotatedLine>::iterator &I,
std::vector<AnnotatedLine>::iterator E,
unsigned Limit) {
+ // No merging if the brace already is on the next line.
+ if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
+ return;
+
// 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.
AnnotatedLine &Line = *I;
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,
+ tok::kw_for, tok::kw_namespace,
// This gets rid of all ObjC @ keywords and methods.
tok::at, tok::minus, tok::plus))
return;
@@ -1418,9 +1482,9 @@ private:
bool touchesLine(const AnnotatedLine &TheLine) {
const FormatToken *First = &TheLine.First.FormatTok;
const FormatToken *Last = &TheLine.Last->FormatTok;
- CharSourceRange LineRange = CharSourceRange::getTokenRange(
+ CharSourceRange LineRange = CharSourceRange::getCharRange(
First->WhiteSpaceStart.getLocWithOffset(First->LastNewlineOffset),
- Last->Tok.getLocation());
+ Last->Tok.getLocation().getLocWithOffset(Last->TokenLength - 1));
return touchesRanges(LineRange);
}
@@ -1473,7 +1537,6 @@ private:
}
}
- DiagnosticsEngine &Diag;
FormatStyle Style;
Lexer &Lex;
SourceManager &SourceMgr;
@@ -1484,20 +1547,8 @@ private:
tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
SourceManager &SourceMgr,
- std::vector<CharSourceRange> Ranges,
- DiagnosticConsumer *DiagClient) {
- IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
- OwningPtr<DiagnosticConsumer> DiagPrinter;
- if (DiagClient == 0) {
- DiagPrinter.reset(new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts));
- DiagPrinter->BeginSourceFile(Lex.getLangOpts(), Lex.getPP());
- DiagClient = DiagPrinter.get();
- }
- DiagnosticsEngine Diagnostics(
- IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
- DiagClient, false);
- Diagnostics.setSourceManager(&SourceMgr);
- Formatter formatter(Diagnostics, Style, Lex, SourceMgr, Ranges);
+ std::vector<CharSourceRange> Ranges) {
+ Formatter formatter(Style, Lex, SourceMgr, Ranges);
return formatter.format();
}
diff --git a/lib/Format/TokenAnnotator.cpp b/lib/Format/TokenAnnotator.cpp
index 12031166e2..21518c6824 100644
--- a/lib/Format/TokenAnnotator.cpp
+++ b/lib/Format/TokenAnnotator.cpp
@@ -101,8 +101,10 @@ private:
return true;
}
if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace,
- tok::pipepipe, tok::ampamp, tok::question,
- tok::colon))
+ tok::question, tok::colon))
+ return false;
+ if (CurrentToken->isOneOf(tok::pipepipe, tok::ampamp) &&
+ Line.First.isNot(tok::kw_template))
return false;
updateParameterCount(Left, CurrentToken);
if (!consumeToken())
@@ -155,6 +157,9 @@ private:
}
if (CurrentToken->is(tok::r_paren)) {
+ if (CurrentToken->Children.empty() ||
+ !CurrentToken->Children[0].isOneOf(tok::l_paren, tok::l_square))
+ Left->DefinesFunctionType = false;
if (CurrentToken->Parent->closesScope())
CurrentToken->Parent->MatchingParen->NoMoreTokensOnLevel = true;
Left->MatchingParen = CurrentToken;
@@ -591,6 +596,7 @@ private:
}
} else if (Current.isOneOf(tok::kw_return, tok::kw_throw) ||
(Current.is(tok::l_paren) && !Line.MustBeDeclaration &&
+ !Line.InPPDirective &&
(!Current.Parent || Current.Parent->isNot(tok::kw_for)))) {
Contexts.back().IsExpression = true;
} else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) {
@@ -871,8 +877,6 @@ void TokenAnnotator::annotate(AnnotatedLine &Line) {
Line.First.SpacesRequiredBefore = 1;
Line.First.MustBreakBefore = Line.First.FormatTok.MustBreakBefore;
Line.First.CanBreakBefore = Line.First.MustBreakBefore;
-
- Line.First.TotalLength = Line.First.FormatTok.TokenLength;
}
void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
diff --git a/lib/Format/TokenAnnotator.h b/lib/Format/TokenAnnotator.h
index 5ea30159a2..227dd52396 100644
--- a/lib/Format/TokenAnnotator.h
+++ b/lib/Format/TokenAnnotator.h
@@ -75,10 +75,11 @@ public:
: FormatTok(FormatTok), Type(TT_Unknown), SpacesRequiredBefore(0),
CanBreakBefore(false), MustBreakBefore(false),
ClosesTemplateDeclaration(false), MatchingParen(NULL),
- ParameterCount(0), BindingStrength(0), SplitPenalty(0),
- LongestObjCSelectorName(0), DefinesFunctionType(false), Parent(NULL),
- FakeRParens(0), LastInChainOfCalls(false),
- PartOfMultiVariableDeclStmt(false), NoMoreTokensOnLevel(false) {}
+ ParameterCount(0), TotalLength(FormatTok.TokenLength),
+ BindingStrength(0), SplitPenalty(0), LongestObjCSelectorName(0),
+ DefinesFunctionType(false), Parent(NULL), FakeRParens(0),
+ LastInChainOfCalls(false), PartOfMultiVariableDeclStmt(false),
+ NoMoreTokensOnLevel(false) {}
bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
diff --git a/lib/Format/UnwrappedLineParser.cpp b/lib/Format/UnwrappedLineParser.cpp
index 722af5d2b7..4138bb98ae 100644
--- a/lib/Format/UnwrappedLineParser.cpp
+++ b/lib/Format/UnwrappedLineParser.cpp
@@ -16,7 +16,6 @@
#define DEBUG_TYPE "format-parser"
#include "UnwrappedLineParser.h"
-#include "clang/Basic/Diagnostic.h"
#include "llvm/Support/Debug.h"
namespace clang {
@@ -125,11 +124,11 @@ private:
UnwrappedLine *PreBlockLine;
};
-UnwrappedLineParser::UnwrappedLineParser(
- clang::DiagnosticsEngine &Diag, const FormatStyle &Style,
- FormatTokenSource &Tokens, UnwrappedLineConsumer &Callback)
+UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style,
+ FormatTokenSource &Tokens,
+ UnwrappedLineConsumer &Callback)
: Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
- CurrentLines(&Lines), StructuralError(false), Diag(Diag), Style(Style),
+ CurrentLines(&Lines), StructuralError(false), Style(Style),
Tokens(&Tokens), Callback(Callback) {}
bool UnwrappedLineParser::parse() {
@@ -173,9 +172,6 @@ void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
case tok::r_brace:
if (HasOpeningBrace)
return;
- Diag.Report(FormatTok.Tok.getLocation(),
- Diag.getCustomDiagID(clang::DiagnosticsEngine::Error,
- "unexpected '}'"));
StructuralError = true;
nextToken();
addUnwrappedLine();
@@ -402,6 +398,10 @@ void UnwrappedLineParser::parseStructuralElement() {
// structural element.
// FIXME: Figure out cases where this is not true, and add projections for
// them (the one we know is missing are lambdas).
+ if (Style.BreakBeforeBraces == FormatStyle::BS_Linux ||
+ Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup)
+ addUnwrappedLine();
+
parseBlock(/*MustBeDeclaration=*/ false);
addUnwrappedLine();
return;
@@ -577,6 +577,9 @@ void UnwrappedLineParser::parseNamespace() {
if (FormatTok.Tok.is(tok::identifier))
nextToken();
if (FormatTok.Tok.is(tok::l_brace)) {
+ if (Style.BreakBeforeBraces == FormatStyle::BS_Linux)
+ addUnwrappedLine();
+
parseBlock(/*MustBeDeclaration=*/ true, 0);
// Munch the semicolon after a namespace. This is more common than one would
// think. Puttin the semicolon into its own line is very ugly.
@@ -751,8 +754,12 @@ void UnwrappedLineParser::parseRecord() {
}
}
}
- if (FormatTok.Tok.is(tok::l_brace))
+ if (FormatTok.Tok.is(tok::l_brace)) {
+ if (Style.BreakBeforeBraces == FormatStyle::BS_Linux)
+ addUnwrappedLine();
+
parseBlock(/*MustBeDeclaration=*/ true);
+ }
// We fall through to parsing a structural element afterwards, so
// class A {} n, m;
// will end up in one unwrapped line.
diff --git a/lib/Format/UnwrappedLineParser.h b/lib/Format/UnwrappedLineParser.h
index 0c618e24d4..82e93bef48 100644
--- a/lib/Format/UnwrappedLineParser.h
+++ b/lib/Format/UnwrappedLineParser.h
@@ -23,9 +23,6 @@
#include <list>
namespace clang {
-
-class DiagnosticsEngine;
-
namespace format {
/// \brief A wrapper around a \c Token storing information about the
@@ -129,8 +126,7 @@ public:
class UnwrappedLineParser {
public:
- UnwrappedLineParser(clang::DiagnosticsEngine &Diag, const FormatStyle &Style,
- FormatTokenSource &Tokens,
+ UnwrappedLineParser(const FormatStyle &Style, FormatTokenSource &Tokens,
UnwrappedLineConsumer &Callback);
/// Returns true in case of a structural error.
@@ -203,7 +199,6 @@ private:
// indentation levels.
bool StructuralError;
- clang::DiagnosticsEngine &Diag;
const FormatStyle &Style;
FormatTokenSource *Tokens;
UnwrappedLineConsumer &Callback;
diff --git a/lib/Format/WhitespaceManager.cpp b/lib/Format/WhitespaceManager.cpp
index a75c592bfe..7ffebacba5 100644
--- a/lib/Format/WhitespaceManager.cpp
+++ b/lib/Format/WhitespaceManager.cpp
@@ -122,7 +122,7 @@ void WhitespaceManager::addUntouchableComment(unsigned Column) {
std::string WhitespaceManager::getNewLineText(unsigned NewLines,
unsigned Spaces) {
- return std::string(NewLines, '\n') + std::string(Spaces, ' ');
+ return std::string(NewLines, '\n') + getIndentText(Spaces);
}
std::string WhitespaceManager::getNewLineText(unsigned NewLines,
@@ -139,7 +139,15 @@ std::string WhitespaceManager::getNewLineText(unsigned NewLines,
Offset = 0;
}
}
- return NewLineText + std::string(Spaces, ' ');
+ return NewLineText + getIndentText(Spaces);
+}
+
+std::string WhitespaceManager::getIndentText(unsigned Spaces) {
+ if (!Style.UseTab)
+ return std::string(Spaces, ' ');
+
+ return std::string(Spaces / Style.IndentWidth, '\t') +
+ std::string(Spaces % Style.IndentWidth, ' ');
}
void WhitespaceManager::alignComments() {
diff --git a/lib/Format/WhitespaceManager.h b/lib/Format/WhitespaceManager.h
index 5f3dc55eda..1b24b3f6d7 100644
--- a/lib/Format/WhitespaceManager.h
+++ b/lib/Format/WhitespaceManager.h
@@ -78,6 +78,8 @@ private:
unsigned WhitespaceStartColumn,
unsigned EscapedNewlineColumn);
+ std::string getIndentText(unsigned Spaces);
+
/// \brief Structure to store tokens for later layout and alignment.
struct StoredToken {
StoredToken(SourceLocation ReplacementLoc, unsigned ReplacementLength,