r-lib / lintr

Static Code Analysis for R
https://lintr.r-lib.org
Other
1.19k stars 184 forks source link

Add argument `bsd_style_braces = FALSE` to `brace_linter` #1103

Open AshesITR opened 2 years ago

AshesITR commented 2 years ago

To enforce Allman / BSD style bracing instead of Java style bracing, i.e., all braces go on their own lines (as long as syntactically possible).

A notable exception where the R parser will throw is a top-level else must come on the same line as its preceding } if there is one. Compare:

if (a)
{
  1
}
else
{
  2
}
#> parser error: unexpected 'else'

function(a)
{
  if (a)
  {
    1
  }
  else
  {
    2
  }
}
#> just fine

Not sure how widespread BSD style bracing is in R packages, so maybe not worth adding for now until someone requests it.

IndrajeetPatil commented 10 months ago

It'd indeed be nice if we can support Allman style (btw, I think we should name this parameter allman_style_braces since that's a more commonly used term AFAICT):

"if (x == y)
{
  f()
}" -> code

lintr::lint(text = code, linters = lintr::all_linters())
#> <text>:2:1: style: [brace_linter] Opening curly braces should never go on their own line and should always be followed by a new line.
#> {
#> ^

Created on 2023-12-02 with reprex v2.0.2

I love that I can just comment out the conditional statement in this style, and the code would remain syntactically valid.


It's a pity that {styler} currently doesn't support this, but that's a different issue:

"if (x == y)
{
  f()
}" -> code

styler::style_text(code)
#> if (x == y) {
#>   f()
#> }

Created on 2023-12-02 with reprex v2.0.2