Commit Graph

942 Commits

Author SHA1 Message Date
Daniel Jasper 77d5d31320 clang-format: Improve <<-formatting.
This fixes a regression caused by r186115.

Before:
  Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
       bbbbbbbbb) << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
                  << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;

After:
  Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)
      << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
      << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;

llvm-svn: 186164
2013-07-12 15:14:05 +00:00
Daniel Jasper 5aad4e5614 clang-format: Fix string literal breaking.
Before this patch, it did not cooperate with
Style::AlwaysBreakBeforeMultilineStrings. Thus, it would turn

  aaaaaaaaaaaa(aaaaaaaaaaaaa, "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa");

into:

  aaaaaaaaaaaa(aaaaaaaaaaaaa, "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa "
                              "aaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa");

and only a second format step would lead to the desired (with that
option):

  aaaaaaaaaaaa(aaaaaaaaaaaaa,
               "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa "
               "aaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa");

This could even lead to clang-format breaking the string at a different
character and thus leading to a completely different end result.

llvm-svn: 186154
2013-07-12 11:37:05 +00:00
Daniel Jasper aea3bde06b clang-format: Break before/between array subscript expressions.
clang-format used to treat array subscript expressions much like
function call (just replacing () with []). However, this is not really
appropriate especially for expressions with multiple subscripts.

Although it might seem counter-intuitive, the most consistent solution
seems to be to always (if necessary) break before a square bracket,
never after it. Also, multiple subscripts of the same expression should
be aligned if they are on subsequent lines.

Before:
  aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa][
      bbbbbbbbbbbbbbbbbbbbbbbbb] = c;
  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[
      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa][
      bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;

After:
  aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]
                           [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;
  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
      [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]
      [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;

llvm-svn: 186153
2013-07-12 11:19:37 +00:00
Daniel Jasper 51efbad732 clang-format: Fix bug concerning the alignment of "}".
Before:
    int i;  // indented 2 space more than clang-format would use.
    SomeReturnType  // clang-format invoked on this line.
    SomeFunctionMakingLBraceEndInColumn80() {
  }  // This is the indent clang-format would prefer.

After:
    int i;  // indented 2 space more than clang-format would use.
    SomeReturnType  // clang-format invoked on this line.
    SomeFunctionMakingLBraceEndInColumn80() {
    }

llvm-svn: 186120
2013-07-11 21:27:40 +00:00
Daniel Jasper 718bd366cf clang-format: Break before trailing annotations.
(if they are not function-like).

Before:
  SomeFunction(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa)
      OVERRIDE;

After:
  SomeFunction(aaaaaaaaaaaaaaaaaaaaaa,
               aaaaaaaaaaaaaaaaaaaaaaaa) OVERRIDE;

llvm-svn: 186117
2013-07-11 21:02:56 +00:00
Daniel Jasper 4e9678f7a1 clang-format: Avoid line breaks before the first <<.
This puts a slight penalty on the linebreak before the first "<<", so
that clang-format generally tries to keep things on the first line.

User feedback has shown that this is generally desirable.

Before:
  llvm::outs()
      << "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =" << aaaaaaaaaaaaaaaaaaaaaaaaaaa;

After:
  llvm::outs() << "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ="
               << aaaaaaaaaaaaaaaaaaaaaaaaaaa;

llvm-svn: 186115
2013-07-11 20:41:21 +00:00
Daniel Jasper a3501d4b81 Improve detection of trailing return types.
Trailing return types can only occur in declaration contexts.

Before:
  void f() { auto a = b -> c(); }

After:
  void f() { auto a = b->c(); }

llvm-svn: 186087
2013-07-11 14:33:06 +00:00
Daniel Jasper 185de2499b Fix indentation problem for comments in call chains
Before:
SomeObject
    // Calling someFunction on SomeObject
        .someFunction();

After:
SomeObject
    // Calling someFunction on SomeObject
    .someFunction();

llvm-svn: 186085
2013-07-11 13:48:16 +00:00
Daniel Jasper 40db06af64 Keep trailing annotations close to their argument.
Before:
bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(
    aaaaaaaaaaaa);

After:
bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
    GUARDED_BY(aaaaaaaaaaaa);

llvm-svn: 186077
2013-07-11 12:34:23 +00:00
James Dennett 86e67a2fc4 Add a hook RecursiveASTVisitor::TraverseLambdaBody, to enable visitors to
use/maintain additional state from the LambdaExpr while visiting the body
of a LambdaExpr.

One use for this arises because Clang's AST currently holds lambda bodies
in a form prior to their adjustment to refer to captured copies of local
variables, and so some clients will need access to the lambda's closure
type in order to query how to map VarDecl*s to the FieldDecls of their
by-copy captures. This hook is sufficient for at least one such client;
to do this without such a hook would require the client to re-implement
the whole of TraverseLambdaExpr, which is non-trivial and would likely be
more brittle.

llvm-svn: 186024
2013-07-10 18:29:15 +00:00
Daniel Jasper b10cbc45ad Add experimental flag for adaptive parameter bin-packing.
This is not activated for any style, might change or go away
completely.

For those that want to play around with it, set
ExperimentalAutoDetectBinPacking to true.

clang-format will then:
Look at whether function calls/declarations/definitions are currently
formatted with one parameter per line (on a case-by-case basis). If so,
clang-format will avoid bin-packing the parameters. If all parameters
are on one line (thus that line is "inconclusive"), clang-format will
make the choice dependent on whether there are other bin-packed
calls/declarations in the same file.

The reason for this change is that bin-packing in some situations can be
really bad and an author might opt to put one parameter on each line. If
the author does that, he might want clang-format not to mess with that.
If the author is unhappy with the one-per-line formatting, clang-format
can easily be convinced to bin-pack by putting any two parameters on the
same line.

llvm-svn: 186003
2013-07-10 14:02:49 +00:00
Daniel Jasper 6cdec7cf05 Initial support for formatting trailing return types.
This fixes llvm.org/PR15170.

For now, the basic formatting rules are (based on the C++11 standard):
* Surround the "->" with spaces.
* Break before "->".

Also fix typo.

llvm-svn: 185938
2013-07-09 14:36:48 +00:00
Daniel Jasper bd05888fa0 Avoid confusing indentations for chained function calls.
Basically treat a function with a trailing call similar to a function
with multiple parameters.

Before:
  aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(
      aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))
      .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();

After:
  aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(
                           aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))
      .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();

Also fix typo.

llvm-svn: 185930
2013-07-09 11:57:27 +00:00
Daniel Jasper b1f74a8152 Fix alignment of closing brace in braced initializers.
Before:
someFunction(OtherParam, BracedList{
                           // comment 1 (Forcing intersting break)
                           param1, param2,
                           // comment 2
                           param3, param4
             });
After:
someFunction(OtherParam, BracedList{
                           // comment 1 (Forcing intersting break)
                           param1, param2,
                           // comment 2
                           param3, param4
                         });

To do so, the UnwrappedLineParser now stores the information about the
kind of brace in the FormatToken.

llvm-svn: 185914
2013-07-09 09:06:29 +00:00
Daniel Jasper 6331da0672 Format overloaded operators like other functions.
This fixes llvm.org/PR16328 (at least partially).

Before:
SomeLoooooooooooooooooooooooooooooogType operator<<(
    const SomeLooooooooogType &a, const SomeLooooooooogType &b);

