Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add CI #5

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
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
32 changes: 32 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: CI

on:
push:
branches: ["main"]
pull_request:
branches: ["main"]

env:
RUSTFLAGS: "-Dwarnings"

jobs:
run_cargo_lints:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: Swatinem/rust-cache@v2
- name: Rustup install nightly
run: rustup toolchain install nightly
- name: Rustup install rustfmt
run: rustup component add rustfmt --toolchain nightly
- name: Run Cargo fmt
run: cargo +nightly fmt --all -- --check
- name: Run Cargo clippy
run: cargo clippy --all-targets --all-features
run_cargo_tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: Swatinem/rust-cache@v2
- name: Run Cargo test
run: cargo test --all-features
2 changes: 1 addition & 1 deletion codama-attributes/src/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::ops::{Deref, DerefMut, Index, IndexMut};
pub struct Attributes<'a>(pub Vec<Attribute<'a>>);

impl<'a> Attributes<'a> {
pub fn parse(attrs: &'a Vec<syn::Attribute>, ctx: AttributeContext<'a>) -> syn::Result<Self> {
pub fn parse(attrs: &'a [syn::Attribute], ctx: AttributeContext<'a>) -> syn::Result<Self> {
let attributes = Self(
attrs
.iter()
Expand Down
2 changes: 1 addition & 1 deletion codama-attributes/src/codama_attribute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ impl<'a> CodamaAttribute<'a> {
};

let mut directive = SetOnce::<CodamaDirective>::new("codama");
list.each(|ref meta| directive.set(CodamaDirective::parse(&meta, ctx)?, meta))?;
list.each(|ref meta| directive.set(CodamaDirective::parse(meta, ctx)?, meta))?;
Ok(Self {
ast,
directive: directive.take(attr)?,
Expand Down
10 changes: 5 additions & 5 deletions codama-attributes/src/codama_directives/account_directive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ impl AccountDirective {
pub fn parse(meta: &Meta, ctx: &AttributeContext) -> syn::Result<Self> {
meta.assert_directive("account")?;
let mut name = SetOnce::<CamelCaseString>::new("name");
match ctx {
AttributeContext::Field(syn::Field {
ident: Some(ident), ..
}) => name = name.initial_value(ident.to_string().into()),
_ => (),
if let AttributeContext::Field(syn::Field {
ident: Some(ident), ..
}) = ctx
{
name = name.initial_value(ident.to_string().into())
}
let mut is_writable = SetOnce::<bool>::new("writable").initial_value(false);
let mut is_signer = SetOnce::<IsAccountSigner>::new("signer").initial_value(false.into());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ impl FromMeta for BooleanTypeNode {
fn from_meta(meta: &Meta) -> syn::Result<Self> {
let mut size: SetOnce<TypeNode> = SetOnce::new("size");
if meta.is_path_or_empty_list() {
return Ok(BooleanTypeNode::default().into());
return Ok(BooleanTypeNode::default());
}
meta.as_path_list()?
.each(|ref meta| match (meta.path_str().as_str(), meta) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,7 @@ impl FromMeta for FixedSizeTypeNode<TypeNode> {
(_, Meta::Expr(expr)) => size.set(expr.as_literal_integer()?, meta),
_ => Err(meta.error("unrecognized attribute")),
})?;
let r#type = match TypeNode::try_from(r#type.take(meta)?) {
Ok(node) => node,
Err(_) => return Err(meta.error("type must be a TypeNode")),
};
let r#type = r#type.take(meta)?;
Ok(Self::new(r#type, size.take(meta)?))
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ impl FromMeta for StringTypeNode {
fn from_meta(meta: &Meta) -> syn::Result<Self> {
let mut encoding: SetOnce<BytesEncoding> = SetOnce::new("encoding");
if meta.is_path_or_empty_list() {
return Ok(StringTypeNode::utf8().into());
return Ok(StringTypeNode::utf8());
}
meta.as_path_list()?
.each(|ref meta| match (meta.path_str().as_str(), meta) {
Expand Down
4 changes: 2 additions & 2 deletions codama-attributes/src/utils/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ macro_rules! assert_type {
({$($attr:tt)*}, $expected:expr) => {
{
let meta: codama_syn_helpers::Meta = syn::parse_quote! { type = $($attr)* };
let node = crate::TypeDirective::parse(&meta).unwrap().node;
let node = $crate::TypeDirective::parse(&meta).unwrap().node;
assert_eq!(node, $expected);
}
};
Expand All @@ -14,7 +14,7 @@ macro_rules! assert_type_err {
({$($attr:tt)*}, $expected:expr) => {
{
let meta: codama_syn_helpers::Meta = syn::parse_quote! { type = $($attr)* };
let message = crate::TypeDirective::parse(&meta).unwrap_err().to_string();
let message = $crate::TypeDirective::parse(&meta).unwrap_err().to_string();
assert_eq!(message, $expected);
}
};
Expand Down
18 changes: 9 additions & 9 deletions codama-korok-plugins/src/default_plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,16 @@ impl KorokPlugin for DefaultPlugin {

pub fn get_default_visitor<'a>() -> ComposeVisitor<'a> {
ComposeVisitor::new()
.add(FilterItemsVisitor::new(
.with(FilterItemsVisitor::new(
|item| item.attributes().unwrap().has_any_codama_derive(),
ComposeVisitor::new()
.add(SetBorshTypesVisitor::new())
.add(SetLinkTypesVisitor::new()),
.with(SetBorshTypesVisitor::new())
.with(SetLinkTypesVisitor::new()),
))
.add(SetProgramMetadataVisitor::new())
.add(ApplyCodamaTypeAttributesVisitor::new())
.add(SetDefinedTypesVisitor::new())
.add(SetAccountsVisitor::new())
.add(SetInstructionsVisitor::new())
.add(CombineModulesVisitor::new())
.with(SetProgramMetadataVisitor::new())
.with(ApplyCodamaTypeAttributesVisitor::new())
.with(SetDefinedTypesVisitor::new())
.with(SetAccountsVisitor::new())
.with(SetInstructionsVisitor::new())
.with(CombineModulesVisitor::new())
}
14 changes: 7 additions & 7 deletions codama-korok-plugins/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ pub trait KorokPlugin {
) -> CodamaResult<()>;
}

pub type ResolvePluginsResult<'a> = Box<dyn Fn(&mut dyn KorokVisitable) -> CodamaResult<()> + 'a>;

/// Reduce all plugins into a single function that runs them in sequence.
///
/// For instance, imagine we have a list of plugins [A, B, C] implemented as:
Expand Down Expand Up @@ -40,9 +42,7 @@ pub trait KorokPlugin {
/// Plugin B - after
/// Plugin C - after
/// ```
pub fn resolve_plugins<'a>(
plugins: &'a [Box<dyn KorokPlugin + 'a>],
) -> Box<dyn Fn(&mut dyn KorokVisitable) -> CodamaResult<()> + 'a> {
pub fn resolve_plugins<'a>(plugins: &'a [Box<dyn KorokPlugin + 'a>]) -> ResolvePluginsResult<'a> {
// We fold from the left to ensure that any code before the
// `next` call is run before the previous plugin on the list.
plugins.iter().fold(
Expand All @@ -61,14 +61,14 @@ pub fn resolve_plugins<'a>(
mod tests {
use super::*;
use codama_korok_visitors::KorokVisitor;
use std::{cell::RefCell, sync::Arc};
use std::{cell::RefCell, rc::Rc};

struct LoggingPluging {
id: String,
logs: Arc<RefCell<Vec<String>>>,
logs: Rc<RefCell<Vec<String>>>,
}
impl LoggingPluging {
fn new(id: &str, logs: Arc<RefCell<Vec<String>>>) -> Self {
fn new(id: &str, logs: Rc<RefCell<Vec<String>>>) -> Self {
Self {
id: id.into(),
logs,
Expand Down Expand Up @@ -104,7 +104,7 @@ mod tests {

#[test]
fn test_resolve_plugins() -> CodamaResult<()> {
let logs = Arc::new(RefCell::new(Vec::new()));
let logs = Rc::new(RefCell::new(Vec::new()));
let plugins: Vec<Box<dyn KorokPlugin>> = vec![
Box::new(LoggingPluging::new("A", logs.clone())),
Box::new(LoggingPluging::new("B", logs.clone())),
Expand Down
42 changes: 18 additions & 24 deletions codama-korok-visitors/src/apply_codama_type_attributes_visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,17 +94,13 @@ fn apply_codama_attributes(mut korok: KorokMut) -> CodamaResult<()> {
Attribute::Codama(attribute) => Some(attribute),
_ => None,
})
.fold(
Ok(korok.node().clone()),
|current_node, attribute| match current_node {
Ok(current_node) => apply_codama_attribute(ApplyAttributeInput {
node: current_node,
attribute,
korok: &korok,
}),
Err(e) => Err(e),
},
)?;
.try_fold(korok.node().clone(), |current_node, attribute| {
apply_codama_attribute(ApplyAttributeInput {
node: current_node,
attribute,
korok: &korok,
})
})?;

korok.set_node(node);
Ok(())
Expand All @@ -128,8 +124,8 @@ fn apply_type_directive(
match input.korok {
// If the `type` directive is applied to a named field then
// we need to wrap the provided node in a `StructFieldTypeNode`.
KorokMut::Field(korok) => match (TypeNode::try_from(node.clone()).ok(), &korok.ast.ident) {
(Some(type_node), Some(ident)) => Ok(Some(
KorokMut::Field(korok) => match (node.clone(), &korok.ast.ident) {
(type_node, Some(ident)) => Ok(Some(
StructFieldTypeNode::new(ident.to_string(), type_node).into(),
)),
_ => Ok(Some(node.into())),
Expand Down Expand Up @@ -223,16 +219,14 @@ fn update_type_node(

match TypeNode::try_from(node.clone()) {
Ok(type_node) => Ok(Some(update(type_node)?.into())),
Err(_) => {
return Err(input
.attribute
.ast
.error(format!(
"Cannot apply attribute `#[codama({})]` on a node of kind `{}`",
input.attribute.directive.name(),
node.kind()
))
.into());
}
Err(_) => Err(input
.attribute
.ast
.error(format!(
"Cannot apply attribute `#[codama({})]` on a node of kind `{}`",
input.attribute.directive.name(),
node.kind()
))
.into()),
}
}
6 changes: 3 additions & 3 deletions codama-korok-visitors/src/combine_types_visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ impl CombineTypesVisitor {
.ast
.error(format!(
"Variant `{}` of {} does not resolve to a `EnumVariantTypeNode`",
variant.ast.ident.to_string(),
variant.ast.ident,
parent.identifier()
))
.into())),
Expand All @@ -98,7 +98,7 @@ impl CombineTypesVisitor {
.ast
.error(format!(
"Field `{}` in {} does not resolve to a `structFieldTypeNode`",
field.ast.ident.as_ref().unwrap().to_string(),
field.ast.ident.as_ref().unwrap(),
parent.identifier()
))
.into())),
Expand All @@ -115,7 +115,7 @@ impl CombineTypesVisitor {
.ast
.error(format!(
"Field `{}` in {} does not resolve to a `TypeNode`",
index.to_string(),
index,
parent.identifier()
))
.into())),
Expand Down
4 changes: 2 additions & 2 deletions codama-korok-visitors/src/compose_visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ impl<'a> ComposeVisitor<'a> {
Self::default()
}

/// Add a new visitor to the composition.
pub fn add<T: KorokVisitor + 'a>(mut self, visitor: T) -> Self {
/// Adds a new visitor to the composition.
pub fn with<T: KorokVisitor + 'a>(mut self, visitor: T) -> Self {
self.visitors.push(Box::new(visitor));
self
}
Expand Down
4 changes: 2 additions & 2 deletions codama-korok-visitors/src/set_accounts_visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ impl KorokVisitor for SetAccountsVisitor {
.map_nested_type_node(|node| {
let mut fields = node.fields;
fields.insert(0, discriminator);
StructTypeNode { fields, ..node }
StructTypeNode { fields }
});
let discriminator_node = FieldDiscriminatorNode::new(discriminator_name, 0);

Expand Down Expand Up @@ -160,7 +160,7 @@ fn get_nested_struct_type_node_from_struct(
// Handle error.
let message = format!(
"The \"{}\" struct could not be used as an Account because its type is not a `NestedTypeNode<StructTypeNode>`.",
korok.ast.ident.to_string(),
korok.ast.ident,
);
Err(korok.ast.error(message).into())
}
Expand Down
Loading
Loading