Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion crates/moxy-ast/src/args/angle_arguments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ impl Parse for AngleArguments {
Ok(Self {
colon2: <_ as Parse>::parse(parser)?,
lt_punct: <_ as Parse>::parse(parser)?,
args: List::parse_nonempty(parser)?,
args: List::parse_nonempty_until::<Token![>]>(parser)?,
gt_punct: <_ as Parse>::parse(parser)?,
})
}
Expand All @@ -34,6 +34,11 @@ impl Parse for AngleArguments {

while <Token![,]>::peek(cursor) {
cursor = <Token![,]>::skip(cursor)?;

if <Token![>]>::peek(cursor) {
break;
}

cursor = GenericArgument::skip(cursor)?;
}

Expand Down
7 changes: 6 additions & 1 deletion crates/moxy-ast/src/generics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ impl Parse for Generics {
fn parse(parser: &Parser) -> Result<Self, ParseError> {
let lt: Option<Token![<]> = <_ as Parse>::parse(parser)?;
let params = if lt.is_some() {
List::parse_nonempty(parser)?
List::parse_nonempty_until::<Token![>]>(parser)?
} else {
List::new()
};
Expand Down Expand Up @@ -87,6 +87,11 @@ impl Parse for Generics {

while <Token![,]>::peek(cursor) {
cursor = <Token![,]>::skip(cursor)?;

if <Token![>]>::peek(cursor) {
break;
}

cursor = GenericParam::skip(cursor)?;
}

Expand Down
27 changes: 27 additions & 0 deletions crates/moxy-ast/src/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,33 @@ impl<T: Parse, P: Parse> List<T, P> {
}
}

impl<T: Parse, P: Parse> List<T, P> {
/// Parses one or more values separated by punctuation, with an optional
/// trailing punctuation before the token `E`, which is left in `parser`.
///
/// Use this for a list closed by a token, such as generic arguments before
/// `>`, where Rust accepts a trailing comma.
pub fn parse_nonempty_until<E: Parse>(parser: &Parser) -> Result<Self, ParseError> {
let mut punctuated = Self::new();

loop {
punctuated.push_value(<_ as Parse>::parse(parser)?);

if !P::peek(parser.cursor()) {
break;
}

punctuated.push_punct(<_ as Parse>::parse(parser)?);

if E::peek(parser.cursor()) {
break;
}
}

Ok(punctuated)
}
}

impl<T: Clone, P: Clone> Clone for List<T, P> {
fn clone(&self) -> Self {
Self {
Expand Down
16 changes: 16 additions & 0 deletions crates/moxy-ast/src/use_tree/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,3 +135,19 @@ impl ToTokens for UseTree {
}
}
}

// A use path segment: an identifier or one of the path keywords `crate`,
// `self`, `super`, and `Self`
fn peek_segment(cursor: Cursor<'_>) -> bool {
cursor.curr().is_some_and(|token| {
token.is_ident()
|| token.is_keyword_crate()
|| token.is_keyword_self_value()
|| token.is_keyword_super()
|| token.is_keyword_self_type()
})
}

fn skip_segment(cursor: Cursor<'_>) -> Option<Cursor<'_>> {
peek_segment(cursor).then(|| cursor.offset(1))
}
15 changes: 10 additions & 5 deletions crates/moxy-ast/src/use_tree/use_group.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,29 @@ pub struct UseGroup {

impl Parse for UseGroup {
fn peek(cursor: Cursor<'_>) -> bool {
cursor.descend(Delim::Brace).map(|c| UseTree::peek(c)).unwrap_or_default()
// An empty group, as in `use a::{};`, is valid and imports nothing
cursor.is_delimited(Delim::Brace)
}

fn parse(parser: &Parser) -> Result<Self, ParseError> {
let (span, parser) = parser.parse_group_spanned(Delim::Brace)?;

Ok(Self {
items: Delimited::brace(span, List::parse_nonempty(&parser)?),
items: Delimited::brace(span, List::parse_all(&parser)?),
})
}

fn skip(cursor: Cursor<'_>) -> Option<Cursor<'_>> {
let mut inner = cursor.descend(Delim::Brace)?;
inner = UseTree::skip(inner)?;

while <Token![,]>::peek(inner) {
inner = <Token![,]>::skip(inner)?;
while !inner.is_empty() {
inner = UseTree::skip(inner)?;

if inner.is_empty() {
break;
}

inner = <Token![,]>::skip(inner)?;
}

if inner.is_empty() { Some(cursor.offset(1)) } else { None }
Expand Down
6 changes: 3 additions & 3 deletions crates/moxy-ast/src/use_tree/use_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,17 @@ pub struct UseName {

impl Parse for UseName {
fn peek(cursor: Cursor<'_>) -> bool {
Ident::peek(cursor)
super::peek_segment(cursor)
}

fn parse(parser: &Parser) -> Result<Self, ParseError> {
Ok(Self {
ident: <_ as Parse>::parse(parser)?,
ident: parser.parse_ident_any()?,
})
}

fn skip(cursor: Cursor<'_>) -> Option<Cursor<'_>> {
Ident::skip(cursor)
super::skip_segment(cursor)
}
}

Expand Down
6 changes: 3 additions & 3 deletions crates/moxy-ast/src/use_tree/use_path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,21 @@ pub struct UsePath {
impl Parse for UsePath {
fn peek(cursor: Cursor<'_>) -> bool {
let cursor = Option::<Token![::]>::skip(cursor).unwrap_or(cursor);
Ident::peek(cursor) && <Token![::]>::peek(cursor.offset(1))
super::peek_segment(cursor) && <Token![::]>::peek(cursor.offset(1))
}

fn parse(parser: &Parser) -> Result<Self, ParseError> {
Ok(Self {
prefix: <_ as Parse>::parse(parser)?,
ident: <_ as Parse>::parse(parser)?,
ident: parser.parse_ident_any()?,
path_sep: <_ as Parse>::parse(parser)?,
tree: Box::new(<_ as Parse>::parse(parser)?),
})
}

fn skip(mut cursor: Cursor<'_>) -> Option<Cursor<'_>> {
cursor = Option::<Token![::]>::skip(cursor)?;
cursor = Ident::skip(cursor)?;
cursor = super::skip_segment(cursor)?;
cursor = <Token![::]>::skip(cursor)?;
UseTree::skip(cursor)
}
Expand Down
6 changes: 3 additions & 3 deletions crates/moxy-ast/src/use_tree/use_rename.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,19 @@ pub struct UseRename {

impl Parse for UseRename {
fn peek(cursor: Cursor<'_>) -> bool {
Ident::peek(cursor) && <Token![as]>::peek(cursor.offset(1)) && Ident::peek(cursor.offset(2))
super::peek_segment(cursor) && <Token![as]>::peek(cursor.offset(1)) && Ident::peek(cursor.offset(2))
}

fn parse(parser: &Parser) -> Result<Self, ParseError> {
Ok(Self {
ident: <_ as Parse>::parse(parser)?,
ident: parser.parse_ident_any()?,
as_keyword: <_ as Parse>::parse(parser)?,
rename: <_ as Parse>::parse(parser)?,
})
}

fn skip(cursor: Cursor<'_>) -> Option<Cursor<'_>> {
Ident::skip(<Token![as]>::skip(Ident::skip(cursor)?)?)
Ident::skip(<Token![as]>::skip(super::skip_segment(cursor)?)?)
}
}

Expand Down
15 changes: 15 additions & 0 deletions tests/generics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,18 @@ fn const_generic_default_permutations_parse() {
let _: Item = moxy::parse!(source as Item).unwrap_or_else(|err| panic!("failed to parse {source:?}: {err}"));
}
}

#[test]
fn closed_lists_accept_a_trailing_comma() {
for (source, tokens) in [
("use a::{b, c,};", "use a :: {b , c ,} ;"),
("fn f<T: A,>(x: Foo<A, B,>) {}", "fn f < T : A , > (x : Foo < A , B , >) {}"),
("struct S<T,>(Vec<T,>);", "struct S < T , > (Vec < T , >) ;"),
] {
let item: Item = moxy::parse!(source).unwrap_or_else(|error| panic!("`{source}`: {error}"));
assert_eq!(item.to_token_stream().to_string(), tokens);
}

let error = moxy::parse!("use a::{b c};" as Item).err().unwrap();
assert_eq!(error.message(), "expected punctuation");
}
29 changes: 29 additions & 0 deletions tests/use_items.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use moxy::ast::Item;
use moxy::token::ToTokenStream;

#[test]
fn grouped_use_items_preserve_renames_globs_and_self_imports() {
Expand All @@ -14,3 +15,31 @@ fn leading_paths_and_single_names_render_without_extra_spaces() {
let item: Item = moxy::parse!("use ::core::fmt;").unwrap();
assert_eq!(moxy::fmt!(&item).unwrap(), "use ::core::fmt;");
}

#[test]
fn use_paths_accept_path_keywords() {
for (source, expected) in [
("use crate::a;", "use crate::a;"),
("use self::a;", "use self::a;"),
("use super::super::a;", "use super::super::a;"),
("use super::{A, B as C};", "use super::{A, B as C};"),
("use a::{self, b};", "use a::{self, b};"),
("use a::{self as c};", "use a::{self as c};"),
] {
let item: Item = moxy::parse!(source).unwrap_or_else(|error| panic!("`{source}`: {error}"));
assert_eq!(moxy::fmt!(&item).unwrap(), expected);
}
}

#[test]
fn empty_use_groups_parse() {
for (source, tokens, formatted) in [
("use a::{};", "use a :: {} ;", "use a::{};"),
("use {};", "use {} ;", "use {};"),
("use a::{b::{}, c};", "use a :: {b :: {} , c} ;", "use a::{b::{}, c};"),
] {
let item: Item = moxy::parse!(source).unwrap_or_else(|error| panic!("`{source}`: {error}"));
assert_eq!(item.to_token_stream().to_string(), tokens);
assert_eq!(moxy::fmt!(&item).unwrap(), formatted);
}
}