After:
SomeLoooooooooooooooooooooooooooooogType
operator<<(const SomeLooooooooogType &a, const SomeLooooooooogType &b);

llvm-svn: 185908
2013-07-09 07:43:55 +00:00
Daniel Jasper 6a09df7964 Fix incorrect incorrect cast identification in clang-format.
This fixes llvm.org/PR16534.

Before:
aaaaa& operator+(const aaaaa&)LLVM_DELETED_FUNCTION;
After:
aaaaa& operator+(const aaaaa&) LLVM_DELETED_FUNCTION;

llvm-svn: 185828
2013-07-08 14:58:01 +00:00
Enea Zaffanella 4c409494d8 Fixed testcase failing under MS by adding "-fno-delayed-template-parsing",
as suggested by Takumi. To this end, added a MatchVerifier::match()
overload accepting a vector of invocation arguments.

llvm-svn: 185827
2013-07-08 14:50:30 +00:00
Daniel Jasper ee7539a387 Prefer similar line breaks.
This adds a penalty for clang-format for each break that occurs in
a set of parentheses (including fake parenthesis that determine
the range of certain operator precendences) that have not yet been
broken. Thereby, clang-format prefers similar line breaks.

This fixes llvm.org/PR15506.

Before:
const int kTrackingOptions =
    NSTrackingMouseMoved | NSTrackingMouseEnteredAndExited |
    NSTrackingActiveAlways;

After:
const int kTrackingOptions = NSTrackingMouseMoved |
                             NSTrackingMouseEnteredAndExited |
                             NSTrackingActiveAlways;

Also removed ParenState::ForFakeParenthesis which has become unused.

llvm-svn: 185822
2013-07-08 14:25:23 +00:00
Alexander Kornienko 614d96a1f6 Fix for corner cases in code handling leading "* " decorations in block comments
Summary:
Fixes problems that lead to incorrect formatting of these and similar snippets:
/*
 **
 */

/*
 **/

/*
 * */

/*
 *test
 */

Clang-format used to think that all the cases above use "* " decoration, and
failed to calculate insertion position properly. It also used to remove leading 
"* " in the last line.

Reviewers: klimek

Reviewed By: klimek

CC: cfe-commits

Differential Revision: http://llvm-reviews.chandlerc.com/D1113

llvm-svn: 185818
2013-07-08 14:12:07 +00:00
NAKAMURA Takumi 58c821a0d9 AST/SourceLocationTest.cpp: Appease MS hosts to suppress CXXUnresolvedConstructExpr.SourceRange, for now.
FIXME: It could pass if MS-compatible mode were disabled with Args.push_back("-fno-delayed-template-parsing").
llvm-svn: 185795
2013-07-08 06:38:46 +00:00
Enea Zaffanella 8421a06314 Fixed source range for functional cast and unresolved construct expr nodes.
Added testcases.

llvm-svn: 185773
2013-07-07 06:41:54 +00:00
Enea Zaffanella a90af72e8f Fixed source location info for UnaryTransformTypeLoc nodes.
llvm-svn: 185765
2013-07-06 18:54:58 +00:00
Rafael Espindola a36e78ef5d Use llvm::sys::fs::createTemporaryFile.
llvm-svn: 185717
2013-07-05 20:00:06 +00:00
Daniel Jasper 6f9c8d2148 Fix formatting for allocation of new pointer variables.
Before:
T **t = new T * ;
T **q = new T * ();

After:
T **t = new T *;
T **q = new T *();

llvm-svn: 185699
2013-07-05 13:30:40 +00:00
Daniel Jasper 0e90c3d92c Improve detection for preventing certain kind of formatting patterns.
This is a better implementation of r183097. The main purpose is to
prevent certain constructs to be formatted "like a block of text".

Before:
aaaaaaaaaaaaa<
    aaaaaaaaaa, aaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>* aaaa = new aaaaaaaaaaaaa<
    aaaaaaaaaa, aaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(bbbbbbbbbbbbbbbbbbbbbbbb);
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[
    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)[
    dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];

After:
aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,
              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>* aaaa =
    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,
                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(
        bbbbbbbbbbbbbbbbbbbbbbbb);
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[
    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] =
    (*cccccccccccccccc)[
        dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];

llvm-svn: 185687
2013-07-05 09:14:35 +00:00
Daniel Jasper 1bc1b502ec Don't break after a "(" following a binary operator.
Additionally, allow breaking after c-style casts, but with a high
penalty.

Before:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (
    aaaaaaaaaaaaaaaaa *)bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;
After:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)
    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;

This fixes llvm.org/PR16049.

llvm-svn: 185685
2013-07-05 07:58:34 +00:00
Alexander Kornienko 5861171893 Added AlwaysBreakBeforeMultilineStrings option.
Summary:
Always breaking before multiline strings can help format complex
expressions containing multiline strings more consistently, and avoid consuming
too much horizontal space.

Reviewers: djasper

Reviewed By: djasper

CC: cfe-commits, klimek

Differential Revision: http://llvm-reviews.chandlerc.com/D1097

llvm-svn: 185622
2013-07-04 12:02:44 +00:00
Daniel Jasper 7ae41cdd22 Don't insert confusing line breaks in comparisons.
In general, clang-format breaks after an operator if the LHS spans
multiple lines. Otherwise, this can lead to confusing effects and
effectively hide the operator precendence, e.g. in

if (aaaaaaaaaaaaaa ==
        bbbbbbbbbbbbbb && c) { ...

This patch removes this rule for comparisons, if the LHS is not a binary
expression itself as many users were wondering why clang-format inserts
an unnecessary linebreak.

Before:
if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) >
    5) { ...

After:
if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) { ...

In the long run, we might:
- Want to do this for other binary expressions as well.
- Do this only if the RHS is short or even only if it is a literal.

llvm-svn: 185530
2013-07-03 10:34:47 +00:00
Daniel Jasper dba1c5587c Fix formatting of long declarations with const type.
Before (exceeding the column limit):
LoooooooooooooooooooooooooooooooooooooooongType const LoooooooooooooooooooooooooooooooooooooooongVariable;

After:
LoooooooooooooooooooooooooooooooooooooooongType const
LoooooooooooooooooooooooooooooooooooooooongVariable;

llvm-svn: 185418
2013-07-02 09:47:29 +00:00
Daniel Jasper ca7bd720eb Fix incorrect token counting introduced by r185319.
This lead to weird formatting.
Before:
DoSomethingWithVector({ {} /* No data */ }, {
  { 1, 2 }
});
After:
DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });

llvm-svn: 185346
2013-07-01 16:43:38 +00:00
Alexander Kornienko aa620e187e Avoid column limit violation in block comments in certain cases.
Summary:
Add penalty when an excessively long line in a block comment can not be
broken on a leading whitespace. Lack of this addition can lead to severe column
width violations when they can be easily avoided.

Reviewers: djasper

Reviewed By: djasper

CC: cfe-commits, klimek

Differential Revision: http://llvm-reviews.chandlerc.com/D1071

llvm-svn: 185337
2013-07-01 13:42:42 +00:00
Daniel Jasper 251b3c9e7e Don't align "} // namespace" comments.
This is not all bad, but people are often surprised by it.

Before:
namespace {
int SomeVariable = 0; // comment
}                     // namespace

