Skip to content

Emit more Cluster arrays as arrays instead of lists of elements. #534

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

Merged
merged 2 commits into from
Jul 21, 2021
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

- Support for device.x generation for riscv targets and `__EXTERNAL_INTERRUPTS` vector table
- Re-export base's module for derived peripherals
- More Cluster arrays are now emitted as an array rather than a list of
elements. An `ArrayProxy` wrapper is used when a Rust built-in array does not
match the cluster layout. Requires the `--const_generic` command line option.

## [v0.19.0] - 2021-05-26

Expand Down
46 changes: 46 additions & 0 deletions src/generate/array_proxy.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@

/// Access an array of `COUNT` items of type `T` with the items `STRIDE` bytes
/// apart. This is a zero-sized-type. No objects of this type are ever
/// actually created, it is only a convenience for wrapping pointer arithmetic.
///
/// There is no safe way to produce items of this type. Unsafe code can produce
/// references by pointer casting. It is up to the unsafe code doing that, to
/// ensure that the memory really is backed by appropriate content.
///
/// Typically, this is used for accessing hardware registers.
pub struct ArrayProxy<T, const COUNT: usize, const STRIDE: usize> {
/// As well as providing a PhantomData, this field is non-public, and
/// therefore ensures that code outside of this module can never create
/// an ArrayProxy.
_array: marker::PhantomData<T>
}

impl<T, const C: usize, const S: usize> ArrayProxy<T, C, S> {
/// Get a reference from an [ArrayProxy] with no bounds checking.
pub unsafe fn get_ref(&self, index: usize) -> &T {
let base = self as *const Self as usize;
let address = base + S * index;
&*(address as *const T)
}
/// Get a reference from an [ArrayProxy], or return `None` if the index
/// is out of bounds.
pub fn get(&self, index: usize) -> Option<&T> {
if index < C {
Some(unsafe { self.get_ref(index) })
}
else {
None
}
}
/// Return the number of items.
pub fn len(&self) -> usize { C }
}

impl<T, const C: usize, const S: usize> core::ops::Index<usize> for ArrayProxy<T, C, S> {
type Output = T;
fn index(&self, index: usize) -> &T {
// Do a real array dereference for the bounds check.
[(); C][index];
unsafe { self.get_ref(index) }
}
}
41 changes: 20 additions & 21 deletions src/generate/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,10 @@ pub fn render(d: &Device, config: &Config, device_x: &mut String) -> Result<Toke
std::str::from_utf8(include_bytes!("generic_msp430_atomic.rs"))?;
writeln!(file, "\n{}", msp430_atomic_file)?;
}
if config.const_generic {
let array_proxy = std::str::from_utf8(include_bytes!("array_proxy.rs"))?;
writeln!(file, "{}", array_proxy)?;
}

if !config.make_mod {
out.extend(quote! {
Expand All @@ -156,32 +160,27 @@ pub fn render(d: &Device, config: &Config, device_x: &mut String) -> Result<Toke
});
}
} else {
let tokens = syn::parse_file(generic_file)?.into_token_stream();

let mut tokens = syn::parse_file(generic_file)?.into_token_stream();
if config.target == Target::Msp430 && config.nightly {
let msp430_atomic_file =
std::str::from_utf8(include_bytes!("generic_msp430_atomic.rs"))?;
let generic_msp430_atomic = syn::parse_file(msp430_atomic_file)?.into_token_stream();
out.extend(quote! {
#[allow(unused_imports)]
use generic::*;
///Common register and bit access and modify traits
pub mod generic {
#tokens

#generic_msp430_atomic
}
});
} else {
out.extend(quote! {
#[allow(unused_imports)]
use generic::*;
///Common register and bit access and modify traits
pub mod generic {
#tokens
}
});
tokens.extend(generic_msp430_atomic);
}
if config.const_generic {
let array_proxy = std::str::from_utf8(include_bytes!("array_proxy.rs"))?;
let generic_array_proxy = syn::parse_file(array_proxy)?.into_token_stream();
tokens.extend(generic_array_proxy);
}

out.extend(quote! {
#[allow(unused_imports)]
use generic::*;
///Common register and bit access and modify traits
pub mod generic {
#tokens
}
});
}

out.extend(interrupt::render(config.target, &d.peripherals, device_x)?);
Expand Down
32 changes: 31 additions & 1 deletion src/generate/peripheral.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ use std::borrow::Cow;
use std::cmp::Ordering;
use std::collections::HashMap;

use crate::svd::{Cluster, ClusterInfo, Peripheral, Register, RegisterCluster, RegisterProperties};
use crate::svd::{
Cluster, ClusterInfo, DimElement, Peripheral, Register, RegisterCluster, RegisterProperties,
};
use log::warn;
use proc_macro2::TokenStream;
use proc_macro2::{Ident, Punct, Spacing, Span};
Expand Down Expand Up @@ -701,6 +703,10 @@ fn expand_cluster(
offset: info.address_offset,
size: cluster_size * array_info.dim,
});
} else if sequential_indexes && config.const_generic {
// Include a ZST ArrayProxy giving indexed access to the
// elements.
cluster_expanded.push(array_proxy(info, array_info, name)?);
} else {
for (field_num, field) in expand_svd_cluster(cluster, name)?.iter().enumerate() {
cluster_expanded.push(RegisterBlockField {
Expand Down Expand Up @@ -901,6 +907,30 @@ fn convert_svd_register(
})
}

/// Return an syn::Type for an ArrayProxy.
fn array_proxy(
info: &ClusterInfo,
array_info: &DimElement,
name: Option<&str>,
) -> Result<RegisterBlockField, syn::Error> {
let ty_name = util::replace_suffix(&info.name, "");
let tys = name_to_ty_str(&ty_name, name);

let ap_path = parse_str::<syn::TypePath>(&format!(
"crate::ArrayProxy<{}, {}, {}>",
tys,
array_info.dim,
util::hex(array_info.dim_increment as u64)
))?;

Ok(RegisterBlockField {
field: new_syn_field(&ty_name.to_sanitized_snake_case(), ap_path.into()),
description: info.description.as_ref().unwrap_or(&info.name).into(),
offset: info.address_offset,
size: 0,
})
}

/// Takes a svd::Cluster which may contain a register array, and turn in into
/// a list of syn::Field where the register arrays have been expanded.
fn expand_svd_cluster(
Expand Down