[clang-format] C# property formatting can be controlled by config options
authorJonathan Coe <jbcoe@google.com>
Fri, 15 May 2020 12:55:48 +0000 (13:55 +0100)
committerJonathan Coe <jbcoe@google.com>
Fri, 15 May 2020 13:08:40 +0000 (14:08 +0100)
Summary:
Allow brace wrapping in C# property accessors to be controlled by configuration options.

Add new tests and revert old test results for Microsoft style to their previous state (as intended).

`FormatStyle.BraceWrapping.AfterFunction = true;` will change automatic property formatting from

```
Type MyType { get; set }
```

to

```
Type MyType
{ get; set }
```

Reviewers: krasimir, MyDeveloperDay

Reviewed By: krasimir, MyDeveloperDay

Subscribers: cfe-commits

Tags: #clang-format, #clang

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

clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestCSharp.cpp

index b303758..58206a0 100644 (file)
@@ -1531,6 +1531,8 @@ bool UnwrappedLineParser::tryToParsePropertyAccessor() {
   // Try to parse the property accessor:
   // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
   Tokens->setPosition(StoredPosition);
+  if (Style.BraceWrapping.AfterFunction == true)
+    addUnwrappedLine();
   nextToken();
   do {
     switch (FormatTok->Tok.getKind()) {
index 6f0b196..5567e19 100644 (file)
@@ -245,11 +245,13 @@ TEST_F(FormatTestCSharp, Attributes) {
                "}");
 
   verifyFormat("[TestMethod]\n"
-               "public string Host { set; get; }");
+               "public string Host\n"
+               "{ set; get; }");
 
   verifyFormat("[TestMethod(\"start\", HelpText = \"Starts the server "
                "listening on provided host\")]\n"
-               "public string Host { set; get; }");
+               "public string Host\n"
+               "{ set; get; }");
 
   verifyFormat(
       "[DllImport(\"Hello\", EntryPoint = \"hello_world\")]\n"
@@ -677,6 +679,32 @@ class MyClass {
                                      DefaultThirdArgument);
 })",
                Style);
+
+  // Brace wrapping and single-lining of accessor can be controlled by config.
+  Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterFunction = true;
+
+  verifyFormat(R"(//
+public class SaleItem {
+  public decimal Price
+  { get; set; }
+})",
+               Style);
+
+  verifyFormat(R"(//
+class TimePeriod {
+  public double Hours
+  {
+    get {
+      return _seconds / 3600;
+    }
+    set {
+      _seconds = value * 3600;
+    }
+  }
+})",
+               Style);
 }
 
 TEST_F(FormatTestCSharp, CSharpSpaces) {