After:
namespace {
int SomeVariable = 0; // comment
} // namespace

llvm-svn: 185327
2013-07-01 11:22:57 +00:00
Daniel Jasper bafa6b711a Don't add an extra space before ellipsis after pointers.
Before (for styles where the pointer binds to the type):
template <class... Ts> void Foo(Ts... ts) {}
template <class... Ts> void Foo(Ts* ... ts) {}
After:
template <class... Ts> void Foo(Ts... ts) {}
template <class... Ts> void Foo(Ts*... ts) {}

llvm-svn: 185321
2013-07-01 09:47:25 +00:00
Daniel Jasper 022612db05 Keep space between pointer and block comment.
Before: void f(int */* unused */) {}
After:  void f(int * /* unused */) {}

The previous version seems to be valid C++ code but confuses many syntax
highlighters.

llvm-svn: 185320
2013-07-01 09:34:09 +00:00
Daniel Jasper 7f5d53e55f Fix braced-list detection in lieu of trailing comments.
Before:
DoSomethingWithVector({
} /* No data */);
After:
DoSomethingWithVector({} /* No data */);

llvm-svn: 185319
2013-07-01 09:15:46 +00:00
James Dennett 9ad9959e51 Bug fix: Make RecursiveASTVisitor<T>::TraverseLambdaExpr call
WalkUpFromLambdaExpr, so that the Visit* functions are called
on that AST node.

llvm-svn: 185277
2013-06-30 03:13:35 +00:00
James Dennett eb576c0a06 Add enumerators to TestVisitor::Language to allow visitor tests to
explicitly specify use of C++98 or C++11. Lang_CXX is preserved as
an alias for Lang_CXX98.

This does not add Lang_CXX1Y or Lang_C11, on the assumption that it's
better to add them if/when they are needed.

(This is a prerequisite for a test in a later patch for RecursiveASTVisitor.)

Reviewed by Richard Smith.

