<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/126844>126844</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            [clang-format] comment immediately preceding `} else` is incorrectly indented
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            clang-format
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          rjmccall
      </td>
    </tr>
</table>

<pre>
    clang-format appears to believe that comments preceding `} else ...` lines should be indented as if they were part of the `if` block. In fact, this is often wrong.

Comments in this position *may* end a narrative about the behavior in the `if` block and say something useful about the control flow out of the block, e.g.

```
// Check for something bad.
if (someCondition) {
  // Oh no, just blow everything up.
  state.reset();
  // Fall through and start over.
} else {
  state.proceed();
}
```

In this case, it is appropriate for the comment to be indented at the level of the inner block.

However, it is more common that these comments continue a narrative about the control flow edge that didn't enter the `if` block:

```
// Check for something bad.
if (someCondition) {
  // Oh no, just blow everything up.
  state.reset();
  // Fall through and start over.

// Thank goodness, we're fine.
} else {
  state.proceed();
}
```

In this case, it is appropriate for the comment to be indented at the level of the outer block, i.e. the same level as the initial comment on the `if`.

This behavior of clang-format can be worked around by separating the end brace and the `else`, but of course this adds an extra line and misleadingly makes the `if` block look like it ends with no `else`:

```
// Check for something bad.
if (someCondition) {
  // Oh no, just blow everything up.
 state.reset();
  // Fall through and start over.

}
// Thank goodness, we're fine.
else {
  state.proceed();
}
```

As a special case, clang-format should check whether these comments match one or the other indentation and preserve that rather than assuming that naive re-indentation is appropriate.

We saw this misbehavior on several lines in the following LLVM PR: https://github.com/llvm/llvm-project/pull/126644
</pre>
<img width="1" height="1" alt="" src="http://email.email.llvm.org/o/eJzUllGL6zYThn-NcjMc48jZJL7IRc4u4TtwPlrKob0eW2NbG1ljJDlu_n2R7Owmhy20tNAWAgEjvTPzzqOR0HvdWqKDePosnl5WOIaO3cG99nWNxqwqVtdDbdC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