rust-analyzer icon indicating copy to clipboard operation
rust-analyzer copied to clipboard

default_field_values grammar

Open sbant opened this issue 11 months ago • 3 comments

Allow struct definitions to provide default values for individual fields and thereby allowing those to be omitted from initializers.

https://rust-lang.github.io/rfcs/3681-default-field-values.html

https://github.com/dtolnay/syn/issues/1774

sbant avatar Jan 14 '25 19:01 sbant

Dropping some pointers here (for anyone interested, no need to do all of this at once, just the parsing part on its own for now is fine)

So the parser needs to be adjusted as follows:

  • Update the grammar https://github.com/rust-lang/rust-analyzer/blob/40710f27486e244eca2d48b830ea2ecb8474d15a/crates/syntax/rust.ungram#L242-L244
  • run cargo codegen grammar to update the syntax tree
  • Adjust the parser for field defs https://github.com/rust-lang/rust-analyzer/blob/40710f27486e244eca2d48b830ea2ecb8474d15a/crates/parser/src/grammar/items/adt.rs#L128-L143
  • And here for constructor expressions https://github.com/rust-lang/rust-analyzer/blob/40710f27486e244eca2d48b830ea2ecb8474d15a/crates/parser/src/grammar/expressions.rs#L675-L764

The trickier part is that all fields now become potential bodies which still kind of struggle to represent properly, generally we'd need to add a new variant to https://github.com/rust-lang/rust-analyzer/blob/40710f27486e244eca2d48b830ea2ecb8474d15a/crates/hir-def/src/lib.rs#L875-L883 that represents struct fields FieldId(FieldId). Then the compiler should guide you through most changes required.

Adjust the default derive https://github.com/rust-lang/rust-analyzer/blob/40710f27486e244eca2d48b830ea2ecb8474d15a/crates/hir-expand/src/builtin/derive_macro.rs#L594-L635

Veykril avatar Jan 15 '25 08:01 Veykril

#![feature(default_field_values)]

struct Config {
    port: u16 = 8080,     
    debug: bool = false,
}
fn main(){
    let a = Config{..};
}

rust analyzer give error

missing structure fields:
- port
- debug

but code can compile

kouhe3 avatar Nov 27 '25 08:11 kouhe3

Yeah, we once had implemented this but it has been disabled by https://github.com/rust-lang/rust-analyzer/pull/19063, to speed-up our salsa migration.

ShoyuVanilla avatar Nov 27 '25 08:11 ShoyuVanilla