Why AST node in rustc use tuple rather than struct?

AST in rustc:
ExprKind in rustc_ast::ast - Rust (rust-lang.org)
AST in syn:
Item in syn - Rust (docs.rs)

It seems a bit of strange for me. Why the compiler team choose to use tuple? Struct could be a bit more clear, I think.

They are probably constructing and matching the AST nodes a lot, and always having to type out field names gets annoying and lengthy.

In the particular case of the while loop, for example, there isn't much extra clarity added by field names, as all three components have a different and obvious type. If a loop has an expression and a block, then the expression has to be the condition, since the body is always a block, and the label must be… well, the label.

2 Likes

Make a lot of sense.
Using struct is a bit of tedious for developer, but friendly to new reader.
Using tuple is compact and friendly to developer, but not that friendly to reader.
Thanks a lot for the quick and detailed answer.

Well, my point is exactly that for ASTs, it doesn't really make a difference. If all the fields were of very general types or if they were all the same type (e.g. Loop(String, u32, f32) or Loop(u16, u16, u16), then named fields would indeed be more readable. However, by the nature of ASTs, this is not the case more often than not, so one can afford using tuples without losing readability.

This is of course a very special/specific use case, and the weight of constructing/matching AST nodes must also be factored in, because it's an overwhelmingly frequent operation. In general, however, the intention may not be so obvious in the case of other data structures, so unless using a tuple can really be justified well, going with named fields instead is indeed a better default choice.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.