llvm-svn: 185276
2013-06-30 03:05:49 +00:00
Alexander Kornienko 1e80887d63 Use lexing mode based on FormatStyle.Standard.
Summary:
Some valid pre-C++11 constructs change meaning when lexed in C++11
mode, e.g.
#define x(_a) printf("foo"_a);
(example from http://llvm.org/bugs/show_bug.cgi?id=16342). "foo"_a is treated as
a user-defined string literal when parsed in C++11 mode.
In order to deal with this correctly, we need to set lexing mode according to
which standard the code conforms to. We already have a configuration value for
this (FormatStyle.Standard), which seems to be appropriate to use in this case
as well.

Reviewers: klimek

CC: cfe-commits, gribozavr

Differential Revision: http://llvm-reviews.chandlerc.com/D1028

llvm-svn: 185149
2013-06-28 12:51:24 +00:00
Rafael Espindola 8b96094420 Sync file handling logic in RewriterTestContext.h and RefactoringTest.cpp.
They are mostly duplicated and got out of sync during the PathV1 removal. We
should factor the code somewhere, but for now a FIXME will do.

llvm-svn: 185019
2013-06-26 21:02:22 +00:00
Rafael Espindola 641c6a182b Remove last use of PathV1.h from clang.
Instead of creating a temporary directory, remember the set of temporary files
we create.

llvm-svn: 184951
2013-06-26 15:01:50 +00:00
Nico Weber 8084cffd0b Formatter: Don't put a space after parameter-naming block comments.
Before: f(a, b, /*doFoo=*/ false);
Now: f(a, b, /*doFoo=*/false);

This style is a lot more common:
$ ack -H '=\*\/\w' lib | wc -l 
    1281
$ ack -H '=\*\/ \w' lib | wc -l 
      70

llvm-svn: 184894
2013-06-26 00:15:19 +00:00
Nico Weber ec9e41076b Formatter/ObjC: Correctly format casts in objc message send expressions.
llvm-svn: 184804
2013-06-25 00:55:57 +00:00
Nico Weber e8d78249ad Formatter/Objc: Add a test that checks that @import is formatted correctly.
llvm-svn: 184796
2013-06-25 00:25:40 +00:00
NAKAMURA Takumi 1d7bdb171a clang/unittests/ASTMatchers/Dynamic/RegistryTest.cpp: Suppress unexpected failures on MS hosts.
FIXME: A couple of tests have been suppressed.
I know it'd be bad with _MSC_VER here, though.

llvm-svn: 184727
2013-06-24 13:19:26 +00:00
Alexander Kornienko 34a87e851a Fixed typo.
llvm-svn: 184625
2013-06-22 01:35:36 +00:00
Manuel Klimek 836c2868f9 Add an option to not indent declarations when breaking after the type.
Make that option the default for LLVM style.

llvm-svn: 184563
2013-06-21 17:25:42 +00:00
Samuel Benzaquen c6f2c9b566 Add support for polymorphic matchers. Use runtime type checking to determine the right polymorphic overload to use.
llvm-svn: 184558
2013-06-21 15:51:31 +00:00
Reid Kleckner f9794c15e7 Disable an assertion death test when using MSVC's assert()
MSVC's debug runtime prints assertion failures in wide characters, which
gtest doesn't understand.

llvm-svn: 184544
2013-06-21 12:58:12 +00:00
Samuel Benzaquen 81ef929b8f Enhancements for the DynTypedMatcher system.
- Added conversion routines and checks in Matcher<T> that take a DynTypedMatcher.
- Added type information on the error messages for the marshallers.
- Allows future work on Polymorphic/overloaded matchers. We should be
  able to disambiguate at runtime and choose the appropriate overload.

llvm-svn: 184429
2013-06-20 14:28:32 +00:00
Manuel Klimek bbb758577f Adds the equalsBoundNode matcher.
Most of the tests contributed by Edwin Vane.

llvm-svn: 184427
2013-06-20 14:06:32 +00:00
Alexander Kornienko b93062e236 Use the same set of whitespace characters for all operations in BreakableToken.
Summary:
Fixes a problem where \t,\v or \f could lead to a crash when placed as
a first character in a line comment. The cause is that rtrim and ltrim handle
these characters, but our code didn't, so some invariants could be broken.

Reviewers: klimek

Reviewed By: klimek

CC: cfe-commits

Differential Revision: http://llvm-reviews.chandlerc.com/D1013

llvm-svn: 184425
2013-06-20 13:58:37 +00:00
Manuel Klimek c16c652ca5 Implements declaratorDecl, parmVarDecl and hassTypeLoc matchers.
llvm-svn: 184419
2013-06-20 13:08:29 +00:00
Alexander Kornienko a3555e2416 Fixed long-standing issue with incorrect length calculation of multi-line comments.
Summary:
A trailing block comment having multiple lines would cause extremely
high penalties if the summary length of its lines is more than the column limit.
Fixed by always considering only the last line of a multi-line block comment.
Removed a long-standing FIXME from relevant tests and added a motivating test
modelled after problem cases from real code.

Reviewers: klimek

Reviewed By: klimek

CC: cfe-commits

Differential Revision: http://llvm-reviews.chandlerc.com/D1010

llvm-svn: 184340
2013-06-19 19:50:11 +00:00
Samuel Benzaquen f226e97dff Enhancements for the DynTypedNode
Added ASTNodeKind as a standalone way to represent node kinds and their hierarchy.
This change is to support ongoing work on D815.

Reviewers: klimek

CC: cfe-commits
llvm-svn: 184331
2013-06-19 18:45:24 +00:00
Manuel Klimek a0c025f5d2 Completely revamp node binding for AST matchers.
This is in preparation for the backwards references to bound
nodes, which will expose a lot more about how matches occur.  Main
changes:
- instead of building the tree of bound nodes, we build a "set" of bound
  nodes and explode all possible match combinations while running
  through the matchers; this will allow us to also implement matchers
  that filter down the current set of matches, like "equalsBoundNode"
- take the set of bound nodes at the start of the match into
  consideration when doing memoization; as part of that, reevaluated
  that memoization gives us benefits that are large enough (it still
  does - the effect on common match patterns is up to an order of
  magnitude)
- reset the bound nodes when a node does not match, thus never leaking
  information from partial sub-matcher matches for failing matchers

Effects:
- we can now correctly "explode" combinatorial matches, for example:
  allOf(forEachDescendant(...bind("a")),
  forEachDescendant(...bind("b"))) will now trigger matches for all
  combinations of matching "a" and "b"s.
- we now never expose bound nodes from partial matches in matchers that
  did not match in the end - this fixes a long-standing issue

FIXMEs:
- rename BoundNodesTreeBuilder to BoundNodesBuilder or
  BoundNodesSetBuilder, as we don't build a tree any more; this is out
  of scope for this change, though
- we're seeing some performance regressions (around 10%), but I expect
  some performance tuning will get that back, and it's easily worth
  the increase in expressiveness for now

llvm-svn: 184313
2013-06-19 15:42:45 +00:00
Alexander Kornienko 7285207486 Split long strings on word boundaries.
Summary: Split strings at word boundaries, when there are no spaces and slashes.

Reviewers: klimek

CC: cfe-commits

Differential Revision: http://llvm-reviews.chandlerc.com/D1003

llvm-svn: 184304
2013-06-19 14:22:47 +00:00
Eli Friedman 2dcbdc0606 Fix source range of CXXNewExpr with parentheses around the type. PR15569.
llvm-svn: 184139
2013-06-17 22:35:10 +00:00
Alexander Kornienko afaa8f556b Fix a problem in ExpressionParser leading to trailing comments affecting indentation of an expression after a line break.
Summary:
E.g. the second line in 

return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
           b; //

is indented 4 characters more than in

return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +
       b;

Reviewers: klimek

Reviewed By: klimek

CC: cfe-commits

Differential Revision: http://llvm-reviews.chandlerc.com/D984

llvm-svn: 184078
2013-06-17 13:19:53 +00:00
Alexander Kornienko 4d26b6efef Fixes incorrect indentation of line comments after break and re-alignment.
Summary:
Selectively propagate the information about token kind in
WhitespaceManager::replaceWhitespaceInToken.For correct alignment of new
segments of line comments in order to align them correctly. Don't set
BreakBeforeParameter in breakProtrudingToken for line comments, as it introduces
a break after the _next_ parameter. Added tests for related functions.

Reviewers: klimek

Reviewed By: klimek

CC: cfe-commits

Differential Revision: http://llvm-reviews.chandlerc.com/D980

llvm-svn: 184076
2013-06-17 12:59:44 +00:00
Reid Kleckner 898229ab4b [Driver] Refactor clang driver to use LLVM's Option library
The big changes are:
- Deleting Driver/(Arg|Opt)*
- Rewriting includes to llvm/Option/ and re-sorting
- 'using namespace llvm::opt' in clang::driver
- Fixing the autoconf build by adding option everywhere

As discussed in the review, this change includes using directives in
header files.  I'll make follow up changes to remove those in favor of
name specifiers.

Reviewers: espindola

Differential Revision: http://llvm-reviews.chandlerc.com/D975

llvm-svn: 183989
2013-06-14 17:17:23 +00:00
Alexander Kornienko be633908be Don't remove backslashes from block comments.
Summary:
Don't remove backslashes from block comments. Previously this
/* \    \ \ \ \ \
*/
would be turned to this:
/*
*/
which spoils some kinds of ASCII-art, people use in their comments. The behavior
was related to handling escaped newlines in block comments inside preprocessor
directives. This patch makes handling it in a more civilized way.

Reviewers: klimek

Reviewed By: klimek

CC: cfe-commits

Differential Revision: http://llvm-reviews.chandlerc.com/D979

llvm-svn: 183978
2013-06-14 11:46:10 +00:00
Alexander Kornienko f370ad9055 Preserve newlines before block comments in static initializers.
Summary:
Basically, don't special-case line comments in this regard. And fixed
an incorrect test, that relied on the wrong behavior.

Reviewers: klimek

Reviewed By: klimek

CC: cfe-commits

Differential Revision: http://llvm-reviews.chandlerc.com/D962

llvm-svn: 183851
2013-06-12 19:04:12 +00:00
Rafael Espindola 552c169ed3 Include Path.h instead of PathV2.h.
I am about to move PathV2.h to Path.h.

llvm-svn: 183795
2013-06-11 22:15:02 +00:00
Rafael Espindola cf833e4c7c Include PathV1.h in a file that uses it.
llvm-svn: 183786
2013-06-11 20:31:32 +00:00
Alexander Kornienko 555efc36d0 Insert a space at the start of a line comment in case it starts with an alphanumeric character.
Summary:
"//Test" becomes "// Test". This change is aimed to improve code
readability and conformance to certain coding styles. If a comment starts with a
non-alphanumeric character, the space isn't added, e.g. "//-*-c++-*-" stays
unchanged.

Reviewers: klimek

Reviewed By: klimek

CC: cfe-commits

Differential Revision: http://llvm-reviews.chandlerc.com/D949

llvm-svn: 183750
2013-06-11 16:01:49 +00:00
Eli Friedman 7152fbe57e Re-commit r183466 with a fix to make the TypeLoc casting machinery work
correctly in the presence of qualified types.

(I had to change the unittest because it was trying to cast a
QualifiedTypeLoc to TemplateSpecializationTypeLoc.)

llvm-svn: 183563
2013-06-07 20:31:48 +00:00
Alexander Kornienko ee4ca9ba0e Improved handling of escaped newlines at the token start.
Summary: Remove them from the TokenText as well.

Reviewers: klimek

Reviewed By: klimek

CC: cfe-commits

Differential Revision: http://llvm-reviews.chandlerc.com/D935

llvm-svn: 183536
2013-06-07 17:45:07 +00:00
Alexander Kornienko dd7ece53a2 Fixed calculation of penalty when breaking tokens.
Summary:
Introduced two new style parameters: PenaltyBreakComment and
PenaltyBreakString. Add penalty for each character of a breakable token beyond
the column limit (this relates mainly to comments, as they are broken only on
whitespace). Tuned PenaltyBreakComment to prefer comment breaking over breaking
inside most binary expressions.
Fixed a bug that prevented *, & and && from being considered TT_BinaryOperator
in the presense of adjacent comments.

Reviewers: klimek, djasper

Reviewed By: klimek

CC: cfe-commits

Differential Revision: http://llvm-reviews.chandlerc.com/D933

llvm-svn: 183530
2013-06-07 16:02:52 +00:00
Manuel Klimek 8122830a67 Adds a test that verifies angle bracket locations.
Regression test to make sure TemplateSpecializationTypeLocs have the
correct locations for angle brackets.

llvm-svn: 183514
2013-06-07 11:27:57 +00:00
Daniel Jasper 61a40782df Fix incorrect line breaking before trailing block comments.
Before, clang-format would happily move a trailing block comment to a
new line, which normally changes the perceived binding of that comment.

E.g., it would move:
void f() { /* comment */
  ...
}
to:
void f() {
  /* comment */
  ...
}

llvm-svn: 183420
2013-06-06 16:08:57 +00:00
Daniel Jasper 6dcecb6b33 Fix clang-format's expression parser for leading }s.
The leading "}" in the construct "} else if (..) {" was confusing the
expression parser. Thus, no fake parentheses were generated and the
indentation was broken in some cases.

llvm-svn: 183393
2013-06-06 09:11:58 +00:00
Daniel Jasper 058663787e Improve c-style cast detection.
Before:
return (my_int) aaaa;
template <> void f<int>(int i)SOME_ANNOTATION;
f("aaaa" SOME_MACRO(aaaa)"aaaa");

After:
return (my_int)aaaa;
template <> void f<int>(int i) SOME_ANNOTATION;
f("aaaa" SOME_MACRO(aaaa) "aaaa");

llvm-svn: 183389
2013-06-06 08:20:20 +00:00
NAKAMURA Takumi 5238eba7f5 clang/unittests/Format/FormatTest.cpp: Suppress utf8 literals with _MSC_VER. MS cl.exe is unaware of BOM-less utf8 source files.
FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
llvm-svn: 183366
2013-06-06 01:14:58 +00:00
Alexander Kornienko ff73c20ccc Added test with characters using four bytes in UTF-8 representation.
llvm-svn: 183315
2013-06-05 15:08:20 +00:00
Alexander Kornienko ffcc010767 UTF-8 support for clang-format.
Summary:
Detect if the file is valid UTF-8, and if this is the case, count code
points instead of just using number of bytes in all (hopefully) places, where
number of columns is needed. In particular, use the new
FormatToken.CodePointCount instead of TokenLength where appropriate.
Changed BreakableToken implementations to respect utf-8 character boundaries
when in utf-8 mode.

Reviewers: klimek, djasper

Reviewed By: djasper

CC: cfe-commits, rsmith, gribozavr

Differential Revision: http://llvm-reviews.chandlerc.com/D918

llvm-svn: 183312
2013-06-05 14:09:10 +00:00
NAKAMURA Takumi 05f4370074 ASTTests/DeclTest.cpp: Tweak on msvc target to add "-fno-ms-extensions".
MS extensions don't prefer imaginary suffix even with -std=c++11.

llvm-svn: 183301
2013-06-05 06:54:06 +00:00
Samuel Benzaquen c31b3524cb Parser/Registry argument enhancements.
Summary:
 Parser/Registry argument enhancements.
  - 2 argument support.
  - unsigned values support.

Reviewers: klimek

CC: cfe-commits, revane

Differential Revision: http://llvm-reviews.chandlerc.com/D915

llvm-svn: 183231
2013-06-04 15:46:22 +00:00
Manuel Klimek d91ac93087 Enables chaining of argument adjusters in clang tools.
This enables changing clang-check to get extra arguments.

Patch by Pavel Labath.

llvm-svn: 183227
2013-06-04 14:44:44 +00:00
Benjamin Kramer 8a8557e629 __uint128_t is only available on 64 bit platforms, only test it when it's around.
llvm-svn: 183146
2013-06-03 19:37:18 +00:00
Samuel Benzaquen 31edb51a4f Add support for .bind("foo") expressions on the dynamic matchers.
Summary: Add support on the parser, registry, and DynTypedMatcher for binding IDs dynamically.

Reviewers: klimek

CC: cfe-commits, revane

Differential Revision: http://llvm-reviews.chandlerc.com/D911

llvm-svn: 183144
2013-06-03 19:31:08 +00:00
Daniel Jasper 1027c6e5dd Let clang-format remove empty lines before "}".
These lines almost never aid readability.

Before:
void f() {
  int i;  // some variable

}

After:
void f() {
  int i;  // some variable
}

llvm-svn: 183112
2013-06-03 16:16:41 +00:00
Manuel Klimek a732899cb4 Fix memory leak for APValues that do memory allocation.
This patch ensures that APValues are deallocated with the ASTContext by
registering a deallocation function for APValues to the ASTContext.

Original version of the patch by James Dennett.

llvm-svn: 183101
2013-06-03 13:51:33 +00:00
Daniel Jasper 8050395236 Improve detection preventing certain kind of formatting patterns.
An oversight in this detection made clang-format unable to format
the following nicely:
void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaa,
                         bbbbbbbbbbbbbbbbbbbbbbbbbb>(
    cccccccccccccccccccccccccccc);

llvm-svn: 183097
2013-06-03 09:54:46 +00:00
Daniel Jasper 68d888cfed Fix line-breaking problem caused by comment.
Before, clang-format would not find a solution for formatting:
if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||
     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa
    cccccc) {
}

