dtolnay / dtolnay/syn

Improve documentation for the `position` field of the `QSelf` type, which is difficult to understand.

Open
#1,386 0 comments 0 reactions 0 assignees View on GitHub
docs
Dominant language
Rust
Stars
3.4k
Forks
374
Avg merge
1d 5h
Merged PRs (30d)
2

Description

I struggled for quite a while to understand how to deal with the position field of the
`syn::QSelf` type. I understand that as an author it is difficult to see parts in a project
that are not understandable, so I made this issue.

I had a few questions that I think the documentation should answer:
The docs mention that the `as` trait and associated item are stored separately,
but there is no mention of where that is.

It also mentions that the position for `AssociatedItem` in ` as a::b::Trait>::AssociatedItem`
is `3`, but not how this number changes depending on the type. For example, what would be the position of
the `a::b::Trait` be? How could one obtain this? An example code would be immensely helpful. I am not good with writing examples, but here is something as an idea:
```rust
use quote::ToTokens;
use syn::punctuated::Punctuated;

let ty: syn::TypePath = syn::parse_quote!( as a::b::Trait>::AssociatedItem);

// the ty.path looks like this a::b::Trait::AssociatedItem
// therefore when a qualified self is involved, it can not
// be treated as a normal path.

// this checks if the ty is cast to a trait and if so, prints
// that trait
if let Some(syn::QSelf {
ty: sub_ty,
as_token,
position,
..
}) = &ty.qself
{
if as_token.is_some() {
// the type has been cast to another trait
// the position is the index where the associated item
// starts in the ty.path
//
// everything up to position (0..position) is the trait
// that it is cast to
let mut trait_path = syn::Path {
leading_colon: None,
segments: Punctuated::new(),
};

for i in 0..*position {
trait_path.segments.push(ty.path.segments[i].clone());
}

// a :: b :: Trait
println!("the ty is cast to {}", trait_path.to_token_stream());
} else {
println!("ty has not been casted");
}
}
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.