Skip to content
Merged
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
2 changes: 2 additions & 0 deletions crates/moxy-ast/src/use_tree/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ mod use_group;
mod use_name;
mod use_path;
mod use_rename;
mod use_segment;

pub use use_glob::*;
pub use use_group::*;
pub use use_name::*;
pub use use_path::*;
pub use use_rename::*;
pub use use_segment::*;

use moxy_token::{Span, Spanner, ToTokens, TokenStream};

Expand Down
8 changes: 4 additions & 4 deletions crates/moxy-ast/src/use_tree/use_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::*;
#[cfg_attr(feature = "derives", derive(Debug, PartialEq, Eq))]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct UseName {
pub ident: Ident,
pub segment: UseSegment,
}

impl Parse for UseName {
Expand All @@ -17,7 +17,7 @@ impl Parse for UseName {

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

Expand All @@ -28,12 +28,12 @@ impl Parse for UseName {

impl Spanner for UseName {
fn span(&self) -> Span {
self.ident.span()
self.segment.span()
}
}

impl ToTokens for UseName {
fn to_tokens(&self, t: &mut TokenStream) {
self.ident.to_tokens(t);
self.segment.to_tokens(t);
}
}
15 changes: 7 additions & 8 deletions crates/moxy-ast/src/use_tree/use_path.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use moxy_token::{Ident, Span, Spanner, ToTokens, TokenStream};
use moxy_token::{Span, Spanner, ToTokens, TokenStream};

use super::UseTree;
use crate::*;

/// A use path segment (`foo::<rest>`).
Expand All @@ -9,44 +8,44 @@ use crate::*;
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct UsePath {
pub prefix: Option<Token![::]>,
pub ident: Ident,
pub segment: UseSegment,
pub path_sep: Token![::],
pub tree: Box<UseTree>,
}

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))
UseSegment::peek(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)?,
segment: <_ as Parse>::parse(parser)?,
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 = UseSegment::skip(cursor)?;
cursor = <Token![::]>::skip(cursor)?;
UseTree::skip(cursor)
}
}

impl Spanner for UsePath {
fn span(&self) -> Span {
self.ident.span().join(self.tree.span())
self.segment.span().join(self.tree.span())
}
}

impl ToTokens for UsePath {
fn to_tokens(&self, t: &mut TokenStream) {
self.prefix.to_tokens(t);
self.ident.to_tokens(t);
self.segment.to_tokens(t);
self.path_sep.to_tokens(t);
self.tree.to_tokens(t);
}
Expand Down
12 changes: 6 additions & 6 deletions crates/moxy-ast/src/use_tree/use_rename.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,38 +7,38 @@ use crate::*;
#[cfg_attr(feature = "derives", derive(Debug, PartialEq, Eq))]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct UseRename {
pub ident: Ident,
pub segment: UseSegment,
pub as_keyword: Token![as],
pub rename: Ident,
}

impl Parse for UseRename {
fn peek(cursor: Cursor<'_>) -> bool {
Ident::peek(cursor) && <Token![as]>::peek(cursor.offset(1)) && Ident::peek(cursor.offset(2))
UseSegment::peek(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)?,
segment: <_ as Parse>::parse(parser)?,
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(UseSegment::skip(cursor)?)?)
}
}

impl Spanner for UseRename {
fn span(&self) -> Span {
self.ident.span().join(self.rename.span())
self.segment.span().join(self.rename.span())
}
}

impl ToTokens for UseRename {
fn to_tokens(&self, t: &mut TokenStream) {
self.ident.to_tokens(t);
self.segment.to_tokens(t);
self.as_keyword.to_tokens(t);
self.rename.to_tokens(t);
}
Expand Down
97 changes: 97 additions & 0 deletions crates/moxy-ast/src/use_tree/use_segment.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
use moxy_token::{Crate, Ident, SelfValue, Span, Spanner, Super, ToTokens, TokenStream};

use crate::{Cursor, Parse, ParseError, Parser};

/// A segment of an `use` path.
#[derive(Clone)]
#[cfg_attr(feature = "derives", derive(Debug, PartialEq, Eq))]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub enum UseSegment {
Ident(Ident),
Super(Super),
Crate(Crate),
SelfValue(SelfValue),
}

impl UseSegment {
pub fn is_ident(&self) -> bool {
matches!(self, Self::Ident(_))
}

pub fn is_super(&self) -> bool {
matches!(self, Self::Super(_))
}

pub fn is_crate(&self) -> bool {
matches!(self, Self::Crate(_))
}

pub fn is_self_value(&self) -> bool {
matches!(self, Self::SelfValue(_))
}

pub fn as_ident(&self) -> Option<&Ident> {
if let Self::Ident(v) = self { Some(v) } else { None }
}

pub fn as_super(&self) -> Option<&Super> {
if let Self::Super(v) = self { Some(v) } else { None }
}

pub fn as_crate(&self) -> Option<&Crate> {
if let Self::Crate(v) = self { Some(v) } else { None }
}

pub fn as_self_value(&self) -> Option<&SelfValue> {
if let Self::SelfValue(v) = self { Some(v) } else { None }
}
}

