diff --git a/crates/moxy-ast/src/args/angle_arguments.rs b/crates/moxy-ast/src/args/angle_arguments.rs index 4b060311..d66b8a27 100644 --- a/crates/moxy-ast/src/args/angle_arguments.rs +++ b/crates/moxy-ast/src/args/angle_arguments.rs @@ -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::]>(parser)?, gt_punct: <_ as Parse>::parse(parser)?, }) } @@ -34,6 +34,11 @@ impl Parse for AngleArguments { while ::peek(cursor) { cursor = ::skip(cursor)?; + + if ]>::peek(cursor) { + break; + } + cursor = GenericArgument::skip(cursor)?; } diff --git a/crates/moxy-ast/src/generics/mod.rs b/crates/moxy-ast/src/generics/mod.rs index 30736013..41177089 100644 --- a/crates/moxy-ast/src/generics/mod.rs +++ b/crates/moxy-ast/src/generics/mod.rs @@ -59,7 +59,7 @@ impl Parse for Generics { fn parse(parser: &Parser) -> Result { let lt: Option = <_ as Parse>::parse(parser)?; let params = if lt.is_some() { - List::parse_nonempty(parser)? + List::parse_nonempty_until::]>(parser)? } else { List::new() }; @@ -87,6 +87,11 @@ impl Parse for Generics { while ::peek(cursor) { cursor = ::skip(cursor)?; + + if ]>::peek(cursor) { + break; + } + cursor = GenericParam::skip(cursor)?; } diff --git a/crates/moxy-ast/src/list.rs b/crates/moxy-ast/src/list.rs index 59c05fed..22a5d6f2 100644 --- a/crates/moxy-ast/src/list.rs +++ b/crates/moxy-ast/src/list.rs @@ -256,6 +256,33 @@ impl List { } } +impl List { + /// 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(parser: &Parser) -> Result { + 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 Clone for List { fn clone(&self) -> Self { Self { diff --git a/crates/moxy-ast/src/use_tree/mod.rs b/crates/moxy-ast/src/use_tree/mod.rs index 6281fb26..cd3e3f37 100644 --- a/crates/moxy-ast/src/use_tree/mod.rs +++ b/crates/moxy-ast/src/use_tree/mod.rs @@ -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> { + peek_segment(cursor).then(|| cursor.offset(1)) +} diff --git a/crates/moxy-ast/src/use_tree/use_group.rs b/crates/moxy-ast/src/use_tree/use_group.rs index 4a57dfb4..ca1edf5c 100644 --- a/crates/moxy-ast/src/use_tree/use_group.rs +++ b/crates/moxy-ast/src/use_tree/use_group.rs @@ -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 { 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> { let mut inner = cursor.descend(Delim::Brace)?; - inner = UseTree::skip(inner)?; - while ::peek(inner) { - inner = ::skip(inner)?; + while !inner.is_empty() { inner = UseTree::skip(inner)?; + + if inner.is_empty() { + break; + } + + inner = ::skip(inner)?; } if inner.is_empty() { Some(cursor.offset(1)) } else { None } diff --git a/crates/moxy-ast/src/use_tree/use_name.rs b/crates/moxy-ast/src/use_tree/use_name.rs index 470788a7..b89182b4 100644 --- a/crates/moxy-ast/src/use_tree/use_name.rs +++ b/crates/moxy-ast/src/use_tree/use_name.rs @@ -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 { Ok(Self { - ident: <_ as Parse>::parse(parser)?, + ident: parser.parse_ident_any()?, }) } fn skip(cursor: Cursor<'_>) -> Option> { - Ident::skip(cursor) + super::skip_segment(cursor) } } diff --git a/crates/moxy-ast/src/use_tree/use_path.rs b/crates/moxy-ast/src/use_tree/use_path.rs index 3d3bc3e6..99b54880 100644 --- a/crates/moxy-ast/src/use_tree/use_path.rs +++ b/crates/moxy-ast/src/use_tree/use_path.rs @@ -17,13 +17,13 @@ pub struct UsePath { impl Parse for UsePath { fn peek(cursor: Cursor<'_>) -> bool { let cursor = Option::::skip(cursor).unwrap_or(cursor); - Ident::peek(cursor) && ::peek(cursor.offset(1)) + super::peek_segment(cursor) && ::peek(cursor.offset(1)) } fn parse(parser: &Parser) -> Result { 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)?), }) @@ -31,7 +31,7 @@ impl Parse for UsePath { fn skip(mut cursor: Cursor<'_>) -> Option> { cursor = Option::::skip(cursor)?; - cursor = Ident::skip(cursor)?; + cursor = super::skip_segment(cursor)?; cursor = ::skip(cursor)?; UseTree::skip(cursor) } diff --git a/crates/moxy-ast/src/use_tree/use_rename.rs b/crates/moxy-ast/src/use_tree/use_rename.rs index c6426cce..12213d40 100644 --- a/crates/moxy-ast/src/use_tree/use_rename.rs +++ b/crates/moxy-ast/src/use_tree/use_rename.rs @@ -14,19 +14,19 @@ pub struct UseRename { impl Parse for UseRename { fn peek(cursor: Cursor<'_>) -> bool { - Ident::peek(cursor) && ::peek(cursor.offset(1)) && Ident::peek(cursor.offset(2)) + super::peek_segment(cursor) && ::peek(cursor.offset(1)) && Ident::peek(cursor.offset(2)) } fn parse(parser: &Parser) -> Result { 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> { - Ident::skip(::skip(Ident::skip(cursor)?)?) + Ident::skip(::skip(super::skip_segment(cursor)?)?) } } diff --git a/tests/generics.rs b/tests/generics.rs index 5e6b94a1..078bcd29 100644 --- a/tests/generics.rs +++ b/tests/generics.rs @@ -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(x: Foo) {}", "fn f < T : A , > (x : Foo < A , B , >) {}"), + ("struct S(Vec);", "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"); +} diff --git a/tests/use_items.rs b/tests/use_items.rs index 2ab65f5c..23d30607 100644 --- a/tests/use_items.rs +++ b/tests/use_items.rs @@ -1,4 +1,5 @@ use moxy::ast::Item; +use moxy::token::ToTokenStream; #[test] fn grouped_use_items_preserve_renames_globs_and_self_imports() { @@ -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); + } +}