domluna / JuliaFormatter.jl

An opinionated code formatter for Julia. Plot twist - the opinion is your own.

Home Page:https://domluna.github.io/JuliaFormatter.jl/dev/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Insertion of return in do block

schillic opened this issue · comments

Explanation

The do keyword creates an anonymous function. So technically there can be a return value of the code block and this result can be used further, e.g., by assigning to a variable. Consistently, the formatter inserts a return with the YAS style.

Still, I presume that in many cases the return value is ignored (I actually only learned about the possibility to have a return value while writing this issue and was going to claim that the formatter is faulty 😅 - a good example why automatic code formatting is great). If this feature is not used, I find a return in a do block a bit off-putting.

I guess it should be possible to statically distinguish these cases ("is the return value used?"). But I also understand that this may be a strict requirement of the style. From the YAS guidelines:

  • The return keyword should always be omitted from return statements within short-form method definitions (f(...) = ...). The return keyword should never be omitted from return statements within any other context (function ... end, macro ... end, etc.).
  • If a function does not have a clearly appropriate return value, then explicitly return nothing.

Suggestions

  1. Should omitting redundant returns be considered for a change, or at least for having an option to opt out? See Example 1 below.
  2. The second rule is actually not enforced by the formatter. See Example 2 below. (There is a somewhat related discussion in #337.)

Since these are two orthogonal suggestions, I can also split this issue in two. I kept them together because they are very related.

Example 1

The following function always returns 2 (assuming file exists).

function foo()
    open("file", "r") do io
        1
    end

    return 2
end

Using YAS style, the formatter adds a return in line 3.

function foo()
    open("file", "r") do io
        return 1
    end

    return 2
end

I thought that this makes the function return 1 instead, but actually it does not (still returns 2). Still, I find it very confusing to read this code.

On the other hand, here is an example where I totally agree that the formatter adds an explicit return:

function foo()
    x = 2
    x = open("file", "r") do io
        1
    end

    return x  # x == 1 here
end

Example 2

The formatter accepts the following code, but it is supposed to insert return nothing.

function foo()
end