roc-lang / roc

A fast, friendly, functional language.
https://roc-lang.org
Universal Permissive License v1.0
4.46k stars 313 forks source link

Implement the `try` keyword with desugaring #7193

Closed smores56 closed 2 weeks ago

smores56 commented 2 weeks ago

Closes https://github.com/roc-lang/roc/issues/7087

This PR adds the try keyword, which is a Zig-reminiscent version of the current ? operator. It basically desugars from try expr to:

when expr is
    Ok ok -> ok
    Err err -> return Err err

# You can also use it in pipelines:

decodedContents =
    try File.read! "myFile.json"
    |> try Json.decode

# this also works
decodedContents =
    try File.read! "myFile.json"
    |> Json.decode
    |> try

This implementation is intentionally very simple, as a non-sugar version was attempted in https://github.com/roc-lang/roc/pull/7192 and resulted in alias analysis errors. That will be attempted later, but we'll stick with this for now to unblock use of try.

Note, I specifically didn't add tests in cli_run.rs because:

dadhi commented 2 weeks ago

@smores56

Hi, is there any particular reason that you did not add TRY keyword to the 'keyword.rs'?

Update: I see that test_fmt_builtins tests start failing when I added TRY to KEYWORDS

smores56 commented 2 weeks ago

@dadhi we currently have a function in the standard library called try, namely Result.try. So long as that exists, we need to be able to parse the use of a bare try var in the Result module's "exposes" statement.

If we remove that function, then we can add it to the KEYWORDS list

dadhi commented 2 weeks ago

@smores56 Thanks for the explanation, appreciated!