llvm-svn: 183096
2013-06-03 08:42:05 +00:00
Daniel Jasper d589391d07 Improve recognition of template parameters.
Before: return a<b &&c> d;
After:  return a < b && c > d;
llvm-svn: 183077
2013-06-01 18:56:00 +00:00
Daniel Jasper da6f225ef9 Improve clang-format's c-style cast detection.
Before:
  x[(uint8) y];
  x = (uint8) y;
  void f() { x = (uint8) y; }
  #define AA(X) sizeof(((X *) NULL)->a)

After:
  x[(uint8)y];
  x = (uint8)y;
  void f() { x = (uint8)y; }
  #define AA(X) sizeof(((X *)NULL)->a)

llvm-svn: 183014
2013-05-31 16:14:28 +00:00
Daniel Jasper 393564fdfe Improve clang-format's error recovery.
If a "}" is found inside parenthesis, this is probably a case of
missing parenthesis. This enables continuing to format after stuff code
like:

class A {
  void f(
};
..

llvm-svn: 183009
2013-05-31 14:56:29 +00:00
Daniel Jasper a9eb2aafa1 Make formatting of empty blocks more consistent.
With this patch, the simplified rule is:
If the block is part of a declaration (class, namespace, function,
enum, ..), merge an empty block onto a single line. Otherwise
(specifically for the compound statements of if, for, while, ...),
keep the braces on two separate lines.

The reasons are:
- Mostly the formatting of empty blocks does not matter much.
- Empty compound statements are really rare and are usually just
  inserted while still working on the code. If they are on two lines,
  inserting code is easier. Also, overlooking the "{}" of an
  "if (...) {}" can be really bad.
- Empty declarations are not uncommon, e.g. empty constructors. Putting
  them on one line saves vertical space at no loss of readability.

llvm-svn: 183008
2013-05-31 14:56:20 +00:00
Daniel Jasper 2c611c0341 Properly format nested conditional operators.
Before:
bool aaaaaa = aaaaaaaaaaaaa //
                  ? aaaaaaaaaaaaaaa
                  : bbbbbbbbbbbbbbb //
                  ? ccccccccccccccc
                  : ddddddddddddddd;

After:
bool aaaaaa = aaaaaaaaaaaaa //
                  ? aaaaaaaaaaaaaaa
                  : bbbbbbbbbbbbbbb //
                        ? ccccccccccccccc
                        : ddddddddddddddd;

llvm-svn: 183007
2013-05-31 14:56:12 +00:00
Daniel Jasper 5648cb32d9 Fix detection/formatting of braced lists in ternary expressions.
Before:
foo = aaaaaaaaaaa ? vector<int> {
  aaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa, aaaaa
}
: vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb, bbbbbbbbbbbbbbbbbbbb, bbbbb };

