Skip to content

Add Error::new_range constructor taking Range<Cursor> - #2068

Merged
dtolnay merged 1 commit into
masterfrom
newrange
Jul 20, 2026
Merged

dtolnay merged 1 commit into
masterfrom
newrange

Conversation

@dtolnay

@dtolnay dtolnay commented Jul 20, 2026 •

Copy link
Copy Markdown
Owner

Example: This parses a sequence of '+'-separated lifetimes and types like Vec<u8> + dyn Display + 'static, at least one of which must be a type.

use syn::{Lifetime, Token, Type};
use syn::parse::{Error, ParseStream, Result};

enum Thing {
    Lifetime(Lifetime),
    Type(Type),
}

fn parse_things(input: ParseStream) -> Result<Vec<Thing>> {
    let things_begin = input.cursor();
    let things_end;
    let mut things = Vec::new();
    let mut has_type = false;
    loop {
        if input.peek(Lifetime) {
            let lifetime: Lifetime = input.parse()?;
            things.push(Thing::Lifetime(lifetime));
        } else {
            let ty = input.call(Type::without_plus)?;
            things.push(Thing::Type(ty));
            has_type = true;
        }
        let plus_token: Option<Token![+]> = input.parse()?;
        if plus_token.is_none() {
            things_end = input.cursor();
            break;
        }
    }

    if has_type {
        Ok(things)
    } else {
        let msg = "things must not be all lifetimes, at least one type is required";
        Err(Error::new_range(things_begin..things_end, msg))
    }
}
error: things must not be all lifetimes, at least one type is required
 --> example.rs:4:23
  |
4 |     example!(THINGS = 'a + 'b, ...);
  |                       ^^^^^^^

@dtolnay
dtolnay force-pushed the newrange branch 2 times, most recently from b1ae745 to 5a05d87 Compare July 20, 2026 04:23
@dtolnay
dtolnay merged commit c6ac5e5 into master Jul 20, 2026
30 checks passed
@dtolnay
dtolnay deleted the newrange branch July 20, 2026 04:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant