Nix backend
The Nix codegen backend is very much based on the JavaScript backend, and is implemented as follows in the compiler:
- The entrypoint is at
compiler-core/src/nix.rs. This Rust module implements the compilation of a Gleam module (file) to a Nix file. Themodulefunction is the entrypoint and invokes thecompilemethod ofnix::Generator, which is ultimately responsible for generating the module's corresponding Nix code.nix::moduleis invoked atcompiler-core/src/codegen.rswhenever the project is being compiled with the Nix target.nix::Generatorcontains methods such as for generating a function definition, a record definition and module constants, as well as handling imports and exports, delegating tonix::importwhere necessary (see below).
- The file
compiler-core/src/nix/expression.rsis very important, as it implements the compilation of each kind of Gleam expression to Nix code. It contains aGeneratorstruct which is initialized once for each function in a module, and it essentially traverses the Typed AST for each expression, converting each inner expression to Nix, recursively. - The file
compiler-core/src/nix/import.rshandles imports, generating a series ofimportlines which appear at the top of the generated Nix file, as well as listing names to be exported at the bottom of the file (which are picked up bynix::Generator::compile). - The file
compiler-core/src/nix/pattern.rsis responsible for traversing patterns (used incaseclauses andlet/let assertstatements) and converting them into assignments and conditionals (in an abstract manner), which are then consumed by generators ofcaseandlet/let assertatnix/expression.rsand translated toif...then...else ifstatements where appropriate. - The file
compiler-core/src/nix/syntax.rscontains multiple helpers to generate specific kinds of Nix expressions. For example, to generate alet...inexpression, to generate an attribute set from a list of name/value pairs, and so on. These helpers are extensively used by other submodules ofnix. - Tests are located in
compiler-core/src/nix/tests.
This page is under construction.