After:
foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,
                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }
                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,
                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };

llvm-svn: 182992
2013-05-31 10:09:55 +00:00
Daniel Jasper ce257f296b More fixes for clang-format's multiline comment breaking.
llvm-svn: 182940
2013-05-30 17:27:48 +00:00
Daniel Jasper 58dd2f0652 Fix another clang-format crasher related to multi-line comments.
This fixes:
/*
*
* something long going over the column limit.
*/

llvm-svn: 182932
2013-05-30 15:20:29 +00:00
Edwin Vane 3a331f3da4 Coding style fix for SourceFileCallbacks
llvm-svn: 182930
2013-05-30 13:59:44 +00:00
Daniel Jasper 51fb2b2151 Fix crasher when formatting certain block comments.
Smallest reproduction:
/*
**
*/

llvm-svn: 182913
2013-05-30 06:40:07 +00:00
Manuel Klimek ae1fbfb740 Fixes error when splitting block comments.
When trying to fall back to search from the end onwards, we
would still find leading whitespace if the leading whitespace
went on after the end of the line.

llvm-svn: 182886
2013-05-29 22:06:18 +00:00
Roman Divacky 95ad7794a9 Turn CLANG_ENABLE_{ARCMT,REWRITER,STATIC_ANALYZER} into proper options so that
users can disable those. Just like in autoconf generated makefiles.

llvm-svn: 182881
2013-05-29 21:09:18 +00:00
Edwin Vane 20c6f54b85 Tooling: Call back for both begin and end of sources
newFrontendActionFactory() took a pointer to a callback to call when a source
file was done being processed by an action. This revision updates the callback
to include an ante-processing callback as well.

Callback-providing class renamed and callback functions themselves renamed.
Functions are no longer pure-virtual so users aren't forced to implement both
callbacks if one isn't needed.

llvm-svn: 182864
2013-05-29 16:01:10 +00:00
Daniel Jasper 41a0f78d43 Add return missing in r182855.
llvm-svn: 182856
2013-05-29 14:09:17 +00:00
Daniel Jasper 40e1921f2a Leave some macros on their own line
If an identifier is on its own line and it is all upper case, it is highly
likely that this is a macro that is meant to stand on a line by itself.

Before:
class A : public QObject {
  Q_OBJECT A() {}
};

Ater:
class A : public QObject {
  Q_OBJECT

  A() {}
};

llvm-svn: 182855
2013-05-29 13:16:10 +00:00
Daniel Jasper 61e6bbf850 Add option to always break template declarations.
With option enabled (e.g. in Google-style):
template <typename T>
void f() {}

With option disabled:
template <typename T> void f() {}

Enabling this for Google-style and Chromium-style, not sure which other
styles would prefer that.

llvm-svn: 182849
2013-05-29 12:07:31 +00:00
Peter Collingbourne 6a55bb2307 Add an overridable MatchCallback::onEndOfTranslationUnit() function.
Differential Revision: http://llvm-reviews.chandlerc.com/D745

llvm-svn: 182798
2013-05-28 19:21:51 +00:00
Daniel Jasper 1ec31065e8 Support uniform inits in braced lists.
This made it necessary to remove an error detection which would let us
bail out of braced lists in certain situations of missing "}". However,
as we always entirely escape from the braced list on finding ";", this
should not be a big problem.

With this, we can no format braced lists with uniformat inits:

return { arg1, SomeType { parameter } };

llvm-svn: 182788
2013-05-28 18:50:02 +00:00
Daniel Jasper 4d03d3b327 Fix formatting regression regarding pointers to arrays.
Before: f( (*PointerToArray)[10]);
After:  f((*PointerToArray)[10]);

This fixes llvm.org/PR16163

llvm-svn: 182777
2013-05-28 15:27:10 +00:00
Daniel Jasper bca4bbe30a Initial support for designated initializers.
llvm-svn: 182767
2013-05-28 11:30:49 +00:00
Manuel Klimek 34d15151c4 Disable tab expansion when counting the columns in block comments.
To fully support this, we also need to expand tabs in the text before
the block comment. This patch breaks indentation when there was a
non-standard mixture of spaces and tabs used for indentation, but
fixes a regression in the simple case:
{
  /*
   * Comment.
   */
  int i;
}
Is now formatted correctly, if there were tabs used for indentation
before.

llvm-svn: 182760
2013-05-28 10:01:59 +00:00
Manuel Klimek 281dcbe026 Fixes indentation of empty lines in block comments.
Block comment indentation of empty lines regressed, as we did not
have a test for it.
 /* Comment with...
  *
  * empty line. */
is now formatted correctly again.

llvm-svn: 182757
2013-05-28 08:55:01 +00:00
Daniel Jasper 3719428c06 Clean up formatting of function types.
Before:
int (*func)(void*);
void f() { int(*func)(void*); }

After (consistent space after "int"):
int (*func)(void*);
void f() { int (*func)(void*); }

llvm-svn: 182756
2013-05-28 08:33:00 +00:00
Daniel Jasper 9f82df295e Fix formatting of expressions containing ">>".
This gets turned into two ">" operators at the beginning in order to
simplify template parameter handling. Thus, we need a special case to
handle those two binary operators correctly.

With this patch, clang-format can now correctly handle cases like:
aaaaaa = aaaaaaa(aaaaaaa, // break
                 aaaaaa) >>
         bbbbbb;

llvm-svn: 182754
2013-05-28 07:42:44 +00:00
Daniel Jasper 1eff9080af Improve formatting of templates.
Before: A < int&& > a;
After:  A<int &&> a;

Also remove obsolete FIXMEs.

llvm-svn: 182741
2013-05-27 16:36:33 +00:00
Manuel Klimek 9043c74f49 Major refactoring of BreakableToken.
Unify handling of whitespace when breaking protruding tokens with other
whitespace replacements.

As a side effect, the BreakableToken structure changed significantly:
- have a common base class for single-line breakable tokens, as they are
  much more similar
- revamp handling of multi-line comments; we now calculate the
  information about lines in multi-line comments similar to normal
  tokens, and always issue replacements

As a result, we were able to get rid of special casing of trailing
whitespace deletion for comments in the whitespace manager and the
BreakableToken and fixed bugs related to tab handling and escaped
newlines.

llvm-svn: 182738
2013-05-27 15:23:34 +00:00
Daniel Jasper 7b27a10b1e Improve indentation of assignments.
Before:
unsigned OriginalStartColumn = SourceMgr.getSpellingColumnNumber(
    Current.FormatTok.getStartOfNonWhitespace()) -
                               1;

After:
unsigned OriginalStartColumn =
    SourceMgr.getSpellingColumnNumber(
        Current.FormatTok.getStartOfNonWhitespace()) -
    1;

