Skip to content

Declarative Grammar for the Nix Language #1102

Closed as not planned
Closed as not planned

Description

@taktoa

Intro

I think we probably all agree that it would be nice to have a proper BNF for the Nix language, and that ideally the "official" parser would be compiled from that BNF. Here's why:

  • It could improve editor support (e.g.: we could have a nix-parse executable that either pretty-prints the AST or outputs it in JSON/XML/s-expression format).
  • It could make projects like hnix, cabal2nix, and nixfmt much easier.
  • It would also serve as an official definition of the Nix syntax, which would be a stepping stone to a formal executable semantics for Nix.
  • The Nix syntax would have improved documentation (I have often seen people complain about the Nix syntax being weird, so the ability to link to the full BNF and say "it's not that bad!" would be quite nice).
  • Code quality in the Nix evaluator would likely increase, and we could decrease the incidence of bugs in our parser (admittedly I don't know if such bugs are common).

There is a tool that would allow for such a thing, called BNFC. It has a very BNF-like syntax and has many backends (C/C++ via Bison/Flex, Haskell via Happy/Alex, OCaml, LaTeX for documentation), and can even generate pretty-printers.

Obstacles

The obstacles I see to using BNFC for the Nix parser are:

  1. The BNF would have to be written. This doesn't seem too hard but someone has to do it. There are a few existing Haskell parsers that one could look at for inspiration, and the Nix expression syntax isn't so complicated anyway. The Nix source code will probably have to refactored to deal with the new intermediate representation, as well.
  2. The parser thus generated could be too slow for nixpkgs – we're already dealing with some major evaluation time problems.
  3. Naively, this would introduce GHC into the compile-time closure of Nix.

Obstacle 1

Regarding obstacle 1, this is unavoidable but I might be willing to do a large amount of the work here (though it would be nice to have a point of contact on IRC for questions about the Nix internals).

Obstacle 2

Regarding obstacle 2: I think we mainly need an answer to the question "How much time is currently spent in the Nix parser versus other parts of evaluation?". If the answer is "not very much", then the speed of the generated parser will probably not be much of an issue. Otherwise, I would be willing to write a BNFC grammar and compare its speed to the current parser, assuming we agree on a solution for obstacle 3.

Obstacle 3

Regarding obstacle 3, I have thought of a few different options for mitigating the issue (I've put the "cons" associated with each option in bold, and any notable "pros" in italics):

Mitigations

  1. We could have the BNFC-based parser in addition to an in-tree parser that is used as a fallback in case BNFC is not available.
    • Could lead to the BNFC parser falling out of sync with the in-tree parser.
    • We now need to maintain two syntax definitions.
    • Could have test code that uses QuickCheck or similar to generate definitions with the BNFC parser and tests if both parsers output the same AST, though this would not cover cases where syntax was added to the non-BNFC parser but not to the BNFC-based parser.
  2. We could add a commit hook and Travis CI test that forces pre-compilation of the BNFC syntax, and check in the generated parser C++ source as well as the BNF file.
    • Adds nothing to the build/runtime closure of Nix.
    • Could be annoying for developers of the Nix package manager.
  3. We could say "screw it" and have the compiled syntax as a nativeBuildInput.
    • Breaks native builds of Nix on platforms where GHC doesn't build.
  4. We could compile BNFC to C via JHC or GHC -fvia-C, check that into a repo, and have Nix depend on the built version of that code.
    • Adds nothing to the build/runtime closure of Nix.
    • JHC seems unmaintained (last commit is 1 year old).
    • -fvia-C may not support the required extensions.
    • There isn't yet an unregistered build of GHC in nixpkgs, AFAICT.
    • Adds minor maintenance hassle.
  5. We could compile BNFC to JavaScript using GHCJS, check that into a repo, and have Nix depend on that code plus Node.
    • Adds node.js to the build-time closure of Nix.
    • Adds minor maintenance hassle.
  6. We could compile BNFC to LLVM assembly using GHC's LLVM backend, check that into a repo, and have Nix depend on that plus LLVM. This would probably be a good opportunity to switch Nix's build over to Clang, since we are depending on LLVM anyway. Preferably, we'd at least disassemble the LLVM bitcode before checking into a git repo, so that we can diff changes.
    • Adds LLVM and potentially Clang to the build closure of Nix.
    • Adds minor maintenance hassle.
    • Could remove GCC from Nix build closure if we switch to Clang.
    • Clang is a native cross-compiler, so this might speed up cross-compilation of Nix (though I don't think anyone does this?).
  7. We could precompile BNFC (with static linking) and then make a derivation that fetches the binary and patchelfs in the libraries needed for GHC's runtime (GMP, libc, and libpthread, mainly).
    • Adds a non-source package to the build closure of Nix.
    • Adds maintenance hassle.
    • Potentially annoying to make portable.

Personally, I would say that:

  • Option 1 is the best idea iff BNFC generates a parser that is too slow to use and there's no workarounds for that fact.
  • Options 3 and 7 seem like bad ideas.
  • Options 6 and 5 are great, if adding LLVM or Node to the Nix build closure is palatable.
  • Option 4 is great, assuming that BNFC can actually compile with -fvia-C or JHC.
  • Option 2 is probably the most realistic, assuming there is buy-in from you all.

Summary

I might be willing to make the BNF for Nix and do the preliminary work to compare efficiency with the existing parser, iff people think this is a good idea.

The main open questions are:

  1. Is this a good idea?
  2. How much time is spent in the Nix parser versus other parts of evaluation?
  3. Which of the above mitigations is best for addressing the Nix build closure issue?
    • Can BNFC compile under -fvia-C or JHC?
    • How hard is it to compile Node for non-x86_64 platforms, and how big is its closure?
    • How hard is it to compile LLVM for non-x86_64 platforms, and how big is its closure?
    • Would the developers of Nix be willing to deal with installing BNFC and a commit hook?

Activity

  1. taktoa commented on Oct 22, 2016

    @taktoa
    MemberAuthor

    Looks like the BNFC source requires GADTs, DataKinds, etc. (full list here), so JHC is almost certainly not workable.

    I think compiles using -fvia-C are not as portable as I thought, since the GHC runtime contains assembly code.

    Not sure about the portability of GHC-generated LLVM bitcode... probably has the same issue as -fvia-C.

    GHCJS + Node should still definitely be workable, assuming we are okay with adding Node to our build closure (AFAIK it's available on pretty much every platform, considering that it is based on V8, so bootstrapping shouldn't be a big deal, and its runtime closure is only 30 MB).

  2. domenkozar commented on Oct 22, 2016

    @domenkozar
    Member
  3. domenkozar commented on Oct 22, 2016

    @domenkozar
    Member

    How much time is spent in the Nix parser versus other parts of evaluation?

    nix-instantiate has a --parse flag, you could measure that time on nixpkgs source tree.

    Can BNFC track state for our string escaping logic? See Gabriella439/nixfmt#3

  4. taktoa commented on Oct 22, 2016

    @taktoa
    MemberAuthor

    @domenkozar
    Having now sufficiently played around with BNFC, this is an issue. BNFC supports declaration of comment syntax, so I find it reasonably likely that they would be willing to consider adding support for custom string syntax and antiquotation. The main issue is figuring out how to compile it away while still supporting as many backends as possible. I'll take a look at emailing their mailing list.

  5. vcunat commented on Oct 22, 2016

    @vcunat
    Member

    2: Performance. Sometimes we do parse quite large files that are mainly JSON-like data describing even thousands of packages. I expect these are relatively easy on the evaluator and it wouldn't be nice if it should slow down significantly. In as slightly different all-packages.nix case, the file is huge (to parse) but typically only small parts of it are actually interpreted, thanks to laziness.

    3: Making nix depend on Haskell stuff could be problematic, but IMHO it wouldn't be a significant obstacle if we could lift that dependency in released tarballs (by distributing the generated stuff within; few enough people will want to patch the parser).

    x: Some small corners of the syntax do feel unintuitive to me, but I expect most users won't appreciate a BNF-like description. True parser "bugs" seem very rare to me.

  6. Ericson2314 commented on Oct 22, 2016

    @Ericson2314
    Member

    How fancy a grammar do we need? I suppose we could write a grammar that can be compiled to C++ by C++ and compiled to Haskell by Haskell.

  7. taktoa commented on Oct 22, 2016

    @taktoa
    MemberAuthor

    Since I now realize that Nix does not have a context-free grammar (due to string antiquotation), I think there isn't much merit to having a BNF describing the syntax, unless BNFC gets explicit support for string antiquotation.

    That said, I do think there is room for improvement in the Nix expression parser. Particularly:

    There are some less difficult changes we could make to the Nix expression parser that may still be worthwhile:

    1. I think it would be very useful to have an AST representing the expression exactly as parsed, which would allow for better editor support etc. Ideally we could even have a C library/wrapper that exports our parser and its output AST, thus allowing other languages to bind to our API. We would then have a function that transforms this AST into a simpler intermediate representation, which could then be evaluated.
    2. Since we'd be mostly rewriting the parser anyway, we could switch to something like Boost Spirit and get more intuitive (i.e.: not LALR, which IME breaks most peoples' brains) syntax and maybe faster parse speeds as well (apparently their numeric parsers beat hand-written parsers like atof). I'm less confident about this suggestion.
  8. Ericson2314 commented on Oct 22, 2016

    @Ericson2314
    Member

    Since I now realize that Nix does not have a context-free grammar (due to string antiquotation)

    Hmm? I am quite surprised by this.

  9. taktoa commented on Oct 22, 2016

    @taktoa
    MemberAuthor

    At the very least, it requires fancy lexing to be parsed remotely efficiently.
    The meaning of " depends on the depth of previously parsed antiquotations, so you need a stack to lex it.

  10. Ericson2314 commented on Oct 22, 2016

    @Ericson2314
    Member

    Sure that makes sense, but is a rather different from being context-sensitive :).

  11. vcunat commented on Oct 22, 2016

    @vcunat
    Member

    Fancier lexing might work. I expect "somestring${ could be lexed (almost) as "somestring" + followed by a special kind of opening parentheses.

  12. vcunat commented on Oct 22, 2016

    @vcunat
    Member

    IIRC it shouldn't matter that the } token would be used both for closing this one and for standard attribute sets/maps.

  13. taktoa commented on Oct 22, 2016

    @taktoa
    MemberAuthor

    Ericson2314: yeah you're definitely right; it was one of those situations where my inability to come up with a working BNFC led me to rationalize

    vcunat: I had that thought, but what of ${ used outside strings? e.g.: let bar = "baz"; in foo.${bar}

  14. vcunat commented on Oct 22, 2016

    @vcunat
    Member

    Hmm, yes that's also a correct antiquation :-) If the lexer does something like: "somestring${ -> "somestring" + ${, it shouldn't matter that antiquoting (i.e. ${ EXPR }) is also valid in some other cases. In the worst case, some bad usages could be caught during semantic analysis.

  15. Ericson2314 commented on Oct 22, 2016

    @Ericson2314
    Member

    Yeah we just need context-free, not regular, lexing. This isn't so bad: you can think of s-expresion -> lisp and token tree -> Rust as an analogous composition of context-free grammars.

    A "token tree" language for Nix, as @vcunat hints at, could look something like:

    token-tree       ::= '(' token-tree* ')'
                      |  '[' token-tree* ']'
                      |  '{' token-tree* '}'
                      |  '"' string '"'
                      |  '\'\'' multiline-string '\'\''
                      |  # atomic tokens
    
    string           ::= # empty nonterminal
                      |  non-$-or-"-char string
                      |  '$'
                      |  '\$' string
                      |  '$' non-{-or-"-char string
                      |  '${' token-tree* '}' string
    
    multiline-string ::= # empty nonterminal
                      |  non-$-or-\'-char multiline-string
                      |  '\'' non-$-or-\'-char multiline-string
                      |  '$'
                      |  '\'\'${' multiline-string
                      |  '$' non-{-or-\'-char multiline-string
                      |  '${' token-tree* '}' multiline-string
    

    the string stuff is really nothing but escape sequence handling---until you actually parse an antiquoted token tree its regular. I did a fairly ugly and probably not-quite-correct job---somebody with more experience in this area could clean it up.

    In practice, I'd hope we could use some sort of macro / parameterized rule to deduplicate string and multi-line-string.

  16. 15 remaining items

  17. taktoa commented on Jan 6, 2018

    @taktoa
    MemberAuthor

    That issue is actually about something different: the ease of writing parsers in Nix.

  18. peti commented on Apr 21, 2018

    @peti
    Member

    Can we close this issue?

  19. taktoa commented on Apr 21, 2018

    @taktoa
    MemberAuthor

    Sure, though at some point it would probably still be a good idea to rewrite Nix's parser.

  20. peti commented on Apr 21, 2018

    @peti
    Member

    I completely agree. I think this ticket should be closed solely because I don't believe that keeping it open serves any purpose. That's not to say that the subject matter discussed in this ticket wouldn't be important -- it is!

  21. changed the title [-]BNFC-based parser[/-] [+]Declarative Grammar for the Nix Language[/+] on Apr 6, 2023
  22. added
    language
    on Feb 5, 2024
  23. added a commit that references this issue on Mar 8, 2026
    8285288
  24. tomberek commented on Aug 13, 2026

    @tomberek
    Contributor

    Closing as stale. Re-open if needed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

documentationlanguage

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions