nix-community / rnix-parser

A Nix parser written in Rust [maintainer=@oberblastmeister]
MIT License
366 stars 44 forks source link

Node creation #25

Closed DieracDelta closed 3 years ago

DieracDelta commented 3 years ago

Suppose I want to create an AttrSet programmatically. This isn't very easy to do with the current API. The easiest thing to do is to create a string, parse it, and cast the root node to an AttrSet. This feels a bit hacky.

Thoughts on adding in constructors to src/types.rs that add in constructors for the various nodes? For example, something like:

  pub fn new(k: String) -> Key {...}
  pub fn new(k: Key, v: SyntaxNode) -> KeyValue {...}
  pub fn new(kvs: Vec<KeyValue>) -> AttrSet {...}

The idea is that these would add in all of the tokens necessary to make this syntactically valid. If there's interest, I can probably implement this, as we need it anyway for flake generator.

DieracDelta commented 3 years ago

So, I've taken a stab at this. I'm not sure if there's an easier way that I'm just missing, but what I had in mind live in here. If this makes sense and seems like a good idea, I can pull together a draft PR.

oppiliappan commented 3 years ago

rust-analyzer has an AST creation module here. They do exactly what you suggested: create a minimal nix source file with the node kind, parse to tree, find it, and cast.

DieracDelta commented 3 years ago

Wow this is seemingly what I was looking for. Thanks!