llvm-svn: 182733
2013-05-27 12:45:09 +00:00
Daniel Jasper 32a796bc5b Fix hacky way of preventing a certain type of line break.
In general, we like to avoid line breaks like:

  ...
  SomeParameter, OtherParameter).DoSomething(
  ...

as they tend to make code really hard to read (how would you even indent the
next line?). Previously we have implemented this in a hacky way, which has now
shown to lead to problems. This fixes a few weird looking formattings, such as:

Before:
aaaaa(
    aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)
        .aaaaa(aaaaa),
    aaaaaaaaaaaaaaaaaaaaa);
After:
aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa).aaaaa(aaaaa),
      aaaaaaaaaaaaaaaaaaaaa);

llvm-svn: 182731
2013-05-27 11:50:16 +00:00
Nico Weber ced7d41b51 Formatter/ObjC: In dictionary literals, break after ':', not before it.
Before:
  @{ NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
     : regularFont, };

Now:
  @{ NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee :
     regularFont, };

':'s in dictionary literals (and the corresponding {}s) are now marked as
TT_ObjCDictLiteral too, which makes further improvements to dict literal
layout possible.

llvm-svn: 182716
2013-05-26 05:39:26 +00:00
Alexander Kornienko f2e021233c Ignore contents of #if 0 blocks.
Summary:
Added stack of preprocessor branching directives, and ignore all tokens
inside #if 0 except for preprocessor directives.

Reviewers: klimek, djasper

Reviewed By: klimek

CC: cfe-commits

Differential Revision: http://llvm-reviews.chandlerc.com/D855

llvm-svn: 182658
2013-05-24 18:24:24 +00:00
Daniel Jasper f632f69284 More tests and a fix for braced init lists.
Before: f(new vector<int> { 1, 2, 3 });
After:  f(new vector<int>{ 1, 2, 3 });
llvm-svn: 182614
2013-05-23 21:35:49 +00:00
Manuel Klimek 75ef31f607 Fix aligning of comments.
Previously we started sequences to align for single line comments when
the previous line had a trailing comment, but the sequence was broken
for other reasons.

Now we re-format:
// a
 // b
f(); // c
to:
// a
// b
f(); // c

llvm-svn: 182608
2013-05-23 20:46:07 +00:00
Manuel Klimek b27375fcd7 Fix aligning of comments that are at the start of the line.
Now correctly leaves:
f(); // comment
// comment
g(); // comment
... alone if the middle comment was aligned with g() before formatting.

llvm-svn: 182605
2013-05-23 19:54:43 +00:00
Daniel Jasper d443239493 Increase test coverage for braced init lists.
Also fix a minor bug for constructor initializers with braced init lists.

llvm-svn: 182601
2013-05-23 18:29:16 +00:00
Daniel Jasper 5bd0b9e53b Improve formatting of braced lists.
Before: vector<int> v{ -1};
After:  vector<int> v{-1};
llvm-svn: 182597
2013-05-23 18:05:18 +00:00
Manuel Klimek c573080d45 Stop aligning trailing comments which are aligned with the next line.
Previously we would align:
f(); // comment
     // other comment
g();

Even if // other comment was at the start of the line. Now we do not
align trailing comments if they have been already aligned correctly
with the next line.

Thus,
f(); // comment
// other comment
g();
will not be changed, while:
f(); // comment
  // other commment
g();
will lead to the two trailing comments being aligned.

llvm-svn: 182577
2013-05-23 11:42:52 +00:00
Manuel Klimek 5c24cca0f0 Use a SourceRange for the whitespace location in FormatToken.
Replaces the use of WhitespaceStart + WhitspaceLength.
This made a bug in the formatter obvous where we would incorrectly
calculate the next column.

FIXME: There's a similar bug left regarding TokenLength. We should
probably also move to have a TokenRange instead.

llvm-svn: 182572
2013-05-23 10:56:37 +00:00
Daniel Jasper e5777d25d6 Improve formatting of braced lists.
Before:
vector<int> x { 1, 2, 3 };
After:
vector<int> x{ 1, 2, 3 };

Also add a style option to remove the spaces inside braced lists,
so that the above becomes:
std::vector<int> v{1, 2, 3};

llvm-svn: 182570
2013-05-23 10:15:45 +00:00
Manuel Klimek ab41991c07 Expand parsing of braced init lists.
Allows formatting of C++11 braced init list constructs, like:
vector<int> v { 1, 2, 3 };
f({ 1, 2 });

This involves some changes of how tokens are handled in the
UnwrappedLineFormatter. Note that we have a plan to evolve the
design of the token flow into one where we create all tokens
up-front and then annotate them in the various layers (as we
currently already have to create all tokens at once anyway, the
current abstraction does not help). Thus, this introduces
FIXMEs towards that goal.

llvm-svn: 182568
2013-05-23 09:41:43 +00:00
Manuel Klimek 4fe43002f8 Makes whitespace management more consistent.
Instead of selectively storing some changes and directly generating
replacements for others, we now notify the WhitespaceManager of the
whitespace before every token (and optionally with more changes inside
tokens).

Then, we run over all whitespace in the very end in original source
order, where we have all information available to correctly align
comments and escaped newlines.

The future direction is to pull more of the comment alignment
implementation that is now in the BreakableToken into the
WhitespaceManager.

This fixes a bug when aligning comments or escaped newlines in unwrapped
lines that are handled out of order:
  #define A \
    f({     \
      g();  \
    });
... now gets correctly layouted.

llvm-svn: 182467
2013-05-22 12:51:29 +00:00
Daniel Jasper a4c571cd1c Improve clang-format's stream formatting.
clang-format was a bit too aggressive when trying to keep labels and
values on the same line.

Before:
    llvm::outs()
         << "aaaaaaaaaaaaaaaaaaa: " << aaaaaaaaaaaaa(
                                           aaaaaaaaaaaaaaaaaaaaaaaaaaaa);
After:
  llvm::outs() << "aaaaaaaaaaaaaaaaaaa: "
               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);

llvm-svn: 182458
2013-05-22 09:13:26 +00:00
Daniel Jasper 53e8d854fd Fix function declaration behavior.
This only affects styles that prevent bin packing. There, a break after
a template declaration also forced a line break after the function name.

Before:
template <class SomeType, class SomeOtherType>
SomeType
SomeFunction(SomeType Type, SomeOtherType OtherType) {}

After:
template <class SomeType, class SomeOtherType>
SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}

This fixes llvm.org/PR16072.

llvm-svn: 182457
2013-05-22 08:55:55 +00:00
Daniel Jasper 13c37b3483 Improve handling of trailing 'const'.
Reduce the preference for breaking before a trailing 'const' according
to review comments on r182362.

llvm-svn: 182455
2013-05-22 08:28:26 +00:00
Daniel Jasper f8114cf621 Cut-off clang-format analysis.
If clang-format is confronted with long and deeply nested lines (e.g.
complex static initializers or function calls), it can currently try too
hard to find the optimal solution and never finish. The reason is that
the memoization does not work effectively for deeply nested lines.

This patch removes an earlier workaround and instead opts for
accepting a non-optimal solution in rare cases. However, it only does
so only in cases where it would have to analyze an excessive number of
states (currently set to 10000 - the most complex line in Format.cpp
requires ~800 states) so this should not change the behavior in a
relevant way.

llvm-svn: 182449
2013-05-22 05:27:42 +00:00
Daniel Jasper 2a250b8b49 Let clang-format move the cursor appropriately.
With this patch, clang-format will try to keep the cursor at the
original code position in editor integrations (implemented for emacs and
vim). This means, after formatting, clang-format will try to keep the
cursor on the same character of the same token.