impl Spanner for UseSegment {
fn span(&self) -> Span {
match self {
Self::Ident(v) => v.span(),
Self::Super(v) => v.span(),
Self::Crate(v) => v.span(),
Self::SelfValue(v) => v.span(),
}
}
}

impl Parse for UseSegment {
fn peek(cursor: Cursor<'_>) -> bool {
Ident::peek(cursor) || Super::peek(cursor) || Crate::peek(cursor) || SelfValue::peek(cursor)
}

fn parse(parser: &Parser) -> Result<Self, ParseError> {
if Ident::peek(parser.cursor()) {
Ok(Self::Ident(<_ as Parse>::parse(parser)?))
} else if Super::peek(parser.cursor()) {
Ok(Self::Super(<_ as Parse>::parse(parser)?))
} else if Crate::peek(parser.cursor()) {
Ok(Self::Crate(<_ as Parse>::parse(parser)?))
} else if SelfValue::peek(parser.cursor()) {
Ok(Self::SelfValue(<_ as Parse>::parse(parser)?))
} else {
Err(parser.error("expected identifier, 'super', 'crate' or 'self'"))
}
}

fn skip(cursor: Cursor<'_>) -> Option<Cursor<'_>> {
Ident::skip(cursor)
.or_else(|| Super::skip(cursor))
.or_else(|| SelfValue::skip(cursor))
.or_else(|| Crate::skip(cursor))
}
}

impl ToTokens for UseSegment {
fn to_tokens(&self, t: &mut TokenStream) {
match self {
Self::Ident(v) => v.to_tokens(t),
Self::Super(v) => v.to_tokens(t),
Self::SelfValue(v) => v.to_tokens(t),
Self::Crate(v) => v.to_tokens(t),
}
}
}
17 changes: 14 additions & 3 deletions crates/moxy-fmt/src/ast/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,21 +205,32 @@ impl Format for UsePath {
f.text("::")?;
}

self.ident.format(f)?;
self.segment.format(f)?;
f.text("::")?;
self.tree.format(f)
}
}

impl Format for UseSegment {
fn format(&self, f: &mut Formatter) -> Result<(), FmtError> {
match self {
UseSegment::Ident(v) => v.format(f),
UseSegment::Super(_) => f.text("super"),
UseSegment::SelfValue(_) => f.text("self"),
UseSegment::Crate(_) => f.text("crate"),
}
}
}

impl Format for UseName {
fn format(&self, f: &mut Formatter) -> Result<(), FmtError> {
self.ident.format(f)
self.segment.format(f)
}
}

impl Format for UseRename {
fn format(&self, f: &mut Formatter) -> Result<(), FmtError> {
self.ident.format(f)?;
self.segment.format(f)?;
f.text(" as ")?;
self.rename.format(f)
}
Expand Down
21 changes: 21 additions & 0 deletions fixtures/grammar/matrix.json
Original file line number Diff line number Diff line change
Expand Up @@ -674,6 +674,27 @@
"support_expectation": "moxy_accepts",
"fixture_directory": "fixtures/grammar/paths/qualified-path"
},
{
"id": "paths.segments",
"reference": {
"production": "Paths > Simple Path Segment",
"anchor": "https://doc.rust-lang.org/reference/grammar.html"
},
"baseline": {
"toolchain": "stable",
"edition": "2024"
},
"upstream": {
"repository": "rust-lang/rust",
"commit": "2350b22a89d30fe814a299a73c9ab83c72cafaf3",
"paths": [
"tests/ui/parser/"
]
},
"parse_root": "crate",
"support_expectation": "moxy_accepts",
"fixture_directory": "fixtures/grammar/paths/segments"
},
{
"id": "paths.turbofish",
"reference": {
Expand Down
1 change: 1 addition & 0 deletions fixtures/grammar/paths/segments/fail.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
use crate super self;
4 changes: 4 additions & 0 deletions fixtures/grammar/paths/segments/pass.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
use some_ident;
use crate;
use super;
use crate::super::self;
14 changes: 14 additions & 0 deletions tests/use_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,17 @@ 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_path_can_contain_special_segments() {
for case in [
"use crate as my_library;",
"use super::*;",
"use crate::super::self;",
"use crate::super::self::{crate::a, super::b, self::c};",
] {
eprintln!("{case}");
let item: Item = moxy::parse!(case).unwrap();
assert_eq!(moxy::fmt!(&item).unwrap(), case);
}
}