Fortran On Web Using LFortran

Recently, there was a blog post titled Fortran on WebAssembly released by Dr George W Stagg. This article inspired us to compile the same example using our LFortran compiler. We are happy to share that we have the fortran mnist classifier example used in the blog post, compiled to WebAssembly using LFortran (with no hacks to the compiler) and working perfectly in the browser.

MNIST

We cloned the original authors code and just swapped-in two of our generated files mnist.js and mnist.wasm with the original files. We also fixed few minor bugs in the code that we came across (details in the commit history).

Other Examples

Apart from the mnist example, we also have two more examples 2D matrix multiplication and simple linear regression. The sources of these are present here https://github.com/lfortran/Fortran-On-Web.


Compiling to wasm using LFortran

LFortran supports compiling to wasm via different approaches.

  1. Using clang-wasi:
lfortran main.f90 --target=wasm32-wasi -o main.wasm

wasmtime main.wasm
  1. Using emscripten:
lfortran main.f90 --target=wasm32-unknown-emscripten -o main.js

node main.js
  1. Using custom wasm backend:
lfortran main.f90 --backend=wasm -o main

wasmtime main

or

node main.js

Out of the above three approaches, using the clang-wasi or emscripten approach is more stable as it uses our most advanced llvm backend.

To use the clang-wasi approach, one needs the WASI SDK installed and added to PATH. Detailed steps for this are shared here.

To use the emscripten approach, one needs the emscripten SDK (emsdk) installed and added to PATH. Detailed steps for this are shared here.

Contributing

If you liked the above examples, go ahead and try using LFortran to compile your Fortran codes to WebAssembly. Remember that LFortran is alpha quality, so please report all bugs that you discover. It should be however possible to workaround them in most cases.

We also continuously welcome new contributors to join our endeavor. If you’re interested, please reach out to us. Working on a compiler offers a stimulating learning experience, and we’re committed to providing all the necessary guidance and training. Join us in shaping the future of LFortran!

Acknowledgements

We want to thank:

Discussions