llvm-svn: 182373
2013-05-21 12:21:39 +00:00
Daniel Jasper 5be31f728a Allow breaking before a trailing const.
Before:
void someLongFunction(
    int someLongParameter) const;

After:
void someLongFunction(int someLongParameter)
    const;

Also slightly cleanup tests.

llvm-svn: 182362
2013-05-21 09:16:31 +00:00
Alexander Kornienko 006b5c89ce Clang-format: allow -style="{yaml/json}" on command line
Summary: + improved handling of default style and predefined styles.

Reviewers: djasper, klimek

Reviewed By: klimek

CC: cfe-commits

Differential Revision: http://llvm-reviews.chandlerc.com/D813

llvm-svn: 182205
2013-05-19 00:53:30 +00:00
Daniel Jasper 473c62c485 Slightly modify the formatting rules for braced lists.
Basically, the new rule is: The opening "{" always has to be on the
same line as the first element if the braced list is nested
(e.g. in another braced list or in a function).

The solution that clang-format produces almost always adheres to this
rule anyway and this makes clang-format significantly faster for larger
lists. Added a test cases for the only exception I could find
(which doesn't seem to be very important at first sight).

llvm-svn: 182082
2013-05-17 09:35:01 +00:00
Argyrios Kyrtzidis 065d720c31 [Lexer] Improve Lexer::getSourceText() when the given range deals with function macro arguments.
This is a modified version of a patch by Manuel Klimek.

llvm-svn: 182055
2013-05-16 21:37:39 +00:00
Daniel Jasper 9271650e61 Add additional test-case for one-line-function.
This ensures that we format:
void longFunctionName {
} // long comment here

And not:
void longFunctionName {}
// long comment here

As requested in post-commit-review.

llvm-svn: 182024
2013-05-16 16:54:34 +00:00
Daniel Jasper 8bb99e8911 Don't insert a break into include lines with trailing comments.
llvm-svn: 182003
2013-05-16 12:59:13 +00:00
Daniel Jasper 997af66087 Add config parsing test for new parameter.
llvm-svn: 182001
2013-05-16 12:16:23 +00:00
Daniel Jasper 3a685df7e0 Add option to put short loops on a single line.
This enables things like:

for (int &v : vec) v *= 2;

Enabled for Google style.

llvm-svn: 182000
2013-05-16 12:12:21 +00:00
Daniel Jasper ec04c0dba0 Add a more convenient interface to use clang-format.
It turns out that several implementations go through the trouble of
setting up a SourceManager and Lexer and abstracting this into a
function makes usage easier.

Also abstracts SourceManager-independent ranges out of
tooling::Refactoring and provides a convenience function to create them
from line ranges.

llvm-svn: 181997
2013-05-16 10:40:07 +00:00
Daniel Jasper f9eb9b1883 Comments should not prevent single-line functions.
Before:
void f() {}
void g() {
} // comment

After:
void f() {}
void g() {} // comment

llvm-svn: 181996
2013-05-16 10:17:39 +00:00
Daniel Jasper 7dd22c51b1 Add back accidentally deleted line and add test for it.
Before:
f("a", "b"
  "c");
After:
f("a", "b"
       "c");

llvm-svn: 181980
2013-05-16 04:26:02 +00:00
Daniel Jasper abca58c9ee Don't put short namespace on a single line.
Before:
namespace abc { class SomeClass; }
namespace def { void someFunction() {} }

After:
namespace abc {
class Def;
}
namespace def {
void someFunction() {}
}

Rationale:
a) Having anything other than forward declaration on the same line
   as a namespace looks confusing.
b) Formatting namespace-forward-declaration-combinations different
   from other stuff is inconsistent.
c) Wasting vertical space close to such forward declarations really
   does not affect readability.

llvm-svn: 181887
2013-05-15 14:09:55 +00:00
Daniel Jasper 6f05e59f23 Improve recognition of template definitions.
In the long run, this will probably be better fixed by a proper
expression parser..

Before:
  template <typename F>
  Matcher(const Matcher<F> & Other,
          typename enable_if_c < is_base_of<F, T>::value &&
              !is_same<F, T>::value > ::type * = 0)
      : Implementation(new ImplicitCastMatcher<F>(Other)) {}

After:
  template <typename F>
  Matcher(const Matcher<F> & Other,
          typename enable_if_c<is_base_of<F, T>::value &&
                               !is_same<F, T>::value>::type * = 0)
      : Implementation(new ImplicitCastMatcher<F>(Other)) {}

llvm-svn: 181884
2013-05-15 13:46:48 +00:00
Daniel Jasper c6fbc2192c Break function declarations after multi-line return types.
Before:
template <typename A>
SomeLoooooooooooooooooooooongType<
    typename some_namespace::SomeOtherType<A>::Type> Function() {}

After:
template <typename A>
SomeLoooooooooooooooooooooongType<
    typename some_namespace::SomeOtherType<A>::Type>
Function() {}

llvm-svn: 181877
2013-05-15 09:35:08 +00:00
Daniel Jasper 00aca707d5 Don't merge one-line functions in weird brace styles.
llvm-svn: 181872
2013-05-15 08:30:06 +00:00
Daniel Jasper d2ae41a7c6 Remove diagnostics from clang-format.
We only ever implemented one and that one is not actually all that
helpful (e.g. gets incorrectly triggered by macros).

llvm-svn: 181871
2013-05-15 08:14:19 +00:00
Daniel Jasper 5dad58e9df Improve formatting of function types.
The function type detection in r181438 and r181764 detected function
types too eagerly. This led to inconsistent formatting of inline
assembly and (together with r181687) to an incorrect formatting of calls
in macros.

Before: #define DEREF_AND_CALL_F(parameter) f (*parameter)
After:  #define DEREF_AND_CALL_F(parameter) f(*parameter)
llvm-svn: 181870
2013-05-15 07:51:51 +00:00
David Blaikie 7d17010db5 Use only explicit bool conversion operator
The most common (non-buggy) case are where such objects are used as
return expressions in bool-returning functions or as boolean function
arguments. In those cases I've used (& added if necessary) a named
function to provide the equivalent (or sometimes negative, depending on
convenient wording) test.

DiagnosticBuilder kept its implicit conversion operator owing to the
prevalent use of it in return statements.

One bug was found in ExprConstant.cpp involving a comparison of two
PointerUnions (PointerUnion did not previously have an operator==, so
instead both operands were converted to bool & then compared). A test
is included in test/SemaCXX/constant-expression-cxx1y.cpp for the fix
(adding operator== to PointerUnion in LLVM).

llvm-svn: 181869
2013-05-15 07:37:26 +00:00
Daniel Jasper 571f1af0bb Fix expression breaking for one-parameter-per-line styles.
Before:
  if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||
      aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||
      aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||
      aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}
After:
  if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||
      aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||
      aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}

llvm-svn: 181828
2013-05-14 20:39:56 +00:00
Benjamin Kramer 324bf7a159 Take a stab at trying to unbreak the makefile build.
There is no clangRewrite.a.

llvm-svn: 181781
2013-05-14 12:21:21 +00:00
Manuel Klimek cf0a230477 Hopefully fix configure build.
llvm-svn: 181780
2013-05-14 11:59:20 +00:00