Search code examples
nix

What is the syntax of a valid identifier in the Nix language?


Couldn't find the language specification anywhere, it basically the Nix source? The repo's README refers to the Nix manual, but it seems incomplete. For example, 4.2. Identifiers in Nix Pills mentions that the dash (-) can be used, and the manual never even mentions identifier syntax.


update: Just found the already closed (and unresolved) NixOS/nix issue #592 No documentation on valid symbol/variable names


Solution

  • There may be better references, but at the very least you can check out the source of the lexer, which defines an identifier

    ID          [a-zA-Z\_][a-zA-Z0-9\_\'\-]*
    

    as a string consisting of ASCII letters, numbers, _, ', or -, and starting with either a letter or _.


    (Update: this references an out-of-date reference grammar, not the working grammar.)

    According to the grammar, an identifier cannot contain a -:

      <production id="nix.id">
        <lhs>Id</lhs>
        <rhs>[a-zA-Z\_][a-zA-Z0-9\_\']*</rhs>
      </production>
    

    but a path can:

      <production id="nix.path">
        <lhs>Path</lhs>
        <rhs>[a-zA-Z0-9\.\_\-\+]*(\/[a-zA-Z0-9\.\_\-\+]+)+</rhs>
      </production>
    

    I am not entirely sure what evaluation process leads the REPL to report a syntactically valid path as undefined variable.