[clang] [clang-format] Fix a regression in dumping the config (PR #80628)

2024-02-06 Thread Ben Hamilton via cfe-commits


@@ -1,5 +1,8 @@
+// RUN: clang-format -assume-filename=foo.m -dump-config | FileCheck %s

bhamiltoncx wrote:

It looks like you reverted the lit test which just runs `clang-format 
-dump-config` without any other arguments. Is that what you wanted to do?


https://github.com/llvm/llvm-project/pull/80628
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Fix a regression in dumping the config (PR #80628)

2024-02-05 Thread Ben Hamilton via cfe-commits

https://github.com/bhamiltoncx edited 
https://github.com/llvm/llvm-project/pull/80628
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Fix a regression in dumping the config (PR #80628)

2024-02-05 Thread Ben Hamilton via cfe-commits


@@ -0,0 +1,3 @@
+// RUN: clang-format -dump-config 2>&1 | FileCheck %s

bhamiltoncx wrote:

Can you also add a test with `clang-format --assume-filename=foo.m -dump-config 
2>&1 | FileCheck %s`?

It should result in `Language: ObjC`.


https://github.com/llvm/llvm-project/pull/80628
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Fix a regression in dumping the config (PR #80628)

2024-02-05 Thread Ben Hamilton via cfe-commits

https://github.com/bhamiltoncx approved this pull request.

Looks good. Can you add one more test, please?

https://github.com/llvm/llvm-project/pull/80628
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Format] Fix detection of languages when reading from stdin (PR #79051)

2024-02-04 Thread Ben Hamilton via cfe-commits

bhamiltoncx wrote:

Interesting! Might be because you changed the logic to always read from
stdin if no args are specified? I wasn't quite sure what that part of your
change was about.

On Sun, Feb 4, 2024, 16:04 Owen Pan ***@***.***> wrote:

> @bhamiltoncx  Thanks for the fix!
> Nevertheless, it seems that this triggered a new regression. See #80621
> .
>
> —
> Reply to this email directly, view it on GitHub
> ,
> or unsubscribe
> 
> .
> You are receiving this because you were mentioned.Message ID:
> ***@***.***>
>


https://github.com/llvm/llvm-project/pull/79051
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Format] Fix detection of languages when reading from stdin (PR #79051)

2024-01-23 Thread Ben Hamilton via cfe-commits

https://github.com/bhamiltoncx closed 
https://github.com/llvm/llvm-project/pull/79051
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Format] Fix detection of languages when reading from stdin (PR #79051)

2024-01-22 Thread Ben Hamilton via cfe-commits


@@ -547,18 +547,20 @@ static void PrintVersion(raw_ostream ) {
 // Dump the configuration.
 static int dumpConfig(bool IsSTDIN) {
   std::unique_ptr Code;
-  // We can't read the code to detect the language if there's no file name.
-  if (!IsSTDIN) {
-// Read in the code in case the filename alone isn't enough to detect the
-// language.
-ErrorOr> CodeOrErr =
-MemoryBuffer::getFileOrSTDIN(FileNames[0]);
-if (std::error_code EC = CodeOrErr.getError()) {
-  llvm::errs() << EC.message() << "\n";
-  return 1;
-}
-Code = std::move(CodeOrErr.get());
+
+  // FileNames should have at least "-" in it even if no file was specified.

bhamiltoncx wrote:

OK, changed to "must".

https://github.com/llvm/llvm-project/pull/79051
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Format] Fix detection of languages when reading from stdin (PR #79051)

2024-01-22 Thread Ben Hamilton via cfe-commits

https://github.com/bhamiltoncx updated 
https://github.com/llvm/llvm-project/pull/79051

>From 893c295ea7ff5fda9953420068fae2af7457c5c1 Mon Sep 17 00:00:00 2001
From: Ben Hamilton 
Date: Mon, 22 Jan 2024 11:33:18 -0700
Subject: [PATCH] [Format] Fix detection of languages when reading from stdin

---
 clang/test/Format/dump-config-objc-stdin.m |  5 +
 clang/tools/clang-format/ClangFormat.cpp   | 24 --
 clang/unittests/Format/FormatTestObjC.cpp  |  8 
 3 files changed, 26 insertions(+), 11 deletions(-)
 create mode 100644 clang/test/Format/dump-config-objc-stdin.m

diff --git a/clang/test/Format/dump-config-objc-stdin.m 
b/clang/test/Format/dump-config-objc-stdin.m
new file mode 100644
index 000..b22ff7b3328caa5
--- /dev/null
+++ b/clang/test/Format/dump-config-objc-stdin.m
@@ -0,0 +1,5 @@
+// RUN: clang-format -dump-config - < %s | FileCheck %s
+
+// CHECK: Language: ObjC
+@interface Foo
+@end
diff --git a/clang/tools/clang-format/ClangFormat.cpp 
b/clang/tools/clang-format/ClangFormat.cpp
index 49ab7677a3ee9c2..5ee6092bb9bb7f6 100644
--- a/clang/tools/clang-format/ClangFormat.cpp
+++ b/clang/tools/clang-format/ClangFormat.cpp
@@ -547,18 +547,20 @@ static void PrintVersion(raw_ostream ) {
 // Dump the configuration.
 static int dumpConfig(bool IsSTDIN) {
   std::unique_ptr Code;
-  // We can't read the code to detect the language if there's no file name.
-  if (!IsSTDIN) {
-// Read in the code in case the filename alone isn't enough to detect the
-// language.
-ErrorOr> CodeOrErr =
-MemoryBuffer::getFileOrSTDIN(FileNames[0]);
-if (std::error_code EC = CodeOrErr.getError()) {
-  llvm::errs() << EC.message() << "\n";
-  return 1;
-}
-Code = std::move(CodeOrErr.get());
+
+  // `FileNames` must have at least "-" in it even if no file was specified.
+  assert(!FileNames.empty());
+
+  // Read in the code in case the filename alone isn't enough to detect the
+  // language.
+  ErrorOr> CodeOrErr =
+  MemoryBuffer::getFileOrSTDIN(FileNames[0]);
+  if (std::error_code EC = CodeOrErr.getError()) {
+llvm::errs() << EC.message() << "\n";
+return 1;
   }
+  Code = std::move(CodeOrErr.get());
+
   llvm::Expected FormatStyle =
   clang::format::getStyle(Style, IsSTDIN ? AssumeFileName : FileNames[0],
   FallbackStyle, Code ? Code->getBuffer() : "");
diff --git a/clang/unittests/Format/FormatTestObjC.cpp 
b/clang/unittests/Format/FormatTestObjC.cpp
index cd4f9d934127bfd..d2c3459e0f846d7 100644
--- a/clang/unittests/Format/FormatTestObjC.cpp
+++ b/clang/unittests/Format/FormatTestObjC.cpp
@@ -31,6 +31,14 @@ class FormatTestObjC : public FormatTestBase {
   _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__)
 #define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__)
 
+TEST(FormatTestObjCStyle, DetectsObjCInStdin) {
+  auto Style = getStyle("LLVM", "", "none",
+"@interface\n"
+"- (id)init;");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+}
+
 TEST(FormatTestObjCStyle, DetectsObjCInHeaders) {
   auto Style = getStyle("LLVM", "a.h", "none",
 "@interface\n"

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Format] Fix detection of languages when reading from stdin (PR #79051)

2024-01-22 Thread Ben Hamilton via cfe-commits


@@ -0,0 +1,5 @@
+// RUN: clang-format -dump-config - < %s | FileCheck %s

bhamiltoncx wrote:

In this case, we do want two tests (at least, we do need the integration test 
in `clang/test/Format/dump-config-objc-stdin.m` to reproduce the issue).

The reason is, the bug was introduced into `ClangFormat.cpp`, which is only 
linked into the `clang-format` binary executed by the integration test. The 
code which regressed is not actually part of the `Format` library which is 
executed via the unit tests.

The unit tests do not execute the `clang-format` binary; they directly execute 
the formatting / config dumping logic via the `Format` library. But they're 
much faster to build and run, and it's possible this might regress in the 
`Format` library in the future (I was just surprised there were no tests there).

https://github.com/llvm/llvm-project/pull/79051
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format][NFC] Clean up the driver and getStyle() in Format.cpp (PR #74794)

2024-01-22 Thread Ben Hamilton via cfe-commits


@@ -544,28 +544,23 @@ static void PrintVersion(raw_ostream ) {
 }
 
 // Dump the configuration.
-static int dumpConfig() {
-  StringRef FileName;
+static int dumpConfig(bool IsSTDIN) {
   std::unique_ptr Code;
-  if (FileNames.empty()) {
-// We can't read the code to detect the language if there's no
-// file name, so leave Code empty here.
-FileName = AssumeFileName;
-  } else {
-// Read in the code in case the filename alone isn't enough to
-// detect the language.
+  // We can't read the code to detect the language if there's no file name.
+  if (!IsSTDIN) {
+// Read in the code in case the filename alone isn't enough to detect the
+// language.
 ErrorOr> CodeOrErr =
 MemoryBuffer::getFileOrSTDIN(FileNames[0]);

bhamiltoncx wrote:

Sent #79051 with a fix.

https://github.com/llvm/llvm-project/pull/74794
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Format] Fix detection of languages when reading from stdin (PR #79051)

2024-01-22 Thread Ben Hamilton via cfe-commits

https://github.com/bhamiltoncx created 
https://github.com/llvm/llvm-project/pull/79051

The code cleanup in #74794 accidentally broke detection of languages by reading 
file content from stdin, e.g. via `clang-format -dump-config - < 
/path/to/filename`.

This PR adds unit and integration tests to reproduce the issue and adds a fix.

Fixes: #79023 


>From be8f1e9c87875036dc4a00f151abe7d949206472 Mon Sep 17 00:00:00 2001
From: Ben Hamilton 
Date: Mon, 22 Jan 2024 11:33:18 -0700
Subject: [PATCH] [Format] Fix detection of languages when reading from stdin

---
 clang/test/Format/dump-config-objc-stdin.m |  5 +
 clang/tools/clang-format/ClangFormat.cpp   | 24 --
 clang/unittests/Format/FormatTestObjC.cpp  |  8 
 3 files changed, 26 insertions(+), 11 deletions(-)
 create mode 100644 clang/test/Format/dump-config-objc-stdin.m

diff --git a/clang/test/Format/dump-config-objc-stdin.m 
b/clang/test/Format/dump-config-objc-stdin.m
new file mode 100644
index 00..b22ff7b3328caa
--- /dev/null
+++ b/clang/test/Format/dump-config-objc-stdin.m
@@ -0,0 +1,5 @@
+// RUN: clang-format -dump-config - < %s | FileCheck %s
+
+// CHECK: Language: ObjC
+@interface Foo
+@end
diff --git a/clang/tools/clang-format/ClangFormat.cpp 
b/clang/tools/clang-format/ClangFormat.cpp
index 49ab7677a3ee9c..9cd61ed903a551 100644
--- a/clang/tools/clang-format/ClangFormat.cpp
+++ b/clang/tools/clang-format/ClangFormat.cpp
@@ -547,18 +547,20 @@ static void PrintVersion(raw_ostream ) {
 // Dump the configuration.
 static int dumpConfig(bool IsSTDIN) {
   std::unique_ptr Code;
-  // We can't read the code to detect the language if there's no file name.
-  if (!IsSTDIN) {
-// Read in the code in case the filename alone isn't enough to detect the
-// language.
-ErrorOr> CodeOrErr =
-MemoryBuffer::getFileOrSTDIN(FileNames[0]);
-if (std::error_code EC = CodeOrErr.getError()) {
-  llvm::errs() << EC.message() << "\n";
-  return 1;
-}
-Code = std::move(CodeOrErr.get());
+
+  // FileNames should have at least "-" in it even if no file was specified.
+  assert(!FileNames.empty());
+
+  // Read in the code in case the filename alone isn't enough to detect the
+  // language.
+  ErrorOr> CodeOrErr =
+  MemoryBuffer::getFileOrSTDIN(FileNames[0]);
+  if (std::error_code EC = CodeOrErr.getError()) {
+llvm::errs() << EC.message() << "\n";
+return 1;
   }
+  Code = std::move(CodeOrErr.get());
+
   llvm::Expected FormatStyle =
   clang::format::getStyle(Style, IsSTDIN ? AssumeFileName : FileNames[0],
   FallbackStyle, Code ? Code->getBuffer() : "");
diff --git a/clang/unittests/Format/FormatTestObjC.cpp 
b/clang/unittests/Format/FormatTestObjC.cpp
index cd4f9d934127bf..d2c3459e0f846d 100644
--- a/clang/unittests/Format/FormatTestObjC.cpp
+++ b/clang/unittests/Format/FormatTestObjC.cpp
@@ -31,6 +31,14 @@ class FormatTestObjC : public FormatTestBase {
   _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__)
 #define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__)
 
+TEST(FormatTestObjCStyle, DetectsObjCInStdin) {
+  auto Style = getStyle("LLVM", "", "none",
+"@interface\n"
+"- (id)init;");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+}
+
 TEST(FormatTestObjCStyle, DetectsObjCInHeaders) {
   auto Style = getStyle("LLVM", "a.h", "none",
 "@interface\n"

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format][NFC] Clean up the driver and getStyle() in Format.cpp (PR #74794)

2024-01-22 Thread Ben Hamilton via cfe-commits


@@ -544,28 +544,23 @@ static void PrintVersion(raw_ostream ) {
 }
 
 // Dump the configuration.
-static int dumpConfig() {
-  StringRef FileName;
+static int dumpConfig(bool IsSTDIN) {
   std::unique_ptr Code;
-  if (FileNames.empty()) {
-// We can't read the code to detect the language if there's no
-// file name, so leave Code empty here.
-FileName = AssumeFileName;
-  } else {
-// Read in the code in case the filename alone isn't enough to
-// detect the language.
+  // We can't read the code to detect the language if there's no file name.
+  if (!IsSTDIN) {
+// Read in the code in case the filename alone isn't enough to detect the
+// language.
 ErrorOr> CodeOrErr =
 MemoryBuffer::getFileOrSTDIN(FileNames[0]);

bhamiltoncx wrote:

Looks like this is the regression that caused #79023.

Previously, this would try to read in the code to detect the language whether 
or not this was reading from stdin.

Now, this fails to read in the code to detect the language when reading from 
stdin.


https://github.com/llvm/llvm-project/pull/74794
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format][NFC] Clean up the driver and getStyle() in Format.cpp (PR #74794)

2024-01-22 Thread Ben Hamilton via cfe-commits

bhamiltoncx wrote:

Seems like this regressed `clang-format - -dump_config < path/to/objc_file.m`. 
I filed https://github.com/llvm/llvm-project/issues/79023.


https://github.com/llvm/llvm-project/pull/74794
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 85670ac - [Format/ObjC] Support NS_ASSUME_NONNULL_BEGIN and FOUNDATION_EXPORT in ObjC language guesser

2023-05-30 Thread Ben Hamilton via cfe-commits

Author: Ben Hamilton
Date: 2023-05-30T11:12:03-06:00
New Revision: 85670ac86813b170c9301aa477421c56a71a7e1e

URL: 
https://github.com/llvm/llvm-project/commit/85670ac86813b170c9301aa477421c56a71a7e1e
DIFF: 
https://github.com/llvm/llvm-project/commit/85670ac86813b170c9301aa477421c56a71a7e1e.diff

LOG: [Format/ObjC] Support NS_ASSUME_NONNULL_BEGIN and FOUNDATION_EXPORT in 
ObjC language guesser

This adds to the ObjC language guesser a few more common macros used
in ObjC headers. These can help distinguish ObjC headers which
otherwise lack ObjC types from C++ headers.

Contributed by danblakemore.

Tested: New tests included. Ran unit tests with:
  ```
  % cmake -S llvm -B build -G Ninja && \
ninja -C build FormatTests && \
./build/tools/clang/unittests/Format/FormatTests 
--gtest_filter="*FormatTestObjC*"

  (snip)
  [--] 24 tests from FormatTestObjC (265 ms total)

  [--] Global test environment tear-down
  [==] 26 tests from 2 test suites ran. (270 ms total)
  [  PASSED  ] 26 tests.
  ```

Reviewed By: MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D151578

Added: 
clang/test/Format/dump-config-objc-macros.h

Modified: 
clang/lib/Format/Format.cpp
clang/unittests/Format/FormatTestObjC.cpp

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 154e6a21981e8..d7128ed558dc5 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -2687,6 +2687,8 @@ class ObjCHeaderStyleGuesser : public TokenAnalyzer {
 "CGSizeMake",
 "CGVector",
 "CGVectorMake",
+"FOUNDATION_EXPORT", // This is an alias for FOUNDATION_EXTERN.
+"FOUNDATION_EXTERN",
 "NSAffineTransform",
 "NSArray",
 "NSAttributedString",
@@ -2743,6 +2745,7 @@ class ObjCHeaderStyleGuesser : public TokenAnalyzer {
 "NSURLQueryItem",
 "NSUUID",
 "NSValue",
+"NS_ASSUME_NONNULL_BEGIN",
 "UIImage",
 "UIView",
 };

diff  --git a/clang/test/Format/dump-config-objc-macros.h 
b/clang/test/Format/dump-config-objc-macros.h
new file mode 100644
index 0..c90aa6067b1f4
--- /dev/null
+++ b/clang/test/Format/dump-config-objc-macros.h
@@ -0,0 +1,8 @@
+// RUN: clang-format -dump-config %s | FileCheck %s
+
+// CHECK: Language: ObjC
+NS_ASSUME_NONNULL_BEGIN
+
+FOUNDATION_EXTERN int kConstant;
+
+NS_ASSUME_NONNULL_END

diff  --git a/clang/unittests/Format/FormatTestObjC.cpp 
b/clang/unittests/Format/FormatTestObjC.cpp
index 55969ff6fd4a9..0cae6e2950fe6 100644
--- a/clang/unittests/Format/FormatTestObjC.cpp
+++ b/clang/unittests/Format/FormatTestObjC.cpp
@@ -94,6 +94,26 @@ TEST(FormatTestObjCStyle, DetectsObjCInHeaders) {
   ASSERT_TRUE((bool)Style);
   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
 
+  Style = getStyle("{}", "a.h", "none", R"objc(
+NS_ASSUME_NONNULL_BEGIN
+extern int i;
+NS_ASSUME_NONNULL_END
+)objc");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
+  Style = getStyle("{}", "a.h", "none", R"objc(
+FOUNDATION_EXTERN void DoStuff(void);
+)objc");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
+  Style = getStyle("{}", "a.h", "none", R"objc(
+FOUNDATION_EXPORT void DoStuff(void);
+)objc");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
   Style = getStyle("{}", "a.h", "none", "enum Foo {};");
   ASSERT_TRUE((bool)Style);
   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 00ea679 - [Format/ObjC] Support NS_ERROR_ENUM in ObjC language guesser

2023-04-07 Thread Ben Hamilton via cfe-commits

Author: Ben Hamilton
Date: 2023-04-07T16:10:52-06:00
New Revision: 00ea6798959d358aff9d7ef0907bbe241be7f7a4

URL: 
https://github.com/llvm/llvm-project/commit/00ea6798959d358aff9d7ef0907bbe241be7f7a4
DIFF: 
https://github.com/llvm/llvm-project/commit/00ea6798959d358aff9d7ef0907bbe241be7f7a4.diff

LOG: [Format/ObjC] Support NS_ERROR_ENUM in ObjC language guesser

Apple added a new NS_ERROR_ENUM macro to help define enums for
NSError codes.

This updates libformat's Objective-C language-guessing heuristic
to detect the new macro as well as related NSError types.

Tested: New tests added.

Reviewed By: MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D147577

Added: 


Modified: 
clang/lib/Format/Format.cpp
clang/lib/Format/FormatToken.h
clang/unittests/Format/FormatTestObjC.cpp

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 248d3684d01f2..6f377bb28e520 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -2699,6 +2699,8 @@ class ObjCHeaderStyleGuesser : public TokenAnalyzer {
 "NSDecimalNumber",
 "NSDictionary",
 "NSEdgeInsets",
+"NSError",
+"NSErrorDomain",
 "NSHashTable",
 "NSIndexPath",
 "NSIndexSet",
@@ -2760,6 +2762,7 @@ class ObjCHeaderStyleGuesser : public TokenAnalyzer {
 FormatTok->TokenText)) ||
 FormatTok->is(TT_ObjCStringLiteral) ||
 FormatTok->isOneOf(Keywords.kw_NS_CLOSED_ENUM, Keywords.kw_NS_ENUM,
+   Keywords.kw_NS_ERROR_ENUM,
Keywords.kw_NS_OPTIONS, TT_ObjCBlockLBrace,
TT_ObjCBlockLParen, TT_ObjCDecl, TT_ObjCForIn,
TT_ObjCMethodExpr, TT_ObjCMethodSpecifier,

diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index dc136428082e0..834ebf6f8b204 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -949,6 +949,7 @@ struct AdditionalKeywords {
 kw_CF_OPTIONS = ("CF_OPTIONS");
 kw_NS_CLOSED_ENUM = ("NS_CLOSED_ENUM");
 kw_NS_ENUM = ("NS_ENUM");
+kw_NS_ERROR_ENUM = ("NS_ERROR_ENUM");
 kw_NS_OPTIONS = ("NS_OPTIONS");
 
 kw_as = ("as");
@@ -1334,6 +1335,7 @@ struct AdditionalKeywords {
   IdentifierInfo *kw_CF_OPTIONS;
   IdentifierInfo *kw_NS_CLOSED_ENUM;
   IdentifierInfo *kw_NS_ENUM;
+  IdentifierInfo *kw_NS_ERROR_ENUM;
   IdentifierInfo *kw_NS_OPTIONS;
   IdentifierInfo *kw___except;
   IdentifierInfo *kw___has_include;

diff  --git a/clang/unittests/Format/FormatTestObjC.cpp 
b/clang/unittests/Format/FormatTestObjC.cpp
index e32b09239ae45..55969ff6fd4a9 100644
--- a/clang/unittests/Format/FormatTestObjC.cpp
+++ b/clang/unittests/Format/FormatTestObjC.cpp
@@ -89,6 +89,11 @@ TEST(FormatTestObjCStyle, DetectsObjCInHeaders) {
   ASSERT_TRUE((bool)Style);
   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
 
+  Style =
+  getStyle("{}", "a.h", "none", "typedef NS_ERROR_ENUM(int, Foo) {};\n");
+  ASSERT_TRUE((bool)Style);
+  EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
+
   Style = getStyle("{}", "a.h", "none", "enum Foo {};");
   ASSERT_TRUE((bool)Style);
   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 24b5266 - [Format/ObjC] Correctly handle base class with lightweight generics and protocol

2020-10-16 Thread Ben Hamilton via cfe-commits

Author: Ben Hamilton
Date: 2020-10-16T15:12:25-06:00
New Revision: 24b5266892c30e2c9cb6ea28c2631e988a5754b6

URL: 
https://github.com/llvm/llvm-project/commit/24b5266892c30e2c9cb6ea28c2631e988a5754b6
DIFF: 
https://github.com/llvm/llvm-project/commit/24b5266892c30e2c9cb6ea28c2631e988a5754b6.diff

LOG: [Format/ObjC] Correctly handle base class with lightweight generics and 
protocol

ClangFormat does not correctly handle an Objective-C interface declaration
with both lightweight generics and a protocol conformance.

This simple example:

```
@interface Foo : Bar  

@end
```

means `Foo` extends `Bar` (a lightweight generic class whose type
parameter is `Baz`) and also conforms to the protocol `Blech`.

ClangFormat should not apply any changes to the above example, but
instead it currently formats it quite poorly:

```
@interface Foo : Bar 


@end
```

The bug is that `UnwrappedLineParser` assumes an open-angle bracket
after a base class name is a protocol list, but it can also be a
lightweight generic specification.

This diff fixes the bug by factoring out the logic to parse
lightweight generics so it can apply both to the declared class
as well as the base class.

Test Plan: New tests added. Ran tests with:
  % ninja FormatTests && ./tools/clang/unittests/Format/FormatTests
  Confirmed tests failed before diff and passed after diff.

Reviewed By: sammccall, MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D89496

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/lib/Format/UnwrappedLineParser.h
clang/unittests/Format/FormatTestObjC.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 7075a6fe33f7..ab1f647481d0 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2612,32 +2612,15 @@ void 
UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
   // @interface can be followed by a lightweight generic
   // specialization list, then either a base class or a category.
   if (FormatTok->Tok.is(tok::less)) {
-// Unlike protocol lists, generic parameterizations support
-// nested angles:
-//
-// @interface Foo> :
-// NSObject 
-//
-// so we need to count how many open angles we have left.
-unsigned NumOpenAngles = 1;
-do {
-  nextToken();
-  // Early exit in case someone forgot a close angle.
-  if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
-  FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
-break;
-  if (FormatTok->Tok.is(tok::less))
-++NumOpenAngles;
-  else if (FormatTok->Tok.is(tok::greater)) {
-assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative");
---NumOpenAngles;
-  }
-} while (!eof() && NumOpenAngles != 0);
-nextToken(); // Skip '>'.
+parseObjCLightweightGenerics();
   }
   if (FormatTok->Tok.is(tok::colon)) {
 nextToken();
 nextToken(); // base class name
+// The base class can also have lightweight generics applied to it.
+if (FormatTok->Tok.is(tok::less)) {
+  parseObjCLightweightGenerics();
+}
   } else if (FormatTok->Tok.is(tok::l_paren))
 // Skip category, if present.
 parseParens();
@@ -2658,6 +2641,32 @@ void 
UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
   parseObjCUntilAtEnd();
 }
 
+void UnwrappedLineParser::parseObjCLightweightGenerics() {
+  assert(FormatTok->Tok.is(tok::less));
+  // Unlike protocol lists, generic parameterizations support
+  // nested angles:
+  //
+  // @interface Foo> :
+  // NSObject 
+  //
+  // so we need to count how many open angles we have left.
+  unsigned NumOpenAngles = 1;
+  do {
+nextToken();
+// Early exit in case someone forgot a close angle.
+if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
+FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
+  break;
+if (FormatTok->Tok.is(tok::less))
+  ++NumOpenAngles;
+else if (FormatTok->Tok.is(tok::greater)) {
+  assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative");
+  --NumOpenAngles;
+}
+  } while (!eof() && NumOpenAngles != 0);
+  nextToken(); // Skip '>'.
+}
+
 // Returns true for the declaration/definition form of @protocol,
 // false for the expression form.
 bool UnwrappedLineParser::parseObjCProtocol() {

diff  --git a/clang/lib/Format/UnwrappedLineParser.h 
b/clang/lib/Format/UnwrappedLineParser.h
index 8b3aa4c84edb..d682b4d6acd8 100644
--- a/clang/lib/Format/UnwrappedLineParser.h
+++ b/clang/lib/Format/UnwrappedLineParser.h
@@ -118,6 +118,7 @@ class UnwrappedLineParser {
   // parses the record as a child block, i.e. if the class declaration is an
   // expression.
   void parseRecord(bool ParseAsExpr = false);
+  void parseObjCLightweightGenerics();
   void parseObjCMethod();
   void 

[clang] e7b4fee - [Format/ObjC] Add NS_SWIFT_NAME() and CF_SWIFT_NAME() to WhitespaceSensitiveMacros

2020-10-14 Thread Ben Hamilton via cfe-commits

Author: Ben Hamilton
Date: 2020-10-14T15:42:51-06:00
New Revision: e7b4feea8e1bf520b34ad8c116abab6677344b74

URL: 
https://github.com/llvm/llvm-project/commit/e7b4feea8e1bf520b34ad8c116abab6677344b74
DIFF: 
https://github.com/llvm/llvm-project/commit/e7b4feea8e1bf520b34ad8c116abab6677344b74.diff

LOG: [Format/ObjC] Add NS_SWIFT_NAME() and CF_SWIFT_NAME() to 
WhitespaceSensitiveMacros

The argument passed to the preprocessor macros `NS_SWIFT_NAME(x)` and
`CF_SWIFT_NAME(x)` is stringified before passing to
`__attribute__((swift_name("x")))`.

ClangFormat didn't know about this stringification, so its custom parser
tried to parse the argument(s) passed to the macro as if they were
normal function arguments.

That means ClangFormat currently incorrectly inserts whitespace
between `NS_SWIFT_NAME` arguments with colons and dots, so:

```
extern UIWindow *MainWindow(void) NS_SWIFT_NAME(getter:MyHelper.mainWindow());
```

becomes:

```
extern UIWindow *MainWindow(void) NS_SWIFT_NAME(getter : MyHelper.mainWindow());
```

which clang treats as a parser error:

```
error: 'swift_name' attribute has invalid identifier for context name 
[-Werror,-Wswift-name-attribute]
```

Thankfully, D82620 recently added the ability to treat specific macros
as "whitespace sensitive", meaning their arguments are implicitly
treated as strings (so whitespace is not added anywhere inside).

This diff adds `NS_SWIFT_NAME` and `CF_SWIFT_NAME` to
`WhitespaceSensitiveMacros` so their arguments are implicitly treated
as whitespace-sensitive.

Test Plan:
  New tests added. Ran tests with:
  % ninja FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewed By: sammccall

Differential Revision: https://reviews.llvm.org/D89425

Added: 


Modified: 
clang/lib/Format/Format.cpp
clang/unittests/Format/FormatTestObjC.cpp

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 8e4f65ace3f0..f2215e255c2b 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -964,6 +964,8 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind 
Language) {
   LLVMStyle.WhitespaceSensitiveMacros.push_back("STRINGIZE");
   LLVMStyle.WhitespaceSensitiveMacros.push_back("PP_STRINGIZE");
   LLVMStyle.WhitespaceSensitiveMacros.push_back("BOOST_PP_STRINGIZE");
+  LLVMStyle.WhitespaceSensitiveMacros.push_back("NS_SWIFT_NAME");
+  LLVMStyle.WhitespaceSensitiveMacros.push_back("CF_SWIFT_NAME");
 
   // Defaults that 
diff er when not C++.
   if (Language == FormatStyle::LK_TableGen) {

diff  --git a/clang/unittests/Format/FormatTestObjC.cpp 
b/clang/unittests/Format/FormatTestObjC.cpp
index 28d33dcdaa54..f3be942ab913 100644
--- a/clang/unittests/Format/FormatTestObjC.cpp
+++ b/clang/unittests/Format/FormatTestObjC.cpp
@@ -1024,6 +1024,12 @@ TEST_F(FormatTestObjC, ObjCSnippets) {
   verifyFormat("@property(assign, nonatomic) CGFloat hoverAlpha;");
   verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
 
+  verifyFormat("extern UIWindow *MainWindow(void) "
+   "NS_SWIFT_NAME(getter:MyHelper.mainWindow());");
+
+  verifyFormat("extern UIWindow *MainWindow(void) "
+   "CF_SWIFT_NAME(getter:MyHelper.mainWindow());");
+
   Style.ColumnLimit = 50;
   verifyFormat("@interface Foo\n"
"- (void)doStuffWithFoo:(id)name\n"



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] 0151ddc - Create a clang-tidy check to warn when -dealloc is implemented inside an ObjC class category.

2020-02-10 Thread Ben Hamilton via cfe-commits

Author: Michael Wyman
Date: 2020-02-10T08:56:28-07:00
New Revision: 0151ddc2e834ab4949789cbed4e03a958284cd54

URL: 
https://github.com/llvm/llvm-project/commit/0151ddc2e834ab4949789cbed4e03a958284cd54
DIFF: 
https://github.com/llvm/llvm-project/commit/0151ddc2e834ab4949789cbed4e03a958284cd54.diff

LOG: Create a clang-tidy check to warn when -dealloc is implemented inside an 
ObjC class category.

Summary: Such implementations may override the class's own implementation, and 
even be a danger in case someone later comes and adds one to the class itself. 
Most times this has been encountered have been a mistake.

Reviewers: stephanemoore, benhamilton, dmaclach

Reviewed By: stephanemoore, benhamilton, dmaclach

Subscribers: dmaclach, mgorny, cfe-commits

Tags: #clang-tools-extra, #clang

Differential Revision: https://reviews.llvm.org/D72876

Added: 
clang-tools-extra/clang-tidy/objc/DeallocInCategoryCheck.cpp
clang-tools-extra/clang-tidy/objc/DeallocInCategoryCheck.h
clang-tools-extra/docs/clang-tidy/checks/objc-dealloc-in-category.rst
clang-tools-extra/test/clang-tidy/checkers/objc-dealloc-in-category.m

Modified: 
clang-tools-extra/clang-tidy/objc/CMakeLists.txt
clang-tools-extra/clang-tidy/objc/ObjCTidyModule.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/objc/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/objc/CMakeLists.txt
index 68dda6530f7f..1e39e02e7b92 100644
--- a/clang-tools-extra/clang-tidy/objc/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/objc/CMakeLists.txt
@@ -2,6 +2,7 @@ set(LLVM_LINK_COMPONENTS support)
 
 add_clang_library(clangTidyObjCModule
   AvoidNSErrorInitCheck.cpp
+  DeallocInCategoryCheck.cpp
   ForbiddenSubclassingCheck.cpp
   MissingHashCheck.cpp
   ObjCTidyModule.cpp

diff  --git a/clang-tools-extra/clang-tidy/objc/DeallocInCategoryCheck.cpp 
b/clang-tools-extra/clang-tidy/objc/DeallocInCategoryCheck.cpp
new file mode 100644
index ..468065742670
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/objc/DeallocInCategoryCheck.cpp
@@ -0,0 +1,46 @@
+//===--- DeallocInCategoryCheck.cpp - clang-tidy ---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "DeallocInCategoryCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/DeclObjC.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace objc {
+
+void DeallocInCategoryCheck::registerMatchers(MatchFinder *Finder) {
+  // This check should only be applied to Objective-C sources.
+  if (!getLangOpts().ObjC)
+return;
+
+  // Non-NSObject/NSProxy-derived objects may not have -dealloc as a special
+  // method. However, it seems highly unrealistic to expect many 
false-positives
+  // by warning on -dealloc in categories on classes without one of those
+  // base classes.
+  Finder->addMatcher(
+  objcMethodDecl(isInstanceMethod(), hasName("dealloc"),
+ hasDeclContext(objcCategoryImplDecl().bind("impl")))
+  .bind("dealloc"),
+  this);
+}
+
+void DeallocInCategoryCheck::check(const MatchFinder::MatchResult ) {
+  const auto *DeallocDecl = Result.Nodes.getNodeAs("dealloc");
+  const auto *CID = Result.Nodes.getNodeAs("impl");
+  assert(DeallocDecl != nullptr);
+  diag(DeallocDecl->getLocation(), "category %0 should not implement -dealloc")
+  << CID;
+}
+
+} // namespace objc
+} // namespace tidy
+} // namespace clang

diff  --git a/clang-tools-extra/clang-tidy/objc/DeallocInCategoryCheck.h 
b/clang-tools-extra/clang-tidy/objc/DeallocInCategoryCheck.h
new file mode 100644
index ..f8e1f70e216b
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/objc/DeallocInCategoryCheck.h
@@ -0,0 +1,36 @@
+//===--- DeallocInCategoryCheck.h - clang-tidy --*- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_OBJC_DEALLOCINCATEGORYCHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_OBJC_DEALLOCINCATEGORYCHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang {
+namespace tidy {
+namespace objc {
+
+/// Finds implementations of -dealloc in Objective-C categories. The category
+/// implementation will override any dealloc in the class implementation,
+/// potentially causing issues.
+///
+/// 

r366719 - Adds support for formatting NS_CLOSED_ENUM and CF_CLOSED_ENUM alongside NS_ENUM and CF_ENUM.

2019-07-22 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Mon Jul 22 11:20:01 2019
New Revision: 366719

URL: http://llvm.org/viewvc/llvm-project?rev=366719=rev
Log:
Adds support for formatting NS_CLOSED_ENUM and CF_CLOSED_ENUM alongside NS_ENUM 
and CF_ENUM.

Summary:
Addresses the formatting of NS_CLOSED_ENUM and CF_CLOSED_ENUM, introduced in 
Swift 5.

Before:

```
typedef NS_CLOSED_ENUM(NSInteger, Foo){FooValueOne = 1, FooValueTwo,
   FooValueThree};
```

After:

```
typedef NS_CLOSED_ENUM(NSInteger, Foo) {
  FooValueOne = 1,
  FooValueTwo,
  FooValueThree
};
```

Contributed by heijink.

Reviewers: benhamilton, krasimir

Reviewed By: benhamilton

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D65012

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/lib/Format/FormatToken.h
cfe/trunk/lib/Format/UnwrappedLineParser.cpp
cfe/trunk/unittests/Format/FormatTest.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=366719=366718=366719=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Mon Jul 22 11:20:01 2019
@@ -1685,10 +1685,11 @@ private:
 std::end(FoundationIdentifiers),
 FormatTok->TokenText)) ||
 FormatTok->is(TT_ObjCStringLiteral) ||
-FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
-   TT_ObjCBlockLBrace, TT_ObjCBlockLParen,
-   TT_ObjCDecl, TT_ObjCForIn, TT_ObjCMethodExpr,
-   TT_ObjCMethodSpecifier, TT_ObjCProperty)) {
+FormatTok->isOneOf(Keywords.kw_NS_CLOSED_ENUM, Keywords.kw_NS_ENUM,
+   Keywords.kw_NS_OPTIONS, TT_ObjCBlockLBrace,
+   TT_ObjCBlockLParen, TT_ObjCDecl, TT_ObjCForIn,
+   TT_ObjCMethodExpr, TT_ObjCMethodSpecifier,
+   TT_ObjCProperty)) {
   LLVM_DEBUG(llvm::dbgs()
  << "Detected ObjC at location "
  << FormatTok->Tok.getLocation().printToString(

Modified: cfe/trunk/lib/Format/FormatToken.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/FormatToken.h?rev=366719=366718=366719=diff
==
--- cfe/trunk/lib/Format/FormatToken.h (original)
+++ cfe/trunk/lib/Format/FormatToken.h Mon Jul 22 11:20:01 2019
@@ -677,8 +677,10 @@ struct AdditionalKeywords {
 kw_override = ("override");
 kw_in = ("in");
 kw_of = ("of");
+kw_CF_CLOSED_ENUM = ("CF_CLOSED_ENUM");
 kw_CF_ENUM = ("CF_ENUM");
 kw_CF_OPTIONS = ("CF_OPTIONS");
+kw_NS_CLOSED_ENUM = ("NS_CLOSED_ENUM");
 kw_NS_ENUM = ("NS_ENUM");
 kw_NS_OPTIONS = ("NS_OPTIONS");
 
@@ -787,8 +789,10 @@ struct AdditionalKeywords {
   IdentifierInfo *kw_override;
   IdentifierInfo *kw_in;
   IdentifierInfo *kw_of;
+  IdentifierInfo *kw_CF_CLOSED_ENUM;
   IdentifierInfo *kw_CF_ENUM;
   IdentifierInfo *kw_CF_OPTIONS;
+  IdentifierInfo *kw_NS_CLOSED_ENUM;
   IdentifierInfo *kw_NS_ENUM;
   IdentifierInfo *kw_NS_OPTIONS;
   IdentifierInfo *kw___except;

Modified: cfe/trunk/lib/Format/UnwrappedLineParser.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineParser.cpp?rev=366719=366718=366719=diff
==
--- cfe/trunk/lib/Format/UnwrappedLineParser.cpp (original)
+++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp Mon Jul 22 11:20:01 2019
@@ -1215,7 +1215,8 @@ void UnwrappedLineParser::parseStructura
 case tok::kw_typedef:
   nextToken();
   if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
- Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS))
+ Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
+ Keywords.kw_CF_CLOSED_ENUM, 
Keywords.kw_NS_CLOSED_ENUM))
 parseEnum();
   break;
 case tok::kw_struct:

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=366719=366718=366719=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Mon Jul 22 11:20:01 2019
@@ -1716,6 +1716,8 @@ TEST_F(FormatTest, FormatsTypedefEnum) {
 
 TEST_F(FormatTest, FormatsNSEnums) {
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
+  verifyGoogleFormat(
+  "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
   verifyGoogleFormat("typedef NS_ENUM(NSInteger, 

r366592 - [Format/ObjC] Avoid breaking between unary operators and operands

2019-07-19 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Fri Jul 19 09:50:24 2019
New Revision: 366592

URL: http://llvm.org/viewvc/llvm-project?rev=366592=rev
Log:
[Format/ObjC] Avoid breaking between unary operators and operands

Summary:
Test Plan:
  New tests added. Ran tests with:
  % ninja FormatTests && ./tools/clang/unittests/Format/FormatTests
  Confirmed tests failed before change and passed after change.

Reviewers: krasimir, djasper, sammccall, klimek

Reviewed By: sammccall

Subscribers: klimek, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D64775

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=366592=366591=366592=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Fri Jul 19 09:50:24 2019
@@ -2429,6 +2429,8 @@ unsigned TokenAnnotator::splitPenalty(co
   if (Left.is(TT_JavaAnnotation))
 return 50;
 
+  if (Left.is(TT_UnaryOperator))
+return 60;
   if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
   Left.Previous->isLabelString() &&
   (Left.NextOperator || Left.OperatorIndex != 0))

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=366592=366591=366592=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Fri Jul 19 09:50:24 2019
@@ -886,6 +886,18 @@ TEST_F(FormatTestObjC, FormatObjCMethodE
" bb:42\n"
" cc:42];");
 
+  // Avoid breaking between unary operators and ObjC method expressions.
+  Style.ColumnLimit = 45;
+  verifyFormat("if (a012345678901234567890123 &&\n"
+   "![foo bar]) {\n"
+   "}");
+  verifyFormat("if (a012345678901234567890123 &&\n"
+   "+[foo bar]) {\n"
+   "}");
+  verifyFormat("if (a012345678901234567890123 &&\n"
+   "-[foo bar]) {\n"
+   "}");
+
   Style.ColumnLimit = 70;
   verifyFormat(
   "void f() {\n"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r366267 - [clang-format] Don't detect call to ObjC class method as C++11 attribute specifier

2019-07-16 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Tue Jul 16 14:29:40 2019
New Revision: 366267

URL: http://llvm.org/viewvc/llvm-project?rev=366267=rev
Log:
[clang-format] Don't detect call to ObjC class method as C++11 attribute 
specifier

Summary:
Previously, clang-format detected something like the following as a C++11 
attribute specifier.

  @[[NSArray class]]

instead of an array with an Objective-C method call inside. In general, when 
the attribute specifier checking runs, if it sees 2 identifiers in a row, it 
decides that the square brackets represent an Objective-C method call. However, 
here, `class` is tokenized as a keyword instead of an identifier, so this check 
fails.

To fix this, the attribute specifier first checks whether the first square 
bracket has an "@" before it. If it does, then that square bracket is not the 
start of a attribute specifier because it is an Objective-C array literal. (The 
assumption is that @[[.*]] is not valid C/C++.)

Contributed by rkgibson2.

Reviewers: benhamilton

Reviewed By: benhamilton

Subscribers: aaron.ballman, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D64632

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=366267=366266=366267=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Tue Jul 16 14:29:40 2019
@@ -388,6 +388,10 @@ private:
   bool isCpp11AttributeSpecifier(const FormatToken ) {
 if (!Style.isCpp() || !Tok.startsSequence(tok::l_square, tok::l_square))
   return false;
+// The first square bracket is part of an ObjC array literal
+if (Tok.Previous && Tok.Previous->is(tok::at)) {
+  return false;
+}
 const FormatToken *AttrTok = Tok.Next->Next;
 if (!AttrTok)
   return false;
@@ -400,7 +404,7 @@ private:
 while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) {
   // ObjC message send. We assume nobody will use : in a C++11 attribute
   // specifier parameter, although this is technically valid:
-  // [[foo(:)]]
+  // [[foo(:)]].
   if (AttrTok->is(tok::colon) ||
   AttrTok->startsSequence(tok::identifier, tok::identifier) ||
   AttrTok->startsSequence(tok::r_paren, tok::identifier))

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=366267=366266=366267=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Tue Jul 16 14:29:40 2019
@@ -7027,6 +7027,12 @@ TEST_F(FormatTest, UnderstandsSquareAttr
   // On the other hand, we still need to correctly find array subscripts.
   verifyFormat("int a = std::vector{1, 2, 3}[0];");
 
+  // Make sure that we do not mistake Objective-C method inside array literals
+  // as attributes, even if those method names are also keywords.
+  verifyFormat("@[ [foo bar] ];");
+  verifyFormat("@[ [NSArray class] ];");
+  verifyFormat("@[ [foo enum] ];");
+
   // Make sure we do not parse attributes as lambda introducers.
   FormatStyle MultiLineFunctions = getLLVMStyle();
   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r358904 - [ASTMatchers] Introduce Objective-C matchers `isClassMessage`, `isClassMethod`, and `isInstanceMethod`

2019-04-22 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Mon Apr 22 10:54:11 2019
New Revision: 358904

URL: http://llvm.org/viewvc/llvm-project?rev=358904=rev
Log:
[ASTMatchers] Introduce Objective-C matchers `isClassMessage`, `isClassMethod`, 
and `isInstanceMethod`

Summary:
isClassMessage is an equivalent to isInstanceMessage for ObjCMessageExpr, but 
matches message expressions to classes.

isClassMethod and isInstanceMethod check whether a method declaration (or 
definition) is for a class method or instance method (respectively).

Contributed by @mywman!

Reviewers: benhamilton, klimek, mwyman

Reviewed By: benhamilton, mwyman

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D60920

Modified:
cfe/trunk/docs/LibASTMatchersReference.html
cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
cfe/trunk/lib/ASTMatchers/Dynamic/Registry.cpp
cfe/trunk/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp

Modified: cfe/trunk/docs/LibASTMatchersReference.html
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/LibASTMatchersReference.html?rev=358904=358903=358904=diff
==
--- cfe/trunk/docs/LibASTMatchersReference.html (original)
+++ cfe/trunk/docs/LibASTMatchersReference.html Mon Apr 22 10:54:11 2019
@@ -3567,11 +3567,24 @@ represent an error condition in the tree
 
 
 
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1ObjCMessageExpr.html;>ObjCMessageExprisClassMessage
+Returns true when 
the Objective-C message is sent to a class.
+
+Example
+matcher = objcMessageExpr(isClassMessage())
+matches
+  [NSString stringWithFormat:@"format"];
+but not
+  NSString *x = @"hello";
+  [x containsString:@"h"];
+
+
+
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1ObjCMessageExpr.html;>ObjCMessageExprisInstanceMessage
 Returns true when 
the Objective-C message is sent to an instance.
 
 Example
-matcher = objcMessagaeExpr(isInstanceMessage())
+matcher = objcMessageExpr(isInstanceMessage())
 matches
   NSString *x = @"hello";
   [x containsString:@"h"];
@@ -3580,6 +3593,30 @@ but not
 
 
 
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1ObjCMethodDecl.html;>ObjCMethodDeclisClassMethod
+Returns true when the 
Objective-C method declaration is a class method.
+
+Example
+matcher = objcMethodDecl(isClassMethod())
+matches
+  @interface I + (void)foo; @end
+but not
+  @interface I - (void)bar; @end
+
+
+
+Matcherhttps://clang.llvm.org/doxygen/classclang_1_1ObjCMethodDecl.html;>ObjCMethodDeclisInstanceMethod
+Returns true when 
the Objective-C method declaration is an instance method.
+
+Example
+matcher = objcMethodDecl(isInstanceMethod())
+matches
+  @interface I - (void)bar; @end
+but not
+  @interface I + (void)foo; @end
+
+
+
 Matcherhttps://clang.llvm.org/doxygen/classclang_1_1ObjCMessageExpr.html;>ObjCMessageExprmatchesSelectorstd::string 
RegExp
 Matches ObjC 
selectors whose name contains
 a substring matched by the given RegExp.

Modified: cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h?rev=358904=358903=358904=diff
==
--- cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h (original)
+++ cfe/trunk/include/clang/ASTMatchers/ASTMatchers.h Mon Apr 22 10:54:11 2019
@@ -2938,10 +2938,59 @@ AST_MATCHER_P(ObjCMessageExpr, hasReceiv
   return InnerMatcher.matches(TypeDecl, Finder, Builder);
 }
 
+/// Returns true when the Objective-C method declaration is a class method.
+///
+/// Example
+/// matcher = objcMethodDecl(isClassMethod())
+/// matches
+/// \code
+/// @interface I + (void)foo; @end
+/// \endcode
+/// but not
+/// \code
+/// @interface I - (void)bar; @end
+/// \endcode
+AST_MATCHER(ObjCMethodDecl, isClassMethod) {
+  return Node.isClassMethod();
+}
+
+/// Returns true when the Objective-C method declaration is an instance method.
+///
+/// Example
+/// matcher = objcMethodDecl(isInstanceMethod())
+/// matches
+/// \code
+/// @interface I - (void)bar; @end
+/// \endcode
+/// but not
+/// \code
+/// @interface I + (void)foo; @end
+/// \endcode
+AST_MATCHER(ObjCMethodDecl, isInstanceMethod) {
+  return Node.isInstanceMethod();
+}
+
+/// Returns true when the Objective-C message is sent to a class.
+///
+/// Example
+/// matcher = objcMessageExpr(isClassMessage())
+/// matches
+/// \code
+///   [NSString stringWithFormat:@"format"];
+/// \endcode
+/// but not
+/// \code
+///   NSString *x = @"hello";
+///   [x containsString:@"h"];
+/// \endcode
+AST_MATCHER(ObjCMessageExpr, isClassMessage) {
+  return Node.isClassMessage();
+}
+
 /// Returns true when the Objective-C message is sent to an instance.
 ///
 /// Example
-/// matcher = objcMessagaeExpr(isInstanceMessage())
+/// matcher = objcMessageExpr(isInstanceMessage())
 /// matches
 /// \code
 ///   NSString *x = @"hello";

Modified: cfe/trunk/lib/ASTMatchers/Dynamic/Registry.cpp
URL: 

r353531 - [Format/ObjC] Fix [foo bar]->baz formatting as lambda arrow

2019-02-08 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Fri Feb  8 07:55:18 2019
New Revision: 353531

URL: http://llvm.org/viewvc/llvm-project?rev=353531=rev
Log:
[Format/ObjC] Fix [foo bar]->baz formatting as lambda arrow

Summary:
Currently, `UnwrappedLineParser` thinks an arrow token after
an ObjC method expression is a C++ lambda arrow, so it formats:

```
[foo bar]->baz
```

as:

```
[foo bar] -> baz
```

Because `UnwrappedLineParser` runs before `TokenAnnotator`, it can't
know if the arrow token is after an ObjC method expression or not.

This diff makes `TokenAnnotator` remove the TT_LambdaArrow on
the arrow token if it follows an ObjC method expression.

Test Plan: New test added. Ran test with:
  % ninja FormatTests && ./tools/clang/unittests/Format/FormatTests
  Confirmed test failed before diff and passed after diff.

Reviewers: krasimir, djasper, sammccall

Reviewed By: sammccall

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D57923

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/lib/Format/UnwrappedLineParser.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=353531=353530=353531=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Fri Feb  8 07:55:18 2019
@@ -520,6 +520,10 @@ private:
   if (Parent && Parent->is(TT_PointerOrReference))
 Parent->Type = TT_BinaryOperator;
 }
+// An arrow after an ObjC method expression is not a lambda arrow.
+if (CurrentToken->Type == TT_ObjCMethodExpr && CurrentToken->Next &&
+CurrentToken->Next->is(TT_LambdaArrow))
+  CurrentToken->Next->Type = TT_Unknown;
 Left->MatchingParen = CurrentToken;
 CurrentToken->MatchingParen = Left;
 // FirstObjCSelectorName is set when a colon is found. This does

Modified: cfe/trunk/lib/Format/UnwrappedLineParser.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineParser.cpp?rev=353531=353530=353531=diff
==
--- cfe/trunk/lib/Format/UnwrappedLineParser.cpp (original)
+++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp Fri Feb  8 07:55:18 2019
@@ -1426,6 +1426,9 @@ bool UnwrappedLineParser::tryToParseLamb
   nextToken();
   break;
 case tok::arrow:
+  // This might or might not actually be a lambda arrow (this could be an
+  // ObjC method invocation followed by a dereferencing arrow). We might
+  // reset this back to TT_Unknown in TokenAnnotator.
   FormatTok->Type = TT_LambdaArrow;
   nextToken();
   break;

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=353531=353530=353531=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Fri Feb  8 07:55:18 2019
@@ -611,6 +611,7 @@ TEST_F(FormatTestObjC, FormatObjCMethodD
 
 TEST_F(FormatTestObjC, FormatObjCMethodExpr) {
   verifyFormat("[foo bar:baz];");
+  verifyFormat("[foo bar]->baz;");
   verifyFormat("return [foo bar:baz];");
   verifyFormat("return (a)[foo bar:baz];");
   verifyFormat("f([foo bar:baz]);");


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r352622 - [clang-format] Fix line parsing for noexcept lambdas

2019-01-30 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Wed Jan 30 05:54:32 2019
New Revision: 352622

URL: http://llvm.org/viewvc/llvm-project?rev=352622=rev
Log:
[clang-format] Fix line parsing for noexcept lambdas

Summary:
> $ echo "int c = [b]() mutable noexcept { return [] { return b++; }(); }();" 
> |clang-format

```
int c = [b]() mutable noexcept {
  return [] { return b++; }();
}
();
```
with patch:
> $ echo "int c = [b]() mutable noexcept { return [] { return b++; }(); }();" 
> |bin/clang-format
```
int c = [b]() mutable noexcept { return [] { return b++; }(); }();
```

Contributed by hultman.

Reviewers: benhamilton, jolesiak, klimek, Wizard

Reviewed By: benhamilton

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D56909

Modified:
cfe/trunk/lib/Format/UnwrappedLineParser.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/UnwrappedLineParser.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineParser.cpp?rev=352622=352621=352622=diff
==
--- cfe/trunk/lib/Format/UnwrappedLineParser.cpp (original)
+++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp Wed Jan 30 05:54:32 2019
@@ -1422,6 +1422,7 @@ bool UnwrappedLineParser::tryToParseLamb
 case tok::numeric_constant:
 case tok::coloncolon:
 case tok::kw_mutable:
+case tok::kw_noexcept:
   nextToken();
   break;
 case tok::arrow:

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=352622=352621=352622=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Wed Jan 30 05:54:32 2019
@@ -11725,6 +11725,8 @@ TEST_F(FormatTest, FormatsWithWebKitStyl
 
 TEST_F(FormatTest, FormatsLambdas) {
   verifyFormat("int c = [b]() mutable { return [] { return b++; }(); 
}();\n");
+  verifyFormat(
+  "int c = [b]() mutable noexcept { return [] { return b++; }(); 
}();\n");
   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
   verifyFormat("int c = [&, , a] { [=, c, ] { return b++; }(); }();\n");
   verifyFormat("int c = [, , a] { [=, a, b, ] { return b++; }(); 
}();\n");


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r346144 - [Format] Add debugging to ObjC language guesser

2018-11-05 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Mon Nov  5 08:59:33 2018
New Revision: 346144

URL: http://llvm.org/viewvc/llvm-project?rev=346144=rev
Log:
[Format] Add debugging to ObjC language guesser

Summary:
To handle diagnosing bugs where ObjCHeaderStyleGuesser guesses
wrong, this diff adds a bit more debug logging to the Objective-C
language guesser.

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D54110

Modified:
cfe/trunk/lib/Format/Format.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=346144=346143=346144=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Mon Nov  5 08:59:33 2018
@@ -1504,7 +1504,8 @@ public:
   SmallVectorImpl ,
   FormatTokenLexer ) override {
 assert(Style.Language == FormatStyle::LK_Cpp);
-IsObjC = guessIsObjC(AnnotatedLines, Tokens.getKeywords());
+IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
+ Tokens.getKeywords());
 tooling::Replacements Result;
 return {Result, 0};
   }
@@ -1512,8 +1513,10 @@ public:
   bool isObjC() { return IsObjC; }
 
 private:
-  static bool guessIsObjC(const SmallVectorImpl 
,
-  const AdditionalKeywords ) {
+  static bool
+  guessIsObjC(const SourceManager ,
+  const SmallVectorImpl ,
+  const AdditionalKeywords ) {
 // Keep this array sorted, since we are binary searching over it.
 static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
 "CGFloat",
@@ -1604,9 +1607,15 @@ private:
TT_ObjCBlockLBrace, TT_ObjCBlockLParen,
TT_ObjCDecl, TT_ObjCForIn, TT_ObjCMethodExpr,
TT_ObjCMethodSpecifier, TT_ObjCProperty)) {
+  LLVM_DEBUG(llvm::dbgs()
+ << "Detected ObjC at location "
+ << FormatTok->Tok.getLocation().printToString(
+SourceManager)
+ << " token: " << FormatTok->TokenText << " token type: "
+ << getTokenTypeName(FormatTok->Type) << "\n");
   return true;
 }
-if (guessIsObjC(Line->Children, Keywords))
+if (guessIsObjC(SourceManager, Line->Children, Keywords))
   return true;
   }
 }


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r344406 - [clang-format] Fix BraceWrapping AfterFunction for ObjC methods

2018-10-12 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Fri Oct 12 12:43:01 2018
New Revision: 344406

URL: http://llvm.org/viewvc/llvm-project?rev=344406=rev
Log:
[clang-format] Fix BraceWrapping AfterFunction for ObjC methods

Summary:
> clang-format --version
> clang-format version 7.0.0 (tags/RELEASE_700/final)
> echo "@implementation Foo\n- (void)foo:(id)bar\n{\n}\n@end\n" |clang-format 
> -style='{BreakBeforeBraces: Custom, BraceWrapping: {AfterFunction: true}}'
```
@implementation Foo
- (void)foo:(id)bar {
}
@end
```

with patch:

> bin/clang-format --version
> clang-format version 8.0.0 (trunk 344285)
> echo "@implementation Foo\n- (void)foo:(id)bar\n{\n}\n@end\n" 
> |bin/clang-format -style='{BreakBeforeBraces: Custom, BraceWrapping: 
> {AfterFunction: true}}'
```
@implementation Foo
- (void)foo:(id)bar
{
}
@end
```

Contributed by hultman@.

Reviewers: benhamilton, jolesiak, klimek, Wizard

Reviewed By: benhamilton

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D53197

Modified:
cfe/trunk/lib/Format/UnwrappedLineParser.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/UnwrappedLineParser.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineParser.cpp?rev=344406=344405=344406=diff
==
--- cfe/trunk/lib/Format/UnwrappedLineParser.cpp (original)
+++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp Fri Oct 12 12:43:01 2018
@@ -2164,6 +2164,8 @@ void UnwrappedLineParser::parseObjCMetho
   addUnwrappedLine();
   return;
 } else if (FormatTok->Tok.is(tok::l_brace)) {
+  if (Style.BraceWrapping.AfterFunction)
+addUnwrappedLine();
   parseBlock(/*MustBeDeclaration=*/false);
   addUnwrappedLine();
   return;

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=344406=344405=344406=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Fri Oct 12 12:43:01 2018
@@ -584,6 +584,16 @@ TEST_F(FormatTestObjC, FormatObjCMethodD
" a:(a)yyy\n"
"   bbb:(d);");
   verifyFormat("- (void)drawRectOn:(id)surface 
ofSize:(aaa)height:(bbb)width;");
+
+  // BraceWrapping AfterFunction is respected for ObjC methods 
+  Style = getGoogleStyle(FormatStyle::LK_ObjC);
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterFunction = true;
+  verifyFormat("@implementation Foo\n"
+   "- (void)foo:(id)bar\n"
+   "{\n"
+   "}\n"
+   "@end\n");
 }
 
 TEST_F(FormatTestObjC, FormatObjCMethodExpr) {


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r341721 - [clang-tidy/ObjC] Update list of acronyms in PropertyDeclarationCheck

2018-09-07 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Fri Sep  7 15:03:48 2018
New Revision: 341721

URL: http://llvm.org/viewvc/llvm-project?rev=341721=rev
Log:
[clang-tidy/ObjC] Update list of acronyms in PropertyDeclarationCheck

Summary: This adds a few common acronyms we found were missing from 
PropertyDeclarationCheck.

Reviewers: Wizard, hokein

Reviewed By: hokein

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D51819

Modified:
clang-tools-extra/trunk/docs/clang-tidy/checks/objc-property-declaration.rst

Modified: 
clang-tools-extra/trunk/docs/clang-tidy/checks/objc-property-declaration.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/objc-property-declaration.rst?rev=341721=341720=341721=diff
==
--- 
clang-tools-extra/trunk/docs/clang-tidy/checks/objc-property-declaration.rst 
(original)
+++ 
clang-tools-extra/trunk/docs/clang-tidy/checks/objc-property-declaration.rst 
Fri Sep  7 15:03:48 2018
@@ -63,7 +63,7 @@ Options
If set to ``1``, the value in ``Acronyms`` is appended to the
default list of acronyms:
 
-   
``ACL;API;ARGB;ASCII;BGRA;CMYK;DNS;FPS;FTP;GIF;GPS;HD;HDR;HTML;HTTP;HTTPS;HUD;ID;JPG;JS;LAN;LZW;MDNS;MIDI;OS;PDF;PIN;PNG;POI;PSTN;PTR;QA;QOS;RGB;RGBA;RGBX;ROM;RPC;RTF;RTL;SDK;SSO;TCP;TIFF;TTS;UI;URI;URL;VC;VOIP;VPN;VR;WAN;XML``.
+   
``[2-9]G;ACL;API;APN;APNS;AR;ARGB;ASCII;AV;BGRA;CA;CDN;CF;CG;CI;CRC;CV;CMYK;DNS;FPS;FTP;GIF;GL;GPS;GUID;HD;HDR;HMAC;HTML;HTTP;HTTPS;HUD;ID;JPG;JS;JSON;LAN;LZW;LTR;MAC;MD;MDNS;MIDI;NS;OS;P2P;PDF;PIN;PNG;POI;PSTN;PTR;QA;QOS;RGB;RGBA;RGBX;RIPEMD;ROM;RPC;RTF;RTL;SC;SDK;SHA;SQL;SSO;TCP;TIFF;TOS;TTS;UI;URI;URL;UUID;VC;VO;VOIP;VPN;VR;W;WAN;X;XML;Y;Z``.
 
If set to ``0``, the value in ``Acronyms`` replaces the default list
of acronyms.


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r341720 - [clang-tidy/ObjC] Update list of acronyms in PropertyDeclarationCheck

2018-09-07 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Fri Sep  7 15:02:38 2018
New Revision: 341720

URL: http://llvm.org/viewvc/llvm-project?rev=341720=rev
Log:
[clang-tidy/ObjC] Update list of acronyms in PropertyDeclarationCheck

Summary: This adds a few common acronyms we found were missing from 
PropertyDeclarationCheck.

Reviewers: Wizard, hokein

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D51819

Modified:
clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp

Modified: clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp?rev=341720=341719=341720=diff
==
--- clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp Fri 
Sep  7 15:02:38 2018
@@ -42,12 +42,15 @@ constexpr llvm::StringLiteral DefaultSpe
 "[2-9]G",
 "ACL",
 "API",
+"APN",
+"APNS",
 "AR",
 "ARGB",
 "ASCII",
 "AV",
 "BGRA",
 "CA",
+"CDN",
 "CF",
 "CG",
 "CI",
@@ -71,14 +74,17 @@ constexpr llvm::StringLiteral DefaultSpe
 "ID",
 "JPG",
 "JS",
+"JSON",
 "LAN",
 "LZW",
+"LTR",
 "MAC",
 "MD",
 "MDNS",
 "MIDI",
 "NS",
 "OS",
+"P2P",
 "PDF",
 "PIN",
 "PNG",
@@ -102,12 +108,14 @@ constexpr llvm::StringLiteral DefaultSpe
 "SSO",
 "TCP",
 "TIFF",
+"TOS",
 "TTS",
 "UI",
 "URI",
 "URL",
 "UUID",
 "VC",
+"VO",
 "VOIP",
 "VPN",
 "VR",


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r336919 - [clang-tidy/ObjC] Add SQL to list of acronyms

2018-07-12 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Thu Jul 12 10:32:55 2018
New Revision: 336919

URL: http://llvm.org/viewvc/llvm-project?rev=336919=rev
Log:
[clang-tidy/ObjC] Add SQL to list of acronyms

Summary: SQL is a common acronym.

Reviewers: Wizard, hokein

Reviewed By: Wizard, hokein

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D49190

Modified:
clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp

Modified: clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp?rev=336919=336918=336919=diff
==
--- clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp Thu 
Jul 12 10:32:55 2018
@@ -98,6 +98,7 @@ constexpr llvm::StringLiteral DefaultSpe
 "SC",
 "SDK",
 "SHA",
+"SQL",
 "SSO",
 "TCP",
 "TIFF",


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r335983 - [clang-format/ObjC] Fix NS_SWIFT_NAME(foo(bar:baz:)) after ObjC method decl

2018-06-29 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Fri Jun 29 08:26:37 2018
New Revision: 335983

URL: http://llvm.org/viewvc/llvm-project?rev=335983=rev
Log:
[clang-format/ObjC] Fix NS_SWIFT_NAME(foo(bar:baz:)) after ObjC method decl

Summary:
In D44638, I partially fixed `NS_SWIFT_NAME(foo(bar:baz:))`-style
annotations on C functions, but didn't add a test for Objective-C
method declarations.

For ObjC method declarations which are annotated with `NS_SWIFT_NAME(...)`,
we currently fail to annotate the final component of the selector
name as `TT_SelectorName`.

Because the token type is left unknown, clang-format will happily
cause a compilation error when it changes the following:

```
@interface Foo
- (void)doStuffWithFoo:(id)name
   bar:(id)bar
   baz:(id)baz
NS_SWIFT_NAME(doStuff(withFoo:bar:baz:));
@end
```

to:

```
@interface Foo
- (void)doStuffWithFoo:(id)name
   bar:(id)bar
   baz:(id)baz
NS_SWIFT_NAME(doStuff(withFoo:bar:baz
:));
@end
```

(note the linebreak before the final `:`).

The logic which decides whether or not to annotate the token before a
`:` with `TT_SelectorName` is pretty fragile, and has to handle some
pretty odd cases like pair-parameters:

```
[I drawRectOn:surface ofSize:aa:bbb atOrigin:cc:dd];
```

So, to minimize the effect of this change, I decided to only annotate
unknown identifiers before a `:` as `TT_SelectorName` for Objective-C
declaration lines.

Test Plan: New tests included. Confirmed tests failed before change and
  passed after change. Ran tests with:
  % make -j16 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: djasper, krasimir, jolesiak

Reviewed By: krasimir

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D48679

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=335983=335982=335983=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Fri Jun 29 08:26:37 2018
@@ -698,13 +698,19 @@ private:
  Line.startsWith(TT_ObjCMethodSpecifier)) {
 Tok->Type = TT_ObjCMethodExpr;
 const FormatToken *BeforePrevious = Tok->Previous->Previous;
+// Ensure we tag all identifiers in method declarations as
+// TT_SelectorName.
+bool UnknownIdentifierInMethodDeclaration =
+Line.startsWith(TT_ObjCMethodSpecifier) &&
+Tok->Previous->is(tok::identifier) && 
Tok->Previous->is(TT_Unknown);
 if (!BeforePrevious ||
 // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
 !(BeforePrevious->is(TT_CastRParen) ||
   (BeforePrevious->is(TT_ObjCMethodExpr) &&
BeforePrevious->is(tok::colon))) ||
 BeforePrevious->is(tok::r_square) ||
-Contexts.back().LongestObjCSelectorName == 0) {
+Contexts.back().LongestObjCSelectorName == 0 ||
+UnknownIdentifierInMethodDeclaration) {
   Tok->Previous->Type = TT_SelectorName;
   if (!Contexts.back().FirstObjCSelectorName)
 Contexts.back().FirstObjCSelectorName = Tok->Previous;

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=335983=335982=335983=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Fri Jun 29 08:26:37 2018
@@ -923,6 +923,14 @@ TEST_F(FormatTestObjC, ObjCSnippets) {
   verifyFormat("@property(assign, nonatomic) CGFloat hoverAlpha;");
   verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
 
+  Style.ColumnLimit = 50;
+  verifyFormat("@interface Foo\n"
+   "- (void)doStuffWithFoo:(id)name\n"
+   "   bar:(id)bar\n"
+   "   baz:(id)baz\n"
+   "NS_SWIFT_NAME(doStuff(withFoo:bar:baz:));\n"
+   "@end");
+
   Style = getMozillaStyle();
   verifyFormat("@property (assign, getter=isEditable) BOOL editable;");
   verifyFormat("@property BOOL editable;");


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r335770 - [clang-tidy/ObjC] Add hashing algorithm acronyms to objc-property-declaration

2018-06-27 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Wed Jun 27 12:13:09 2018
New Revision: 335770

URL: http://llvm.org/viewvc/llvm-project?rev=335770=rev
Log:
[clang-tidy/ObjC] Add hashing algorithm acronyms to objc-property-declaration

Summary:
This PR adds a few acronyms related to hashing algorithms to the standard
list in `objc-property-declaration`.

Reviewers: Wizard

Reviewed By: Wizard

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D48652

Modified:
clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp

Modified: clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp?rev=335770=335769=335770=diff
==
--- clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp Wed 
Jun 27 12:13:09 2018
@@ -51,6 +51,7 @@ constexpr llvm::StringLiteral DefaultSpe
 "CF",
 "CG",
 "CI",
+"CRC",
 "CV",
 "CMYK",
 "DNS",
@@ -62,6 +63,7 @@ constexpr llvm::StringLiteral DefaultSpe
 "GUID",
 "HD",
 "HDR",
+"HMAC",
 "HTML",
 "HTTP",
 "HTTPS",
@@ -71,6 +73,8 @@ constexpr llvm::StringLiteral DefaultSpe
 "JS",
 "LAN",
 "LZW",
+"MAC",
+"MD",
 "MDNS",
 "MIDI",
 "NS",
@@ -86,12 +90,14 @@ constexpr llvm::StringLiteral DefaultSpe
 "RGB",
 "RGBA",
 "RGBX",
+"RIPEMD",
 "ROM",
 "RPC",
 "RTF",
 "RTL",
 "SC",
 "SDK",
+"SHA",
 "SSO",
 "TCP",
 "TIFF",


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r333553 - [clang-format/ObjC] Correctly parse Objective-C methods with 'class' in name

2018-05-30 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Wed May 30 08:21:38 2018
New Revision: 333553

URL: http://llvm.org/viewvc/llvm-project?rev=333553=rev
Log:
[clang-format/ObjC] Correctly parse Objective-C methods with 'class' in name

Summary:
Please take a close look at this CL. I haven't touched much of
`UnwrappedLineParser` before, so I may have gotten things wrong.

Previously, clang-format would incorrectly format the following:

```
@implementation Foo

- (Class)class {
}

- (void)foo {
}

@end
```

as:

```
@implementation Foo

- (Class)class {
}

- (void)foo {
}

@end
```

The problem is whenever `UnwrappedLineParser::parseStructuralElement()`
sees any of the keywords `class`, `struct`, or `enum`, it calls
`parseRecord()` to parse them as a C/C++ record.

This causes subsequent lines to be parsed incorrectly, which
causes them to be indented incorrectly.

In Objective-C/Objective-C++, these keywords are valid selector
components.

This diff fixes the issue by explicitly handling `+` and `-` lines
inside `@implementation` / `@interface` / `@protocol` blocks
and parsing them as Objective-C methods.

Test Plan: New tests added. Ran tests with:
  make -j16 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: jolesiak, klimek

Reviewed By: jolesiak, klimek

Subscribers: klimek, cfe-commits, Wizard

Differential Revision: https://reviews.llvm.org/D47095

Modified:
cfe/trunk/lib/Format/UnwrappedLineParser.cpp
cfe/trunk/lib/Format/UnwrappedLineParser.h
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/UnwrappedLineParser.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineParser.cpp?rev=333553=333552=333553=diff
==
--- cfe/trunk/lib/Format/UnwrappedLineParser.cpp (original)
+++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp Wed May 30 08:21:38 2018
@@ -2130,6 +2130,24 @@ void UnwrappedLineParser::parseRecord(bo
   // "} n, m;" will end up in one unwrapped line.
 }
 
+void UnwrappedLineParser::parseObjCMethod() {
+  assert(FormatTok->Tok.isOneOf(tok::l_paren, tok::identifier) &&
+ "'(' or identifier expected.");
+  do {
+if (FormatTok->Tok.is(tok::semi)) {
+  nextToken();
+  addUnwrappedLine();
+  return;
+} else if (FormatTok->Tok.is(tok::l_brace)) {
+  parseBlock(/*MustBeDeclaration=*/false);
+  addUnwrappedLine();
+  return;
+} else {
+  nextToken();
+}
+  } while (!eof());
+}
+
 void UnwrappedLineParser::parseObjCProtocolList() {
   assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
   do {
@@ -2157,6 +2175,9 @@ void UnwrappedLineParser::parseObjCUntil
   // Ignore stray "}". parseStructuralElement doesn't consume them.
   nextToken();
   addUnwrappedLine();
+} else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
+  nextToken();
+  parseObjCMethod();
 } else {
   parseStructuralElement();
 }

Modified: cfe/trunk/lib/Format/UnwrappedLineParser.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineParser.h?rev=333553=333552=333553=diff
==
--- cfe/trunk/lib/Format/UnwrappedLineParser.h (original)
+++ cfe/trunk/lib/Format/UnwrappedLineParser.h Wed May 30 08:21:38 2018
@@ -120,6 +120,7 @@ private:
   // parses the record as a child block, i.e. if the class declaration is an
   // expression.
   void parseRecord(bool ParseAsExpr = false);
+  void parseObjCMethod();
   void parseObjCProtocolList();
   void parseObjCUntilAtEnd();
   void parseObjCInterfaceOrImplementation();

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=333553=333552=333553=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Wed May 30 08:21:38 2018
@@ -328,7 +328,14 @@ TEST_F(FormatTestObjC, FormatObjCInterfa
"}\n"
"+ (id)init;\n"
"@end");
-
+  verifyFormat("@interface Foo\n"
+   "- (void)foo {\n"
+   "}\n"
+   "@end\n"
+   "@implementation Bar\n"
+   "- (void)bar {\n"
+   "}\n"
+   "@end");
   Style.ColumnLimit = 40;
   verifyFormat("@interface c () <\n"
"c, c,\n"
@@ -969,6 +976,59 @@ TEST_F(FormatTestObjC, ObjCCxxKeywords)
   verifyFormat("MACRO(new:)\n");
   verifyFormat("MACRO(delete:)\n");
   verifyFormat("foo = @{MACRO(new:) : MACRO(delete:)}\n");
+  verifyFormat("@implementation Foo\n"
+   "// Testing\n"
+   "- (Class)class {\n"
+   "}\n"
+   "- (void)foo {\n"
+   "}\n"
+   "@end\n");
+  

r332727 - [clang-format/ObjC] Correctly annotate single-component ObjC method invocations

2018-05-18 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Fri May 18 08:27:02 2018
New Revision: 332727

URL: http://llvm.org/viewvc/llvm-project?rev=332727=rev
Log:
[clang-format/ObjC] Correctly annotate single-component ObjC method invocations

Summary:
Previously, clang-format's parser would fail to annotate the
selector in a single-component Objective-C method invocation with
`TT_SelectorName`. For example, the following:

  [foo bar];

would parse `bar` as `TT_Unknown`:

  M=0 C=1 T=Unknown S=0 B=0 BK=0 P=140 Name=identifier L=34 PPK=2
  FakeLParens= FakeRParens=0 II=0x559d5db51770 Text='bar'

This caused us to fail to insert a space after a closing cast rparen,
so the following:

  [((Foo *)foo) bar];

would format as:

  [((Foo *)foo)bar];

This diff fixes the issue by ensuring we annotate the selector
in a single-component Objective-C method invocation as
`TT_SelectorName`.

Test Plan: New tests added. Ran tests with:
  % make -j16 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: djasper, jolesiak

Reviewed By: jolesiak

Subscribers: Wizard, klimek, hokein, cfe-commits

Differential Revision: https://reviews.llvm.org/D47028

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=332727=332726=332727=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Fri May 18 08:27:02 2018
@@ -501,6 +501,12 @@ private:
 }
 if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
   CurrentToken->Type = TT_ObjCMethodExpr;
+  // If we haven't seen a colon yet, make sure the last identifier
+  // before the r_square is tagged as a selector name component.
+  if (!ColonFound && CurrentToken->Previous &&
+  CurrentToken->Previous->is(TT_Unknown) &&
+  canBeObjCSelectorComponent(*CurrentToken->Previous))
+CurrentToken->Previous->Type = TT_SelectorName;
   // determineStarAmpUsage() thinks that '*' '[' is allocating an
   // array of pointers, but if '[' starts a selector then '*' is a
   // binary operator.

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=332727=332726=332727=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Fri May 18 08:27:02 2018
@@ -792,6 +792,10 @@ TEST_F(FormatTestObjC, FormatObjCMethodE
"  a = 42;\n"
"}];");
 
+  // Space between cast rparen and selector name component.
+  verifyFormat("[((Foo *)foo) bar];");
+  verifyFormat("[((Foo *)foo) bar:1 blech:2];");
+
   // Message receiver taking multiple lines.
   Style.ColumnLimit = 20;
   // Non-corner case.


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r332516 - [clang-tidy/google-readability-casting] Disable check for Objective-C++

2018-05-16 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Wed May 16 13:07:19 2018
New Revision: 332516

URL: http://llvm.org/viewvc/llvm-project?rev=332516=rev
Log:
[clang-tidy/google-readability-casting] Disable check for Objective-C++

Summary:
Previously, `google-readability-casting` was disabled for Objective-C.

The Google Objective-C++ style allows both Objective-C and
C++ style in the same file. Since clang-tidy doesn't have a good
way to allow multiple styles per file, this disables the
check for Objective-C++.

Test Plan: New tests added. Ran tests with:
  % make -j16 check-clang-tools
  Before diff, confirmed tests failed:
  https://reviews.llvm.org/P8081
  After diff, confirrmed tests passed.

Reviewers: alexfh, Wizard, hokein, stephanemoore

Reviewed By: alexfh, Wizard, stephanemoore

Subscribers: stephanemoore, cfe-commits, bkramer, klimek

Differential Revision: https://reviews.llvm.org/D46659

Added:
clang-tools-extra/trunk/test/clang-tidy/google-readability-casting.mm
Modified:
clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp

Modified: clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp?rev=332516=332515=332516=diff
==
--- clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/google/AvoidCStyleCastsCheck.cpp Wed May 
16 13:07:19 2018
@@ -100,7 +100,8 @@ void AvoidCStyleCastsCheck::check(const
   }
 
   // The rest of this check is only relevant to C++.
-  if (!getLangOpts().CPlusPlus)
+  // We also disable it for Objective-C++.
+  if (!getLangOpts().CPlusPlus || getLangOpts().ObjC1 || getLangOpts().ObjC2)
 return;
   // Ignore code inside extern "C" {} blocks.
   if (!match(expr(hasAncestor(linkageSpecDecl())), *CastExpr, *Result.Context)

Added: clang-tools-extra/trunk/test/clang-tidy/google-readability-casting.mm
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/google-readability-casting.mm?rev=332516=auto
==
--- clang-tools-extra/trunk/test/clang-tidy/google-readability-casting.mm 
(added)
+++ clang-tools-extra/trunk/test/clang-tidy/google-readability-casting.mm Wed 
May 16 13:07:19 2018
@@ -0,0 +1,179 @@
+// RUN: clang-tidy %s -checks=-*,google-readability-casting -- \
+// RUN:   -xobjective-c++ -fobjc-abi-version=2 -fobjc-arc | count 0
+
+// Note: this test expects no diagnostics, but FileCheck cannot handle that,
+// hence the use of | count 0.
+
+bool g() { return false; }
+
+enum Enum { Enum1 };
+struct X {};
+struct Y : public X {};
+
+void f(int a, double b, const char *cpc, const void *cpv, X *pX) {
+
+  typedef const char *Typedef1;
+  typedef const char *Typedef2;
+  Typedef1 t1;
+  (Typedef2)t1;
+  (const char*)t1;
+  (Typedef1)cpc;
+
+  typedef char Char;
+  char *pc;
+  Char *pChar = (Char*)pc;
+
+  (Char)*cpc;
+
+  (char)*pChar;
+
+  (const char*)cpv;
+
+  char *pc2 = (char*)(cpc + 33);
+
+  const char  = *cpc;
+  char  = (char&)crc;
+
+  char  = (char&)*cpc;
+
+  char ** const* const* ppcpcpc;
+  char c = (char)ppcpcpc;
+
+  char ***pppc = (char***)*(ppcpcpc);
+
+  char ***pppc2 = (char***)(*ppcpcpc);
+
+  char *pc5 = (char*)(const char*)(cpv);
+
+  int b1 = (int)b;
+  b1 = (const int&)b;
+
+  b1 = (int) b;
+
+  b1 = (int) b;
+
+  b1 = (int) (b);
+
+  b1 = (int) (b);
+
+  Y *pB = (Y*)pX;
+  Y  = (Y&)*pX;
+
+  const char *pc3 = (const char*)cpv;
+
+  char *pc4 = (char*)cpv;
+
+  b1 = (int)Enum1;
+
+  Enum e = (Enum)b1;
+
+  int b2 = int(b);
+  int b3 = static_cast(b);
+  int b4 = b;
+  double aa = a;
+  (void)b2;
+  return (void)g();
+}
+
+template 
+void template_function(T t, int n) {
+  int i = (int)t;
+}
+
+template 
+struct TemplateStruct {
+  void f(T t, int n) {
+int k = (int)t;
+  }
+};
+
+void test_templates() {
+  template_function(1, 42);
+  template_function(1.0, 42);
+  TemplateStruct().f(1, 42);
+  TemplateStruct().f(1.0, 42);
+}
+
+extern "C" {
+void extern_c_code(const char *cpc) {
+  char *pc = (char*)cpc;
+}
+}
+
+#define CAST(type, value) (type)(value)
+void macros(double d) {
+  int i = CAST(int, d);
+}
+
+enum E { E1 = 1 };
+template 
+struct A {
+  // Usage of template argument e = E1 is represented as (E)1 in the AST for
+  // some reason. We have a special treatment of this case to avoid warnings
+  // here.
+  static const E ee = e;
+};
+struct B : public A {};
+
+
+void overloaded_function();
+void overloaded_function(int);
+
+template
+void g(Fn fn) {
+  fn();
+}
+
+void function_casts() {
+  typedef void (*FnPtrVoid)();
+  typedef void ()();
+  typedef void ()(int);
+
+  g((void (*)())overloaded_function);
+  g((void (*)())_function);
+  g((void (&)())overloaded_function);
+
+  g((FnPtrVoid)overloaded_function);
+  g((FnPtrVoid)_function);
+  

[clang-tools-extra] r331267 - [clang-tidy] Add Apple prefix acronyms to objc-property-declaration

2018-05-01 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Tue May  1 07:48:51 2018
New Revision: 331267

URL: http://llvm.org/viewvc/llvm-project?rev=331267=rev
Log:
[clang-tidy] Add Apple prefix acronyms to objc-property-declaration

Summary:
This adds a few common Apple first-party API prefixes as acronyms to
`objc-property-declaration`.

Here's a list showing where these come from:

http://nshipster.com/namespacing/

Test Plan: New tests added. Ran tests with:
  % make -j16 check-clang-tools

Reviewers: Wizard, hokein

Subscribers: klimek, xazax.hun, cfe-commits

Differential Revision: https://reviews.llvm.org/D46206

Modified:
clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp
clang-tools-extra/trunk/test/clang-tidy/objc-property-declaration.m

Modified: clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp?rev=331267=331266=331267=diff
==
--- clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp Tue 
May  1 07:48:51 2018
@@ -45,11 +45,17 @@ constexpr llvm::StringLiteral DefaultSpe
 "ARGB",
 "ASCII",
 "BGRA",
+"CA",
+"CF",
+"CG",
+"CI",
+"CV",
 "CMYK",
 "DNS",
 "FPS",
 "FTP",
 "GIF",
+"GL",
 "GPS",
 "GUID",
 "HD",
@@ -65,6 +71,7 @@ constexpr llvm::StringLiteral DefaultSpe
 "LZW",
 "MDNS",
 "MIDI",
+"NS",
 "OS",
 "PDF",
 "PIN",
@@ -81,6 +88,7 @@ constexpr llvm::StringLiteral DefaultSpe
 "RPC",
 "RTF",
 "RTL",
+"SC",
 "SDK",
 "SSO",
 "TCP",

Modified: clang-tools-extra/trunk/test/clang-tidy/objc-property-declaration.m
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/objc-property-declaration.m?rev=331267=331266=331267=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/objc-property-declaration.m 
(original)
+++ clang-tools-extra/trunk/test/clang-tidy/objc-property-declaration.m Tue May 
 1 07:48:51 2018
@@ -19,6 +19,8 @@
 @property(strong, nonatomic) NSString *VCsPluralToAdd;
 @property(assign, nonatomic) int centerX;
 @property(assign, nonatomic) int enable2GBackgroundFetch;
+@property(assign, nonatomic) int shouldUseCFPreferences;
+@property(assign, nonatomic) int enableGLAcceleration;
 @end
 
 @interface Foo (Bar)


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r331268 - [clang-tidy/google-runtime-int] Allow passing non-bitwidth types to printf()-style APIs

2018-05-01 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Tue May  1 07:48:54 2018
New Revision: 331268

URL: http://llvm.org/viewvc/llvm-project?rev=331268=rev
Log:
[clang-tidy/google-runtime-int] Allow passing non-bitwidth types to 
printf()-style APIs

Summary:
The `google-runtime-int` check currently fires on calls like:

  printf("%lu", (unsigned long)foo);

However, the style guide says:

> Where possible, avoid passing arguments of types specified by
> bitwidth typedefs to printf-based APIs.

http://google.github.io/styleguide/cppguide.html#64-bit_Portability

This diff relaxes the check to not fire on parameters to functions
with the `__format__` attribute. (I didn't specifically check
for `__printf__` since there are a few variations.)

Test Plan: New tests added. Ran tests with:
  % make -j16 check-clang-tools

Reviewers: alexfh, bkramer

Reviewed By: alexfh

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D46293

Modified:
clang-tools-extra/trunk/clang-tidy/google/IntegerTypesCheck.cpp
clang-tools-extra/trunk/test/clang-tidy/google-runtime-int.cpp

Modified: clang-tools-extra/trunk/clang-tidy/google/IntegerTypesCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/google/IntegerTypesCheck.cpp?rev=331268=331267=331268=diff
==
--- clang-tools-extra/trunk/clang-tidy/google/IntegerTypesCheck.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/google/IntegerTypesCheck.cpp Tue May  1 
07:48:54 2018
@@ -11,6 +11,7 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Basic/AttrKinds.h"
 #include "clang/Basic/CharInfo.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/TargetInfo.h"
@@ -56,7 +57,16 @@ void IntegerTypesCheck::registerMatchers
   // Find all TypeLocs. The relevant Style Guide rule only applies to C++.
   if (!getLangOpts().CPlusPlus)
 return;
-  Finder->addMatcher(typeLoc(loc(isInteger())).bind("tl"), this);
+  // Match any integer types, unless they are passed to a printf-based API:
+  //
+  // http://google.github.io/styleguide/cppguide.html#64-bit_Portability
+  // "Where possible, avoid passing arguments of types specified by
+  // bitwidth typedefs to printf-based APIs."
+  Finder->addMatcher(typeLoc(loc(isInteger()),
+ unless(hasAncestor(callExpr(
+ 
callee(functionDecl(hasAttr(attr::Format)))
+ .bind("tl"),
+ this);
   IdentTable = llvm::make_unique(getLangOpts());
 }
 

Modified: clang-tools-extra/trunk/test/clang-tidy/google-runtime-int.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/google-runtime-int.cpp?rev=331268=331267=331268=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/google-runtime-int.cpp (original)
+++ clang-tools-extra/trunk/test/clang-tidy/google-runtime-int.cpp Tue May  1 
07:48:54 2018
@@ -72,3 +72,20 @@ void fff() {
   B a, b;
   a = b;
 }
+
+__attribute__((__format__ (__printf__, 1, 2)))
+void myprintf(const char* s, ...);
+
+void doprint_no_warning() {
+  uint64 foo = 23;
+  myprintf("foo %lu %lu", (unsigned long)42, (unsigned long)foo);
+}
+
+void myprintf_no_attribute(const char* s, ...);
+
+void doprint_warning() {
+  uint64 foo = 23;
+  myprintf_no_attribute("foo %lu %lu", (unsigned long)42, (unsigned long)foo);
+// CHECK-MESSAGES: [[@LINE-1]]:41: warning: consider replacing 'unsigned long'
+// CHECK-MESSAGES: [[@LINE-2]]:60: warning: consider replacing 'unsigned long'
+}


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r331067 - [clang-format/ObjC] Use getIdentifierInfo() instead of tok::identifier

2018-04-27 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Fri Apr 27 11:51:12 2018
New Revision: 331067

URL: http://llvm.org/viewvc/llvm-project?rev=331067=rev
Log:
[clang-format/ObjC] Use getIdentifierInfo() instead of tok::identifier

Summary:
Previously, we checked tokens for `tok::identifier` to see if they
were identifiers inside an Objective-C selector.

However, this missed C++ keywords like `new` and `delete`.

To fix this, this diff uses `getIdentifierInfo()` to find
identifiers or keywords inside Objective-C selectors.

Test Plan: New tests added. Ran tests with:
  % make -j16 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: djasper, jolesiak

Reviewed By: djasper

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D46143

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=331067=331066=331067=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Fri Apr 27 11:51:12 2018
@@ -25,6 +25,21 @@ namespace format {
 
 namespace {
 
+/// \brief Returns \c true if the token can be used as an identifier in
+/// an Objective-C \c @selector, \c false otherwise.
+///
+/// Because getFormattingLangOpts() always lexes source code as
+/// Objective-C++, C++ keywords like \c new and \c delete are
+/// lexed as tok::kw_*, not tok::identifier, even for Objective-C.
+///
+/// For Objective-C and Objective-C++, both identifiers and keywords
+/// are valid inside @selector(...) (or a macro which
+/// invokes @selector(...)). So, we allow treat any identifier or
+/// keyword as a potential Objective-C selector component.
+static bool canBeObjCSelectorComponent(const FormatToken ) {
+  return Tok.Tok.getIdentifierInfo() != nullptr;
+}
+
 /// \brief A parser that gathers additional information about tokens.
 ///
 /// The \c TokenAnnotator tries to match parenthesis and square brakets and
@@ -703,9 +718,10 @@ private:
   Tok->Type = TT_CtorInitializerColon;
 else
   Tok->Type = TT_InheritanceColon;
-  } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
+  } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next &&
  (Tok->Next->isOneOf(tok::r_paren, tok::comma) ||
-  Tok->Next->startsSequence(tok::identifier, tok::colon))) {
+  (canBeObjCSelectorComponent(*Tok->Next) && Tok->Next->Next &&
+   Tok->Next->Next->is(tok::colon {
 // This handles a special macro in ObjC code where selectors including
 // the colon are passed as macro arguments.
 Tok->Type = TT_ObjCMethodExpr;
@@ -1346,7 +1362,7 @@ private:
  TT_LeadingJavaAnnotation)) {
 Current.Type = Current.Previous->Type;
   }
-} else if (Current.isOneOf(tok::identifier, tok::kw_new) &&
+} else if (canBeObjCSelectorComponent(Current) &&
// FIXME(bug 36976): ObjC return types shouldn't use 
TT_CastRParen.
Current.Previous && Current.Previous->is(TT_CastRParen) &&
Current.Previous->MatchingParen &&
@@ -2650,7 +2666,7 @@ bool TokenAnnotator::spaceRequiredBefore
   if (Line.Type == LT_ObjCMethodDecl) {
 if (Left.is(TT_ObjCMethodSpecifier))
   return true;
-if (Left.is(tok::r_paren) && Right.isOneOf(tok::identifier, tok::kw_new))
+if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right))
   // Don't space between ')' and  or ')' and 'new'. 'new' is not a
   // keyword in Objective-C, and '+ (instancetype)new;' is a standard class
   // method declaration.
@@ -3128,6 +3144,7 @@ void TokenAnnotator::printDebugInfo(cons
 for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
   llvm::errs() << Tok->FakeLParens[i] << "/";
 llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
+llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
 llvm::errs() << " Text='" << Tok->TokenText << "'\n";
 if (!Tok->Next)
   assert(Tok == Line.Last);

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=331067=331066=331067=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Fri Apr 27 11:51:12 2018
@@ -945,7 +945,7 @@ TEST_F(FormatTestObjC, ObjCForIn) {
" }]) {\n}");
 }
 
-TEST_F(FormatTestObjC, ObjCNew) {
+TEST_F(FormatTestObjC, ObjCCxxKeywords) {
   verifyFormat("+ (instancetype)new {\n"
"  return nil;\n"
"}\n");
@@ -954,6 +954,17 @@ TEST_F(FormatTestObjC, ObjCNew) 

r329921 - [Test Fix] Fix broken test Index/comment-objc-parameterized-classes.m

2018-04-12 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Thu Apr 12 09:00:05 2018
New Revision: 329921

URL: http://llvm.org/viewvc/llvm-project?rev=329921=rev
Log:
[Test Fix] Fix broken test Index/comment-objc-parameterized-classes.m

I broke this test in D45498 when I changed the formatter to remove
spaces before Objective-C lightweight generics.

This fixes the test.

Test Plan:
  % make -j16 check-llvm-tools-llvm-lit && ./bin/llvm-lit -sv 
../llvm/tools/clang/test/Index/comment-objc-parameterized-classes.m

Modified:
cfe/trunk/test/Index/comment-objc-parameterized-classes.m

Modified: cfe/trunk/test/Index/comment-objc-parameterized-classes.m
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Index/comment-objc-parameterized-classes.m?rev=329921=329920=329921=diff
==
--- cfe/trunk/test/Index/comment-objc-parameterized-classes.m (original)
+++ cfe/trunk/test/Index/comment-objc-parameterized-classes.m Thu Apr 12 
09:00:05 2018
@@ -13,7 +13,7 @@
 @interface NSObject
 @end
 
-// CHECK: @interface A __covariant T : id, U : NSObject * 
: NSObject
+// CHECK: @interface A__covariant T : id, U : NSObject * 
: NSObject
 /// A
 @interface A<__covariant T : id, U : NSObject *> : NSObject
 @end


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r329918 - [clang-format] Improve ObjC guessing heuristic by supporting all @keywords

2018-04-12 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Thu Apr 12 08:11:53 2018
New Revision: 329918

URL: http://llvm.org/viewvc/llvm-project?rev=329918=rev
Log:
[clang-format] Improve ObjC guessing heuristic by supporting all @keywords

Summary:
This diff improves the Objective-C guessing heuristic by
replacing the hard-coded list of a subset of Objective-C @keywords
with a general check which supports all @keywords.

I also added a few more Foundation keywords which were missing from
the heuristic.

Test Plan: Unit tests updated. Ran tests with:
  % make -j16 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: djasper, jolesiak

Reviewed By: djasper

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D45521

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=329918=329917=329918=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Thu Apr 12 08:11:53 2018
@@ -1465,6 +1465,7 @@ private:
 "NSAffineTransform",
 "NSArray",
 "NSAttributedString",
+"NSBlockOperation",
 "NSBundle",
 "NSCache",
 "NSCalendar",
@@ -1480,6 +1481,7 @@ private:
 "NSIndexPath",
 "NSIndexSet",
 "NSInteger",
+"NSInvocationOperation",
 "NSLocale",
 "NSMapTable",
 "NSMutableArray",
@@ -1494,9 +1496,13 @@ private:
 "NSNumber",
 "NSNumberFormatter",
 "NSObject",
+"NSOperation",
+"NSOperationQueue",
+"NSOperationQueuePriority",
 "NSOrderedSet",
 "NSPoint",
 "NSPointerArray",
+"NSQualityOfService",
 "NSRange",
 "NSRect",
 "NSRegularExpression",
@@ -1518,10 +1524,7 @@ private:
   for (const FormatToken *FormatTok = Line->First; FormatTok;
FormatTok = FormatTok->Next) {
 if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
- (FormatTok->isObjCAtKeyword(tok::objc_interface) ||
-  FormatTok->isObjCAtKeyword(tok::objc_implementation) ||
-  FormatTok->isObjCAtKeyword(tok::objc_protocol) ||
-  FormatTok->isObjCAtKeyword(tok::objc_end) ||
+ (FormatTok->Tok.getObjCKeywordID() != tok::objc_not_keyword ||
   FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
  tok::l_brace))) ||
 (FormatTok->Tok.isAnyIdentifier() &&

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=329918=329917=329918=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Thu Apr 12 08:11:53 2018
@@ -12118,6 +12118,12 @@ TEST_F(FormatTest, FileAndCode) {
   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@interface 
Foo\n@end\n"));
+  EXPECT_EQ(
+  FormatStyle::LK_ObjC,
+  guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
+  EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo", "@interface 
Foo\n@end\n"));
   EXPECT_EQ(FormatStyle::LK_ObjC,


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r329919 - [clang-format] Do not break after ObjC category open paren

2018-04-12 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Thu Apr 12 08:11:55 2018
New Revision: 329919

URL: http://llvm.org/viewvc/llvm-project?rev=329919=rev
Log:
[clang-format] Do not break after ObjC category open paren

Summary:
Previously, `clang-format` would break Objective-C
category extensions after the opening parenthesis to avoid
breaking the protocol list:

```
% echo "@interface c (ccc)  { }" | \
  clang-format -assume-filename=foo.h -style="{BasedOnStyle: llvm, \
  ColumnLimit: 40}"
@interface c (
ccc)  {
}
```

This looks fairly odd, as we could have kept the category extension
on the previous line.

Category extensions are a single item, so they are generally very
short compared to protocol lists. We should prefer breaking after the
opening `<` of the protocol list over breaking after the opening `(`
of the category extension.

With this diff, we now avoid breaking after the category extension's
open paren, which causes us to break after the protocol list's
open angle bracket:

```
% echo "@interface c (ccc)  { }" | \
  ./bin/clang-format -assume-filename=foo.h -style="{BasedOnStyle: llvm, \
  ColumnLimit: 40}"
@interface c (ccc) <
c> {
}
```

Test Plan: New test added. Confirmed test failed before diff and
  passed after diff by running:
  % make -j16 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: djasper, jolesiak

Reviewed By: djasper

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D45526

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=329919=329918=329919=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Thu Apr 12 08:11:55 2018
@@ -2272,6 +2272,13 @@ unsigned TokenAnnotator::splitPenalty(co
   if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
 return Line.MightBeFunctionDecl ? 50 : 500;
 
+  // In Objective-C type declarations, avoid breaking after the category's
+  // open paren (we'll prefer breaking after the protocol list's opening
+  // angle bracket, if present).
+  if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous &&
+  Left.Previous->isOneOf(tok::identifier, tok::greater))
+return 500;
+
   if (Left.is(tok::l_paren) && InFunctionDecl &&
   Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign)
 return 100;

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=329919=329918=329919=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Thu Apr 12 08:11:55 2018
@@ -334,6 +334,9 @@ TEST_F(FormatTestObjC, FormatObjCInterfa
"c, c,\n"
"c, c> {\n"
"}");
+  verifyFormat("@interface c (ccc) <\n"
+   "c> {\n"
+   "}");
   Style.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
   verifyFormat("@interface d () <\n"
"d,\n"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r329917 - [clang-format] Don't insert space between ObjC class and lightweight generic

2018-04-12 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Thu Apr 12 08:11:51 2018
New Revision: 329917

URL: http://llvm.org/viewvc/llvm-project?rev=329917=rev
Log:
[clang-format] Don't insert space between ObjC class and lightweight generic

Summary:
In D45185, I added clang-format parser support for Objective-C
generics. However, I didn't touch the whitespace logic, so they
got the same space logic as Objective-C protocol lists.

In every example in the Apple SDK and in the documentation,
there is no space between the class name and the opening `<`
for the lightweight generic specification, so this diff
removes the space and updates the tests.

Test Plan: Tests updated. Ran tests with:
  % make -j16 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: djasper, jolesiak

Reviewed By: djasper

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D45498

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=329917=329916=329917=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Thu Apr 12 08:11:51 2018
@@ -2349,9 +2349,12 @@ bool TokenAnnotator::spaceRequiredBetwee
: Style.SpacesInParentheses;
   if (Right.isOneOf(tok::semi, tok::comma))
 return false;
-  if (Right.is(tok::less) && Line.Type == LT_ObjCDecl &&
-  Style.ObjCSpaceBeforeProtocolList)
-return true;
+  if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) {
+bool IsLightweightGeneric =
+Right.MatchingParen && Right.MatchingParen->Next &&
+Right.MatchingParen->Next->is(tok::colon);
+return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
+  }
   if (Right.is(tok::less) && Left.is(tok::kw_template))
 return Style.SpaceAfterTemplateKeyword;
   if (Left.isOneOf(tok::exclaim, tok::tilde))

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=329917=329916=329917=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Thu Apr 12 08:11:51 2018
@@ -299,13 +299,13 @@ TEST_F(FormatTestObjC, FormatObjCInterfa
"+ (id)init;\n"
"@end");
 
-  verifyFormat("@interface Foo  : Bar  {\n"
+  verifyFormat("@interface Foo : Bar  {\n"
"  int _i;\n"
"}\n"
"+ (id)init;\n"
"@end");
 
-  verifyFormat("@interface Foo > : Xyzzy  {\n"
+  verifyFormat("@interface Foo> : Xyzzy  {\n"
"  int _i;\n"
"}\n"
"+ (id)init;\n"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r329916 - [clang-format] Always indent wrapped Objective-C selector names

2018-04-12 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Thu Apr 12 08:11:48 2018
New Revision: 329916

URL: http://llvm.org/viewvc/llvm-project?rev=329916=rev
Log:
[clang-format] Always indent wrapped Objective-C selector names

Summary:
Currently, indentation of Objective-C method names which are wrapped
onto the next line due to a long return type is controlled by the
style option `IndentWrappedFunctionNames`.

This diff changes the behavior so we always indent wrapped Objective-C
selector names.

NOTE: I partially reverted 
https://github.com/llvm-mirror/clang/commit/6159c0fbd1876c7f5f984b4830c664cc78f16e2e
 / rL242484, as it was causing wrapped selectors to be double-indented. Its 
tests in FormatTestObjC.cpp still pass.

Test Plan: Tests updated. Ran tests with:
  % make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: djasper, jolesiak, stephanemoore, thakis

Reviewed By: djasper

Subscribers: stephanemoore, klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D45004

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/unittests/Format/FormatTest.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=329916=329915=329916=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Thu Apr 12 08:11:48 2018
@@ -26,6 +26,13 @@
 namespace clang {
 namespace format {
 
+// Returns true if a TT_SelectorName should be indented when wrapped,
+// false otherwise.
+static bool shouldIndentWrappedSelectorName(const FormatStyle ,
+LineType LineType) {
+  return Style.IndentWrappedFunctionNames || LineType == LT_ObjCMethodDecl;
+}
+
 // Returns the length of everything up to the first possible line break after
 // the ), ], } or > matching \c Tok.
 static unsigned getLengthToMatchingParen(const FormatToken ) {
@@ -698,7 +705,7 @@ unsigned ContinuationIndenter::addTokenO
 State.Stack.back().AlignColons = false;
   } else {
 State.Stack.back().ColonPos =
-(Style.IndentWrappedFunctionNames
+(shouldIndentWrappedSelectorName(Style, State.Line->Type)
  ? std::max(State.Stack.back().Indent,
 State.FirstIndent + Style.ContinuationIndentWidth)
  : State.Stack.back().Indent) +
@@ -897,7 +904,7 @@ unsigned ContinuationIndenter::getNewLin
   if (NextNonComment->is(TT_SelectorName)) {
 if (!State.Stack.back().ObjCSelectorNameFound) {
   unsigned MinIndent = State.Stack.back().Indent;
-  if (Style.IndentWrappedFunctionNames)
+  if (shouldIndentWrappedSelectorName(Style, State.Line->Type))
 MinIndent = std::max(MinIndent,
  State.FirstIndent + 
Style.ContinuationIndentWidth);
   // If LongestObjCSelectorName is 0, we are indenting the first
@@ -1000,13 +1007,8 @@ unsigned ContinuationIndenter::moveState
   if (Current.isMemberAccess())
 State.Stack.back().StartOfFunctionCall =
 !Current.NextOperator ? 0 : State.Column;
-  if (Current.is(TT_SelectorName)) {
+  if (Current.is(TT_SelectorName))
 State.Stack.back().ObjCSelectorNameFound = true;
-if (Style.IndentWrappedFunctionNames) {
-  State.Stack.back().Indent =
-  State.FirstIndent + Style.ContinuationIndentWidth;
-}
-  }
   if (Current.is(TT_CtorInitializerColon) &&
   Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon) {
 // Indent 2 from the column, so:

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=329916=329915=329916=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Thu Apr 12 08:11:48 2018
@@ -7678,16 +7678,18 @@ TEST_F(FormatTest, FormatForObjectiveCMe
 
   // When the function name has to be wrapped.
   FormatStyle Style = getLLVMStyle();
+  // ObjC ignores IndentWrappedFunctionNames when wrapping methods
+  // and always indents instead.
   Style.IndentWrappedFunctionNames = false;
   verifyFormat("- (SomeLongType *)\n"
-   "veryLooongName:(NSString)aa\n"
-   "   anotherName:(NSString)bb {\n"
+   "veryLooongName:(NSString)aa\n"
+   "   anotherName:(NSString)bb {\n"
"}",
Style);
   Style.IndentWrappedFunctionNames = true;
   verifyFormat("- (SomeLongType *)\n"
-   "veryLooongName:(NSString)aa\n"
-   "   

Re: [PATCH] D45526: [clang-format] Prefer breaking after ObjC category close paren

2018-04-12 Thread Ben Hamilton via cfe-commits
True. I will reword the description to clarify.

On Thu, Apr 12, 2018, 07:58 Daniel Jasper via Phabricator <
revi...@reviews.llvm.org> wrote:

> djasper added a comment.
>
> I understand that, but the test example does not break after the closing
> paren. It breaks after the subsequent "<".
>
>
> Repository:
>   rC Clang
>
> https://reviews.llvm.org/D45526
>
>
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D45526: [clang-format] Prefer breaking after ObjC category close paren

2018-04-12 Thread Ben Hamilton via cfe-commits
Fair point. I'll update the diff description.

The net effect of the patch is to break after the closing paren; the way I
implemented that was to raise the penalty for breaking after the opening
paren.

On Thu, Apr 12, 2018, 06:37 Daniel Jasper via Phabricator <
revi...@reviews.llvm.org> wrote:

> djasper added a comment.
>
> Both patch and comment inside patch say "break after closing paren" and
> yet that's not what the test or example in the description actually do. Why
> is that?
>
>
> Repository:
>   rC Clang
>
> https://reviews.llvm.org/D45526
>
>
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r329298 - [clang-format] Support lightweight Objective-C generics

2018-04-05 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Thu Apr  5 08:26:25 2018
New Revision: 329298

URL: http://llvm.org/viewvc/llvm-project?rev=329298=rev
Log:
[clang-format] Support lightweight Objective-C generics

Summary:
Previously, `clang-format` didn't understand lightweight
Objective-C generics, which have the form:

```
@interface Foo  ...
```

The lightweight generic specifier list appears before the base
class, if present, but because it starts with < like the protocol
specifier list, `UnwrappedLineParser` was getting confused and
failed to parse interfaces with both generics and protocol lists:

```
@interface Foo  : NSObject 
```

Since the parsed line would be incomplete, the format result
would be very confused (e.g., https://bugs.llvm.org/show_bug.cgi?id=24381).

This fixes the issue by explicitly parsing the ObjC lightweight
generic conformance list, so the line is fully parsed.

Fixes: https://bugs.llvm.org/show_bug.cgi?id=24381

Test Plan: New tests added. Ran tests with:
  % make -j16 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: djasper, jolesiak

Reviewed By: djasper

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D45185

Modified:
cfe/trunk/lib/Format/UnwrappedLineParser.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/UnwrappedLineParser.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineParser.cpp?rev=329298=329297=329298=diff
==
--- cfe/trunk/lib/Format/UnwrappedLineParser.cpp (original)
+++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp Thu Apr  5 08:26:25 2018
@@ -2122,9 +2122,13 @@ void UnwrappedLineParser::parseRecord(bo
 
 void UnwrappedLineParser::parseObjCProtocolList() {
   assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
-  do
+  do {
 nextToken();
-  while (!eof() && FormatTok->Tok.isNot(tok::greater));
+// Early exit in case someone forgot a close angle.
+if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
+FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
+  return;
+  } while (!eof() && FormatTok->Tok.isNot(tok::greater));
   nextToken(); // Skip '>'.
 }
 
@@ -2155,7 +2159,32 @@ void UnwrappedLineParser::parseObjCInter
   nextToken();
   nextToken(); // interface name
 
-  // @interface can be followed by either a base class, or a category.
+  // @interface can be followed by a lightweight generic
+  // specialization list, then either a base class or a category.
+  if (FormatTok->Tok.is(tok::less)) {
+// Unlike protocol lists, generic parameterizations support
+// nested angles:
+//
+// @interface Foo> :
+// NSObject 
+//
+// so we need to count how many open angles we have left.
+unsigned NumOpenAngles = 1;
+do {
+  nextToken();
+  // Early exit in case someone forgot a close angle.
+  if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
+  FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
+break;
+  if (FormatTok->Tok.is(tok::less))
+++NumOpenAngles;
+  else if (FormatTok->Tok.is(tok::greater)) {
+assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative");
+--NumOpenAngles;
+  }
+} while (!eof() && NumOpenAngles != 0);
+nextToken(); // Skip '>'.
+  }
   if (FormatTok->Tok.is(tok::colon)) {
 nextToken();
 nextToken(); // base class name

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=329298=329297=329298=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Thu Apr  5 08:26:25 2018
@@ -299,6 +299,18 @@ TEST_F(FormatTestObjC, FormatObjCInterfa
"+ (id)init;\n"
"@end");
 
+  verifyFormat("@interface Foo  : Bar  {\n"
+   "  int _i;\n"
+   "}\n"
+   "+ (id)init;\n"
+   "@end");
+
+  verifyFormat("@interface Foo > : Xyzzy  {\n"
+   "  int _i;\n"
+   "}\n"
+   "+ (id)init;\n"
+   "@end");
+
   verifyFormat("@interface Foo (HackStuff) {\n"
"  int _i;\n"
"}\n"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r329297 - [clang-format] Ensure ObjC selectors with 0 args are annotated correctly

2018-04-05 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Thu Apr  5 08:26:23 2018
New Revision: 329297

URL: http://llvm.org/viewvc/llvm-project?rev=329297=rev
Log:
[clang-format] Ensure ObjC selectors with 0 args are annotated correctly

Summary:
Previously, clang-format would incorrectly annotate 0-argument
Objective-C selector names as TT_TrailingAnnotation:

```
% echo "-(void)foo;" > /tmp/test.m
% ./bin/clang-format -debug /tmp/test.m
Language: Objective-C

Line(0, FSC=0): minus[T=68, OC=0] l_paren[T=68, OC=1] void[T=68, OC=2]
r_paren[T=68, OC=6] identifier[T=68, OC=7] semi[T=68, OC=10]
Line(0, FSC=0): eof[T=68, OC=0]
Run 0...
AnnotatedTokens(L=0):
 M=0 C=0 T=ObjCMethodSpecifier S=1 B=0 BK=0 P=0 Name=minus L=1 PPK=2
 FakeLParens= FakeRParens=0 Text='-'
 M=0 C=1 T=Unknown S=1 B=0 BK=0 P=33 Name=l_paren L=3 PPK=2
 FakeLParens= FakeRParens=0 Text='('
 M=0 C=1 T=Unknown S=0 B=0 BK=0 P=140 Name=void L=7 PPK=2 FakeLParens=
 FakeRParens=0 Text='void'
 M=0 C=0 T=CastRParen S=0 B=0 BK=0 P=43 Name=r_paren L=8 PPK=2
 FakeLParens= FakeRParens=0 Text=')'
 M=0 C=1 T=TrailingAnnotation S=0 B=0 BK=0 P=120 Name=identifier L=11
 PPK=2 FakeLParens= FakeRParens=0 Text='foo'
 M=0 C=0 T=Unknown S=0 B=0 BK=0 P=23 Name=semi L=12 PPK=2 FakeLParens=
 FakeRParens=0 Text=';'
```

This caused us to incorrectly indent 0-argument wrapped selectors
when Style.IndentWrappedFunctionNames was false, as we thought
the 0-argument ObjC selector name was actually a trailing
annotation (which is always indented).

This diff fixes the issue and adds tests.

Test Plan: New tests added. Confirmed tests failed before diff.
  After diff, tests passed. Ran tests with:
  % make -j12 FormatTests &&
  ./tools/clang/unittests/Format/FormatTests

Reviewers: djasper, jolesiak

Reviewed By: djasper, jolesiak

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D44996

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=329297=329296=329297=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Thu Apr  5 08:26:23 2018
@@ -391,6 +391,7 @@ private:
  Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
  tok::kw_return, tok::kw_throw) ||
  Parent->isUnaryOperator() ||
+ // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
  Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
  getBinOpPrecedence(Parent->Tok.getKind(), true, true) > 
prec::Unknown);
 bool ColonFound = false;
@@ -524,6 +525,7 @@ private:
   Left->ParameterCount = 0;
   Contexts.back().ColonIsObjCMethodExpr = true;
   if (Parent && Parent->is(tok::r_paren))
+// FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
 Parent->Type = TT_CastRParen;
 }
 ColonFound = true;
@@ -676,6 +678,7 @@ private:
 Tok->Type = TT_ObjCMethodExpr;
 const FormatToken *BeforePrevious = Tok->Previous->Previous;
 if (!BeforePrevious ||
+// FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
 !(BeforePrevious->is(TT_CastRParen) ||
   (BeforePrevious->is(TT_ObjCMethodExpr) &&
BeforePrevious->is(tok::colon))) ||
@@ -1343,6 +1346,17 @@ private:
  TT_LeadingJavaAnnotation)) {
 Current.Type = Current.Previous->Type;
   }
+} else if (Current.isOneOf(tok::identifier, tok::kw_new) &&
+   // FIXME(bug 36976): ObjC return types shouldn't use 
TT_CastRParen.
+   Current.Previous && Current.Previous->is(TT_CastRParen) &&
+   Current.Previous->MatchingParen &&
+   Current.Previous->MatchingParen->Previous &&
+   Current.Previous->MatchingParen->Previous->is(
+   TT_ObjCMethodSpecifier)) {
+  // This is the first part of an Objective-C selector name. (If there's no
+  // colon after this, this is the only place which annotates the 
identifier
+  // as a selector.)
+  Current.Type = TT_SelectorName;
 } else if (Current.isOneOf(tok::identifier, tok::kw_const) &&
Current.Previous &&
!Current.Previous->isOneOf(tok::equal, tok::at) &&

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=329297=329296=329297=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Thu Apr  5 08:26:23 2018
@@ -523,6 +523,23 @@ TEST_F(FormatTestObjC, FormatObjCMethodD
   verifyFormat("- 

r329070 - [clang-format/ObjC] Do not detect "[]" as ObjC method expression

2018-04-03 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Tue Apr  3 07:07:11 2018
New Revision: 329070

URL: http://llvm.org/viewvc/llvm-project?rev=329070=rev
Log:
[clang-format/ObjC] Do not detect "[]" as ObjC method expression

Summary:
The following C++ code was being detected by
`guessLanguage()` as Objective-C:

  #define FOO(...) auto bar = [] __VA_ARGS__;

This was because `[] __VA_ARGS__` is not currently detected as a C++
lambda expression (it has no parens or braces), so
`TokenAnnotator::parseSquare()` incorrectly treats the opening square
as an ObjC method expression.

We have two options to fix this:

1. Parse `[] __VA_ARGS__` explicitly as a C++ lambda
2. Make it so `[]` is never parsed as an Objective-C method expression

This diff implements option 2, which causes the `[` to be parsed
as `TT_ArraySubscriptLSquare` instead of `TT_ObjCMethodExpr`.

Note that when I fixed this, it caused one change in formatting
behavior, where the following was implicitly relying on the `[`
being parsed as `TT_ObjCMethodExpr`:

  A a;

becomes:

  A a;

with `Style.PointerAlignment = Middle`.

I don't really know what the desired format is for this syntax; the
test was added by Janusz Sobczak and integrated by @djasper in
https://github.com/llvm-mirror/clang/commit/b511fe9818829d7ece0cc0b2ce1fbe04a1f0739a
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r329069 - [clang-format/ObjC] Do not insert space after opening brace of ObjC dict literal

2018-04-03 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Tue Apr  3 07:07:09 2018
New Revision: 329069

URL: http://llvm.org/viewvc/llvm-project?rev=329069=rev
Log:
[clang-format/ObjC] Do not insert space after opening brace of ObjC dict literal

Summary:
D44816 attempted to fix a few cases where `clang-format` incorrectly
inserted a space before the closing brace of an Objective-C dictionary
literal.

This revealed there were still a few cases where we inserted a space
after the opening brace of an Objective-C dictionary literal.

This fixes the formatting to be consistent and adds more tests.

Test Plan: New tests added. Confirmed tests failed before
  diff and passed after diff.
  Ran tests with:
  % make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: djasper, jolesiak, krasimir

Reviewed By: djasper

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D45168

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=329069=329068=329069=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Tue Apr  3 07:07:09 2018
@@ -2480,6 +2480,9 @@ bool TokenAnnotator::spaceRequiredBetwee
 return false;
   if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
 return false;
+  if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at))
+// Objective-C dictionary literal -> no space after opening brace.
+return false;
   if (Right.is(tok::r_brace) && Right.MatchingParen &&
   Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at))
 // Objective-C dictionary literal -> no space before closing brace.

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=329069=329068=329069=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Tue Apr  3 07:07:09 2018
@@ -1021,8 +1021,17 @@ TEST_F(FormatTestObjC, ObjCDictLiterals)
"  a12345 = @{a12345 : a12345};\n"
"}");
   verifyFormat("int Foo() {\n"
+   "  a12345 = @{a12345 : @(a12345)};\n"
+   "}");
+  verifyFormat("int Foo() {\n"
"  a12345 = @{(Foo *)a12345 : @(a12345)};\n"
"}");
+  verifyFormat("int Foo() {\n"
+   "  a12345 = @{@(a12345) : a12345};\n"
+   "}");
+  verifyFormat("int Foo() {\n"
+   "  a12345 = @{@(a12345) : @YES};\n"
+   "}");
   Style.SpacesInContainerLiterals = false;
   verifyFormat("int Foo() {\n"
"  b12345 = @{b12345: b12345};\n"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r328871 - [clang-format] Ensure wrapped ObjC selectors with 1 arg obey IndentWrappedFunctionNames

2018-03-30 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Fri Mar 30 08:38:45 2018
New Revision: 328871

URL: http://llvm.org/viewvc/llvm-project?rev=328871=rev
Log:
[clang-format] Ensure wrapped ObjC selectors with 1 arg obey 
IndentWrappedFunctionNames

Summary:
In D43121, @Typz introduced logic to avoid indenting 2-or-more
argument ObjC selectors too far to the right if the first component
of the selector was longer than the others.

This had a small side effect of causing wrapped ObjC selectors with
exactly 1 argument to not obey IndentWrappedFunctionNames:

```
- (aa)
aa;
```

This diff fixes the issue by ensuring we align wrapped 1-argument
ObjC selectors correctly:

```
- (aa)
aa;
```

Test Plan: New tests added. Test failed before change, passed
  after change. Ran tests with:
  % make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: djasper, klimek, Typz, jolesiak

Reviewed By: djasper, jolesiak

Subscribers: cfe-commits, Typz

Differential Revision: https://reviews.llvm.org/D44994

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=328871=328870=328871=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Fri Mar 30 08:38:45 2018
@@ -896,12 +896,20 @@ unsigned ContinuationIndenter::getNewLin
 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);
   if (NextNonComment->is(TT_SelectorName)) {
 if (!State.Stack.back().ObjCSelectorNameFound) {
-  if (NextNonComment->LongestObjCSelectorName == 0)
-return State.Stack.back().Indent;
-  return (Style.IndentWrappedFunctionNames
-  ? std::max(State.Stack.back().Indent,
- State.FirstIndent + Style.ContinuationIndentWidth)
-  : State.Stack.back().Indent) +
+  unsigned MinIndent = State.Stack.back().Indent;
+  if (Style.IndentWrappedFunctionNames)
+MinIndent = std::max(MinIndent,
+ State.FirstIndent + 
Style.ContinuationIndentWidth);
+  // If LongestObjCSelectorName is 0, we are indenting the first
+  // part of an ObjC selector (or a selector component which is
+  // not colon-aligned due to block formatting).
+  //
+  // Otherwise, we are indenting a subsequent part of an ObjC
+  // selector which should be colon-aligned to the longest
+  // component of the ObjC selector.
+  //
+  // In either case, we want to respect Style.IndentWrappedFunctionNames.
+  return MinIndent +
  std::max(NextNonComment->LongestObjCSelectorName,
   NextNonComment->ColumnWidth) -
  NextNonComment->ColumnWidth;

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=328871=328870=328871=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Fri Mar 30 08:38:45 2018
@@ -537,6 +537,22 @@ TEST_F(FormatTestObjC, FormatObjCMethodD
"   aShortf:(NSRect)theRect {\n"
"}");
 
+  // Make sure selectors with 0, 1, or more arguments are indented
+  // when IndentWrappedFunctionNames is true.
+  verifyFormat("- (a)\n"
+   ";\n");
+  verifyFormat("- (a)\n"
+   ":(int)a;\n");
+  verifyFormat("- (a)\n"
+   ":(int)a\n"
+   ":(int)a;\n");
+  verifyFormat("- (a)\n"
+   " aaa:(int)a\n"
+   ":(int)a;\n");
+  verifyFormat("- (a)\n"
+   ":(int)a\n"
+   " aaa:(int)a;\n");
+
   // Format pairs correctly.
   Style.ColumnLimit = 80;
   verifyFormat("- (void)drawRectOn:(id)surface\n"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r328627 - [clang-format] Do not insert space before closing brace in ObjC dict literal

2018-03-27 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Tue Mar 27 08:01:17 2018
New Revision: 328627

URL: http://llvm.org/viewvc/llvm-project?rev=328627=rev
Log:
[clang-format] Do not insert space before closing brace in ObjC dict literal

Summary:
Previously, `clang-format` would sometimes insert a space
before the closing brace in an Objective-C dictionary literal.

Unlike array literals (which obey `Style.SpacesInContainerLiterals`
to add a space after `[` and before `]`), Objective-C dictionary
literals currently are not meant to insert a space after `{` and before
`}`, regardless of `Style.SpacesInContainerLiterals`.

However, some constructs like `@{foo : @(bar)}` caused `clang-format`
to insert a space between `)` and `}`.

This fixes the issue and adds tests. (I understand the behavior is
not consistent between array literals and dictionary literals, but
that's existing behavior that's a much larger change.)

Test Plan: New tests added. Ran tests with:
  % make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: djasper, jolesiak, Wizard

Reviewed By: djasper

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D44816

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=328627=328626=328627=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Tue Mar 27 08:01:17 2018
@@ -2480,6 +2480,10 @@ bool TokenAnnotator::spaceRequiredBetwee
 return false;
   if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square))
 return false;
+  if (Right.is(tok::r_brace) && Right.MatchingParen &&
+  Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at))
+// Objective-C dictionary literal -> no space before closing brace.
+return false;
   return true;
 }
 

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=328627=328626=328627=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Tue Mar 27 08:01:17 2018
@@ -1000,6 +1000,21 @@ TEST_F(FormatTestObjC, ObjCDictLiterals)
   "  ( id)a : ( id),\n"
   "  ( id)aa : ( id)aa,\n"
   "};");
+  Style.ColumnLimit = 40;
+  verifyFormat("int Foo() {\n"
+   "  a12345 = @{a12345 : a12345};\n"
+   "}");
+  verifyFormat("int Foo() {\n"
+   "  a12345 = @{(Foo *)a12345 : @(a12345)};\n"
+   "}");
+  Style.SpacesInContainerLiterals = false;
+  verifyFormat("int Foo() {\n"
+   "  b12345 = @{b12345: b12345};\n"
+   "}");
+  verifyFormat("int Foo() {\n"
+   "  b12345 = @{(Foo *)b12345: @(b12345)};\n"
+   "}");
+  Style.SpacesInContainerLiterals = true;
 
   Style = getGoogleStyle(FormatStyle::LK_ObjC);
   verifyFormat(
@@ -1055,6 +1070,21 @@ TEST_F(FormatTestObjC, ObjCArrayLiterals
   verifyFormat("[someFunction someLongParameter:@[\n"
"  NSBundle.mainBundle.infoDictionary[@\"a\"]\n"
"]];");
+  Style.ColumnLimit = 40;
+  verifyFormat("int Foo() {\n"
+   "  a12345 = @[ a12345, a12345 ];\n"
+   "}");
+  verifyFormat("int Foo() {\n"
+   "  a123 = @[ (Foo *)a12345, @(a12345) ];\n"
+   "}");
+  Style.SpacesInContainerLiterals = false;
+  verifyFormat("int Foo() {\n"
+   "  b12345 = @[b12345, b12345];\n"
+   "}");
+  verifyFormat("int Foo() {\n"
+   "  b12345 = @[(Foo *)b12345, @(b12345)];\n"
+   "}");
+  Style.SpacesInContainerLiterals = true;
   Style.ColumnLimit = 20;
   // We can't break string literals inside NSArray literals
   // (that raises -Wobjc-string-concatenation).


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r328628 - [clang-format] Refine ObjC guesser to handle child lines of child lines

2018-03-27 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Tue Mar 27 08:01:21 2018
New Revision: 328628

URL: http://llvm.org/viewvc/llvm-project?rev=328628=rev
Log:
[clang-format] Refine ObjC guesser to handle child lines of child lines

Summary:
This fixes an issue brought up by djasper@ in his review of D44790. We
handled top-level child lines, but if those child lines themselves
had child lines, we didn't handle them.

Rather than use recursion (which could blow out the stack), I use a
DenseSet to hold the set of lines we haven't yet checked (since order
doesn't matter), and update the set to add the children of each
line as we check it.

Test Plan: New tests added. Confirmed tests failed before fix
  and passed after fix.

Reviewers: djasper

Reviewed By: djasper

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D44831

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=328628=328627=328628=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Tue Mar 27 08:01:21 2018
@@ -1514,8 +1514,8 @@ private:
 "UIView",
 };
 
-auto LineContainsObjCCode = [](const AnnotatedLine ) {
-  for (const FormatToken *FormatTok = Line.First; FormatTok;
+for (auto Line : AnnotatedLines) {
+  for (const FormatToken *FormatTok = Line->First; FormatTok;
FormatTok = FormatTok->Next) {
 if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
  (FormatTok->isObjCAtKeyword(tok::objc_interface) ||
@@ -1535,14 +1535,7 @@ private:
TT_ObjCMethodSpecifier, TT_ObjCProperty)) {
   return true;
 }
-  }
-  return false;
-};
-for (auto Line : AnnotatedLines) {
-  if (LineContainsObjCCode(*Line))
-return true;
-  for (auto ChildLine : Line->Children) {
-if (LineContainsObjCCode(*ChildLine))
+if (guessIsObjC(Line->Children, Keywords))
   return true;
   }
 }

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=328628=328627=328628=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Tue Mar 27 08:01:21 2018
@@ -12159,6 +12159,12 @@ TEST_F(FormatTest, GuessLanguageWithChil
 guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
   EXPECT_EQ(FormatStyle::LK_ObjC,
 guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
+  EXPECT_EQ(
+  FormatStyle::LK_Cpp,
+  guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
+  EXPECT_EQ(
+  FormatStyle::LK_ObjC,
+  guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
 }
 
 } // end namespace


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r328220 - [clang-format] Fix ObjC style guesser to also iterate over child lines

2018-03-22 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Thu Mar 22 10:37:19 2018
New Revision: 328220

URL: http://llvm.org/viewvc/llvm-project?rev=328220=rev
Log:
[clang-format] Fix ObjC style guesser to also iterate over child lines

Summary:
When I wrote `ObjCHeaderStyleGuesser`, I incorrectly assumed the
correct way to iterate over all tokens in `AnnotatedLine` was to
iterate over the linked list tokens starting with
`AnnotatedLine::First`.

However, `AnnotatedLine` also contains a vector
`AnnotedLine::Children` with child `AnnotedLine`s which have their own
tokens which we need to iterate over.

Because I didn't iterate over the tokens in the children lines, the
ObjC style guesser would fail on syntax like:

  #define FOO ({ NSString *s = ... })

as the statement(s) inside { ... } are child lines.

This fixes the bug and adds a test. I confirmed the test
failed before the fix, and passed after the fix.

Test Plan: New tests added. Ran tests with:
  % make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: djasper, jolesiak, Wizard

Reviewed By: djasper

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D44790

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=328220=328219=328220=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Thu Mar 22 10:37:19 2018
@@ -1514,8 +1514,8 @@ private:
 "UIView",
 };
 
-for (auto  : AnnotatedLines) {
-  for (FormatToken *FormatTok = Line->First; FormatTok;
+auto LineContainsObjCCode = [](const AnnotatedLine ) {
+  for (const FormatToken *FormatTok = Line.First; FormatTok;
FormatTok = FormatTok->Next) {
 if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
  (FormatTok->isObjCAtKeyword(tok::objc_interface) ||
@@ -1536,6 +1536,15 @@ private:
   return true;
 }
   }
+  return false;
+};
+for (auto Line : AnnotatedLines) {
+  if (LineContainsObjCCode(*Line))
+return true;
+  for (auto ChildLine : Line->Children) {
+if (LineContainsObjCCode(*ChildLine))
+  return true;
+  }
 }
 return false;
   }

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=328220=328219=328220=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Thu Mar 22 10:37:19 2018
@@ -12166,6 +12166,13 @@ TEST_F(FormatTest, GuessLanguageWithCare
   guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
 }
 
+TEST_F(FormatTest, GuessLanguageWithChildLines) {
+  EXPECT_EQ(FormatStyle::LK_Cpp,
+guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r328175 - [clang-format] Add a few more Core Graphics identifiers to ObjC heuristic

2018-03-21 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Wed Mar 21 20:25:22 2018
New Revision: 328175

URL: http://llvm.org/viewvc/llvm-project?rev=328175=rev
Log:
[clang-format] Add a few more Core Graphics identifiers to ObjC heuristic

Summary:
We received reports of the Objective-C style guesser getting a false
negative on header files like:

CGSize SizeOfThing(MyThing thing);

This adds more Core Graphics identifiers to the Objective-C style
guesser.

Test Plan: New tests added. Ran tests with:
  % make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: jolesiak, djasper

Reviewed By: jolesiak, djasper

Subscribers: krasimir, klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D44632

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=328175=328174=328175=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Wed Mar 21 20:25:22 2018
@@ -1449,6 +1449,19 @@ private:
 // Keep this array sorted, since we are binary searching over it.
 static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
 "CGFloat",
+"CGPoint",
+"CGPointMake",
+"CGPointZero",
+"CGRect",
+"CGRectEdge",
+"CGRectInfinite",
+"CGRectMake",
+"CGRectNull",
+"CGRectZero",
+"CGSize",
+"CGSizeMake",
+"CGVector",
+"CGVectorMake",
 "NSAffineTransform",
 "NSArray",
 "NSAttributedString",
@@ -1497,6 +1510,8 @@ private:
 "NSURLQueryItem",
 "NSUUID",
 "NSValue",
+"UIImage",
+"UIView",
 };
 
 for (auto  : AnnotatedLines) {

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=328175=328174=328175=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Wed Mar 21 20:25:22 2018
@@ -12108,6 +12108,12 @@ TEST_F(FormatTest, FileAndCode) {
   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@interface 
Foo\n@end\n"));
   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo", "@interface 
Foo\n@end\n"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
+  EXPECT_EQ(
+  FormatStyle::LK_ObjC,
+  guessLanguage("foo.h",
+"#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
 }
 
 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r328174 - [clang-format] Don't insert space between r_paren and 'new' in ObjC decl

2018-03-21 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Wed Mar 21 20:23:53 2018
New Revision: 328174

URL: http://llvm.org/viewvc/llvm-project?rev=328174=rev
Log:
[clang-format] Don't insert space between r_paren and 'new' in ObjC decl

Summary:
Previously, clang-format would insert a space between
the closing parenthesis and 'new' in the following valid Objective-C
declaration:

  + (instancetype)new;

This was because 'new' is treated as a keyword, not an identifier.

TokenAnnotator::spaceRequiredBefore() already handled the case where
r_paren came before an identifier, so this diff extends it to
handle r_paren before 'new'.

Test Plan: New tests added. Ran tests with:
  % make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: djasper, jolesiak, stephanemoore

Reviewed By: djasper, jolesiak, stephanemoore

Subscribers: stephanemoore, klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D44692

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=328174=328173=328174=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Wed Mar 21 20:23:53 2018
@@ -2615,8 +2615,10 @@ bool TokenAnnotator::spaceRequiredBefore
   if (Line.Type == LT_ObjCMethodDecl) {
 if (Left.is(TT_ObjCMethodSpecifier))
   return true;
-if (Left.is(tok::r_paren) && Right.is(tok::identifier))
-  // Don't space between ')' and 
+if (Left.is(tok::r_paren) && Right.isOneOf(tok::identifier, tok::kw_new))
+  // Don't space between ')' and  or ')' and 'new'. 'new' is not a
+  // keyword in Objective-C, and '+ (instancetype)new;' is a standard class
+  // method declaration.
   return false;
   }
   if (Line.Type == LT_ObjCProperty &&

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=328174=328173=328174=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Wed Mar 21 20:23:53 2018
@@ -514,6 +514,7 @@ TEST_F(FormatTestObjC, FormatObjCMethodD
"evenLongerKeyword:(float)theInterval\n"
"error:(NSError **)theError {\n"
"}");
+  verifyFormat("+ (instancetype)new;\n");
   Style.ColumnLimit = 60;
   verifyFormat("- (instancetype)initXx:(id)x\n"
" y:(id)y\n"
@@ -914,6 +915,17 @@ TEST_F(FormatTestObjC, ObjCForIn) {
" }]) {\n}");
 }
 
+TEST_F(FormatTestObjC, ObjCNew) {
+  verifyFormat("+ (instancetype)new {\n"
+   "  return nil;\n"
+   "}\n");
+  verifyFormat("+ (instancetype)myNew {\n"
+   "  return [self new];\n"
+   "}\n");
+  verifyFormat("SEL NewSelector(void) { return @selector(new); }\n");
+  verifyFormat("SEL MacroSelector(void) { return MACRO(new); }\n");
+}
+
 TEST_F(FormatTestObjC, ObjCLiterals) {
   verifyFormat("@\"String\"");
   verifyFormat("@1");


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D44634: [clang-format] Detect Objective-C for #import

2018-03-21 Thread Ben Hamilton via cfe-commits
#import is perfectly legal in C and C++, it's just not commonly used.

On Wed, Mar 21, 2018, 14:27 Yan Zhang via Phabricator <
revi...@reviews.llvm.org> wrote:

> Wizard added a comment.
>
> Why do we only detect system framework? I think any #import could indicate
> ObjC header.
>
>
> Repository:
>   rC Clang
>
> https://reviews.llvm.org/D44634
>
>
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r327986 - [clang-format] Fix ObjC selectors with multiple params passed to macro

2018-03-20 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Tue Mar 20 07:53:25 2018
New Revision: 327986

URL: http://llvm.org/viewvc/llvm-project?rev=327986=rev
Log:
[clang-format] Fix ObjC selectors with multiple params passed to macro

Summary:
Objective-C selectors with arguments take the form of:

foo:
foo:bar:
foo:bar:baz:

These can be passed to a macro, like NS_SWIFT_NAME():

https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html

and must never have spaces inserted around the colons.

Previously, there was logic in TokenAnnotator's tok::colon parser to
handle the single-argument case, but it failed for the
multiple-argument cases.

This diff fixes the bug and adds more tests.

Test Plan: New tests added. Ran tests with:
  % make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: jolesiak, djasper, Wizard

Reviewed By: jolesiak, Wizard

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D44638

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=327986=327985=327986=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Tue Mar 20 07:53:25 2018
@@ -701,7 +701,8 @@ private:
 else
   Tok->Type = TT_InheritanceColon;
   } else if (Tok->Previous->is(tok::identifier) && Tok->Next &&
- Tok->Next->isOneOf(tok::r_paren, tok::comma)) {
+ (Tok->Next->isOneOf(tok::r_paren, tok::comma) ||
+  Tok->Next->startsSequence(tok::identifier, tok::colon))) {
 // This handles a special macro in ObjC code where selectors including
 // the colon are passed as macro arguments.
 Tok->Type = TT_ObjCMethodExpr;

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=327986=327985=327986=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Tue Mar 20 07:53:25 2018
@@ -618,6 +618,9 @@ TEST_F(FormatTestObjC, FormatObjCMethodE
   verifyFormat("for (id foo in [self getStuffFor:bla]) {\n"
"}");
   verifyFormat("[self a:MACRO(a, b:, c:)];");
+  verifyFormat("[self a:MACRO(a, b:c:, d:e:)];");
+  verifyFormat("[self a:MACRO(a, b:c:d:, e:f:g:)];");
+  verifyFormat("int XYMyFoo(int a, int b) NS_SWIFT_NAME(foo(self:scale:));");
   verifyFormat("[self a:(1 + 2) b:3];");
   verifyFormat("[self a:(Type)a b:3];");
 


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r327284 - [clang-format] Don't detect C++11 attribute specifiers as ObjC

2018-03-12 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Mon Mar 12 08:42:38 2018
New Revision: 327284

URL: http://llvm.org/viewvc/llvm-project?rev=327284=rev
Log:
[clang-format] Don't detect C++11 attribute specifiers as ObjC

Summary:
Previously, clang-format would detect C++11 and C++17 attribute
specifiers like the following as Objective-C method invocations:

  [[noreturn]];
  [[clang::fallthrough]];
  [[noreturn, deprecated("so sorry")]];
  [[using gsl: suppress("type")]];

To fix this, I ported part of the logic from
tools/clang/lib/Parse/ParseTentative.cpp into TokenAnnotator.cpp so we
can explicitly parse and identify C++11 attribute specifiers.

This allows the guessLanguage() and getStyle() APIs to correctly
guess files containing the C++11 attribute specifiers as C++,
not Objective-C.

Test Plan: New tests added. Ran tests with:
  make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: krasimir, jolesiak, djasper

Reviewed By: djasper

Subscribers: aaron.ballman, cfe-commits, klimek

Differential Revision: https://reviews.llvm.org/D43902

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/lib/Format/FormatToken.h
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=327284=327283=327284=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Mon Mar 12 08:42:38 2018
@@ -889,8 +889,8 @@ unsigned ContinuationIndenter::getNewLin
   if ((PreviousNonComment &&
(PreviousNonComment->ClosesTemplateDeclaration ||
 PreviousNonComment->isOneOf(
-TT_AttributeParen, TT_FunctionAnnotationRParen, TT_JavaAnnotation,
-TT_LeadingJavaAnnotation))) ||
+TT_AttributeParen, TT_AttributeSquare, TT_FunctionAnnotationRParen,
+TT_JavaAnnotation, TT_LeadingJavaAnnotation))) ||
   (!Style.IndentWrappedFunctionNames &&
NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName)))
 return std::max(State.Stack.back().LastSpace, State.Stack.back().Indent);

Modified: cfe/trunk/lib/Format/FormatToken.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/FormatToken.h?rev=327284=327283=327284=diff
==
--- cfe/trunk/lib/Format/FormatToken.h (original)
+++ cfe/trunk/lib/Format/FormatToken.h Mon Mar 12 08:42:38 2018
@@ -29,7 +29,9 @@ namespace format {
 #define LIST_TOKEN_TYPES   
\
   TYPE(ArrayInitializerLSquare)
\
   TYPE(ArraySubscriptLSquare)  
\
+  TYPE(AttributeColon) 
\
   TYPE(AttributeParen) 
\
+  TYPE(AttributeSquare)
\
   TYPE(BinaryOperator) 
\
   TYPE(BitFieldColon)  
\
   TYPE(BlockComment)   
\

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=327284=327283=327284=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Mon Mar 12 08:42:38 2018
@@ -328,13 +328,40 @@ private:
 return false;
   }
 
+  bool isCpp11AttributeSpecifier(const FormatToken ) {
+if (!Style.isCpp() || !Tok.startsSequence(tok::l_square, tok::l_square))
+  return false;
+const FormatToken *AttrTok = Tok.Next->Next;
+if (!AttrTok)
+  return false;
+// C++17 '[[using ns: foo, bar(baz, blech)]]'
+// We assume nobody will name an ObjC variable 'using'.
+if (AttrTok->startsSequence(tok::kw_using, tok::identifier, tok::colon))
+  return true;
+if (AttrTok->isNot(tok::identifier))
+  return false;
+while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) {
+  // ObjC message send. We assume nobody will use : in a C++11 attribute
+  // specifier parameter, although this is technically valid:
+  // [[foo(:)]]
+  if (AttrTok->is(tok::colon) ||
+  AttrTok->startsSequence(tok::identifier, tok::identifier))
+return false;
+  if (AttrTok->is(tok::ellipsis))
+return true;
+  AttrTok = AttrTok->Next;
+}
+return AttrTok && AttrTok->startsSequence(tok::r_square, tok::r_square);
+  }
+
   bool parseSquare() {
 if (!CurrentToken)
   return 

r327285 - [clang-format] Improve detection of Objective-C block types

2018-03-12 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Mon Mar 12 08:42:40 2018
New Revision: 327285

URL: http://llvm.org/viewvc/llvm-project?rev=327285=rev
Log:
[clang-format] Improve detection of Objective-C block types

Summary:
Previously, clang-format would detect the following as an
Objective-C block type:

  FOO(^);

when it actually must be a C or C++ macro dealing with an XOR
statement or an XOR operator overload.

According to the Clang Block Language Spec:

https://clang.llvm.org/docs/BlockLanguageSpec.html

block types are of the form:

  int (^)(char, float)

and block variables of block type are of the form:

  void (^blockReturningVoidWithVoidArgument)(void);
  int (^blockReturningIntWithIntAndCharArguments)(int, char);
  void (^arrayOfTenBlocksReturningVoidWithIntArgument[10])(int);

This tightens up the detection so we don't unnecessarily detect
C macros which pass in the XOR operator.

Depends On D43904

Test Plan: New tests added. Ran tests with:
  make -j12 FormatTests &&
  ./tools/clang/unittests/Format/FormatTests

Reviewers: krasimir, jolesiak, djasper

Reviewed By: djasper

Subscribers: djasper, cfe-commits, klimek

Differential Revision: https://reviews.llvm.org/D43906

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTest.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=327285=327284=327285=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Mon Mar 12 08:42:40 2018
@@ -141,10 +141,7 @@ private:
 Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
 
 bool StartsObjCMethodExpr = false;
-if (CurrentToken->is(tok::caret)) {
-  // (^ can start a block type.
-  Left->Type = TT_ObjCBlockLParen;
-} else if (FormatToken *MaybeSel = Left->Previous) {
+if (FormatToken *MaybeSel = Left->Previous) {
   // @selector( starts a selector.
   if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous 
&&
   MaybeSel->Previous->is(tok::at)) {
@@ -210,8 +207,16 @@ private:
   Left->Type = TT_ObjCMethodExpr;
 }
 
+// MightBeFunctionType and ProbablyFunctionType are used for
+// function pointer and reference types as well as Objective-C
+// block types:
+//
+// void (*FunctionPointer)(void);
+// void ()(void);
+// void (^ObjCBlock)(void);
 bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
-bool ProbablyFunctionType = CurrentToken->isOneOf(tok::star, tok::amp);
+bool ProbablyFunctionType =
+CurrentToken->isOneOf(tok::star, tok::amp, tok::caret);
 bool HasMultipleLines = false;
 bool HasMultipleParametersOnALine = false;
 bool MightBeObjCForRangeLoop =
@@ -248,7 +253,8 @@ private:
 if (MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next 
&&
 (CurrentToken->Next->is(tok::l_paren) ||
  (CurrentToken->Next->is(tok::l_square) && 
Line.MustBeDeclaration)))
-  Left->Type = TT_FunctionTypeLParen;
+  Left->Type = Left->Next->is(tok::caret) ? TT_ObjCBlockLParen
+  : TT_FunctionTypeLParen;
 Left->MatchingParen = CurrentToken;
 CurrentToken->MatchingParen = Left;
 

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=327285=327284=327285=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Mon Mar 12 08:42:40 2018
@@ -12128,6 +12128,22 @@ TEST_F(FormatTest, GuessLanguageWithCpp1
   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
 }
 
+TEST_F(FormatTest, GuessLanguageWithCaret) {
+  EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
+  EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "int(^)(char, float);"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "int(^foo)(char, float);"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "int(^foo[10])(char, float);"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
+  EXPECT_EQ(
+  FormatStyle::LK_ObjC,
+  guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=327285=327284=327285=diff

Re: [PATCH] D43902: [clang-format] Don't detect C++11 attribute specifiers as ObjC

2018-03-07 Thread Ben Hamilton via cfe-commits
I made it longer so the two lines (__attribute__((foo)) vs. [[foo]]) had
the same length.

If I shorten it much more, everything goes on one line.

On Wed, Mar 7, 2018, 03:42 Krasimir Georgiev via Phabricator <
revi...@reviews.llvm.org> wrote:

> krasimir added inline comments.
>
>
> 
> Comment at: unittests/Format/FormatTest.cpp:6068-6069
> +  verifyFormat("void f() [[deprecated(\"so sorry\")]];");
> +  verifyFormat("aa\n"
> +   "[[unused]] aaa(int i);");
> +}
> 
> benhamilton wrote:
> > I couldn't figure out why this breaks before the `[` in `[[unused]]`,
> when the identical test using `__attribute__((unused))` above does *not*
> break before the `__attribute__`.
> >
> > I ran with `-debug` and the two seem fairly similar. Can anyone help
> shed light on this?
> >
> > ## With `__attribute__((unused))`
> >
> > P8067
> >
> > ## With `[[unused]]`
> >
> > P8068
> The block of `a`-s appears to be longer here than in the `__attribute__`
> example. That might be a reason.
>
>
> Repository:
>   rC Clang
>
> https://reviews.llvm.org/D43902
>
>
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r326815 - [clang-format] Improve detection of ObjC for-in statements

2018-03-06 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Tue Mar  6 09:21:42 2018
New Revision: 326815

URL: http://llvm.org/viewvc/llvm-project?rev=326815=rev
Log:
[clang-format] Improve detection of ObjC for-in statements

Summary:
Previously, clang-format would detect the following as an
Objective-C for-in statement:

  for (int x = in.value(); ...) {}

because the logic only decided a for-loop was definitely *not*
an Objective-C for-in loop after it saw a semicolon or a colon.

To fix this, I delayed the decision of whether this was a for-in
statement until after we found the matching right-paren, at which
point we know if we've seen a semicolon or not.

Test Plan: New tests added. Ran tests with:
  make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: krasimir, jolesiak

Reviewed By: jolesiak

Subscribers: djasper, cfe-commits, klimek

Differential Revision: https://reviews.llvm.org/D43904

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTest.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=326815=326814=326815=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Tue Mar  6 09:21:42 2018
@@ -216,6 +216,7 @@ private:
 bool HasMultipleParametersOnALine = false;
 bool MightBeObjCForRangeLoop =
 Left->Previous && Left->Previous->is(tok::kw_for);
+FormatToken *PossibleObjCForInToken = nullptr;
 while (CurrentToken) {
   // LookForDecls is set when "if (" has been seen. Check for
   // 'identifier' '*' 'identifier' followed by not '=' -- this
@@ -301,10 +302,17 @@ private:
CurrentToken->Previous->isSimpleTypeSpecifier()) &&
   !CurrentToken->is(tok::l_brace))
 Contexts.back().IsExpression = false;
-  if (CurrentToken->isOneOf(tok::semi, tok::colon))
+  if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
 MightBeObjCForRangeLoop = false;
-  if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in))
-CurrentToken->Type = TT_ObjCForIn;
+if (PossibleObjCForInToken) {
+  PossibleObjCForInToken->Type = TT_Unknown;
+  PossibleObjCForInToken = nullptr;
+}
+  }
+  if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
+PossibleObjCForInToken = CurrentToken;
+PossibleObjCForInToken->Type = TT_ObjCForIn;
+  }
   // When we discover a 'new', we set CanBeExpression to 'false' in order 
to
   // parse the type correctly. Reset that after a comma.
   if (CurrentToken->is(tok::comma))

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=326815=326814=326815=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Tue Mar  6 09:21:42 2018
@@ -742,6 +742,12 @@ TEST_F(FormatTest, FormatsForLoop) {
" aaa != bbb;\n"
" ++aaa) {");
 
+  // These should not be formatted as Objective-C for-in loops.
+  verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
+  verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
+  verifyFormat("Foo *x;\nfor (x in y) {\n}");
+  verifyFormat("for (const Foo  = in.value(); !baz.at_end(); ++baz) 
{\n}");
+
   FormatStyle NoBinPacking = getLLVMStyle();
   NoBinPacking.BinPackParameters = false;
   verifyFormat("for (int aaa = 1;\n"
@@ -12082,6 +12088,31 @@ TEST_F(FormatTest, FileAndCode) {
   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo", "@interface 
Foo\n@end\n"));
 }
 
+TEST_F(FormatTest, GuessLanguageWithForIn) {
+  EXPECT_EQ(FormatStyle::LK_Cpp,
+guessLanguage("foo.h", "for (Foo *x = 0; x != in; x++) {}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "for (Foo *x in bar) {}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "for (Foo *x in [bar baz]) {}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "for (Foo *x in [bar baz:blech]) {}"));
+  EXPECT_EQ(
+  FormatStyle::LK_ObjC,
+  guessLanguage("foo.h", "for (Foo *x in [bar baz:blech, 1, 2, 3, 0]) 
{}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "for (Foo *x in [bar baz:^{[uh oh];}]) 
{}"));
+  EXPECT_EQ(FormatStyle::LK_Cpp,
+guessLanguage("foo.h", "Foo *x; for (x = 0; x != in; x++) {}"));
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "Foo *x; for (x in y) {}"));
+  EXPECT_EQ(
+  FormatStyle::LK_Cpp,
+  guessLanguage(
+  "foo.h",
+  "for (const 

r326205 - [clang-format] Tidy up new API guessLanguage()

2018-02-27 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Tue Feb 27 07:56:40 2018
New Revision: 326205

URL: http://llvm.org/viewvc/llvm-project?rev=326205=rev
Log:
[clang-format] Tidy up new API guessLanguage()

Summary:
This fixes a few issues djasper@ brought up in his review of D43522.

Test Plan:
  make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: djasper

Reviewed By: djasper

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D43598

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=326205=326204=326205=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Tue Feb 27 07:56:40 2018
@@ -2295,8 +2295,8 @@ static FormatStyle::LanguageKind getLang
 }
 
 FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) {
-  FormatStyle::LanguageKind result = getLanguageByFileName(FileName);
-  if (result == FormatStyle::LK_Cpp) {
+  const auto GuessedLanguage = getLanguageByFileName(FileName);
+  if (GuessedLanguage == FormatStyle::LK_Cpp) {
 auto Extension = llvm::sys::path::extension(FileName);
 // If there's no file extension (or it's .h), we need to check the contents
 // of the code to see if it contains Objective-C.
@@ -2306,12 +2306,11 @@ FormatStyle::LanguageKind guessLanguage(
   Environment::CreateVirtualEnvironment(Code, NonEmptyFileName, 
/*Ranges=*/{});
   ObjCHeaderStyleGuesser Guesser(*Env, getLLVMStyle());
   Guesser.process();
-  if (Guesser.isObjC()) {
-result = FormatStyle::LK_ObjC;
-  }
+  if (Guesser.isObjC())
+return FormatStyle::LK_ObjC;
 }
   }
-  return result;
+  return GuessedLanguage;
 }
 
 llvm::Expected getStyle(StringRef StyleName, StringRef FileName,

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=326205=326204=326205=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Tue Feb 27 07:56:40 2018
@@ -11959,34 +11959,16 @@ TEST_F(FormatTest, StructuredBindings) {
   verifyFormat("auto const &[ a, b ] = f();", Spaces);
 }
 
-struct GuessLanguageTestCase {
-  const char *const FileName;
-  const char *const Code;
-  const FormatStyle::LanguageKind ExpectedResult;
-};
-
-class GuessLanguageTest
-: public FormatTest,
-  public ::testing::WithParamInterface {};
-
-TEST_P(GuessLanguageTest, FileAndCode) {
-  auto TestCase = GetParam();
-  EXPECT_EQ(TestCase.ExpectedResult,
-guessLanguage(TestCase.FileName, TestCase.Code));
+TEST_F(FormatTest, FileAndCode) {
+  EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
+  EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
+  EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
+  EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
+  EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@interface 
Foo\n@end\n"));
+  EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
+  EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo", "@interface 
Foo\n@end\n"));
 }
 
-static const GuessLanguageTestCase TestCases[] = {
-{"foo.cc", "", FormatStyle::LK_Cpp},
-{"foo.m", "", FormatStyle::LK_ObjC},
-{"foo.mm", "", FormatStyle::LK_ObjC},
-{"foo.h", "", FormatStyle::LK_Cpp},
-{"foo.h", "@interface Foo\n@end\n", FormatStyle::LK_ObjC},
-{"foo", "", FormatStyle::LK_Cpp},
-{"foo", "@interface Foo\n@end\n", FormatStyle::LK_ObjC},
-};
-INSTANTIATE_TEST_CASE_P(ValidLanguages, GuessLanguageTest,
-::testing::ValuesIn(TestCases));
-
 } // end namespace
 } // end namespace format
 } // end namespace clang


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r325691 - [clang-format] New API guessLanguage()

2018-02-21 Thread Ben Hamilton via cfe-commits
Fix landed in r325722.

On Wed, Feb 21, 2018 at 1:53 PM Ben Hamilton <benhamil...@google.com> wrote:

> Thanks for the report, and sorry for the breakage.
>
> Here's the fix: https://reviews.llvm.org/D43590
>
> Ben
>
> On Wed, Feb 21, 2018 at 1:47 PM <douglas.y...@sony.com> wrote:
>
>> Hi Ben,
>>
>> Your change is causing a test failure on one of the bots, can you take a
>> look?
>>
>>
>> http://lab.llvm.org:8011/builders/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/builds/25515
>>
>> FAIL: Clang Tools :: clang-apply-replacements/format.cpp (12526 of 38114)
>>  TEST 'Clang Tools ::
>> clang-apply-replacements/format.cpp' FAILED 
>> Script:
>> --
>> mkdir -p
>> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format
>> grep -Ev "// *[A-Z-]+:"
>> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.src/tools/clang/tools/extra/test/clang-apply-replacements/Inputs/format/yes.cpp
>> >
>> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format/yes.cpp
>> grep -Ev "// *[A-Z-]+:"
>> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.src/tools/clang/tools/extra/test/clang-apply-replacements/Inputs/format/no.cpp
>> >
>> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format/no.cpp
>> sed
>> "s#\$(path)#/home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format#"
>> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.src/tools/clang/tools/extra/test/clang-apply-replacements/Inputs/format/yes.yaml
>> >
>> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format/yes.yaml
>> sed
>> "s#\$(path)#/home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format#"
>> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.src/tools/clang/tools/extra/test/clang-apply-replacements/Inputs/format/no.yaml
>> >
>> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format/no.yaml
>> clang-apply-replacements -format
>> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format
>> FileCheck --strict-whitespace
>> -input-file=/home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format/yes.cpp
>> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.src/tools/clang/tools/extra/test/clang-apply-replacements/Inputs/format/yes.cpp
>> FileCheck --strict-whitespace
>> -input-file=/home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format/no.cpp
>> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.src/tools/clang/tools/extra/test/clang-apply-replacements/Inputs/format/no.cpp
>> --
>> Exit Code: 134
>>
>> Command Output (stderr):
>> --
>> clang-apply-replacements:
>> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.src/tools/clang/lib/Basic/SourceManager.cpp:393:
>> const clang::SrcMgr::ContentCache
>> *clang::SourceManager::getOrCreateContentCache(const clang::FileEntry *,
>> bool): Assertion `FileEnt && "Didn't specify a file entry to use?"' failed.
>> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/format.cpp.script:
>> line 8: 49680 Aborted             (core dumped)
>> clang-apply-replacements -format
>> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format
>>
>> --
>>
>> 
>>
>> Douglas Yung
>>
>>
>

r325722 - [clang-format] Fix regression when getStyle() called with empty filename

2018-02-21 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Wed Feb 21 13:27:27 2018
New Revision: 325722

URL: http://llvm.org/viewvc/llvm-project?rev=325722=rev
Log:
[clang-format] Fix regression when getStyle() called with empty filename

Summary:
D43522 caused an assertion failure when getStyle() was called with
an empty filename:

P8065

This adds a test to reproduce the failure and fixes the issue by
ensuring we never pass an empty filename to
Environment::CreateVirtualEnvironment().

Test Plan: New test added. Ran test with:
  % make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
  Before diff, test failed with P8065. Now, test passes.

Reviewers: vsapsai, jolesiak, krasimir

Reviewed By: vsapsai

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D43590

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=325722=325721=325722=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Wed Feb 21 13:27:27 2018
@@ -2297,12 +2297,13 @@ static FormatStyle::LanguageKind getLang
 FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) {
   FormatStyle::LanguageKind result = getLanguageByFileName(FileName);
   if (result == FormatStyle::LK_Cpp) {
-auto extension = llvm::sys::path::extension(FileName);
+auto Extension = llvm::sys::path::extension(FileName);
 // If there's no file extension (or it's .h), we need to check the contents
 // of the code to see if it contains Objective-C.
-if (extension.empty() || extension == ".h") {
+if (Extension.empty() || Extension == ".h") {
+  auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName;
   std::unique_ptr Env =
-  Environment::CreateVirtualEnvironment(Code, FileName, /*Ranges=*/{});
+  Environment::CreateVirtualEnvironment(Code, NonEmptyFileName, 
/*Ranges=*/{});
   ObjCHeaderStyleGuesser Guesser(*Env, getLLVMStyle());
   Guesser.process();
   if (Guesser.isObjC()) {

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=325722=325721=325722=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Wed Feb 21 13:27:27 2018
@@ -11723,6 +11723,12 @@ TEST_F(FormatTest, NoSpaceAfterSuper) {
 verifyFormat("__super::FooBar();");
 }
 
+TEST(FormatStyle, GetStyleWithEmptyFileName) {
+  auto Style1 = getStyle("file", "", "Google");
+  ASSERT_TRUE((bool)Style1);
+  ASSERT_EQ(*Style1, getGoogleStyle());
+}
+
 TEST(FormatStyle, GetStyleOfFile) {
   vfs::InMemoryFileSystem FS;
   // Test 1: format file in the same directory.


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: r325691 - [clang-format] New API guessLanguage()

2018-02-21 Thread Ben Hamilton via cfe-commits
Thanks for the report, and sorry for the breakage.

Here's the fix: https://reviews.llvm.org/D43590

Ben

On Wed, Feb 21, 2018 at 1:47 PM <douglas.y...@sony.com> wrote:

> Hi Ben,
>
> Your change is causing a test failure on one of the bots, can you take a
> look?
>
>
> http://lab.llvm.org:8011/builders/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/builds/25515
>
> FAIL: Clang Tools :: clang-apply-replacements/format.cpp (12526 of 38114)
>  TEST 'Clang Tools ::
> clang-apply-replacements/format.cpp' FAILED 
> Script:
> --
> mkdir -p
> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format
> grep -Ev "// *[A-Z-]+:"
> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.src/tools/clang/tools/extra/test/clang-apply-replacements/Inputs/format/yes.cpp
> >
> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format/yes.cpp
> grep -Ev "// *[A-Z-]+:"
> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.src/tools/clang/tools/extra/test/clang-apply-replacements/Inputs/format/no.cpp
> >
> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format/no.cpp
> sed
> "s#\$(path)#/home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format#"
> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.src/tools/clang/tools/extra/test/clang-apply-replacements/Inputs/format/yes.yaml
> >
> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format/yes.yaml
> sed
> "s#\$(path)#/home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format#"
> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.src/tools/clang/tools/extra/test/clang-apply-replacements/Inputs/format/no.yaml
> >
> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format/no.yaml
> clang-apply-replacements -format
> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format
> FileCheck --strict-whitespace
> -input-file=/home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format/yes.cpp
> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.src/tools/clang/tools/extra/test/clang-apply-replacements/Inputs/format/yes.cpp
> FileCheck --strict-whitespace
> -input-file=/home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format/no.cpp
> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.src/tools/clang/tools/extra/test/clang-apply-replacements/Inputs/format/no.cpp
> --
> Exit Code: 134
>
> Command Output (stderr):
> --
> clang-apply-replacements:
> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.src/tools/clang/lib/Basic/SourceManager.cpp:393:
> const clang::SrcMgr::ContentCache
> *clang::SourceManager::getOrCreateContentCache(const clang::FileEntry *,
> bool): Assertion `FileEnt && "Didn't specify a file entry to use?"' failed.
> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/format.cpp.script:
> line 8: 49680 Aborted (core dumped)
> clang-apply-replacements -format
> /home/buildslave/ps4-buildslave4/llvm-clang-lld-x86_64-scei-ps4-ubuntu-fast/llvm.obj/tools/clang/tools/extra/test/clang-apply-replacements/Output/Inputs/format
>
> --
>
> 
>
> Douglas Yung
>
>
> > -Original Message-
> > From: cfe-commits [mailto:cfe-commits-boun...@lists.llvm.org] On Behalf
> Of Ben
> > Hamilton via cfe-commits
> > Sent: Wednesday, February 21, 2018 7:55
> > To: cfe-commits@lists.llvm.org
> > Subject: r325691 - [clang-format] New API guessLanguage()
> >
> > Author: benhamilton
> > Date: Wed Feb 21 07:54:31 2018

r325691 - [clang-format] New API guessLanguage()

2018-02-21 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Wed Feb 21 07:54:31 2018
New Revision: 325691

URL: http://llvm.org/viewvc/llvm-project?rev=325691=rev
Log:
[clang-format] New API guessLanguage()

Summary:
For clients which don't have a filesystem, calling getStyle() doesn't
make much sense (there's no .clang-format files to search for).

In this diff, I hoist out the language-guessing logic from getStyle()
and move it into a new API guessLanguage().

I also added support for guessing the language of files which have no
extension (they could be C++ or ObjC).

Test Plan: New tests added. Ran tests with:
  % make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: jolesiak, krasimir

Reviewed By: jolesiak, krasimir

Subscribers: klimek, cfe-commits, sammccall

Differential Revision: https://reviews.llvm.org/D43522

Modified:
cfe/trunk/include/clang/Format/Format.h
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/include/clang/Format/Format.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Format/Format.h?rev=325691=325690=325691=diff
==
--- cfe/trunk/include/clang/Format/Format.h (original)
+++ cfe/trunk/include/clang/Format/Format.h Wed Feb 21 07:54:31 2018
@@ -1981,6 +1981,10 @@ llvm::Expected getStyle(Str
  StringRef Code = "",
  vfs::FileSystem *FS = nullptr);
 
+// \brief Guesses the language from the ``FileName`` and ``Code`` to be 
formatted.
+// Defaults to FormatStyle::LK_Cpp.
+FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code);
+
 // \brief Returns a string representation of ``Language``.
 inline StringRef getLanguageName(FormatStyle::LanguageKind Language) {
   switch (Language) {

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=325691=325690=325691=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Wed Feb 21 07:54:31 2018
@@ -2294,6 +2294,25 @@ static FormatStyle::LanguageKind getLang
   return FormatStyle::LK_Cpp;
 }
 
+FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) {
+  FormatStyle::LanguageKind result = getLanguageByFileName(FileName);
+  if (result == FormatStyle::LK_Cpp) {
+auto extension = llvm::sys::path::extension(FileName);
+// If there's no file extension (or it's .h), we need to check the contents
+// of the code to see if it contains Objective-C.
+if (extension.empty() || extension == ".h") {
+  std::unique_ptr Env =
+  Environment::CreateVirtualEnvironment(Code, FileName, /*Ranges=*/{});
+  ObjCHeaderStyleGuesser Guesser(*Env, getLLVMStyle());
+  Guesser.process();
+  if (Guesser.isObjC()) {
+result = FormatStyle::LK_ObjC;
+  }
+}
+  }
+  return result;
+}
+
 llvm::Expected getStyle(StringRef StyleName, StringRef FileName,
  StringRef FallbackStyleName,
  StringRef Code, vfs::FileSystem *FS) {
@@ -2301,17 +2320,7 @@ llvm::Expected getStyle(Str
 FS = vfs::getRealFileSystem().get();
   }
   FormatStyle Style = getLLVMStyle();
-  Style.Language = getLanguageByFileName(FileName);
-
-  if (Style.Language == FormatStyle::LK_Cpp && FileName.endswith(".h")) {
-std::unique_ptr Env =
-Environment::CreateVirtualEnvironment(Code, FileName, /*Ranges=*/{});
-ObjCHeaderStyleGuesser Guesser(*Env, Style);
-Guesser.process();
-if (Guesser.isObjC()) {
-  Style.Language = FormatStyle::LK_ObjC;
-}
-  }
+  Style.Language = guessLanguage(FileName, Code);
 
   FormatStyle FallbackStyle = getNoStyle();
   if (!getPredefinedStyle(FallbackStyleName, Style.Language, ))

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=325691=325690=325691=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Wed Feb 21 07:54:31 2018
@@ -11952,6 +11952,34 @@ TEST_F(FormatTest, StructuredBindings) {
   verifyFormat("auto const &[ a, b ] = f();", Spaces);
 }
 
+struct GuessLanguageTestCase {
+  const char *const FileName;
+  const char *const Code;
+  const FormatStyle::LanguageKind ExpectedResult;
+};
+
+class GuessLanguageTest
+: public FormatTest,
+  public ::testing::WithParamInterface {};
+
+TEST_P(GuessLanguageTest, FileAndCode) {
+  auto TestCase = GetParam();
+  EXPECT_EQ(TestCase.ExpectedResult,
+guessLanguage(TestCase.FileName, TestCase.Code));
+}
+
+static const GuessLanguageTestCase TestCases[] = {
+{"foo.cc", "", FormatStyle::LK_Cpp},
+{"foo.m", "", 

r324618 - [clang-format] Do not break Objective-C string literals inside array literals

2018-02-08 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Thu Feb  8 08:07:25 2018
New Revision: 324618

URL: http://llvm.org/viewvc/llvm-project?rev=324618=rev
Log:
[clang-format] Do not break Objective-C string literals inside array literals

Summary:
Concatenating Objective-C string literals inside an array literal
raises the warning -Wobjc-string-concatenation (which is enabled by default).

clang-format currently splits and concatenates string literals like
the following:

  NSArray *myArray = @[ @"a" ];

into:

  NSArray *myArray =
@[ @""
   @"a" ];

which raises the warning. This is https://bugs.llvm.org/show_bug.cgi?id=36153 .

The options I can think of to fix this are:

1) Have clang-format disable Wobjc-string-concatenation by emitting
pragmas around the formatted code
2) Have clang-format wrap the string literals in a macro (which
disables the warning)
3) Disable string splitting for Objective-C string literals inside
array literals

I think 1) has no precedent, and I couldn't find a good
identity() macro for 2). So, this diff implements 3).

Test Plan: make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: jolesiak, stephanemoore, djasper

Reviewed By: jolesiak

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D42704

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/lib/Format/ContinuationIndenter.h
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=324618=324617=324618=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Thu Feb  8 08:07:25 2018
@@ -1285,6 +1285,9 @@ void ContinuationIndenter::moveStatePast
   State.Stack.back().NestedBlockIndent = NestedBlockIndent;
   State.Stack.back().BreakBeforeParameter = BreakBeforeParameter;
   State.Stack.back().HasMultipleNestedBlocks = Current.BlockParameterCount > 1;
+  State.Stack.back().IsInsideObjCArrayLiteral =
+  Current.is(TT_ArrayInitializerLSquare) && Current.Previous &&
+  Current.Previous->is(tok::at);
 }
 
 void ContinuationIndenter::moveStatePastScopeCloser(LineState ) {
@@ -1578,6 +1581,11 @@ std::unique_ptr Continua
 // likely want to terminate the string before any line breaking is done.
 if (Current.IsUnterminatedLiteral)
   return nullptr;
+// Don't break string literals inside Objective-C array literals (doing so
+// raises the warning -Wobjc-string-concatenation).
+if (State.Stack.back().IsInsideObjCArrayLiteral) {
+  return nullptr;
+}
 
 StringRef Text = Current.TokenText;
 StringRef Prefix;

Modified: cfe/trunk/lib/Format/ContinuationIndenter.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.h?rev=324618=324617=324618=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.h (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.h Thu Feb  8 08:07:25 2018
@@ -208,7 +208,8 @@ struct ParenState {
 NoLineBreakInOperand(false), LastOperatorWrapped(true),
 ContainsLineBreak(false), ContainsUnwrappedBuilder(false),
 AlignColons(true), ObjCSelectorNameFound(false),
-HasMultipleNestedBlocks(false), NestedBlockInlined(false) {}
+HasMultipleNestedBlocks(false), NestedBlockInlined(false),
+IsInsideObjCArrayLiteral(false) {}
 
   /// \brief The position to which a specific parenthesis level needs to be
   /// indented.
@@ -318,6 +319,10 @@ struct ParenState {
   /// "function" in JavaScript) is not wrapped to a new line.
   bool NestedBlockInlined : 1;
 
+  /// \brief \c true if the current \c ParenState represents an Objective-C
+  /// array literal.
+  bool IsInsideObjCArrayLiteral : 1;
+
   bool operator<(const ParenState ) const {
 if (Indent != Other.Indent)
   return Indent < Other.Indent;

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=324618=324617=324618=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Thu Feb  8 08:07:25 2018
@@ -975,6 +975,12 @@ TEST_F(FormatTestObjC, ObjCArrayLiterals
   verifyFormat("[someFunction someLongParameter:@[\n"
"  NSBundle.mainBundle.infoDictionary[@\"a\"]\n"
"]];");
+  Style.ColumnLimit = 20;
+  // We can't break string literals inside NSArray literals
+  // (that raises -Wobjc-string-concatenation).
+  verifyFormat("NSArray *foo = @[\n"
+   "  

r324553 - [clang-format] Set ObjCBinPackProtocolList to Never for google style

2018-02-07 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Wed Feb  7 17:49:10 2018
New Revision: 324553

URL: http://llvm.org/viewvc/llvm-project?rev=324553=rev
Log:
[clang-format] Set ObjCBinPackProtocolList to Never for google style

Summary:
This is split off from D42650, and sets ObjCBinPackProtocolList
to Never for the google style.

Depends On D42650

Test Plan: New tests added. make -j12 FormatTests && 
./tools/clang/unittests/Format/FormatTests

Reviewers: krasimir, jolesiak, stephanemoore

Reviewed By: krasimir, jolesiak, stephanemoore

Subscribers: klimek, cfe-commits, hokein, Wizard

Differential Revision: https://reviews.llvm.org/D42708

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=324553=324552=324553=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Wed Feb  7 17:49:10 2018
@@ -710,6 +710,7 @@ FormatStyle getGoogleStyle(FormatStyle::
   GoogleStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
   GoogleStyle.IndentCaseLabels = true;
   GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
+  GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
   GoogleStyle.ObjCSpaceAfterProperty = false;
   GoogleStyle.ObjCSpaceBeforeProtocolList = true;
   GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=324553=324552=324553=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Wed Feb  7 17:49:10 2018
@@ -333,13 +333,16 @@ TEST_F(FormatTestObjC, FormatObjCInterfa
   verifyFormat("@interface Foo (HackStuff) \n"
"+ (id)init;\n"
"@end");
-  Style.BinPackParameters = false;
-  Style.ColumnLimit = 80;
-  verifyFormat("@interface a () <\n"
-   "a,\n"
-   ",\n"
-   "aa,\n"
-   "> {\n"
+  Style.ColumnLimit = 40;
+  // BinPackParameters should be true by default.
+  verifyFormat("void (int e, int e,\n"
+   "  int e, int e);\n");
+  // ObjCBinPackProtocolList should be BPS_Never by default.
+  verifyFormat("@interface f () <\n"
+   "f,\n"
+   "f,\n"
+   "f,\n"
+   "f> {\n"
"}");
 }
 


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r324364 - [clang-format] Add more tests for Objective-C 2.0 generic alignment

2018-02-06 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Tue Feb  6 10:01:47 2018
New Revision: 324364

URL: http://llvm.org/viewvc/llvm-project?rev=324364=rev
Log:
[clang-format] Add more tests for Objective-C 2.0 generic alignment

Summary:
In r236412, @djasper added a comment:

// FIXME: We likely want to do this for more combinations of brackets.
// Verify that it is wanted for ObjC, too.

In D42650, @stephanemoore asked me to confirm this.

This followup to D42650 adds more tests to verify the relative
alignment behavior for Objective-C 2.0 generics passed to functions
and removes the second half of the FIXME comment.

Test Plan:
  make -j12 FormatTests && \
  ./tools/clang/unittests/Format/FormatTests --gtest_filter=FormatTestObjC.\*

Reviewers: stephanemoore, jolesiak, djasper

Reviewed By: jolesiak

Subscribers: klimek, cfe-commits, djasper, stephanemoore, krasimir

Differential Revision: https://reviews.llvm.org/D42864

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=324364=324363=324364=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Tue Feb  6 10:01:47 2018
@@ -1211,7 +1211,6 @@ void ContinuationIndenter::moveStatePast
 // void SomeFunction(vector<  // break
 //   int> v);
 // FIXME: We likely want to do this for more combinations of brackets.
-// Verify that it is wanted for ObjC, too.
 if (Current.is(tok::less) && Current.ParentBracket == tok::l_paren) {
   NewIndent = std::max(NewIndent, State.Stack.back().Indent);
   LastSpace = std::max(LastSpace, State.Stack.back().Indent);

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=324364=324363=324364=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Tue Feb  6 10:01:47 2018
@@ -189,6 +189,17 @@ TEST_F(FormatTestObjC, FormatObjCAutorel
"}\n");
 }
 
+TEST_F(FormatTestObjC, FormatObjCGenerics) {
+  Style.ColumnLimit = 40;
+  verifyFormat("int (\n"
+   "NSArray\n"
+   "a);\n");
+  verifyFormat("int (\n"
+   "NSArray *>\n"
+   "a);\n");
+}
+
 TEST_F(FormatTestObjC, FormatObjCInterface) {
   verifyFormat("@interface Foo : NSObject  {\n"
"@public\n"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r324131 - [clang-format] New format param ObjCBinPackProtocolList

2018-02-02 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Fri Feb  2 12:15:14 2018
New Revision: 324131

URL: http://llvm.org/viewvc/llvm-project?rev=324131=rev
Log:
[clang-format] New format param ObjCBinPackProtocolList

Summary:
This is an alternative approach to D42014 after some
investigation by stephanemoore@ and myself.

Previously, the format parameter `BinPackParameters` controlled both
C function parameter list bin-packing and Objective-C protocol conformance
list bin-packing.

We found in the Google style, some teams were changing
`BinPackParameters` from its default (`true`) to `false` so they could
lay out Objective-C protocol conformance list items one-per-line
instead of bin-packing them into as few lines as possible.

To allow teams to use one-per-line Objective-C protocol lists without
changing bin-packing for other areas like C function parameter lists,
this diff introduces a new LibFormat parameter
`ObjCBinPackProtocolList` to control the behavior just for ObjC
protocol conformance lists.

The new parameter is an enum which defaults to `Auto` to keep the
previous behavior (delegating to `BinPackParameters`).

Depends On D42649

Test Plan: New tests added. make -j12 FormatTests && 
./tools/clang/unittests/Format/FormatTests

Reviewers: jolesiak, stephanemoore, djasper

Reviewed By: stephanemoore

Subscribers: Wizard, hokein, cfe-commits, klimek

Differential Revision: https://reviews.llvm.org/D42650

Modified:
cfe/trunk/include/clang/Format/Format.h
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/include/clang/Format/Format.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Format/Format.h?rev=324131=324130=324131=diff
==
--- cfe/trunk/include/clang/Format/Format.h (original)
+++ cfe/trunk/include/clang/Format/Format.h Fri Feb  2 12:15:14 2018
@@ -390,6 +390,17 @@ struct FormatStyle {
   /// \endcode
   bool BinPackParameters;
 
+  /// \brief The style of wrapping parameters on the same line (bin-packed) or
+  /// on one line each.
+  enum BinPackStyle {
+/// Automatically determine parameter bin-packing behavior.
+BPS_Auto,
+/// Always bin-pack parameters.
+BPS_Always,
+/// Never bin-pack parameters.
+BPS_Never,
+  };
+
   /// \brief The style of breaking before or after binary operators.
   enum BinaryOperatorStyle {
 /// Break after operators.
@@ -1299,6 +1310,38 @@ struct FormatStyle {
   /// \brief The indentation used for namespaces.
   NamespaceIndentationKind NamespaceIndentation;
 
+  /// \brief Controls bin-packing Objective-C protocol conformance list
+  /// items into as few lines as possible when they go over ``ColumnLimit``.
+  ///
+  /// If ``Auto`` (the default), delegates to the value in
+  /// ``BinPackParameters``. If that is ``true``, bin-packs Objective-C
+  /// protocol conformance list items into as few lines as possible
+  /// whenever they go over ``ColumnLimit``.
+  ///
+  /// If ``Always``, always bin-packs Objective-C protocol conformance
+  /// list items into as few lines as possible whenever they go over
+  /// ``ColumnLimit``.
+  ///
+  /// If ``Never``, lays out Objective-C protocol conformance list items
+  /// onto individual lines whenever they go over ``ColumnLimit``.
+  ///
+  /// \code
+  ///Always (or Auto, if BinPackParameters=true):
+  ///@interface c () <
+  ///c, c,
+  ///c, c> {
+  ///}
+  ///
+  ///Never (or Auto, if BinPackParameters=false):
+  ///@interface d () <
+  ///d,
+  ///d,
+  ///d,
+  ///d> {
+  ///}
+  /// \endcode
+  BinPackStyle ObjCBinPackProtocolList;
+
   /// \brief The number of characters to use for indentation of ObjC blocks.
   /// \code{.objc}
   ///ObjCBlockIndentWidth: 4
@@ -1681,6 +1724,7 @@ struct FormatStyle {
MacroBlockEnd == R.MacroBlockEnd &&
MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
NamespaceIndentation == R.NamespaceIndentation &&
+   ObjCBinPackProtocolList == R.ObjCBinPackProtocolList &&
ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=324131=324130=324131=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Fri Feb  2 12:15:14 2018
@@ -1222,9 +1222,20 @@ void ContinuationIndenter::moveStatePast
 

[clang-tools-extra] r324097 - [clang-tidy] ObjC ARC objects should not trigger performance-unnecessary-value-param

2018-02-02 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Fri Feb  2 07:34:33 2018
New Revision: 324097

URL: http://llvm.org/viewvc/llvm-project?rev=324097=rev
Log:
[clang-tidy] ObjC ARC objects should not trigger 
performance-unnecessary-value-param

Summary:
The following Objective-C code currently incorrectly triggers
clang-tidy's performance-unnecessary-value-param check:

```
% cat /tmp/performance-unnecessary-value-param-arc.m
void foo(id object) { }

clang-tidy /tmp/performance-unnecessary-value-param-arc.m
-checks=-\*,performance-unnecessary-value-param -- -xobjective-c
-fobjc-abi-version=2 -fobjc-arc
1 warning generated.
/src/llvm/tools/clang/tools/extra/test/clang-tidy/performance-unnecessary-value-param-arc.m:10:13:
warning: the parameter 'object' is copied for each invocation but only
used as a const reference; consider making it a const reference
[performance-unnecessary-value-param]
void foo(id object) { }
 ~~ ^
 const &
```

This is wrong for a few reasons:

1) Objective-C doesn't have references, so `const &` is not going to help
2) ARC heavily optimizes the "expensive" copy which triggers the warning

This fixes the issue by disabling the warning for non-C++, as well as
disabling it for objects under ARC memory management for
Objective-C++.

Fixes https://bugs.llvm.org/show_bug.cgi?id=32075

Test Plan: New tests added. Ran tests with `make -j12 check-clang-tools`.

Reviewers: alexfh, hokein

Reviewed By: hokein

Subscribers: stephanemoore, klimek, xazax.hun, cfe-commits, Wizard

Differential Revision: https://reviews.llvm.org/D42812

Added:

clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-arc.m

clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-arc.mm
Modified:

clang-tools-extra/trunk/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
clang-tools-extra/trunk/clang-tidy/utils/TypeTraits.cpp

Modified: 
clang-tools-extra/trunk/clang-tidy/performance/UnnecessaryValueParamCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/performance/UnnecessaryValueParamCheck.cpp?rev=324097=324096=324097=diff
==
--- 
clang-tools-extra/trunk/clang-tidy/performance/UnnecessaryValueParamCheck.cpp 
(original)
+++ 
clang-tools-extra/trunk/clang-tidy/performance/UnnecessaryValueParamCheck.cpp 
Fri Feb  2 07:34:33 2018
@@ -79,6 +79,10 @@ UnnecessaryValueParamCheck::UnnecessaryV
   Options.getLocalOrGlobal("IncludeStyle", "llvm"))) {}
 
 void UnnecessaryValueParamCheck::registerMatchers(MatchFinder *Finder) {
+  // This check is specific to C++ and doesn't apply to languages like
+  // Objective-C.
+  if (!getLangOpts().CPlusPlus)
+return;
   const auto ExpensiveValueParamDecl =
   parmVarDecl(hasType(hasCanonicalType(allOf(
   unless(referenceType()), 
matchers::isExpensiveToCopy(,

Modified: clang-tools-extra/trunk/clang-tidy/utils/TypeTraits.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/utils/TypeTraits.cpp?rev=324097=324096=324097=diff
==
--- clang-tools-extra/trunk/clang-tidy/utils/TypeTraits.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/utils/TypeTraits.cpp Fri Feb  2 07:34:33 
2018
@@ -45,7 +45,8 @@ llvm::Optional isExpensiveToCopy(Q
 return llvm::None;
   return !Type.isTriviallyCopyableType(Context) &&
  !classHasTrivialCopyAndDestroy(Type) &&
- !hasDeletedCopyConstructor(Type);
+ !hasDeletedCopyConstructor(Type) &&
+ !Type->isObjCLifetimeType();
 }
 
 bool recordIsTriviallyDefaultConstructible(const RecordDecl ,

Added: 
clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-arc.m
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-arc.m?rev=324097=auto
==
--- 
clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-arc.m
 (added)
+++ 
clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-arc.m
 Fri Feb  2 07:34:33 2018
@@ -0,0 +1,16 @@
+// RUN: clang-tidy %s -checks=-*,performance-unnecessary-value-param -- \
+// RUN:   -xobjective-c -fobjc-abi-version=2 -fobjc-arc | count 0
+
+#if !__has_feature(objc_arc)
+#error Objective-C ARC not enabled as expected
+#endif
+
+// Passing an Objective-C ARC-managed object to a C function should
+// not raise performance-unnecessary-value-param.
+void foo(id object) { }
+
+// Same for explcitly non-ARC-managed Objective-C objects.
+void bar(__unsafe_unretained id object) { }
+
+// Same for Objective-c classes.
+void baz(Class c) { }

Added: 
clang-tools-extra/trunk/test/clang-tidy/performance-unnecessary-value-param-arc.mm
URL: 

[clang-tools-extra] r323919 - [clang-tidy] New argument --language to add_new_check.py

2018-01-31 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Wed Jan 31 13:52:39 2018
New Revision: 323919

URL: http://llvm.org/viewvc/llvm-project?rev=323919=rev
Log:
[clang-tidy] New argument --language to add_new_check.py

Summary:
Currently, add_new_check.py assumes all checks are for C++ code.

This adds a new argument --language=[LANG] to add_new_check.py
so authors of new checks can specify that the test file should
be in a different language.

For example, authors can pass --language=objc for Objective-C
clang-tidy checks.

Reviewers: hokein, alexfh

Reviewed By: alexfh

Subscribers: Wizard, xazax.hun

Differential Revision: https://reviews.llvm.org/D39141

Modified:
clang-tools-extra/trunk/clang-tidy/add_new_check.py

Modified: clang-tools-extra/trunk/clang-tidy/add_new_check.py
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/add_new_check.py?rev=323919=323918=323919=diff
==
--- clang-tools-extra/trunk/clang-tidy/add_new_check.py (original)
+++ clang-tools-extra/trunk/clang-tidy/add_new_check.py Wed Jan 31 13:52:39 2018
@@ -9,6 +9,7 @@
 #
 
#======#
 
+import argparse
 import os
 import re
 import sys
@@ -221,10 +222,10 @@ def add_release_notes(module_path, modul
 
 
 # Adds a test for the check.
-def write_test(module_path, module, check_name):
+def write_test(module_path, module, check_name, test_extension):
   check_name_dashes = module + '-' + check_name
   filename = os.path.normpath(os.path.join(module_path, 
'../../test/clang-tidy',
-   check_name_dashes + '.cpp'))
+   check_name_dashes + '.' + 
test_extension))
   print('Creating %s...' % filename)
   with open(filename, 'wb') as f:
 f.write("""// RUN: %%check_clang_tidy %%s %(check_name_dashes)s %%t
@@ -300,22 +301,37 @@ FIXME: Describe what patterns does the c
 
 
 def main():
-  if len(sys.argv) == 2 and sys.argv[1] == '--update-docs':
-update_checks_list(os.path.dirname(sys.argv[0]))
-return
-
-  if len(sys.argv) != 3:
-print """\
-Usage: add_new_check.py  , e.g.
-  add_new_check.py misc awesome-functions
-
-Alternatively, run 'add_new_check.py --update-docs' to just update the list of
-documentation files."""
+  language_to_extension = {
+  'c': 'c',
+  'c++': 'cpp',
+  'objc': 'm',
+  'objc++': 'mm',
+  }
+  parser = argparse.ArgumentParser()
+  parser.add_argument(
+  '--update-docs',
+  action='store_true',
+  help='just update the list of documentation files, then exit')
+  parser.add_argument(
+  '--language',
+  help='language to use for new check (defaults to c++)',
+  choices=language_to_extension.keys(),
+  default='c++',
+  metavar='LANG')
+  parser.add_argument(
+  'module',
+  help='module directory under which to place the new tidy check (e.g., 
misc)')
+  parser.add_argument(
+  'check',
+  help='name of new tidy check to add (e.g. foo-do-the-stuff)')
+  args = parser.parse_args()
 
+  if args.update_docs:
+update_checks_list(os.path.dirname(sys.argv[0]))
 return
 
-  module = sys.argv[1]
-  check_name = sys.argv[2]
+  module = args.module
+  check_name = args.check
 
   if check_name.startswith(module):
 print 'Check name "%s" must not start with the module "%s". Exiting.' % (
@@ -332,7 +348,8 @@ documentation files."""
   write_implementation(module_path, module, check_name_camel)
   adapt_module(module_path, module, check_name, check_name_camel)
   add_release_notes(module_path, module, check_name)
-  write_test(module_path, module, check_name)
+  test_extension = language_to_extension.get(args.language)
+  write_test(module_path, module, check_name, test_extension)
   write_docs(module_path, module, check_name)
   update_checks_list(clang_tidy_path)
   print('Done. Now it\'s your turn!')


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r323684 - [clang-format] Add more tests for ObjC protocol list formatting behavior

2018-01-29 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Mon Jan 29 12:01:49 2018
New Revision: 323684

URL: http://llvm.org/viewvc/llvm-project?rev=323684=rev
Log:
[clang-format] Add more tests for ObjC protocol list formatting behavior

Summary:
The existing unit tests in FormatTestObjC.cpp didn't fully cover
all the cases for protocol confirmance list formatting.

This extends the unit tests to more cases of protocol
conformance list formatting, especially how the behavior changes
when `BinPackParameters` changes from `true` (the default) to `false`.

Test Plan: make -j12 FormatTests && \
  ./tools/clang/unittests/Format/FormatTests --gtest_filter=FormatTestObjC.\*

Reviewers: krasimir, jolesiak, stephanemoore

Reviewed By: krasimir

Subscribers: benhamilton, klimek, cfe-commits, hokein, Wizard

Differential Revision: https://reviews.llvm.org/D42649

Modified:
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=323684=323683=323684=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Mon Jan 29 12:01:49 2018
@@ -276,6 +276,20 @@ TEST_F(FormatTestObjC, FormatObjCInterfa
"+ (id)init;\n"
"@end");
 
+  Style.ColumnLimit = 40;
+  verifyFormat("@interface c () <\n"
+   "c, c,\n"
+   "c, c> {\n"
+   "}");
+
+  Style.BinPackParameters = false;
+  verifyFormat("@interface d () <\n"
+   "d,\n"
+   "d,\n"
+   "d,\n"
+   "d> {\n"
+   "}");
+
   Style = getGoogleStyle(FormatStyle::LK_ObjC);
   verifyFormat("@interface Foo : NSObject  {\n"
" @public\n"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r323668 - [clang-format] Fix bug where -dump-config failed on ObjC header

2018-01-29 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Mon Jan 29 09:36:43 2018
New Revision: 323668

URL: http://llvm.org/viewvc/llvm-project?rev=323668=rev
Log:
[clang-format] Fix bug where -dump-config failed on ObjC header

Summary:
`clang-format -dump-config path/to/file.h` never passed
anything for the Code parameter to clang::format::getStyle().

This meant the logic to guess Objective-C from the contents
of a .h file never worked, because LibFormat didn't have the
code to work with.

With this fix, we now correctly read in the contents of the
file if possible with -dump-config.

I had to update the lit config for test/Format/ because
the default config ignores .h files.

Test Plan: make -j12 check-clang

Reviewers: jolesiak, krasimir

Reviewed By: jolesiak, krasimir

Subscribers: Wizard, klimek, cfe-commits, djasper

Differential Revision: https://reviews.llvm.org/D42395

Added:
cfe/trunk/test/Format/dump-config-cxx.h
cfe/trunk/test/Format/dump-config-objc.h
cfe/trunk/test/Format/lit.local.cfg
Modified:
cfe/trunk/tools/clang-format/ClangFormat.cpp

Added: cfe/trunk/test/Format/dump-config-cxx.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Format/dump-config-cxx.h?rev=323668=auto
==
--- cfe/trunk/test/Format/dump-config-cxx.h (added)
+++ cfe/trunk/test/Format/dump-config-cxx.h Mon Jan 29 09:36:43 2018
@@ -0,0 +1,3 @@
+// RUN: clang-format -dump-config %s | FileCheck %s
+
+// CHECK: Language: Cpp

Added: cfe/trunk/test/Format/dump-config-objc.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Format/dump-config-objc.h?rev=323668=auto
==
--- cfe/trunk/test/Format/dump-config-objc.h (added)
+++ cfe/trunk/test/Format/dump-config-objc.h Mon Jan 29 09:36:43 2018
@@ -0,0 +1,5 @@
+// RUN: clang-format -dump-config %s | FileCheck %s
+
+// CHECK: Language: ObjC
+@interface Foo
+@end

Added: cfe/trunk/test/Format/lit.local.cfg
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Format/lit.local.cfg?rev=323668=auto
==
--- cfe/trunk/test/Format/lit.local.cfg (added)
+++ cfe/trunk/test/Format/lit.local.cfg Mon Jan 29 09:36:43 2018
@@ -0,0 +1,4 @@
+# Suffixes supported by clang-format.
+config.suffixes = ['.c', '.cc', '.cpp', '.h', '.m', '.mm', '.java', '.js',
+   '.ts', '.proto', '.protodevel', '.pb.txt', '.textproto',
+   '.textpb', '.asciipb', '.td']

Modified: cfe/trunk/tools/clang-format/ClangFormat.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-format/ClangFormat.cpp?rev=323668=323667=323668=diff
==
--- cfe/trunk/tools/clang-format/ClangFormat.cpp (original)
+++ cfe/trunk/tools/clang-format/ClangFormat.cpp Mon Jan 29 09:36:43 2018
@@ -357,10 +357,27 @@ int main(int argc, const char **argv) {
   }
 
   if (DumpConfig) {
+StringRef FileName;
+std::unique_ptr Code;
+if (FileNames.empty()) {
+  // We can't read the code to detect the language if there's no
+  // file name, so leave Code empty here.
+  FileName = AssumeFileName;
+} else {
+  // Read in the code in case the filename alone isn't enough to
+  // detect the language.
+  ErrorOr CodeOrErr =
+  MemoryBuffer::getFileOrSTDIN(FileNames[0]);
+  if (std::error_code EC = CodeOrErr.getError()) {
+llvm::errs() << EC.message() << "\n";
+return 1;
+  }
+  FileName = (FileNames[0] == "-") ? AssumeFileName : FileNames[0];
+  Code = std::move(CodeOrErr.get());
+}
 llvm::Expected FormatStyle =
-clang::format::getStyle(
-Style, FileNames.empty() ? AssumeFileName : FileNames[0],
-FallbackStyle);
+clang::format::getStyle(Style, FileName, FallbackStyle,
+Code ? Code->getBuffer() : "");
 if (!FormatStyle) {
   llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
   return 1;


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: [PATCH] D42395: [clang-format] Fix bug where -dump-config failed on ObjC header

2018-01-26 Thread Ben Hamilton via cfe-commits
It's needed because otherwise lit ignores the .h file, which is the
configuration specified in the lit config in the parent directory.

On Fri, Jan 26, 2018, 01:55 Krasimir Georgiev via Phabricator <
revi...@reviews.llvm.org> wrote:

> krasimir requested changes to this revision.
> krasimir added inline comments.
> This revision now requires changes to proceed.
>
>
> 
> Comment at: test/Format/lit.local.cfg:1
> +# Suffixes supported by clang-format.
> +config.suffixes = ['.c', '.cc', '.cpp', '.h', '.m', '.mm', '.java', '.js',
> 
> Why is this needed?
>
>
> Repository:
>   rC Clang
>
> https://reviews.llvm.org/D42395
>
>
>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: Please subscribe "rUNW libunwind" to cfe-commits.

2018-01-25 Thread Ben Hamilton via cfe-commits
Yes, that's currently a submit time feature built in to Phabricator which i
believe we'll have to fix upstream.

Because both the top level LLVM SVN report and the sub repos see the same
files, Phabricator automatically subscribes both lists to the commits.

I wasn't able to find an easy way to disable this feature. If you can find
one, please let me know! (I was punting in hopes the migration to git would
happen first.)

On Thu, Jan 25, 2018 at 11:01 AM Don Hinton  wrote:

> Btw, I'm seeing other inconsistencies, e.g., I just committed
> https://reviews.llvm.org/D42460 and herald ended up adding both
> cfe-commits and llvm-commits to subscribers.
>
> When I created it, I left subscribers blank, so herald added cfe-commits
> -- which seems to be correct.
> Then, when I committed it, herald added llvm-commits -- which doesn't seem
> correct.
>
>
>
> On Thu, Jan 25, 2018 at 10:04 AM, Don Hinton  wrote:
>
>> Thanks Ben...
>>
>> On Thu, Jan 25, 2018 at 9:53 AM, Ben Hamilton 
>> wrote:
>>
>>> Ah, I see from
>>> http://bcain-llvm.readthedocs.io/projects/libunwind/en/latest/ that
>>> libunwind review discussion does take place on cfe-commits.
>>>
>>> Added. Sorry about not doing that earlier!
>>>
>>> Ben
>>>
>>> On Thu, Jan 25, 2018 at 8:37 AM Ben Hamilton 
>>> wrote:
>>>
 Great question. Is there an existing separate list for libunwind?

 If libunwind discussion already happens on cfe-commits, then I'll make
 reviews for libunwind subscribe that list.

 On Tue, Jan 23, 2018, 21:40 Don Hinton  wrote:

> Currently, herald doesn't subscribe libunwind to any group.  Should it
> be added to cfe-commits?
>
>   https://reviews.llvm.org/H268
>

>>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: Please subscribe "rUNW libunwind" to cfe-commits.

2018-01-25 Thread Ben Hamilton via cfe-commits
Ah, I see from
http://bcain-llvm.readthedocs.io/projects/libunwind/en/latest/ that
libunwind review discussion does take place on cfe-commits.

Added. Sorry about not doing that earlier!

Ben

On Thu, Jan 25, 2018 at 8:37 AM Ben Hamilton  wrote:

> Great question. Is there an existing separate list for libunwind?
>
> If libunwind discussion already happens on cfe-commits, then I'll make
> reviews for libunwind subscribe that list.
>
> On Tue, Jan 23, 2018, 21:40 Don Hinton  wrote:
>
>> Currently, herald doesn't subscribe libunwind to any group.  Should it be
>> added to cfe-commits?
>>
>>   https://reviews.llvm.org/H268
>>
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


Re: Please subscribe "rUNW libunwind" to cfe-commits.

2018-01-25 Thread Ben Hamilton via cfe-commits
Great question. Is there an existing separate list for libunwind?

If libunwind discussion already happens on cfe-commits, then I'll make
reviews for libunwind subscribe that list.

On Tue, Jan 23, 2018, 21:40 Don Hinton  wrote:

> Currently, herald doesn't subscribe libunwind to any group.  Should it be
> added to cfe-commits?
>
>   https://reviews.llvm.org/H268
>
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r323130 - [clang-tidy objc-property-declaration] New option IncludeDefaultAcronyms

2018-01-22 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Mon Jan 22 07:45:25 2018
New Revision: 323130

URL: http://llvm.org/viewvc/llvm-project?rev=323130=rev
Log:
[clang-tidy objc-property-declaration] New option IncludeDefaultAcronyms

Summary:
The existing option objc-property-declaration.Acronyms
replaces the built-in set of acronyms.

While this behavior is OK for clients that don't want the default
behavior, many clients may just want to add their own custom acronyms
to the default list.

This revision introduces a new option,
objc-property-declaration.IncludeDefaultAcronyms, which controls
whether the acronyms in objc-property-declaration.Acronyms are
appended to the default list (the default behavior) or whether they
replace.

I also updated the documentation.

Test Plan: make -j12 check-clang-tools

Reviewers: Wizard, hokein, klimek

Reviewed By: hokein

Subscribers: Eugene.Zelenko, cfe-commits

Differential Revision: https://reviews.llvm.org/D42261

Added:

clang-tools-extra/trunk/test/clang-tidy/objc-property-declaration-additional.m
  - copied, changed from r323112, 
clang-tools-extra/trunk/test/clang-tidy/objc-property-declaration-custom.m
Modified:
clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp
clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.h
clang-tools-extra/trunk/docs/clang-tidy/checks/objc-property-declaration.rst
clang-tools-extra/trunk/test/clang-tidy/objc-property-declaration-custom.m

Modified: clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp?rev=323130=323129=323130=diff
==
--- clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp Mon 
Jan 22 07:45:25 2018
@@ -11,6 +11,7 @@
 #include "../utils/OptionsUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/Support/Regex.h"
 #include 
@@ -26,61 +27,62 @@ namespace {
 /// 
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/APIAbbreviations.html#//apple_ref/doc/uid/20001285-BCIHCGAE
 ///
 /// Keep this list sorted.
-constexpr char DefaultSpecialAcronyms[] =
-"ACL;"
-"API;"
-"ARGB;"
-"ASCII;"
-"BGRA;"
-"CMYK;"
-"DNS;"
-"FPS;"
-"FTP;"
-"GIF;"
-"GPS;"
-"HD;"
-"HDR;"
-"HTML;"
-"HTTP;"
-"HTTPS;"
-"HUD;"
-"ID;"
-"JPG;"
-"JS;"
-"LAN;"
-"LZW;"
-"MDNS;"
-"MIDI;"
-"OS;"
-"PDF;"
-"PIN;"
-"PNG;"
-"POI;"
-"PSTN;"
-"PTR;"
-"QA;"
-"QOS;"
-"RGB;"
-"RGBA;"
-"RGBX;"
-"ROM;"
-"RPC;"
-"RTF;"
-"RTL;"
-"SDK;"
-"SSO;"
-"TCP;"
-"TIFF;"
-"TTS;"
-"UI;"
-"URI;"
-"URL;"
-"VC;"
-"VOIP;"
-"VPN;"
-"VR;"
-"WAN;"
-"XML";
+constexpr llvm::StringLiteral DefaultSpecialAcronyms[] = {
+"ACL",
+"API",
+"ARGB",
+"ASCII",
+"BGRA",
+"CMYK",
+"DNS",
+"FPS",
+"FTP",
+"GIF",
+"GPS",
+"HD",
+"HDR",
+"HTML",
+"HTTP",
+"HTTPS",
+"HUD",
+"ID",
+"JPG",
+"JS",
+"LAN",
+"LZW",
+"MDNS",
+"MIDI",
+"OS",
+"PDF",
+"PIN",
+"PNG",
+"POI",
+"PSTN",
+"PTR",
+"QA",
+"QOS",
+"RGB",
+"RGBA",
+"RGBX",
+"ROM",
+"RPC",
+"RTF",
+"RTL",
+"SDK",
+"SSO",
+"TCP",
+"TIFF",
+"TTS",
+"UI",
+"URI",
+"URL",
+"VC",
+"VOIP",
+"VPN",
+"VR",
+"WAN",
+"XML",
+};
 
 /// For now we will only fix 'CamelCase' property to
 /// 'camelCase'. For other cases the users need to
@@ -97,14 +99,7 @@ FixItHint generateFixItHint(const ObjCPr
   return FixItHint();
 }
 
-std::string validPropertyNameRegex(const std::vector ) {
-  std::vector EscapedAcronyms;
-  EscapedAcronyms.reserve(Acronyms.size());
-  // In case someone defines a custom prefix which includes a regex
-  // special character, escape all the prefixes.
-  std::transform(Acronyms.begin(), Acronyms.end(),
- std::back_inserter(EscapedAcronyms), [](const std::string& s) 
{
-   return llvm::Regex::escape(s); });
+std::string validPropertyNameRegex(const std::vector 
) {
   // Allow any of these names:
   // foo
   // fooBar
@@ -123,15 +118,32 @@ std::string validPropertyNameRegex(const
 PropertyDeclarationCheck::PropertyDeclarationCheck(StringRef Name,
ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
-  SpecialAcronyms(utils::options::parseStringList(
-  Options.get("Acronyms", DefaultSpecialAcronyms))) {}
+  SpecialAcronyms(
+ 

[clang-tools-extra] r322886 - [clang-tidy objc-property-declaration] Expand list of ObjC acronyms

2018-01-18 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Thu Jan 18 12:51:24 2018
New Revision: 322886

URL: http://llvm.org/viewvc/llvm-project?rev=322886=rev
Log:
[clang-tidy objc-property-declaration] Expand list of ObjC acronyms

Summary:
We were missing some pretty common acronyms in the camelCase
property name check objc-property-declaration.

This expands the list and sorts it lexicographically, so we can
avoid duplicates.

Test Plan: make -j12 check-clang-tools

Reviewers: Wizard, hokein, klimek

Reviewed By: Wizard

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D42253

Modified:
clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp
clang-tools-extra/trunk/docs/clang-tidy/checks/objc-property-declaration.rst
clang-tools-extra/trunk/test/clang-tidy/objc-property-declaration.m

Modified: clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp?rev=322886=322885=322886=diff
==
--- clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp Thu 
Jan 18 12:51:24 2018
@@ -24,25 +24,63 @@ namespace objc {
 namespace {
 /// The acronyms are from
 /// 
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/APIAbbreviations.html#//apple_ref/doc/uid/20001285-BCIHCGAE
+///
+/// Keep this list sorted.
 constexpr char DefaultSpecialAcronyms[] =
+"ACL;"
+"API;"
+"ARGB;"
 "ASCII;"
-"PDF;"
-"XML;"
+"BGRA;"
+"CMYK;"
+"DNS;"
+"FPS;"
+"FTP;"
+"GIF;"
+"GPS;"
+"HD;"
+"HDR;"
 "HTML;"
-"URL;"
-"RTF;"
 "HTTP;"
-"TIFF;"
+"HTTPS;"
+"HUD;"
+"ID;"
 "JPG;"
-"PNG;"
-"GIF;"
+"JS;"
+"LAN;"
 "LZW;"
-"ROM;"
-"RGB;"
-"CMYK;"
+"MDNS;"
 "MIDI;"
-"FTP;"
-"ID";
+"OS;"
+"PDF;"
+"PIN;"
+"PNG;"
+"POI;"
+"PSTN;"
+"PTR;"
+"QA;"
+"QOS;"
+"RGB;"
+"RGBA;"
+"RGBX;"
+"ROM;"
+"RPC;"
+"RTF;"
+"RTL;"
+"SDK;"
+"SSO;"
+"TCP;"
+"TIFF;"
+"TTS;"
+"UI;"
+"URI;"
+"URL;"
+"VC;"
+"VOIP;"
+"VPN;"
+"VR;"
+"WAN;"
+"XML";
 
 /// For now we will only fix 'CamelCase' property to
 /// 'camelCase'. For other cases the users need to

Modified: 
clang-tools-extra/trunk/docs/clang-tidy/checks/objc-property-declaration.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/objc-property-declaration.rst?rev=322886=322885=322886=diff
==
--- 
clang-tools-extra/trunk/docs/clang-tidy/checks/objc-property-declaration.rst 
(original)
+++ 
clang-tools-extra/trunk/docs/clang-tidy/checks/objc-property-declaration.rst 
Thu Jan 18 12:51:24 2018
@@ -23,8 +23,8 @@ The check will only fix 'CamelCase' to '
 only provide warning messages since the property name could be complicated.
 Users will need to come up with a proper name by their own.
 
-This check also accepts special acronyms as prefix. Such prefix will suppress
-the check of Lower Camel Case according to the guide:
+This check also accepts special acronyms as prefixes or suffixes. Such 
prefixes or suffixes
+will suppress the Lower Camel Case check according to the guide:
 
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingBasics.html#//apple_ref/doc/uid/20001281-1002931-BBCFHEAB
 
 For a full list of well-known acronyms:
@@ -37,7 +37,7 @@ Options
 
 .. option:: Acronyms
 
-   Semicolon-separated list of acronyms that can be used as prefix
-   of property names.
+   Semicolon-separated list of acronyms that can be used as a prefix
+   or a suffix of property names.
 
-   Defaults to 
`ASCII;PDF;XML;HTML;URL;RTF;HTTP;TIFF;JPG;PNG;GIF;LZW;ROM;RGB;CMYK;MIDI;FTP`.
+   If unset, defaults to 
"ACL;API;ARGB;ASCII;BGRA;CMYK;DNS;FPS;FTP;GIF;GPS;HD;HDR;HTML;HTTP;HTTPS;HUD;ID;JPG;JS;LAN;LZW;MDNS;MIDI;OS;PDF;PIN;PNG;POI;PSTN;PTR;QA;QOS;RGB;RGBA;RGBX;ROM;RPC;RTF;RTL;SDK;SSO;TCP;TIFF;TTS;UI;URI;URL;VC;VOIP;VPN;VR;WAN;XML".

Modified: clang-tools-extra/trunk/test/clang-tidy/objc-property-declaration.m
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/objc-property-declaration.m?rev=322886=322885=322886=diff
==
--- clang-tools-extra/trunk/test/clang-tidy/objc-property-declaration.m 
(original)
+++ clang-tools-extra/trunk/test/clang-tidy/objc-property-declaration.m Thu Jan 
18 12:51:24 2018
@@ -1,5 +1,7 @@
 // RUN: %check_clang_tidy %s objc-property-declaration %t
+@class NSData;
 @class NSString;
+@class UIViewController;
 
 @interface Foo
 

r322873 - [ClangFormat] ObjCSpaceBeforeProtocolList should be true in the google style

2018-01-18 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Thu Jan 18 10:37:16 2018
New Revision: 322873

URL: http://llvm.org/viewvc/llvm-project?rev=322873=rev
Log:
[ClangFormat] ObjCSpaceBeforeProtocolList should be true in the google style

Summary:
The Google style guide is neutral on whether there should be a
space before the protocol list in an Objective-C @interface or
@implementation.

The majority of Objective-C code in both Apple's public
header files and Google's open-source uses a space before
the protocol list, so this changes the google style to
default ObjCSpaceBeforeProtocolList to true.

Test Plan: make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: krasimir, djasper, klimek

Reviewed By: krasimir

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D41074

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=322873=322872=322873=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Thu Jan 18 10:37:16 2018
@@ -694,7 +694,7 @@ FormatStyle getGoogleStyle(FormatStyle::
   GoogleStyle.IndentCaseLabels = true;
   GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
   GoogleStyle.ObjCSpaceAfterProperty = false;
-  GoogleStyle.ObjCSpaceBeforeProtocolList = false;
+  GoogleStyle.ObjCSpaceBeforeProtocolList = true;
   GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
   GoogleStyle.RawStringFormats = {{
   FormatStyle::LK_TextProto,

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=322873=322872=322873=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Thu Jan 18 10:37:16 2018
@@ -271,7 +271,7 @@ TEST_F(FormatTestObjC, FormatObjCInterfa
"@end");
 
   Style = getGoogleStyle(FormatStyle::LK_ObjC);
-  verifyFormat("@interface Foo : NSObject {\n"
+  verifyFormat("@interface Foo : NSObject  {\n"
" @public\n"
"  int field1;\n"
" @protected\n"
@@ -283,15 +283,15 @@ TEST_F(FormatTestObjC, FormatObjCInterfa
"}\n"
"+ (id)init;\n"
"@end");
-  verifyFormat("@interface Foo : Bar\n"
+  verifyFormat("@interface Foo : Bar \n"
"+ (id)init;\n"
"@end");
-  verifyFormat("@interface Foo (HackStuff)\n"
+  verifyFormat("@interface Foo (HackStuff) \n"
"+ (id)init;\n"
"@end");
   Style.BinPackParameters = false;
   Style.ColumnLimit = 80;
-  verifyFormat("@interface a ()<\n"
+  verifyFormat("@interface a () <\n"
"a,\n"
",\n"
"aa,\n"
@@ -414,7 +414,7 @@ TEST_F(FormatTestObjC, FormatObjCProtoco
"@end");
 
   Style = getGoogleStyle(FormatStyle::LK_ObjC);
-  verifyFormat("@protocol MyProtocol\n"
+  verifyFormat("@protocol MyProtocol \n"
"- (NSUInteger)numberOfThings;\n"
"@end");
 }


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r322690 - [Format] Improve ObjC header guessing heuristic

2018-01-17 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Wed Jan 17 09:33:08 2018
New Revision: 322690

URL: http://llvm.org/viewvc/llvm-project?rev=322690=rev
Log:
[Format] Improve ObjC header guessing heuristic

Summary:
This improves upon the previous Objective-C header guessing heuristic
from rC320479.

Now, we run the lexer on C++ header files and look for Objective-C
keywords and syntax. We also look for Foundation types.

Test Plan: make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: jolesiak, krasimir

Reviewed By: jolesiak

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D42135

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=322690=322689=322690=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Wed Jan 17 09:33:08 2018
@@ -32,6 +32,7 @@
 #include "clang/Basic/VirtualFileSystem.h"
 #include "clang/Lex/Lexer.h"
 #include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/StringRef.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/Path.h"
@@ -40,6 +41,7 @@
 #include 
 #include 
 #include 
+#include 
 
 #define DEBUG_TYPE "format-formatter"
 
@@ -48,6 +50,16 @@ using clang::format::FormatStyle;
 LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::IncludeCategory)
 LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::RawStringFormat)
 
+namespace std {
+// Allow using StringRef in std::unordered_set.
+template <> struct hash {
+public:
+  size_t operator()(const llvm::StringRef ) const {
+return llvm::hash_value(s);
+  }
+};
+} // namespace std
+
 namespace llvm {
 namespace yaml {
 template <> struct ScalarEnumerationTraits {
@@ -1400,6 +1412,101 @@ private:
   std::set DeletedTokens;
 };
 
+class ObjCHeaderStyleGuesser : public TokenAnalyzer {
+public:
+  ObjCHeaderStyleGuesser(const Environment , const FormatStyle )
+  : TokenAnalyzer(Env, Style), IsObjC(false) {}
+
+  std::pair
+  analyze(TokenAnnotator ,
+  SmallVectorImpl ,
+  FormatTokenLexer ) override {
+assert(Style.Language == FormatStyle::LK_Cpp);
+IsObjC = guessIsObjC(AnnotatedLines, Tokens.getKeywords());
+tooling::Replacements Result;
+return {Result, 0};
+  }
+
+  bool isObjC() { return IsObjC; }
+
+private:
+  static bool guessIsObjC(const SmallVectorImpl 
,
+  const AdditionalKeywords ) {
+static const std::unordered_set FoundationIdentifiers = {
+"CGFloat",
+"NSAffineTransform",
+"NSArray",
+"NSAttributedString",
+"NSCache",
+"NSCharacterSet",
+"NSCountedSet",
+"NSData",
+"NSDataDetector",
+"NSDecimal",
+"NSDecimalNumber",
+"NSDictionary",
+"NSEdgeInsets",
+"NSHashTable",
+"NSIndexPath",
+"NSIndexSet",
+"NSInteger",
+"NSLocale",
+"NSMapTable",
+"NSMutableArray",
+"NSMutableAttributedString",
+"NSMutableCharacterSet",
+"NSMutableData",
+"NSMutableDictionary",
+"NSMutableIndexSet",
+"NSMutableOrderedSet",
+"NSMutableSet",
+"NSMutableString",
+"NSNumber",
+"NSNumberFormatter",
+"NSOrderedSet",
+"NSPoint",
+"NSPointerArray",
+"NSRange",
+"NSRect",
+"NSRegularExpression",
+"NSSet",
+"NSSize",
+"NSString",
+"NSUInteger",
+"NSURL",
+"NSURLComponents",
+"NSURLQueryItem",
+"NSUUID",
+};
+
+for (auto  : AnnotatedLines) {
+  for (FormatToken *FormatTok = Line->First->Next; FormatTok;
+   FormatTok = FormatTok->Next) {
+if ((FormatTok->Previous->is(tok::at) &&
+ (FormatTok->isObjCAtKeyword(tok::objc_interface) ||
+  FormatTok->isObjCAtKeyword(tok::objc_implementation) ||
+  FormatTok->isObjCAtKeyword(tok::objc_protocol) ||
+  FormatTok->isObjCAtKeyword(tok::objc_end) ||
+  FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
+ tok::l_brace))) ||
+(FormatTok->Tok.isAnyIdentifier() &&
+ FoundationIdentifiers.find(FormatTok->TokenText) !=
+ FoundationIdentifiers.end()) ||
+FormatTok->is(TT_ObjCStringLiteral) ||
+FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
+   TT_ObjCBlockLBrace, TT_ObjCBlockLParen,
+   TT_ObjCDecl, TT_ObjCForIn, TT_ObjCMethodExpr,
+   TT_ObjCMethodSpecifier, TT_ObjCProperty)) {
+  return true;
+}
+  }
+}
+return 

[clang-tools-extra] r321914 - [clang-tidy] Function-scoped static variables should not trigger google-objc-global-variable-declaration

2018-01-05 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Fri Jan  5 15:26:06 2018
New Revision: 321914

URL: http://llvm.org/viewvc/llvm-project?rev=321914=rev
Log:
[clang-tidy] Function-scoped static variables should not trigger 
google-objc-global-variable-declaration

Summary:
google-objc-global-variable-declaration currently triggers on
valid code like:

  - (void)foo {
static dispatch_once_t onceToken;
dispatch_once(, ^{ /* ... */ });
  }

The Google Objective-C style guide says:

http://google.github.io/styleguide/objcguide.html#common-variable-names

> File scope or global variables (as opposed to constants) declared
> outside the scope of a method or function should be rare, and should
> have the prefix g.

which is meant to insinuate that static variables inside a method or
function don't need a special name.

Test Plan: `make -j12 check-clang-tools`

Reviewers: Wizard, hokein, klimek

Reviewed By: Wizard

Subscribers: xazax.hun, cfe-commits

Differential Revision: https://reviews.llvm.org/D41789

Modified:
clang-tools-extra/trunk/clang-tidy/google/GlobalVariableDeclarationCheck.cpp

clang-tools-extra/trunk/test/clang-tidy/google-objc-global-variable-declaration.m

Modified: 
clang-tools-extra/trunk/clang-tidy/google/GlobalVariableDeclarationCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/google/GlobalVariableDeclarationCheck.cpp?rev=321914=321913=321914=diff
==
--- 
clang-tools-extra/trunk/clang-tidy/google/GlobalVariableDeclarationCheck.cpp 
(original)
+++ 
clang-tools-extra/trunk/clang-tidy/google/GlobalVariableDeclarationCheck.cpp 
Fri Jan  5 15:26:06 2018
@@ -24,6 +24,10 @@ namespace objc {
 
 namespace {
 
+AST_MATCHER(VarDecl, isLocalVariable) {
+  return Node.isLocalVarDecl();
+}
+
 FixItHint generateFixItHint(const VarDecl *Decl, bool IsConst) {
   char FC = Decl->getName()[0];
   if (!llvm::isAlpha(FC) || Decl->getName().size() == 1) {
@@ -57,12 +61,17 @@ void GlobalVariableDeclarationCheck::reg
   // need to add two matchers since we need to bind different ids to 
distinguish
   // constants and variables. Since bind() can only be called on node matchers,
   // we cannot make it in one matcher.
+  //
+  // Note that hasGlobalStorage() matches static variables declared locally
+  // inside a function or method, so we need to exclude those with
+  // isLocalVariable().
   Finder->addMatcher(
   varDecl(hasGlobalStorage(), unless(hasType(isConstQualified())),
-  unless(matchesName("::g[A-Z]")))
+  unless(isLocalVariable()), unless(matchesName("::g[A-Z]")))
   .bind("global_var"),
   this);
   Finder->addMatcher(varDecl(hasGlobalStorage(), hasType(isConstQualified()),
+ unless(isLocalVariable()),
  unless(matchesName("::k[A-Z]")))
  .bind("global_const"),
  this);

Modified: 
clang-tools-extra/trunk/test/clang-tidy/google-objc-global-variable-declaration.m
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/test/clang-tidy/google-objc-global-variable-declaration.m?rev=321914=321913=321914=diff
==
--- 
clang-tools-extra/trunk/test/clang-tidy/google-objc-global-variable-declaration.m
 (original)
+++ 
clang-tools-extra/trunk/test/clang-tidy/google-objc-global-variable-declaration.m
 Fri Jan  5 15:26:06 2018
@@ -30,12 +30,12 @@ static NSString* const k_Alpha = @"Secon
 // CHECK-FIXES: static NSString* const k_Alpha = @"SecondNotAlpha";
 
 static NSString* const kGood = @"hello";
-// CHECK-MESSAGES-NOT: :[[@LINE-1]]:24: warning: const global variable 'kGood' 
must have a name which starts with 'k[A-Z]' 
[google-objc-global-variable-declaration]
 static NSString* gMyIntGood = 0;
-// CHECK-MESSAGES-NOT: :[[@LINE-1]]:18: warning: non-const global variable 
'gMyIntGood' must have a name which starts with 'g[A-Z]' 
[google-objc-global-variable-declaration]
+
 @implementation Foo
 - (void)f {
 int x = 0;
-// CHECK-MESSAGES-NOT: :[[@LINE-1]]:9: warning: non-const global variable 
'gMyIntGood' must have a name which starts with 'g[A-Z]' 
[google-objc-global-variable-declaration]
+static int bar;
+static const int baz = 42;
 }
 @end


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r320747 - Revert "[ClangFormat] IndentWrappedFunctionNames should be true in the google ObjC style"

2017-12-14 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Thu Dec 14 13:44:11 2017
New Revision: 320747

URL: http://llvm.org/viewvc/llvm-project?rev=320747=rev
Log:
Revert "[ClangFormat] IndentWrappedFunctionNames should be true in the google 
ObjC style"

This reverts commit 37e69667f748e1458b46483b7c1b8f9ba33eec44.

We're going to discuss its ramifications further before making a
conclusion.

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=320747=320746=320747=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Thu Dec 14 13:44:11 2017
@@ -732,7 +732,6 @@ FormatStyle getGoogleStyle(FormatStyle::
 GoogleStyle.SpacesInContainerLiterals = false;
   } else if (Language == FormatStyle::LK_ObjC) {
 GoogleStyle.ColumnLimit = 100;
-GoogleStyle.IndentWrappedFunctionNames = true;
   }
 
   return GoogleStyle;

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=320747=320746=320747=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Thu Dec 14 13:44:11 2017
@@ -382,9 +382,9 @@ TEST_F(FormatTestObjC, FormatObjCMethodD
"ofSize:(size_t)height\n"
"  :(size_t)width;");
 
-  Style = getGoogleStyle(FormatStyle::LK_ObjC);
   // Continuation indent width should win over aligning colons if the function
   // name is long.
+  Style = getGoogleStyle(FormatStyle::LK_ObjC);
   Style.ColumnLimit = 40;
   Style.IndentWrappedFunctionNames = true;
   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
@@ -395,10 +395,7 @@ TEST_F(FormatTestObjC, FormatObjCMethodD
   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
"   aShortf:(NSRect)theRect {\n"
"}");
-  // Wrapped method parameters should be indented.
-  verifyFormat("- (LongReturnTypeName)\n"
-   "longParam:(ParamName)longParamName\n"
-   "param:(paramName)paramName;");
+
   // Format pairs correctly.
   Style.ColumnLimit = 80;
   verifyFormat("- (void)drawRectOn:(id)surface\n"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r320714 - [ClangFormat] IndentWrappedFunctionNames should be true in the google ObjC style

2017-12-14 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Thu Dec 14 08:17:38 2017
New Revision: 320714

URL: http://llvm.org/viewvc/llvm-project?rev=320714=rev
Log:
[ClangFormat] IndentWrappedFunctionNames should be true in the google ObjC style

Summary:
If we write the following code, it goes over 100 columns, so we need to wrap it:

```
- 
(VeryLongReturnTypeName)veryLongMethodParameter:(VeryLongParameterName)thisIsAVeryLongParameterName
  
longMethodParameter:(LongParameterName)thisIsAlsoAnotherLongParameterName;
```

Currently, clang-format with the google style aligns the method parameter names 
on the first column:

```
- (VeryLongReturnTypeName)
veryLongMethodParameter:(VeryLongParameterName)thisIsAVeryLongParameterName
longMethodParameter:(LongParameterName)thisIsAlsoAnotherLongParameterName;
```

We'd like clang-format in the google style to align these to column 4 for 
Objective-C:

```
- (VeryLongReturnTypeName)
veryLongMethodParameter:(VeryLongParameterName)thisIsAVeryLongParameterName

longMethodParameter:(LongParameterName)thisIsAlsoAnotherLongParameterName;
```

Test Plan: make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests

Reviewers: krasimir, djasper, klimek

Reviewed By: djasper

Subscribers: cfe-commits, thakis

Differential Revision: https://reviews.llvm.org/D41195

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=320714=320713=320714=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Thu Dec 14 08:17:38 2017
@@ -732,6 +732,7 @@ FormatStyle getGoogleStyle(FormatStyle::
 GoogleStyle.SpacesInContainerLiterals = false;
   } else if (Language == FormatStyle::LK_ObjC) {
 GoogleStyle.ColumnLimit = 100;
+GoogleStyle.IndentWrappedFunctionNames = true;
   }
 
   return GoogleStyle;

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=320714=320713=320714=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Thu Dec 14 08:17:38 2017
@@ -382,9 +382,9 @@ TEST_F(FormatTestObjC, FormatObjCMethodD
"ofSize:(size_t)height\n"
"  :(size_t)width;");
 
+  Style = getGoogleStyle(FormatStyle::LK_ObjC);
   // Continuation indent width should win over aligning colons if the function
   // name is long.
-  Style = getGoogleStyle(FormatStyle::LK_ObjC);
   Style.ColumnLimit = 40;
   Style.IndentWrappedFunctionNames = true;
   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
@@ -395,7 +395,10 @@ TEST_F(FormatTestObjC, FormatObjCMethodD
   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
"   aShortf:(NSRect)theRect {\n"
"}");
-
+  // Wrapped method parameters should be indented.
+  verifyFormat("- (LongReturnTypeName)\n"
+   "longParam:(ParamName)longParamName\n"
+   "param:(paramName)paramName;");
   // Format pairs correctly.
   Style.ColumnLimit = 80;
   verifyFormat("- (void)drawRectOn:(id)surface\n"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[libcxx] r319666 - [libcxx] Set up .arcconfig to point to new Diffusion CXX repository

2017-12-04 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Mon Dec  4 09:55:28 2017
New Revision: 319666

URL: http://llvm.org/viewvc/llvm-project?rev=319666=rev
Log:
[libcxx] Set up .arcconfig to point to new Diffusion CXX repository

Summary:
We want to automatically copy the appropriate mailing list
for review requests to the libc++ repository.

For context, see the proposal and discussion here:

http://lists.llvm.org/pipermail/cfe-dev/2017-November/056032.html

Similar to D40179, I set up a new Diffusion repository with callsign
"CXX" for libc++:

https://reviews.llvm.org/source/libcxx/

This explicitly updates libcxx's .arcconfig to point to the new
CXX repository in Diffusion, which will let us use Herald rule H268.

Reviewers: halyavin, EricWF, mclow.lists, compnerd, mstorsjo

Reviewed By: compnerd

Subscribers: cfe-commits, bkramer, dlj, sammccall, klimek, smeenai, mstorsjo, 
krytarowski

Differential Revision: https://reviews.llvm.org/D40500

Modified:
libcxx/trunk/.arcconfig

Modified: libcxx/trunk/.arcconfig
URL: 
http://llvm.org/viewvc/llvm-project/libcxx/trunk/.arcconfig?rev=319666=319665=319666=diff
==
--- libcxx/trunk/.arcconfig (original)
+++ libcxx/trunk/.arcconfig Mon Dec  4 09:55:28 2017
@@ -1,4 +1,4 @@
 {
-  "project_id" : "libcxx",
+  "repository.callsign" : "CXX",
   "conduit_uri" : "https://reviews.llvm.org/;
 }


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r319052 - [clang] Set up .arcconfig to point to new Diffusion C repository

2017-11-27 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Mon Nov 27 09:21:24 2017
New Revision: 319052

URL: http://llvm.org/viewvc/llvm-project?rev=319052=rev
Log:
[clang] Set up .arcconfig to point to new Diffusion C repository

Summary:
We want to automatically copy cfe-commits@ on review requests
to the clang repository.

Similar to D40179, I set up a new Diffusion repository with callsign
"C" for clang:

https://reviews.llvm.org/source/clang/

This explicitly updates clang's .arcconfig to point to the new C
repository in Diffusion, which will let us use Herald rule H268.

Reviewers: klimek, sammccall

Reviewed By: klimek

Subscribers: dlj, bkramer

Differential Revision: https://reviews.llvm.org/D40494

Modified:
cfe/trunk/.arcconfig

Modified: cfe/trunk/.arcconfig
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/.arcconfig?rev=319052=319051=319052=diff
==
--- cfe/trunk/.arcconfig (original)
+++ cfe/trunk/.arcconfig Mon Nov 27 09:21:24 2017
@@ -1,4 +1,4 @@
 {
-  "project_id" : "clang",
+  "repository.callsign" : "C",
   "conduit_uri" : "https://reviews.llvm.org/;
 }


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r319039 - [clang-tools-extra] Set up .arcconfig to point to new Diffusion CTE repository

2017-11-27 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Mon Nov 27 07:58:25 2017
New Revision: 319039

URL: http://llvm.org/viewvc/llvm-project?rev=319039=rev
Log:
[clang-tools-extra] Set up .arcconfig to point to new Diffusion CTE repository

Summary:
I'm testing out a new Diffusion repository `CTE`:

https://reviews.llvm.org/source/clang-tools-extra/

This explicitly updates clang-tools-extra's `.arcconfig` to point to
the new `CTE` repository in Diffusion, which will let us set up Herald
rules, etc.

Reviewers: klimek, sammccall

Reviewed By: sammccall

Subscribers: bkramer, dlj

Differential Revision: https://reviews.llvm.org/D40179

Modified:
clang-tools-extra/trunk/.arcconfig

Modified: clang-tools-extra/trunk/.arcconfig
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/.arcconfig?rev=319039=319038=319039=diff
==
--- clang-tools-extra/trunk/.arcconfig (original)
+++ clang-tools-extra/trunk/.arcconfig Mon Nov 27 07:58:25 2017
@@ -1,4 +1,4 @@
 {
-  "project_id" : "clang-tools-extra",
+  "repository.callsign" : "CTE",
   "conduit_uri" : "https://reviews.llvm.org/;
 }


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r319040 - [clang-tools-extra] Fix small typo in docs/ReleaseNotes.rst

2017-11-27 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Mon Nov 27 07:58:26 2017
New Revision: 319040

URL: http://llvm.org/viewvc/llvm-project?rev=319040=rev
Log:
[clang-tools-extra] Fix small typo in docs/ReleaseNotes.rst

Summary:
This is mainly a test diff to check the new Herald rule I
added in LLVM Phabricator to automatically Cc: cfe-commits on all
clang-tools-extra diffs.

Reviewers: Wizard, hokein, klimek

Reviewed By: Wizard

Subscribers: dlj, bkramer, sammccall

Differential Revision: https://reviews.llvm.org/D40180

Modified:
clang-tools-extra/trunk/docs/ReleaseNotes.rst

Modified: clang-tools-extra/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/ReleaseNotes.rst?rev=319040=319039=319040=diff
==
--- clang-tools-extra/trunk/docs/ReleaseNotes.rst (original)
+++ clang-tools-extra/trunk/docs/ReleaseNotes.rst Mon Nov 27 07:58:26 2017
@@ -99,7 +99,7 @@ Improvements to clang-tidy
 - The 'misc-string-constructor' check was renamed to 
`bugprone-string-constructor
   
`_
 
-- New `google-avoid-throwing-objc-exception
+- New `google-objc-avoid-throwing-exception
   
`_
 check
 
   Add new check to detect throwing exceptions in Objective-C code, which 
should be avoided.


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r318445 - [VirtualFileSystem] Support creating directories then adding files inside

2017-11-16 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Thu Nov 16 11:34:08 2017
New Revision: 318445

URL: http://llvm.org/viewvc/llvm-project?rev=318445=rev
Log:
[VirtualFileSystem] Support creating directories then adding files inside

Summary:
In https://reviews.llvm.org/D39572 , I added support for specifying
`Type` when invoking `InMemoryFileSystem::addFile()`.

However, I didn't account for the fact that when `Type` is
`directory_file`, we need to construct an `InMemoryDirectory`, not an
`InMemoryFile`, or else clients cannot create files inside that
directory.

This diff fixes the bug and adds a test.

Test Plan: New test added. Ran test with:

  % make -j12 check-clang-tools

Reviewers: bkramer, hokein

Reviewed By: bkramer

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D40140

Modified:
cfe/trunk/include/clang/Basic/VirtualFileSystem.h
cfe/trunk/lib/Basic/VirtualFileSystem.cpp
cfe/trunk/unittests/Basic/VirtualFileSystemTest.cpp

Modified: cfe/trunk/include/clang/Basic/VirtualFileSystem.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/VirtualFileSystem.h?rev=318445=318444=318445=diff
==
--- cfe/trunk/include/clang/Basic/VirtualFileSystem.h (original)
+++ cfe/trunk/include/clang/Basic/VirtualFileSystem.h Thu Nov 16 11:34:08 2017
@@ -319,19 +319,23 @@ public:
   explicit InMemoryFileSystem(bool UseNormalizedPaths = true);
   ~InMemoryFileSystem() override;
 
-  /// Add a buffer to the VFS with a path. The VFS owns the buffer.
-  /// If present, User, Group, Type and Perms apply to the newly-created file.
-  /// \return true if the file was successfully added, false if the file 
already
-  /// exists in the file system with different contents.
+  /// Add a file containing a buffer or a directory to the VFS with a
+  /// path. The VFS owns the buffer.  If present, User, Group, Type
+  /// and Perms apply to the newly-created file or directory.
+  /// \return true if the file or directory was successfully added,
+  /// false if the file or directory already exists in the file system with
+  /// different contents.
   bool addFile(const Twine , time_t ModificationTime,
std::unique_ptr Buffer,
Optional User = None, Optional Group = None,
Optional Type = None,
Optional Perms = None);
   /// Add a buffer to the VFS with a path. The VFS does not own the buffer.
-  /// If present, User, Group, Type and Perms apply to the newly-created file.
-  /// \return true if the file was successfully added, false if the file 
already
-  /// exists in the file system with different contents.
+  /// If present, User, Group, Type and Perms apply to the newly-created file
+  /// or directory.
+  /// \return true if the file or directory was successfully added,
+  /// false if the file or directory already exists in the file system with
+  /// different contents.
   bool addFileNoOwn(const Twine , time_t ModificationTime,
 llvm::MemoryBuffer *Buffer,
 Optional User = None,

Modified: cfe/trunk/lib/Basic/VirtualFileSystem.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/VirtualFileSystem.cpp?rev=318445=318444=318445=diff
==
--- cfe/trunk/lib/Basic/VirtualFileSystem.cpp (original)
+++ cfe/trunk/lib/Basic/VirtualFileSystem.cpp Thu Nov 16 11:34:08 2017
@@ -527,13 +527,19 @@ bool InMemoryFileSystem::addFile(const T
 ++I;
 if (!Node) {
   if (I == E) {
-// End of the path, create a new file.
+// End of the path, create a new file or directory.
 Status Stat(P.str(), getNextVirtualUniqueID(),
 llvm::sys::toTimePoint(ModificationTime), ResolvedUser,
 ResolvedGroup, Buffer->getBufferSize(), ResolvedType,
 ResolvedPerms);
-Dir->addChild(Name, llvm::make_unique(
-std::move(Stat), std::move(Buffer)));
+std::unique_ptr Child;
+if (ResolvedType == sys::fs::file_type::directory_file) {
+  Child.reset(new detail::InMemoryDirectory(std::move(Stat)));
+} else {
+  Child.reset(new detail::InMemoryFile(std::move(Stat),
+   std::move(Buffer)));
+}
+Dir->addChild(Name, std::move(Child));
 return true;
   }
 

Modified: cfe/trunk/unittests/Basic/VirtualFileSystemTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Basic/VirtualFileSystemTest.cpp?rev=318445=318444=318445=diff
==
--- cfe/trunk/unittests/Basic/VirtualFileSystemTest.cpp (original)
+++ cfe/trunk/unittests/Basic/VirtualFileSystemTest.cpp Thu Nov 16 11:34:08 2017
@@ -829,6 +829,19 @@ TEST_F(InMemoryFileSystemTest, AddFileWi
 

[clang-tools-extra] r318117 - add new check for property declaration

2017-11-13 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Mon Nov 13 15:54:31 2017
New Revision: 318117

URL: http://llvm.org/viewvc/llvm-project?rev=318117=rev
Log:
add new check for property declaration

Summary:
This check finds property declarations in Objective-C files that do not follow 
the pattern of property names in Apple's programming guide. The property name 
should be in the format of Lower Camel Case or with some particular acronyms as 
prefix.

Example:
@property(nonatomic, assign) int lowerCamelCase;

@property(nonatomic, strong) NSString *URLString;

Test plan:  ninja check-clang-tools

Reviewers: benhamilton, hokein

Reviewed By: hokein

Subscribers: cfe-commits, mgorny

Differential Revision: https://reviews.llvm.org/D39829

Added:
clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp
clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.h
clang-tools-extra/trunk/docs/clang-tidy/checks/objc-property-declaration.rst
clang-tools-extra/trunk/test/clang-tidy/objc-property-declaration-custom.m
clang-tools-extra/trunk/test/clang-tidy/objc-property-declaration.m
Modified:
clang-tools-extra/trunk/clang-tidy/objc/CMakeLists.txt
clang-tools-extra/trunk/clang-tidy/objc/ObjCTidyModule.cpp
clang-tools-extra/trunk/docs/ReleaseNotes.rst

clang-tools-extra/trunk/docs/clang-tidy/checks/google-objc-global-variable-declaration.rst
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

Modified: clang-tools-extra/trunk/clang-tidy/objc/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/CMakeLists.txt?rev=318117=318116=318117=diff
==
--- clang-tools-extra/trunk/clang-tidy/objc/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clang-tidy/objc/CMakeLists.txt Mon Nov 13 15:54:31 
2017
@@ -3,6 +3,7 @@ set(LLVM_LINK_COMPONENTS support)
 add_clang_library(clangTidyObjCModule
   ForbiddenSubclassingCheck.cpp
   ObjCTidyModule.cpp
+  PropertyDeclarationCheck.cpp
 
   LINK_LIBS
   clangAST

Modified: clang-tools-extra/trunk/clang-tidy/objc/ObjCTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/ObjCTidyModule.cpp?rev=318117=318116=318117=diff
==
--- clang-tools-extra/trunk/clang-tidy/objc/ObjCTidyModule.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/objc/ObjCTidyModule.cpp Mon Nov 13 
15:54:31 2017
@@ -11,6 +11,7 @@
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
 #include "ForbiddenSubclassingCheck.h"
+#include "PropertyDeclarationCheck.h"
 
 using namespace clang::ast_matchers;
 
@@ -23,6 +24,8 @@ public:
   void addCheckFactories(ClangTidyCheckFactories ) override {
 CheckFactories.registerCheck(
 "objc-forbidden-subclassing");
+CheckFactories.registerCheck(
+"objc-property-declaration");
   }
 };
 

Added: clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp?rev=318117=auto
==
--- clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp (added)
+++ clang-tools-extra/trunk/clang-tidy/objc/PropertyDeclarationCheck.cpp Mon 
Nov 13 15:54:31 2017
@@ -0,0 +1,115 @@
+//===--- PropertyDeclarationCheck.cpp - 
clang-tidy-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "PropertyDeclarationCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/Support/Regex.h"
+#include 
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace objc {
+
+namespace {
+/// The acronyms are from
+/// 
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/APIAbbreviations.html#//apple_ref/doc/uid/20001285-BCIHCGAE
+constexpr char DefaultSpecialAcronyms[] =
+"ASCII;"
+"PDF;"
+"XML;"
+"HTML;"
+"URL;"
+"RTF;"
+"HTTP;"
+"TIFF;"
+"JPG;"
+"PNG;"
+"GIF;"
+"LZW;"
+"ROM;"
+"RGB;"
+"CMYK;"
+"MIDI;"
+"FTP";
+
+/// For now we will only fix 'CamelCase' property to
+/// 'camelCase'. For other cases the users need to
+/// come up with a proper name by their own.
+/// FIXME: provide fix for snake_case to snakeCase
+FixItHint generateFixItHint(const ObjCPropertyDecl *Decl) {
+  if (isupper(Decl->getName()[0])) {
+auto NewName = Decl->getName().str();
+NewName[0] = tolower(NewName[0]);
+   

r317800 - [VirtualFileSystem] InMemoryFileSystem::addFile(): Type and Perms

2017-11-09 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Thu Nov  9 08:01:16 2017
New Revision: 317800

URL: http://llvm.org/viewvc/llvm-project?rev=317800=rev
Log:
[VirtualFileSystem] InMemoryFileSystem::addFile(): Type and Perms

Summary:
This implements a FIXME in InMemoryFileSystem::addFile(), allowing
clients to specify User, Group, Type, and/or Perms when creating a
file in an in-memory filesystem.

New tests included. Ran tests with:

% ninja BasicTests && ./tools/clang/unittests/Basic/BasicTests

Fixes PR#35172 (https://bugs.llvm.org/show_bug.cgi?id=35172)

Reviewers: bkramer, hokein

Reviewed By: bkramer, hokein

Subscribers: alexfh

Differential Revision: https://reviews.llvm.org/D39572

Modified:
cfe/trunk/include/clang/Basic/VirtualFileSystem.h
cfe/trunk/lib/Basic/VirtualFileSystem.cpp
cfe/trunk/unittests/Basic/VirtualFileSystemTest.cpp

Modified: cfe/trunk/include/clang/Basic/VirtualFileSystem.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Basic/VirtualFileSystem.h?rev=317800=317799=317800=diff
==
--- cfe/trunk/include/clang/Basic/VirtualFileSystem.h (original)
+++ cfe/trunk/include/clang/Basic/VirtualFileSystem.h Thu Nov  9 08:01:16 2017
@@ -320,15 +320,25 @@ public:
   ~InMemoryFileSystem() override;
 
   /// Add a buffer to the VFS with a path. The VFS owns the buffer.
+  /// If present, User, Group, Type and Perms apply to the newly-created file.
   /// \return true if the file was successfully added, false if the file 
already
   /// exists in the file system with different contents.
   bool addFile(const Twine , time_t ModificationTime,
-   std::unique_ptr Buffer);
+   std::unique_ptr Buffer,
+   Optional User = None, Optional Group = None,
+   Optional Type = None,
+   Optional Perms = None);
   /// Add a buffer to the VFS with a path. The VFS does not own the buffer.
+  /// If present, User, Group, Type and Perms apply to the newly-created file.
   /// \return true if the file was successfully added, false if the file 
already
   /// exists in the file system with different contents.
   bool addFileNoOwn(const Twine , time_t ModificationTime,
-llvm::MemoryBuffer *Buffer);
+llvm::MemoryBuffer *Buffer,
+Optional User = None,
+Optional Group = None,
+Optional Type = None,
+Optional Perms = None);
+
   std::string toString() const;
   /// Return true if this file system normalizes . and .. in paths.
   bool useNormalizedPaths() const { return UseNormalizedPaths; }

Modified: cfe/trunk/lib/Basic/VirtualFileSystem.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Basic/VirtualFileSystem.cpp?rev=317800=317799=317800=diff
==
--- cfe/trunk/lib/Basic/VirtualFileSystem.cpp (original)
+++ cfe/trunk/lib/Basic/VirtualFileSystem.cpp Thu Nov  9 08:01:16 2017
@@ -493,7 +493,11 @@ std::string InMemoryFileSystem::toString
 }
 
 bool InMemoryFileSystem::addFile(const Twine , time_t ModificationTime,
- std::unique_ptr Buffer) {
+ std::unique_ptr Buffer,
+ Optional User,
+ Optional Group,
+ Optional Type,
+ Optional Perms) {
   SmallString<128> Path;
   P.toVector(Path);
 
@@ -509,7 +513,14 @@ bool InMemoryFileSystem::addFile(const T
 return false;
 
   detail::InMemoryDirectory *Dir = Root.get();
-  auto I = llvm::sys::path::begin(Path), E = llvm::sys::path::end(Path);
+  auto I = llvm::sys::path::begin(Path), E = sys::path::end(Path);
+  const auto ResolvedUser = User.getValueOr(0);
+  const auto ResolvedGroup = Group.getValueOr(0);
+  const auto ResolvedType = Type.getValueOr(sys::fs::file_type::regular_file);
+  const auto ResolvedPerms = Perms.getValueOr(sys::fs::all_all);
+  // Any intermediate directories we create should be accessible by
+  // the owner, even if Perms says otherwise for the final path.
+  const auto NewDirectoryPerms = ResolvedPerms | sys::fs::owner_all;
   while (true) {
 StringRef Name = *I;
 detail::InMemoryNode *Node = Dir->getChild(Name);
@@ -517,24 +528,21 @@ bool InMemoryFileSystem::addFile(const T
 if (!Node) {
   if (I == E) {
 // End of the path, create a new file.
-// FIXME: expose the status details in the interface.
 Status Stat(P.str(), getNextVirtualUniqueID(),
-llvm::sys::toTimePoint(ModificationTime), 0, 0,
-Buffer->getBufferSize(),
-llvm::sys::fs::file_type::regular_file,
-llvm::sys::fs::all_all);
+llvm::sys::toTimePoint(ModificationTime), ResolvedUser,
+ResolvedGroup, 

[clang-tools-extra] r317261 - Update release notes (check SVN commit-after-approval access)

2017-11-02 Thread Ben Hamilton via cfe-commits
Author: benhamilton
Date: Thu Nov  2 13:00:17 2017
New Revision: 317261

URL: http://llvm.org/viewvc/llvm-project?rev=317261=rev
Log:
Update release notes (check SVN commit-after-approval access)

Summary:
I was just granted commit-after-approval access to SVN,
and @clattner recommended I try a test commit.

So, this tweaks the release notes as a test.

Reviewers: hokein, alexfh

Reviewed By: hokein

Subscribers: Wizard

Differential Revision: https://reviews.llvm.org/D39559

Modified:
clang-tools-extra/trunk/docs/ReleaseNotes.rst

Modified: clang-tools-extra/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/ReleaseNotes.rst?rev=317261=317260=317261=diff
==
--- clang-tools-extra/trunk/docs/ReleaseNotes.rst (original)
+++ clang-tools-extra/trunk/docs/ReleaseNotes.rst Thu Nov  2 13:00:17 2017
@@ -63,7 +63,8 @@ Improvements to clang-tidy
   
`_
 check
 
   Ensures Objective-C classes do not subclass any classes which are
-  not intended to be subclassed.
+  not intended to be subclassed. Includes a list of classes from Foundation
+  and UIKit which are documented as not supporting subclassing.
 
 - Renamed checks to use correct term "implicit conversion" instead of "implicit
   cast" and modified messages and option names accordingly:


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits