fable-compiler / Fable

F# to JavaScript, TypeScript, Python, Rust and Dart Compiler
http://fable.io/
MIT License
2.92k stars 300 forks source link

`use` in top-level expression results in invalid Python syntax #3912

Open joprice opened 1 month ago

joprice commented 1 month ago

Description

When useing an IDisposable at the top-level, the generated code contains a return statement, which is not valid outside of the context of a function definition.

Repro code

https://fable.io/repl/#?code=PYBwpgdgBAYghgIwDZgHQGFgCcwChcAuAnuFABpQC8UAlhABZhY0FQDKRAzgWALaoBJACI1OIYJ0Qp8AbQA8AcSTAEcJAD4AurhSsAHgC5yVKBDgEaANzAB5CEiL5dUABQBKE7ihQArpzBQeiZ6Xq5uQA&html=Q&css=Q

Expected and actual results

The expression should be wrapped in something like an IIFE, as is the case for the js backend.

Related information

MangelMaxime commented 1 month ago

I didn't even know it was a valid F# syntax to have a function without a name 😅

joprice commented 1 month ago

It's not actually a function, but an assignment of a top-level expression to unit, a habit I picked up from ocaml that is similar to x |> ignore<unit>, where if the result type changes, the unused value will be detected. You can reproduce it like this as well:

(
  use x = x
  ()
)

Or

let _ =
  use x = x
  ()