Skip to content

Commit

Permalink
[WIP] Using syn v2
Browse files Browse the repository at this point in the history
  • Loading branch information
notdanilo committed Aug 30, 2024
1 parent e0d725e commit be3813b
Show file tree
Hide file tree
Showing 16 changed files with 190 additions and 138 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ shrinkwraprs = "0.3"
derive_more = "0.99"
lazy_static = "1.4.0"
pretty_assertions = "1.4.0"
syn = { version = "1.0.73", features = [ "full" ] }
syn = { version = "2.0.76", features = [ "full" ] }
regex = "1"

# If you want to use the bleeding edge version of egui and eframe:
Expand Down
19 changes: 5 additions & 14 deletions ecosystem/rust/parser/src/function/method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,13 @@ use crate::visibility::VisibilityParser;

pub struct MethodParser;

impl Parser<syn::ImplItemMethod> for MethodParser {
impl Parser<syn::ImplItemFn> for MethodParser {
type Output = Method;
fn parse(&self, method: syn::ImplItemMethod, config: &ParserConfig) -> Result<Self::Output> {
let mutability = method.sig.receiver().map(|arg| {
match arg {
syn::FnArg::Receiver(receiver) => if receiver.mutability.is_some() { Mutability::Mutable } else { Mutability::Constant },
syn::FnArg::Typed(_pat) => Mutability::Constant // FIXME: This needs better treatment.
}
fn parse(&self, method: syn::ImplItemFn, config: &ParserConfig) -> Result<Self::Output> {
let mutability = method.sig.receiver().map(|receiver| {
if receiver.mutability.is_some() { Mutability::Mutable } else { Mutability::Constant }
}).unwrap_or(Mutability::Constant);
let syn::Signature {
asyncness,
ident,
inputs,
output,
..
} = method.sig;
let syn::Signature { asyncness, ident, inputs, output, .. } = method.sig;
let inputs: Vec<Parameter> = inputs
.clone()
.into_iter()
Expand Down
4 changes: 2 additions & 2 deletions ecosystem/rust/parser/src/function/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ impl Parser<syn::ItemFn> for FunctionParser {
}
}

impl Parser<syn::ImplItemMethod> for FunctionParser {
impl Parser<syn::ImplItemFn> for FunctionParser {
type Output = Function;
fn parse(&self, method: syn::ImplItemMethod, config: &ParserConfig) -> Result<Self::Output> {
fn parse(&self, method: syn::ImplItemFn, config: &ParserConfig) -> Result<Self::Output> {
let attributes = AttributesParser::default().parse(method.attrs, config)?;
let visibility = VisibilityParser.parse(method.vis, config)?;
let synchrony = SynchronyParser.parse(method.sig.asyncness, config)?;
Expand Down
15 changes: 12 additions & 3 deletions ecosystem/rust/parser/src/literal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ impl Parser<syn::Lit> for LiteralParser {
syn::Lit::Int(litint) => Self::Output::Integer(litint.base10_parse().unwrap()),
syn::Lit::Float(litfloat) => Self::Output::Float(litfloat.base10_parse().unwrap()),
syn::Lit::Bool(litbool) => Self::Output::Boolean(litbool.value),
syn::Lit::CStr(litcstr) => Self::Output::String(litcstr.value().to_str().unwrap().to_string()),
_ => return Err(Error::Message("Failed to parse literal".into())),
})
}
}
Expand Down Expand Up @@ -73,9 +75,11 @@ impl Parser<String> for LiteralParser {
impl Parser<&str> for LiteralParser {
type Output = Literal;
fn parse(&self, input: &str, config: &ParserConfig) -> Result<Self::Output> {
syn::parse_str::<syn::Lit>(input)
.map_err(|e| Error::Message(format!("Failed to parse literal: {:?}", e)))
.and_then(|literal| self.parse(literal, config))
if let Ok(lit) = syn::parse_str::<syn::Lit>(input) {
Ok(self.parse(lit, config)?)
} else {
Ok(Literal::Unknown(input.to_string()))
}
}
}

Expand Down Expand Up @@ -125,4 +129,9 @@ mod test {
fn literal_float() -> Result<()> {
assert_eq(LiteralParser, mock::literal_float(), "3.5")
}

#[test]
fn literal_unknown() -> Result<()> {
assert_eq(LiteralParser, mock::literal_unknown(), ".0") // FIXME: This is actually an expression.
}
}
5 changes: 3 additions & 2 deletions ecosystem/rust/parser/src/module/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,9 @@ impl Parser<&std::path::Path> for ModuleParser {
let semi = Default::default();
let mod_token = Default::default();
let content = Some((Default::default(), module.items));
let vis = syn::Visibility::Public(syn::VisPublic { pub_token });
let module = syn::ItemMod { attrs, vis, mod_token, ident, semi, content };
let vis = syn::Visibility::Public(pub_token);
let unsafety = Default::default();
let module = syn::ItemMod { unsafety, attrs, vis, mod_token, ident, semi, content };
self.parse(module, config)
}
}
Expand Down
19 changes: 12 additions & 7 deletions ecosystem/rust/parser/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ impl Parser<syn::Path> for PathParser {
.segments
.iter()
// FIXME: This isn't parsing generics, just the identifiers.
.map(|segment| IdentifierParser::new().parse(segment.ident.clone(), config).expect("Failed to parse segment."))
.map(|segment| IdentifierParser::new().parse(segment.ident.clone(), config).expect("Failed to parse segment.")) // FIXME: Remove this expect.
.map(PathSegment::from)
.collect();
Ok(Self::Output { segments })
Expand All @@ -34,6 +34,15 @@ impl Parser<syn::Ident> for PathParser {
}
}

impl Parser<&str> for PathParser {
type Output = Path;
fn parse(&self, input: &str, config: &ParserConfig) -> Result<Self::Output> {
syn::parse_str::<syn::Path>(input)
.map_err(|e| Error::Message(format!("Failed to parse path: {:?}", e)))
.and_then(|path| self.parse(path, config))
}
}

impl Parser<proc_macro::TokenStream> for PathParser {
type Output = Path;
fn parse(&self, input: proc_macro::TokenStream, config: &ParserConfig) -> Result<Self::Output> {
Expand All @@ -60,15 +69,11 @@ mod test {

#[test]
fn identifier_as_path() -> Result<()> {
assert_eq(PathParser::default(), mock::identifier_as_path(), quote! {
u8
})
assert_eq(PathParser::default(), mock::identifier_as_path(), "u8")
}

#[test]
fn path() -> Result<()> {
assert_eq(PathParser::default(), mock::path(), quote! {
std::convert::TryFrom
})
assert_eq(PathParser::default(), mock::path(), "std::convert::TryFrom")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,18 @@ impl Parser<syn::punctuated::Punctuated<syn::Variant, syn::token::Comma>> for Va

#[cfg(test)]
mod tests {
use quote::quote;
use syn::parse_quote::parse;
use syn::parse_quote;
use ligen::ir::Variant;
use ligen::parser::Parser;
use crate::types::type_definition::enumeration::variant::VariantParser;

#[test]
fn parameter_primitive() {
let enumeration = parse::<syn::ItemEnum>(quote! {
let enumeration: syn::ItemEnum = parse_quote! {
enum Enumeration {
Integer
}
});
};
let variant = enumeration.variants.into_iter().next().expect("Couldn't get field.");
assert_eq!(
VariantParser.parse(variant, &Default::default()).expect("Failed to convert field."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,18 @@ impl Parser<syn::Fields> for FieldParser {

#[cfg(test)]
mod tests {
use syn::parse_quote::parse;
use syn::parse_quote;
use ligen::ir::{Field, Visibility, Path};
use crate::types::structure::FieldParser;
use crate::prelude::*;

#[test]
fn field() -> Result<()> {
let structure = parse::<syn::ItemStruct>(quote! {
let structure: syn::ItemStruct = parse_quote! {
struct Structure {
instant: std::time::Instant
}
});
};
let field = structure.fields.into_iter().next().expect("Couldn't get field.");
assert_eq!(
FieldParser.parse(field, &Default::default())?,
Expand Down
4 changes: 4 additions & 0 deletions ligen/ir/src/literal/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,8 @@ pub fn literal_integer() -> Literal {

pub fn literal_float() -> Literal {
Literal::Float(3.5)
}

pub fn literal_unknown() -> Literal {
Literal::Unknown(".0".into())
}
6 changes: 3 additions & 3 deletions ligen/ir/src/macro_attributes/attributes/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ pub fn parse_expressions() -> Attributes {
"error",
vec![
Attribute::Literal("the {} field name: '{}' is invalid, path: {:?}".into()),
Attribute::Group(".0.field_type".into()),
Attribute::Group(".0.field_name".into()),
Attribute::Group(".0.path".into())
Attribute::from(Literal::Unknown("self.0.field_type".into())),
Attribute::from(Literal::Unknown("self.0.field_name".into())),
Attribute::from(Literal::Unknown("self.0.path".into()))
]
).into()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
pub(crate) enum IntermediaryAttribute {
Meta(syn::Meta),
Lit(syn::Lit),
Expr(syn::Expr),
Unknown(String)
}

impl syn::parse::Parse for IntermediaryAttribute {
fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
println!("{}", input);
if input.peek(syn::Lit) {
input.parse().map(IntermediaryAttribute::Lit)
} else {
if let Ok(attribute) = input.parse().map(IntermediaryAttribute::Expr) {
Ok(attribute)
} else {
Ok(input.parse().map(IntermediaryAttribute::Meta).unwrap_or(IntermediaryAttribute::Unknown(input.to_string())))
}
}
}
}
Loading

0 comments on commit be3813b

Please sign in to comment.