646: Debloat stm32-metapac r=Dirbaio a=Dirbaio

- Remove usage of `peripheral_counts!` macrotables.
- Remove `dbgmcu!` macrotable.
- Move the remaining macrotables to embassy-stm32 build.rs. This brings metapac decompressed size from ~250mb to ~100mb
- Deduplicate files with identical metadata. This brings decompressed size from ~100mb to ~70mb, compressed from ~10mb to ~4mb, which is finally small enough to publish on crates.io!

Co-authored-by: Dario Nieuwenhuis <dirbaio@dirbaio.net>
This commit is contained in:
bors[bot] 2022-02-26 02:42:26 +00:00 committed by GitHub
commit 141e007acf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 697 additions and 660 deletions

View File

@ -2,6 +2,7 @@ use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use std::collections::{HashMap, HashSet};
use std::env;
use std::fmt::Write as _;
use std::fs;
use std::path::PathBuf;
use stm32_metapac::metadata::METADATA;
@ -530,9 +531,127 @@ fn main() {
}
// ========
// Write generated.rs
// Write foreach_foo! macrotables
let mut interrupts_table: Vec<Vec<String>> = Vec::new();
let mut peripherals_table: Vec<Vec<String>> = Vec::new();
let mut pins_table: Vec<Vec<String>> = Vec::new();
let mut dma_channels_table: Vec<Vec<String>> = Vec::new();
let gpio_base = METADATA
.peripherals
.iter()
.find(|p| p.name == "GPIOA")
.unwrap()
.address as u32;
let gpio_stride = 0x400;
for p in METADATA.peripherals {
if let Some(regs) = &p.registers {
if regs.kind == "gpio" {
let port_letter = p.name.chars().skip(4).next().unwrap();
assert_eq!(0, (p.address as u32 - gpio_base) % gpio_stride);
let port_num = (p.address as u32 - gpio_base) / gpio_stride;
for pin_num in 0u32..16 {
let pin_name = format!("P{}{}", port_letter, pin_num);
pins_table.push(vec![
pin_name,
p.name.to_string(),
port_num.to_string(),
pin_num.to_string(),
format!("EXTI{}", pin_num),
]);
}
}
for irq in p.interrupts {
let mut row = Vec::new();
row.push(p.name.to_string());
row.push(regs.kind.to_string());
row.push(regs.block.to_string());
row.push(irq.signal.to_string());
row.push(irq.interrupt.to_ascii_uppercase());
interrupts_table.push(row)
}
let mut row = Vec::new();
row.push(regs.kind.to_string());
row.push(p.name.to_string());
peripherals_table.push(row);
}
}
let mut dma_channel_count: usize = 0;
let mut bdma_channel_count: usize = 0;
for ch in METADATA.dma_channels {
let mut row = Vec::new();
let dma_peri = METADATA
.peripherals
.iter()
.find(|p| p.name == ch.dma)
.unwrap();
let bi = dma_peri.registers.as_ref().unwrap();
let num;
match bi.kind {
"dma" => {
num = dma_channel_count;
dma_channel_count += 1;
}
"bdma" => {
num = bdma_channel_count;
bdma_channel_count += 1;
}
_ => panic!("bad dma channel kind {}", bi.kind),
}
row.push(ch.name.to_string());
row.push(ch.dma.to_string());
row.push(bi.kind.to_string());
row.push(ch.channel.to_string());
row.push(num.to_string());
if let Some(dmamux) = &ch.dmamux {
let dmamux_channel = ch.dmamux_channel.unwrap();
row.push(format!(
"{{dmamux: {}, dmamux_channel: {}}}",
dmamux, dmamux_channel
));
} else {
row.push("{}".to_string());
}
dma_channels_table.push(row);
}
g.extend(quote! {
pub(crate) const DMA_CHANNEL_COUNT: usize = #dma_channel_count;
pub(crate) const BDMA_CHANNEL_COUNT: usize = #bdma_channel_count;
});
for irq in METADATA.interrupts {
let name = irq.name.to_ascii_uppercase();
interrupts_table.push(vec![name.clone()]);
if name.contains("EXTI") {
interrupts_table.push(vec!["EXTI".to_string(), name.clone()]);
}
}
let mut m = String::new();
make_table(&mut m, "foreach_interrupt", &interrupts_table);
make_table(&mut m, "foreach_peripheral", &peripherals_table);
make_table(&mut m, "foreach_pin", &pins_table);
make_table(&mut m, "foreach_dma_channel", &dma_channels_table);
let out_dir = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
let out_file = out_dir.join("macros.rs").to_string_lossy().to_string();
fs::write(out_file, m).unwrap();
// ========
// Write generated.rs
let out_file = out_dir.join("generated.rs").to_string_lossy().to_string();
fs::write(out_file, g.to_string()).unwrap();
@ -644,3 +763,30 @@ impl<T: Iterator> IteratorExt for T {
}
}
}
fn make_table(out: &mut String, name: &str, data: &Vec<Vec<String>>) {
write!(
out,
"#[macro_export]
macro_rules! {} {{
($($pat:tt => $code:tt;)*) => {{
macro_rules! __{}_inner {{
$(($pat) => $code;)*
($_:tt) => {{}}
}}
",
name, name
)
.unwrap();
for row in data {
write!(out, " __{}_inner!(({}));\n", name, row.join(",")).unwrap();
}
write!(
out,
" }};
}}"
)
.unwrap();
}

View File

@ -36,7 +36,7 @@ pub trait Instance: sealed::Instance + crate::rcc::RccPeripheral + 'static {}
pub trait Common: sealed::Common + 'static {}
pub trait AdcPin<T: Instance>: sealed::AdcPin<T> {}
crate::pac::peripherals!(
foreach_peripheral!(
(adc, $inst:ident) => {
impl crate::adc::sealed::Instance for peripherals::$inst {
fn regs() -> &'static crate::pac::adc::Adc {
@ -44,7 +44,7 @@ crate::pac::peripherals!(
}
#[cfg(not(adc_f1))]
fn common_regs() -> &'static crate::pac::adccommon::AdcCommon {
crate::pac::peripherals!{
foreach_peripheral!{
(adccommon, $common_inst:ident) => {
return &crate::pac::$common_inst
};
@ -57,7 +57,7 @@ crate::pac::peripherals!(
);
#[cfg(not(adc_f1))]
crate::pac::peripherals!(
foreach_peripheral!(
(adccommon, $inst:ident) => {
impl sealed::Common for peripherals::$inst {
fn regs() -> &'static crate::pac::adccommon::AdcCommon {

View File

@ -70,7 +70,7 @@ pub(crate) mod sealed {
pub trait Instance: sealed::Instance + RccPeripheral {}
crate::pac::peripherals!(
foreach_peripheral!(
(can, $inst:ident) => {
impl sealed::Instance for peripherals::$inst {
fn regs() -> &'static crate::pac::can::Can {
@ -86,7 +86,7 @@ crate::pac::peripherals!(
};
);
crate::pac::peripherals!(
foreach_peripheral!(
(can, CAN) => {
unsafe impl bxcan::FilterOwner for peripherals::CAN {
const NUM_FILTER_BANKS: u8 = 14;

View File

@ -16,7 +16,7 @@ pub trait Instance: sealed::Instance + 'static {}
pub trait DacPin<T: Instance, const C: u8>: crate::gpio::Pin + 'static {}
crate::pac::peripherals!(
foreach_peripheral!(
(dac, $inst:ident) => {
impl crate::dac::sealed::Instance for peripherals::$inst {
fn regs() -> &'static crate::pac::dac::Dac {

View File

@ -474,7 +474,7 @@ macro_rules! impl_peripheral {
};
}
crate::pac::interrupts! {
foreach_interrupt! {
($inst:ident, dcmi, $block:ident, GLOBAL, $irq:ident) => {
impl_peripheral!($inst, $irq);
};

View File

@ -7,6 +7,7 @@ use embassy::interrupt::{Interrupt, InterruptExt};
use embassy::waitqueue::AtomicWaker;
use crate::dma::Request;
use crate::generated::BDMA_CHANNEL_COUNT;
use crate::pac;
use crate::pac::bdma::vals;
@ -22,62 +23,44 @@ impl From<WordSize> for vals::Size {
}
}
const CH_COUNT: usize = pac::peripheral_count!(bdma) * 8;
struct State {
ch_wakers: [AtomicWaker; CH_COUNT],
ch_wakers: [AtomicWaker; BDMA_CHANNEL_COUNT],
}
impl State {
const fn new() -> Self {
const AW: AtomicWaker = AtomicWaker::new();
Self {
ch_wakers: [AW; CH_COUNT],
ch_wakers: [AW; BDMA_CHANNEL_COUNT],
}
}
}
static STATE: State = State::new();
macro_rules! dma_num {
(DMA1) => {
0
};
(DMA2) => {
1
};
(BDMA) => {
0
};
(BDMA1) => {
0
};
(BDMA2) => {
1
};
}
pub(crate) unsafe fn on_irq() {
pac::peripherals! {
foreach_peripheral! {
(bdma, BDMA1) => {
// BDMA1 in H7 doesn't use DMAMUX, which breaks
};
(bdma, $dma:ident) => {
let isr = pac::$dma.isr().read();
let dman = dma_num!($dma);
for chn in 0..pac::dma_channels_count!($dma) {
let cr = pac::$dma.ch(chn).cr();
if isr.tcif(chn) && cr.read().tcie() {
let isr = pac::$dma.isr().read();
foreach_dma_channel! {
($channel_peri:ident, $dma, bdma, $channel_num:expr, $index:expr, $dmamux:tt) => {
let cr = pac::$dma.ch($channel_num).cr();
if isr.tcif($channel_num) && cr.read().tcie() {
cr.write(|_| ()); // Disable channel interrupts with the default value.
let n = dma_num!($dma) * 8 + chn;
STATE.ch_wakers[n].wake();
STATE.ch_wakers[$index].wake();
}
}
};
}
};
}
}
/// safety: must be called only once
pub(crate) unsafe fn init() {
pac::interrupts! {
foreach_interrupt! {
($peri:ident, bdma, $block:ident, $signal_name:ident, $irq:ident) => {
crate::interrupt::$irq::steal().enable();
};
@ -85,20 +68,20 @@ pub(crate) unsafe fn init() {
crate::generated::init_bdma();
}
pac::dma_channels! {
($channel_peri:ident, BDMA1, bdma, $channel_num:expr, $dmamux:tt) => {
foreach_dma_channel! {
($channel_peri:ident, BDMA1, bdma, $channel_num:expr, $index:expr, $dmamux:tt) => {
// BDMA1 in H7 doesn't use DMAMUX, which breaks
};
($channel_peri:ident, $dma_peri:ident, bdma, $channel_num:expr, $dmamux:tt) => {
($channel_peri:ident, $dma_peri:ident, bdma, $channel_num:expr, $index:expr, $dmamux:tt) => {
impl crate::dma::sealed::Channel for crate::peripherals::$channel_peri {
unsafe fn start_write<W: Word>(&mut self, request: Request, buf: *const[W], reg_addr: *mut W) {
unsafe fn start_write<W: Word>(&mut self, _request: Request, buf: *const[W], reg_addr: *mut W) {
let (ptr, len) = super::slice_ptr_parts(buf);
low_level_api::start_transfer(
pac::$dma_peri,
$channel_num,
#[cfg(any(bdma_v2, dmamux))]
request,
_request,
vals::Dir::FROMMEMORY,
reg_addr as *const u32,
ptr as *mut u32,
@ -113,13 +96,13 @@ pac::dma_channels! {
}
unsafe fn start_write_repeated<W: Word>(&mut self, request: Request, repeated: W, count: usize, reg_addr: *mut W) {
unsafe fn start_write_repeated<W: Word>(&mut self, _request: Request, repeated: W, count: usize, reg_addr: *mut W) {
let buf = [repeated];
low_level_api::start_transfer(
pac::$dma_peri,
$channel_num,
#[cfg(any(bdma_v2, dmamux))]
request,
_request,
vals::Dir::FROMMEMORY,
reg_addr as *const u32,
buf.as_ptr() as *mut u32,
@ -133,13 +116,13 @@ pac::dma_channels! {
)
}
unsafe fn start_read<W: Word>(&mut self, request: Request, reg_addr: *const W, buf: *mut [W]) {
unsafe fn start_read<W: Word>(&mut self, _request: Request, reg_addr: *const W, buf: *mut [W]) {
let (ptr, len) = super::slice_ptr_parts_mut(buf);
low_level_api::start_transfer(
pac::$dma_peri,
$channel_num,
#[cfg(any(bdma_v2, dmamux))]
request,
_request,
vals::Dir::FROMPERIPHERAL,
reg_addr as *const u32,
ptr as *mut u32,
@ -165,7 +148,7 @@ pac::dma_channels! {
}
fn set_waker(&mut self, waker: &Waker) {
unsafe {low_level_api::set_waker(dma_num!($dma_peri) * 8 + $channel_num, waker )}
unsafe { low_level_api::set_waker($index, waker) }
}
}

View File

@ -4,14 +4,13 @@ use core::task::Waker;
use embassy::interrupt::{Interrupt, InterruptExt};
use embassy::waitqueue::AtomicWaker;
use crate::generated::DMA_CHANNEL_COUNT;
use crate::interrupt;
use crate::pac;
use crate::pac::dma::{regs, vals};
use super::{Request, Word, WordSize};
const CH_COUNT: usize = pac::peripheral_count!(DMA) * 8;
impl From<WordSize> for vals::Size {
fn from(raw: WordSize) -> Self {
match raw {
@ -23,44 +22,31 @@ impl From<WordSize> for vals::Size {
}
struct State {
ch_wakers: [AtomicWaker; CH_COUNT],
ch_wakers: [AtomicWaker; DMA_CHANNEL_COUNT],
}
impl State {
const fn new() -> Self {
const AW: AtomicWaker = AtomicWaker::new();
Self {
ch_wakers: [AW; CH_COUNT],
ch_wakers: [AW; DMA_CHANNEL_COUNT],
}
}
}
static STATE: State = State::new();
macro_rules! dma_num {
(DMA1) => {
0
};
(DMA2) => {
1
};
}
pub(crate) unsafe fn on_irq() {
pac::peripherals! {
foreach_peripheral! {
(dma, $dma:ident) => {
for isrn in 0..2 {
let isr = pac::$dma.isr(isrn).read();
for chn in 0..4 {
let cr = pac::$dma.st(isrn * 4 + chn).cr();
if isr.tcif(chn) && cr.read().tcie() {
foreach_dma_channel! {
($channel_peri:ident, $dma, dma, $channel_num:expr, $index:expr, $dmamux:tt) => {
let cr = pac::$dma.st($channel_num).cr();
if pac::$dma.isr($channel_num/4).read().tcif($channel_num%4) && cr.read().tcie() {
cr.write(|_| ()); // Disable channel interrupts with the default value.
let n = dma_num!($dma) * 8 + isrn * 4 + chn;
STATE.ch_wakers[n].wake();
STATE.ch_wakers[$index].wake();
}
}
};
}
};
}
@ -68,7 +54,7 @@ pub(crate) unsafe fn on_irq() {
/// safety: must be called only once
pub(crate) unsafe fn init() {
pac::interrupts! {
foreach_interrupt! {
($peri:ident, dma, $block:ident, $signal_name:ident, $irq:ident) => {
interrupt::$irq::steal().enable();
};
@ -76,8 +62,8 @@ pub(crate) unsafe fn init() {
crate::generated::init_dma();
}
pac::dma_channels! {
($channel_peri:ident, $dma_peri:ident, dma, $channel_num:expr, $dmamux:tt) => {
foreach_dma_channel! {
($channel_peri:ident, $dma_peri:ident, dma, $channel_num:expr, $index:expr, $dmamux:tt) => {
impl crate::dma::sealed::Channel for crate::peripherals::$channel_peri {
unsafe fn start_write<W: Word>(&mut self, request: Request, buf: *const [W], reg_addr: *mut W) {
let (ptr, len) = super::slice_ptr_parts(buf);
@ -149,7 +135,7 @@ pac::dma_channels! {
}
fn set_waker(&mut self, waker: &Waker) {
unsafe {low_level_api::set_waker(dma_num!($dma_peri) * 8 + $channel_num, waker )}
unsafe {low_level_api::set_waker($index, waker )}
}
}

View File

@ -35,8 +35,8 @@ pub trait MuxChannel: sealed::MuxChannel + super::Channel {
type Mux;
}
pac::dma_channels! {
($channel_peri:ident, $dma_peri:ident, $version:ident, $channel_num:expr, {dmamux: $dmamux:ident, dmamux_channel: $dmamux_channel:expr}) => {
foreach_dma_channel! {
($channel_peri:ident, $dma_peri:ident, $version:ident, $channel_num:expr, $index:expr, {dmamux: $dmamux:ident, dmamux_channel: $dmamux_channel:expr}) => {
impl sealed::MuxChannel for peripherals::$channel_peri {
const DMAMUX_CH_NUM: u8 = $dmamux_channel;
const DMAMUX_REGS: pac::dmamux::Dmamux = pac::$dmamux;

View File

@ -278,7 +278,7 @@ impl<'a> Future for ExtiInputFuture<'a> {
macro_rules! foreach_exti_irq {
($action:ident) => {
crate::pac::interrupts!(
foreach_interrupt!(
(EXTI0) => { $action!(EXTI0); };
(EXTI1) => { $action!(EXTI1); };
(EXTI2) => { $action!(EXTI2); };

View File

@ -127,7 +127,7 @@ impl<'d, T: Instance> Fmc<'d, T> {
));
}
crate::pac::peripherals!(
foreach_peripheral!(
(fmc, $inst:ident) => {
impl crate::fmc::sealed::Instance for crate::peripherals::$inst {
fn regs() -> stm32_metapac::fmc::Fmc {

View File

@ -558,7 +558,7 @@ impl sealed::Pin for AnyPin {
// ====================
crate::pac::pins!(
foreach_pin!(
($pin_name:ident, $port_name:ident, $port_num:expr, $pin_num:expr, $exti_ch:ident) => {
impl Pin for peripherals::$pin_name {
#[cfg(feature = "exti")]

View File

@ -21,9 +21,10 @@ pub enum Error {
}
pub(crate) mod sealed {
use super::*;
pub trait Instance: crate::rcc::RccPeripheral {
fn regs() -> crate::pac::i2c::I2c;
fn state_number() -> usize;
fn state() -> &'static State;
}
}
@ -36,33 +37,16 @@ pin_trait!(SdaPin, Instance);
dma_trait!(RxDma, Instance);
dma_trait!(TxDma, Instance);
macro_rules! i2c_state {
(I2C1) => {
0
};
(I2C2) => {
1
};
(I2C3) => {
2
};
(I2C4) => {
3
};
(I2C5) => {
4
};
}
crate::pac::interrupts!(
foreach_interrupt!(
($inst:ident, i2c, $block:ident, EV, $irq:ident) => {
impl sealed::Instance for peripherals::$inst {
fn regs() -> crate::pac::i2c::I2c {
crate::pac::$inst
}
fn state_number() -> usize {
i2c_state!($inst)
fn state() -> &'static State {
static STATE: State = State::new();
&STATE
}
}

View File

@ -7,6 +7,14 @@ use crate::i2c::{Error, Instance, SclPin, SdaPin};
use crate::pac::i2c;
use crate::time::Hertz;
pub struct State {}
impl State {
pub(crate) const fn new() -> Self {
Self {}
}
}
pub struct I2c<'d, T: Instance> {
phantom: PhantomData<&'d mut T>,
}

View File

@ -13,31 +13,23 @@ use futures::future::poll_fn;
use crate::dma::NoDma;
use crate::gpio::sealed::AFType;
use crate::i2c::{Error, Instance, SclPin, SdaPin};
use crate::pac;
use crate::pac::i2c;
use crate::time::Hertz;
const I2C_COUNT: usize = pac::peripheral_count!(i2c);
pub struct State {
waker: [AtomicWaker; I2C_COUNT],
chunks_transferred: [AtomicUsize; I2C_COUNT],
waker: AtomicWaker,
chunks_transferred: AtomicUsize,
}
impl State {
const fn new() -> Self {
const AW: AtomicWaker = AtomicWaker::new();
const CT: AtomicUsize = AtomicUsize::new(0);
pub(crate) const fn new() -> Self {
Self {
waker: [AW; I2C_COUNT],
chunks_transferred: [CT; I2C_COUNT],
waker: AtomicWaker::new(),
chunks_transferred: AtomicUsize::new(0),
}
}
}
static STATE: State = State::new();
pub struct I2c<'d, T: Instance, TXDMA = NoDma, RXDMA = NoDma> {
phantom: PhantomData<&'d mut T>,
tx_dma: TXDMA,
@ -108,9 +100,9 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> {
let isr = regs.isr().read();
if isr.tcr() || isr.tc() {
let n = T::state_number();
STATE.chunks_transferred[n].fetch_add(1, Ordering::Relaxed);
STATE.waker[n].wake();
let state = T::state();
state.chunks_transferred.fetch_add(1, Ordering::Relaxed);
state.waker.wake();
}
// The flag can only be cleared by writting to nbytes, we won't do that here, so disable
// the interrupt
@ -411,8 +403,8 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> {
crate::dma::write(ch, request, bytes, dst)
};
let state_number = T::state_number();
STATE.chunks_transferred[state_number].store(0, Ordering::Relaxed);
let state = T::state();
state.chunks_transferred.store(0, Ordering::Relaxed);
let mut remaining_len = total_len;
let _on_drop = OnDrop::new(|| {
@ -445,8 +437,8 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> {
}
poll_fn(|cx| {
STATE.waker[state_number].register(cx.waker());
let chunks_transferred = STATE.chunks_transferred[state_number].load(Ordering::Relaxed);
state.waker.register(cx.waker());
let chunks_transferred = state.chunks_transferred.load(Ordering::Relaxed);
if chunks_transferred == total_chunks {
return Poll::Ready(());
@ -504,8 +496,8 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> {
crate::dma::read(ch, request, src, buffer)
};
let state_number = T::state_number();
STATE.chunks_transferred[state_number].store(0, Ordering::Relaxed);
let state = T::state();
state.chunks_transferred.store(0, Ordering::Relaxed);
let mut remaining_len = total_len;
let _on_drop = OnDrop::new(|| {
@ -530,8 +522,8 @@ impl<'d, T: Instance, TXDMA, RXDMA> I2c<'d, T, TXDMA, RXDMA> {
}
poll_fn(|cx| {
STATE.waker[state_number].register(cx.waker());
let chunks_transferred = STATE.chunks_transferred[state_number].load(Ordering::Relaxed);
state.waker.register(cx.waker());
let chunks_transferred = state.chunks_transferred.load(Ordering::Relaxed);
if chunks_transferred == total_chunks {
return Poll::Ready(());

View File

@ -11,6 +11,7 @@ pub(crate) use stm32_metapac as pac;
// This must go FIRST so that all the other modules see its macros.
pub mod fmt;
include!(concat!(env!("OUT_DIR"), "/macros.rs"));
// Utilities
pub mod interrupt;
@ -62,7 +63,7 @@ pub mod usb_otg;
pub mod subghz;
// This must go last, so that it sees all the impl_foo! macros defined earlier.
mod generated {
pub(crate) mod generated {
#![allow(dead_code)]
#![allow(unused_imports)]
@ -98,10 +99,27 @@ pub fn init(config: Config) -> Peripherals {
#[cfg(dbgmcu)]
if config.enable_debug_during_sleep {
crate::pac::DBGMCU.cr().modify(|cr| {
crate::pac::dbgmcu! {
(cr, $fn_name:ident) => {
cr.$fn_name(true);
};
#[cfg(any(dbgmcu_f0, dbgmcu_g0, dbgmcu_u5))]
{
cr.set_dbg_stop(true);
cr.set_dbg_standby(true);
}
#[cfg(any(
dbgmcu_f1, dbgmcu_f2, dbgmcu_f3, dbgmcu_f4, dbgmcu_f7, dbgmcu_g4, dbgmcu_f7,
dbgmcu_l0, dbgmcu_l1, dbgmcu_l4, dbgmcu_wb, dbgmcu_wl
))]
{
cr.set_dbg_sleep(true);
cr.set_dbg_stop(true);
cr.set_dbg_standby(true);
}
#[cfg(dbgmcu_h7)]
{
cr.set_d1dbgcken(true);
cr.set_d3dbgcken(true);
cr.set_dbgsleep_d1(true);
cr.set_dbgstby_d1(true);
cr.set_dbgstop_d1(true);
}
});
}

View File

@ -127,7 +127,7 @@ macro_rules! impl_compare_capable_16bit {
};
}
crate::pac::interrupts! {
foreach_interrupt! {
($inst:ident, timer, TIM_GP16, UP, $irq:ident) => {
impl crate::pwm::sealed::CaptureCompare16bitInstance for crate::peripherals::$inst {
unsafe fn set_output_compare_mode(

View File

@ -136,7 +136,7 @@ pub(crate) mod sealed {
pub trait Instance: sealed::Instance + crate::rcc::RccPeripheral {}
crate::pac::peripherals!(
foreach_peripheral!(
(rng, $inst:ident) => {
impl Instance for peripherals::$inst {}
@ -165,7 +165,7 @@ macro_rules! irq {
};
}
crate::pac::interrupts!(
foreach_interrupt!(
(RNG) => {
irq!(RNG);
};

View File

@ -1271,7 +1271,7 @@ where
}
}
crate::pac::peripherals!(
foreach_peripheral!(
(sdmmc, $inst:ident) => {
impl sealed::Instance for peripherals::$inst {
type Interrupt = crate::interrupt::$inst;

View File

@ -874,7 +874,7 @@ pin_trait!(MisoPin, Instance);
dma_trait!(RxDma, Instance);
dma_trait!(TxDma, Instance);
crate::pac::peripherals!(
foreach_peripheral!(
(spi, $inst:ident) => {
impl sealed::Instance for peripherals::$inst {
fn regs() -> &'static crate::pac::spi::Spi {

View File

@ -29,7 +29,7 @@ type T = peripherals::TIM4;
#[cfg(time_driver_tim5)]
type T = peripherals::TIM5;
crate::pac::interrupts! {
foreach_interrupt! {
(TIM2, timer, $block:ident, UP, $irq:ident) => {
#[cfg(time_driver_tim2)]
#[interrupt]

View File

@ -155,7 +155,7 @@ macro_rules! impl_32bit_timer {
};
}
crate::pac::interrupts! {
foreach_interrupt! {
($inst:ident, timer, TIM_BASIC, UP, $irq:ident) => {
impl_basic_16bit_timer!($inst, $irq);

View File

@ -601,7 +601,7 @@ pin_trait!(CkPin, Instance);
dma_trait!(TxDma, Instance);
dma_trait!(RxDma, Instance);
crate::pac::interrupts!(
foreach_interrupt!(
($inst:ident, usart, $block:ident, $signal_name:ident, $irq:ident) => {
impl sealed::Instance for peripherals::$inst {
fn regs(&self) -> crate::pac::usart::Usart {

View File

@ -135,7 +135,7 @@ pin_trait!(UlpiD5Pin, Instance);
pin_trait!(UlpiD6Pin, Instance);
pin_trait!(UlpiD7Pin, Instance);
crate::pac::peripherals!(
foreach_peripheral!(
(otgfs, $inst:ident) => {
impl sealed::Instance for peripherals::$inst {
const REGISTERS: *const () = crate::pac::$inst.0 as *const ();
@ -223,7 +223,7 @@ crate::pac::peripherals!(
};
);
crate::pac::interrupts!(
foreach_interrupt!(
($inst:ident, otgfs, $block:ident, GLOBAL, $irq:ident) => {
unsafe impl USBInterrupt for crate::interrupt::$irq {}
};

View File

@ -1,6 +0,0 @@
// GEN PATHS HERE
mod inner;
pub mod common;
pub use inner::*;

View File

@ -1,8 +1,9 @@
use chiptool::generate::CommonModule;
use chiptool::{generate, ir, transform};
use proc_macro2::TokenStream;
use regex::Regex;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt::Write as _;
use std::fmt::{Debug, Write as _};
use std::fs;
use std::fs::File;
use std::io::Write;
@ -10,9 +11,6 @@ use std::path::Path;
use std::path::PathBuf;
use std::str::FromStr;
use chiptool::util::ToSanitizedSnakeCase;
use chiptool::{generate, ir, transform};
mod data;
use data::*;
@ -27,532 +25,322 @@ struct Metadata<'a> {
dma_channels: &'a [DmaChannel],
}
fn make_peripheral_counts(out: &mut String, data: &BTreeMap<String, u8>) {
write!(
out,
"#[macro_export]
macro_rules! peripheral_count {{
"
)
.unwrap();
for (name, count) in data {
write!(out, "({}) => ({});\n", name, count,).unwrap();
}
write!(out, " }}\n").unwrap();
}
fn make_dma_channel_counts(out: &mut String, data: &BTreeMap<String, u8>) {
if data.len() == 0 {
return;
}
write!(
out,
"#[macro_export]
macro_rules! dma_channels_count {{
"
)
.unwrap();
for (name, count) in data {
write!(out, "({}) => ({});\n", name, count,).unwrap();
}
write!(out, " }}\n").unwrap();
}
fn make_table(out: &mut String, name: &str, data: &Vec<Vec<String>>) {
write!(
out,
"#[macro_export]
macro_rules! {} {{
($($pat:tt => $code:tt;)*) => {{
macro_rules! __{}_inner {{
$(($pat) => $code;)*
($_:tt) => {{}}
}}
",
name, name
)
.unwrap();
for row in data {
write!(out, " __{}_inner!(({}));\n", name, row.join(",")).unwrap();
}
write!(
out,
" }};
}}"
)
.unwrap();
}
pub struct Options {
pub chips: Vec<String>,
pub out_dir: PathBuf,
pub data_dir: PathBuf,
}
pub fn gen_chip(
options: &Options,
chip_core_name: &str,
chip: &Chip,
core: &Core,
core_index: usize,
all_peripheral_versions: &mut HashSet<(String, String)>,
) {
let mut ir = ir::IR::new();
pub struct Gen {
opts: Options,
all_peripheral_versions: HashSet<(String, String)>,
metadata_dedup: HashMap<String, String>,
}
let mut dev = ir::Device {
interrupts: Vec::new(),
peripherals: Vec::new(),
};
// Load DBGMCU register for chip
let mut dbgmcu: Option<ir::IR> = core.peripherals.iter().find_map(|p| {
if p.name == "DBGMCU" {
p.registers.as_ref().map(|bi| {
let dbgmcu_reg_path = options
.data_dir
.join("registers")
.join(&format!("{}_{}.yaml", bi.kind, bi.version));
serde_yaml::from_reader(File::open(dbgmcu_reg_path).unwrap()).unwrap()
})
} else {
None
}
});
let mut peripheral_versions: BTreeMap<String, String> = BTreeMap::new();
let mut pin_table: Vec<Vec<String>> = Vec::new();
let mut interrupt_table: Vec<Vec<String>> = Vec::new();
let mut peripherals_table: Vec<Vec<String>> = Vec::new();
let mut dma_channels_table: Vec<Vec<String>> = Vec::new();
let mut peripheral_counts: BTreeMap<String, u8> = BTreeMap::new();
let mut dma_channel_counts: BTreeMap<String, u8> = BTreeMap::new();
let mut dbgmcu_table: Vec<Vec<String>> = Vec::new();
let gpio_base = core
.peripherals
.iter()
.find(|p| p.name == "GPIOA")
.unwrap()
.address as u32;
let gpio_stride = 0x400;
let number_suffix_re = Regex::new("^(.*?)[0-9]*$").unwrap();
if let Some(ref mut reg) = dbgmcu {
if let Some(ref cr) = reg.fieldsets.get("CR") {
for field in cr.fields.iter().filter(|e| e.name.contains("DBG")) {
let mut fn_name = String::new();
fn_name.push_str("set_");
fn_name.push_str(&field.name.to_sanitized_snake_case());
dbgmcu_table.push(vec!["cr".into(), fn_name]);
}
impl Gen {
pub fn new(opts: Options) -> Self {
Self {
opts,
all_peripheral_versions: HashSet::new(),
metadata_dedup: HashMap::new(),
}
}
for p in &core.peripherals {
let captures = number_suffix_re.captures(&p.name).unwrap();
let root_peri_name = captures.get(1).unwrap().as_str().to_string();
peripheral_counts.insert(
root_peri_name.clone(),
peripheral_counts.get(&root_peri_name).map_or(1, |v| v + 1),
);
let mut ir_peri = ir::Peripheral {
name: p.name.clone(),
array: None,
base_address: p.address,
block: None,
description: None,
interrupts: HashMap::new(),
fn gen_chip(&mut self, chip_core_name: &str, chip: &Chip, core: &Core, core_index: usize) {
let mut ir = ir::IR::new();
let mut dev = ir::Device {
interrupts: Vec::new(),
peripherals: Vec::new(),
};
if let Some(bi) = &p.registers {
peripheral_counts.insert(
bi.kind.clone(),
peripheral_counts.get(&bi.kind).map_or(1, |v| v + 1),
);
let mut peripheral_versions: BTreeMap<String, String> = BTreeMap::new();
for irq in &p.interrupts {
let mut row = Vec::new();
row.push(p.name.clone());
row.push(bi.kind.clone());
row.push(bi.block.clone());
row.push(irq.signal.clone());
row.push(irq.interrupt.to_ascii_uppercase());
interrupt_table.push(row)
}
let gpio_base = core
.peripherals
.iter()
.find(|p| p.name == "GPIOA")
.unwrap()
.address as u32;
let gpio_stride = 0x400;
let mut peripheral_row = Vec::new();
peripheral_row.push(bi.kind.clone());
peripheral_row.push(p.name.clone());
peripherals_table.push(peripheral_row);
if let Some(old_version) =
peripheral_versions.insert(bi.kind.clone(), bi.version.clone())
{
if old_version != bi.version {
panic!(
"Peripheral {} has multiple versions: {} and {}",
bi.kind, old_version, bi.version
);
}
}
ir_peri.block = Some(format!("{}::{}", bi.kind, bi.block));
match bi.kind.as_str() {
"gpio" => {
let port_letter = p.name.chars().skip(4).next().unwrap();
assert_eq!(0, (p.address as u32 - gpio_base) % gpio_stride);
let port_num = (p.address as u32 - gpio_base) / gpio_stride;
for pin_num in 0u32..16 {
let pin_name = format!("P{}{}", port_letter, pin_num);
pin_table.push(vec![
pin_name.clone(),
p.name.clone(),
port_num.to_string(),
pin_num.to_string(),
format!("EXTI{}", pin_num),
]);
}
}
_ => {}
}
}
dev.peripherals.push(ir_peri);
}
for ch in &core.dma_channels {
let mut row = Vec::new();
let dma_peri = core.peripherals.iter().find(|p| p.name == ch.dma).unwrap();
let bi = dma_peri.registers.as_ref().unwrap();
row.push(ch.name.clone());
row.push(ch.dma.clone());
row.push(bi.kind.clone());
row.push(ch.channel.to_string());
if let Some(dmamux) = &ch.dmamux {
let dmamux_channel = ch.dmamux_channel.unwrap();
row.push(format!(
"{{dmamux: {}, dmamux_channel: {}}}",
dmamux, dmamux_channel
));
} else {
row.push("{}".to_string());
}
dma_channels_table.push(row);
let dma_peri_name = ch.dma.clone();
dma_channel_counts.insert(
dma_peri_name.clone(),
dma_channel_counts.get(&dma_peri_name).map_or(1, |v| v + 1),
);
}
for irq in &core.interrupts {
dev.interrupts.push(ir::Interrupt {
name: irq.name.clone(),
description: None,
value: irq.number,
});
let name = irq.name.to_ascii_uppercase();
interrupt_table.push(vec![name.clone()]);
if name.contains("EXTI") {
interrupt_table.push(vec!["EXTI".to_string(), name.clone()]);
}
}
ir.devices.insert("".to_string(), dev);
let mut extra = format!(
"pub fn GPIO(n: usize) -> gpio::Gpio {{
gpio::Gpio(({} + {}*n) as _)
}}",
gpio_base, gpio_stride,
);
for (module, version) in &peripheral_versions {
all_peripheral_versions.insert((module.clone(), version.clone()));
write!(
&mut extra,
"#[path=\"../../peripherals/{}_{}.rs\"] pub mod {};\n",
module, version, module
)
.unwrap();
}
write!(
&mut extra,
"pub const CORE_INDEX: usize = {};\n",
core_index
)
.unwrap();
// Cleanups!
transform::sort::Sort {}.run(&mut ir).unwrap();
transform::Sanitize {}.run(&mut ir).unwrap();
// ==============================
// Setup chip dir
let chip_dir = options
.out_dir
.join("src/chips")
.join(chip_core_name.to_ascii_lowercase());
fs::create_dir_all(&chip_dir).unwrap();
// ==============================
// generate pac.rs
let data = generate::render(&ir, &gen_opts()).unwrap().to_string();
let data = data.replace("] ", "]\n");
// Remove inner attributes like #![no_std]
let data = Regex::new("# *! *\\[.*\\]").unwrap().replace_all(&data, "");
let mut file = File::create(chip_dir.join("pac.rs")).unwrap();
file.write_all(data.as_bytes()).unwrap();
file.write_all(extra.as_bytes()).unwrap();
let mut device_x = String::new();
for irq in &core.interrupts {
write!(&mut device_x, "PROVIDE({} = DefaultHandler);\n", irq.name).unwrap();
}
// ==============================
// generate mod.rs
let mut data = String::new();
write!(&mut data, "#[cfg(feature=\"metadata\")] pub mod metadata;").unwrap();
write!(&mut data, "#[cfg(feature=\"pac\")] mod pac;").unwrap();
write!(&mut data, "#[cfg(feature=\"pac\")] pub use pac::*; ").unwrap();
let peripheral_version_table = peripheral_versions
.iter()
.map(|(kind, version)| vec![kind.clone(), version.clone()])
.collect();
make_table(&mut data, "pins", &pin_table);
make_table(&mut data, "interrupts", &interrupt_table);
make_table(&mut data, "peripherals", &peripherals_table);
make_table(&mut data, "peripheral_versions", &peripheral_version_table);
make_table(&mut data, "dma_channels", &dma_channels_table);
make_table(&mut data, "dbgmcu", &dbgmcu_table);
make_peripheral_counts(&mut data, &peripheral_counts);
make_dma_channel_counts(&mut data, &dma_channel_counts);
let mut file = File::create(chip_dir.join("mod.rs")).unwrap();
file.write_all(data.as_bytes()).unwrap();
// ==============================
// generate metadata.rs
let metadata = Metadata {
name: &chip.name,
family: &chip.family,
line: &chip.line,
memory: &chip.memory,
peripherals: &core.peripherals,
interrupts: &core.interrupts,
dma_channels: &core.dma_channels,
};
let metadata = format!("{:#?}", metadata);
let metadata = metadata.replace("[\n", "&[\n");
let metadata = metadata.replace("[],\n", "&[],\n");
let mut data = String::new();
write!(
&mut data,
"
include!(\"../../metadata.rs\");
use MemoryRegionKind::*;
pub const METADATA: Metadata = {};
",
metadata
)
.unwrap();
let mut file = File::create(chip_dir.join("metadata.rs")).unwrap();
file.write_all(data.as_bytes()).unwrap();
// ==============================
// generate device.x
File::create(chip_dir.join("device.x"))
.unwrap()
.write_all(device_x.as_bytes())
.unwrap();
// ==============================
// generate default memory.x
gen_memory_x(&chip_dir, &chip);
}
fn load_chip(options: &Options, name: &str) -> Chip {
let chip_path = options
.data_dir
.join("chips")
.join(&format!("{}.json", name));
let chip = fs::read(chip_path).expect(&format!("Could not load chip {}", name));
serde_yaml::from_slice(&chip).unwrap()
}
fn gen_opts() -> generate::Options {
generate::Options {
common_module: CommonModule::External(TokenStream::from_str("crate::common").unwrap()),
}
}
pub fn gen(options: Options) {
fs::create_dir_all(options.out_dir.join("src/peripherals")).unwrap();
fs::create_dir_all(options.out_dir.join("src/chips")).unwrap();
let mut all_peripheral_versions: HashSet<(String, String)> = HashSet::new();
let mut chip_core_names: Vec<String> = Vec::new();
for chip_name in &options.chips {
println!("Generating {}...", chip_name);
let mut chip = load_chip(&options, chip_name);
// Cleanup
for core in &mut chip.cores {
for irq in &mut core.interrupts {
irq.name = irq.name.to_ascii_uppercase();
}
for p in &mut core.peripherals {
for irq in &mut p.interrupts {
irq.interrupt = irq.interrupt.to_ascii_uppercase();
}
}
}
// Generate
for (core_index, core) in chip.cores.iter().enumerate() {
let chip_core_name = match chip.cores.len() {
1 => chip_name.clone(),
_ => format!("{}-{}", chip_name, core.name),
for p in &core.peripherals {
let mut ir_peri = ir::Peripheral {
name: p.name.clone(),
array: None,
base_address: p.address,
block: None,
description: None,
interrupts: HashMap::new(),
};
chip_core_names.push(chip_core_name.clone());
gen_chip(
&options,
&chip_core_name,
&chip,
core,
core_index,
&mut all_peripheral_versions,
)
if let Some(bi) = &p.registers {
if let Some(old_version) =
peripheral_versions.insert(bi.kind.clone(), bi.version.clone())
{
if old_version != bi.version {
panic!(
"Peripheral {} has multiple versions: {} and {}",
bi.kind, old_version, bi.version
);
}
}
ir_peri.block = Some(format!("{}::{}", bi.kind, bi.block));
if bi.kind == "gpio" {
assert_eq!(0, (p.address as u32 - gpio_base) % gpio_stride);
}
}
dev.peripherals.push(ir_peri);
}
}
for (module, version) in all_peripheral_versions {
println!("loading {} {}", module, version);
for irq in &core.interrupts {
dev.interrupts.push(ir::Interrupt {
name: irq.name.clone(),
description: None,
value: irq.number,
});
}
let regs_path = Path::new(&options.data_dir)
.join("registers")
.join(&format!("{}_{}.yaml", module, version));
ir.devices.insert("".to_string(), dev);
let mut ir: ir::IR = serde_yaml::from_reader(File::open(regs_path).unwrap()).unwrap();
let mut extra = format!(
"pub fn GPIO(n: usize) -> gpio::Gpio {{
gpio::Gpio(({} + {}*n) as _)
}}",
gpio_base, gpio_stride,
);
transform::expand_extends::ExpandExtends {}
.run(&mut ir)
for (module, version) in &peripheral_versions {
self.all_peripheral_versions
.insert((module.clone(), version.clone()));
write!(
&mut extra,
"#[path=\"../../peripherals/{}_{}.rs\"] pub mod {};\n",
module, version, module
)
.unwrap();
}
write!(
&mut extra,
"pub const CORE_INDEX: usize = {};\n",
core_index
)
.unwrap();
transform::map_names(&mut ir, |k, s| match k {
transform::NameKind::Block => *s = format!("{}", s),
transform::NameKind::Fieldset => *s = format!("regs::{}", s),
transform::NameKind::Enum => *s = format!("vals::{}", s),
_ => {}
});
// Cleanups!
transform::sort::Sort {}.run(&mut ir).unwrap();
transform::Sanitize {}.run(&mut ir).unwrap();
let items = generate::render(&ir, &gen_opts()).unwrap();
let mut file = File::create(
options
.out_dir
.join("src/peripherals")
.join(format!("{}_{}.rs", module, version)),
)
.unwrap();
let data = items.to_string().replace("] ", "]\n");
// ==============================
// Setup chip dir
let chip_dir = self
.opts
.out_dir
.join("src/chips")
.join(chip_core_name.to_ascii_lowercase());
fs::create_dir_all(&chip_dir).unwrap();
// ==============================
// generate pac.rs
let data = generate::render(&ir, &gen_opts()).unwrap().to_string();
let data = data.replace("] ", "]\n");
// Remove inner attributes like #![no_std]
let re = Regex::new("# *! *\\[.*\\]").unwrap();
let data = re.replace_all(&data, "");
let data = Regex::new("# *! *\\[.*\\]").unwrap().replace_all(&data, "");
let mut file = File::create(chip_dir.join("pac.rs")).unwrap();
file.write_all(data.as_bytes()).unwrap();
file.write_all(extra.as_bytes()).unwrap();
let mut device_x = String::new();
for irq in &core.interrupts {
write!(&mut device_x, "PROVIDE({} = DefaultHandler);\n", irq.name).unwrap();
}
// ==============================
// generate metadata.rs
// (peripherals, interrupts, dma_channels) are often equal across multiple chips.
// To reduce bloat, deduplicate them.
let mut data = String::new();
write!(
&mut data,
"
const PERIPHERALS: &'static [Peripheral] = {};
const INTERRUPTS: &'static [Interrupt] = {};
const DMA_CHANNELS: &'static [DmaChannel] = {};
",
stringify(&core.peripherals),
stringify(&core.interrupts),
stringify(&core.dma_channels),
)
.unwrap();
let out_dir = self.opts.out_dir.clone();
let n = self.metadata_dedup.len();
let deduped_file = self.metadata_dedup.entry(data.clone()).or_insert_with(|| {
let file = format!("metadata_{:04}.rs", n);
let path = out_dir.join("src/chips").join(&file);
fs::write(path, data).unwrap();
file
});
let data = format!(
"include!(\"../{}\");
pub const METADATA: Metadata = Metadata {{
name: {:?},
family: {:?},
line: {:?},
memory: {},
peripherals: PERIPHERALS,
interrupts: INTERRUPTS,
dma_channels: DMA_CHANNELS,
}};",
deduped_file,
&chip.name,
&chip.family,
&chip.line,
stringify(&chip.memory),
);
let mut file = File::create(chip_dir.join("metadata.rs")).unwrap();
file.write_all(data.as_bytes()).unwrap();
// ==============================
// generate device.x
File::create(chip_dir.join("device.x"))
.unwrap()
.write_all(device_x.as_bytes())
.unwrap();
// ==============================
// generate default memory.x
gen_memory_x(&chip_dir, &chip);
}
// Generate src/lib_inner.rs
const PATHS_MARKER: &[u8] = b"// GEN PATHS HERE";
let librs = include_bytes!("assets/lib_inner.rs");
let i = bytes_find(librs, PATHS_MARKER).unwrap();
let mut paths = String::new();
fn load_chip(&mut self, name: &str) -> Chip {
let chip_path = self
.opts
.data_dir
.join("chips")
.join(&format!("{}.json", name));
let chip = fs::read(chip_path).expect(&format!("Could not load chip {}", name));
serde_yaml::from_slice(&chip).unwrap()
}
for name in chip_core_names {
let x = name.to_ascii_lowercase();
write!(
&mut paths,
"#[cfg_attr(feature=\"{}\", path = \"chips/{}/mod.rs\")]",
x, x
pub fn gen(&mut self) {
fs::create_dir_all(self.opts.out_dir.join("src/peripherals")).unwrap();
fs::create_dir_all(self.opts.out_dir.join("src/chips")).unwrap();
let mut chip_core_names: Vec<String> = Vec::new();
for chip_name in &self.opts.chips.clone() {
println!("Generating {}...", chip_name);
let mut chip = self.load_chip(chip_name);
// Cleanup
for core in &mut chip.cores {
for irq in &mut core.interrupts {
irq.name = irq.name.to_ascii_uppercase();
}
for p in &mut core.peripherals {
for irq in &mut p.interrupts {
irq.interrupt = irq.interrupt.to_ascii_uppercase();
}
}
}
// Generate
for (core_index, core) in chip.cores.iter().enumerate() {
let chip_core_name = match chip.cores.len() {
1 => chip_name.clone(),
_ => format!("{}-{}", chip_name, core.name),
};
chip_core_names.push(chip_core_name.clone());
self.gen_chip(&chip_core_name, &chip, core, core_index)
}
}
for (module, version) in &self.all_peripheral_versions {
println!("loading {} {}", module, version);
let regs_path = Path::new(&self.opts.data_dir)
.join("registers")
.join(&format!("{}_{}.yaml", module, version));
let mut ir: ir::IR = serde_yaml::from_reader(File::open(regs_path).unwrap()).unwrap();
transform::expand_extends::ExpandExtends {}
.run(&mut ir)
.unwrap();
transform::map_names(&mut ir, |k, s| match k {
transform::NameKind::Block => *s = format!("{}", s),
transform::NameKind::Fieldset => *s = format!("regs::{}", s),
transform::NameKind::Enum => *s = format!("vals::{}", s),
_ => {}
});
transform::sort::Sort {}.run(&mut ir).unwrap();
transform::Sanitize {}.run(&mut ir).unwrap();
let items = generate::render(&ir, &gen_opts()).unwrap();
let mut file = File::create(
self.opts
.out_dir
.join("src/peripherals")
.join(format!("{}_{}.rs", module, version)),
)
.unwrap();
let data = items.to_string().replace("] ", "]\n");
// Remove inner attributes like #![no_std]
let re = Regex::new("# *! *\\[.*\\]").unwrap();
let data = re.replace_all(&data, "");
file.write_all(data.as_bytes()).unwrap();
}
// Generate Cargo.toml
const BUILDDEP_BEGIN: &[u8] = b"# BEGIN BUILD DEPENDENCIES";
const BUILDDEP_END: &[u8] = b"# END BUILD DEPENDENCIES";
let mut contents = include_bytes!("../../stm32-metapac/Cargo.toml").to_vec();
let begin = bytes_find(&contents, BUILDDEP_BEGIN).unwrap();
let end = bytes_find(&contents, BUILDDEP_END).unwrap() + BUILDDEP_END.len();
contents.drain(begin..end);
fs::write(self.opts.out_dir.join("Cargo.toml"), contents).unwrap();
// copy misc files
fs::write(
self.opts.out_dir.join("build.rs"),
include_bytes!("../../stm32-metapac/build_pregenerated.rs"),
)
.unwrap();
fs::write(
self.opts.out_dir.join("src/lib.rs"),
include_bytes!("../../stm32-metapac/src/lib.rs"),
)
.unwrap();
fs::write(
self.opts.out_dir.join("src/common.rs"),
include_bytes!("../../stm32-metapac/src/common.rs"),
)
.unwrap();
fs::write(
self.opts.out_dir.join("src/metadata.rs"),
include_bytes!("../../stm32-metapac/src/metadata.rs"),
)
.unwrap();
}
let mut contents: Vec<u8> = Vec::new();
contents.extend(&librs[..i]);
contents.extend(paths.as_bytes());
contents.extend(&librs[i + PATHS_MARKER.len()..]);
fs::write(options.out_dir.join("src").join("lib_inner.rs"), &contents).unwrap();
// Generate src/lib.rs
const CUT_MARKER: &[u8] = b"// GEN CUT HERE";
let librs = include_bytes!("../../stm32-metapac/src/lib.rs");
let i = bytes_find(librs, CUT_MARKER).unwrap();
let mut contents: Vec<u8> = Vec::new();
contents.extend(&librs[..i]);
contents.extend(b"include!(\"lib_inner.rs\");\n");
fs::write(options.out_dir.join("src").join("lib.rs"), contents).unwrap();
// Generate src/common.rs
fs::write(
options.out_dir.join("src").join("common.rs"),
generate::COMMON_MODULE,
)
.unwrap();
// Generate src/metadata.rs
fs::write(
options.out_dir.join("src").join("metadata.rs"),
include_bytes!("assets/metadata.rs"),
)
.unwrap();
// Generate Cargo.toml
const BUILDDEP_BEGIN: &[u8] = b"# BEGIN BUILD DEPENDENCIES";
const BUILDDEP_END: &[u8] = b"# END BUILD DEPENDENCIES";
let mut contents = include_bytes!("../../stm32-metapac/Cargo.toml").to_vec();
let begin = bytes_find(&contents, BUILDDEP_BEGIN).unwrap();
let end = bytes_find(&contents, BUILDDEP_END).unwrap() + BUILDDEP_END.len();
contents.drain(begin..end);
fs::write(options.out_dir.join("Cargo.toml"), contents).unwrap();
// Generate build.rs
fs::write(
options.out_dir.join("build.rs"),
include_bytes!("assets/build.rs"),
)
.unwrap();
}
fn bytes_find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
@ -561,6 +349,23 @@ fn bytes_find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
.position(|window| window == needle)
}
fn stringify<T: Debug>(metadata: T) -> String {
let mut metadata = format!("{:?}", metadata);
if metadata.starts_with('[') {
metadata = format!("&{}", metadata);
}
metadata = metadata.replace(": [", ": &[");
metadata = metadata.replace("kind: Ram", "kind: MemoryRegionKind::Ram");
metadata = metadata.replace("kind: Flash", "kind: MemoryRegionKind::Flash");
metadata
}
fn gen_opts() -> generate::Options {
generate::Options {
common_module: CommonModule::External(TokenStream::from_str("crate::common").unwrap()),
}
}
fn gen_memory_x(out_dir: &PathBuf, chip: &Chip) {
let mut memory_x = String::new();

View File

@ -26,9 +26,10 @@ fn main() {
chips.sort();
gen(Options {
let opts = Options {
out_dir,
data_dir,
chips,
})
};
Gen::new(opts).gen();
}

View File

@ -3,6 +3,21 @@ name = "stm32-metapac"
version = "0.1.0"
edition = "2018"
resolver = "2"
license = "MIT OR Apache-2.0"
repository = "https://github.com/embassy-rs/embassy"
description = "Peripheral Access Crate (PAC) for all STM32 chips, including metadata."
# `cargo publish` is unable to figure out which .rs files are needed due to the include! magic.
include = [
"**/*.rs",
"**/*.x",
"Cargo.toml",
]
[package.metadata.docs.rs]
features = ["stm32h755zi-cm7", "pac", "metadata"]
default-target = "thumbv7em-none-eabihf"
targets = []
[dependencies]
cortex-m = "0.7.3"

View File

@ -6,7 +6,7 @@ fn parse_chip_core(chip_and_core: &str) -> (String, Option<String>) {
let mut s = chip_and_core.split('-');
let chip_name: String = s.next().unwrap().to_string();
if let Some(c) = s.next() {
if c.starts_with("CM") {
if c.starts_with("cm") {
return (chip_name, Some(c.to_ascii_lowercase()));
}
}
@ -18,36 +18,45 @@ fn main() {
let out_dir = PathBuf::from(env::var_os("OUT_DIR").unwrap());
let data_dir = PathBuf::from("../stm32-data/data");
println!("cwd: {:?}", env::current_dir());
let chip_core_name = env::vars_os()
.map(|(a, _)| a.to_string_lossy().to_string())
.find(|x| x.starts_with("CARGO_FEATURE_STM32"))
.expect("No stm32xx Cargo feature enabled")
.strip_prefix("CARGO_FEATURE_")
.unwrap()
.to_ascii_uppercase()
.to_ascii_lowercase()
.replace('_', "-");
let (chip_name, _) = parse_chip_core(&chip_core_name);
gen(Options {
let opts = Options {
out_dir: out_dir.clone(),
data_dir: data_dir.clone(),
chips: vec![chip_name],
});
chips: vec![chip_name.to_ascii_uppercase()],
};
Gen::new(opts).gen();
println!(
"cargo:rustc-link-search={}/src/chips/{}",
out_dir.display(),
chip_core_name.to_ascii_lowercase()
chip_core_name,
);
#[cfg(feature = "memory-x")]
println!(
"cargo:rustc-link-search={}/src/chips/{}/memory_x/",
out_dir.display(),
chip_core_name.to_ascii_lowercase()
chip_core_name
);
println!(
"cargo:rustc-env=STM32_METAPAC_PAC_PATH={}/src/chips/{}/pac.rs",
out_dir.display(),
chip_core_name
);
println!(
"cargo:rustc-env=STM32_METAPAC_METADATA_PATH={}/src/chips/{}/metadata.rs",
out_dir.display(),
chip_core_name
);
println!("cargo:rerun-if-changed=build.rs");

View File

@ -23,7 +23,15 @@ fn main() {
println!(
"cargo:rustc-link-search={}/src/chips/{}/memory_x/",
crate_dir.display(),
chip_core_name,
chip_core_name
);
println!(
"cargo:rustc-env=STM32_METAPAC_PAC_PATH=chips/{}/pac.rs",
chip_core_name
);
println!(
"cargo:rustc-env=STM32_METAPAC_METADATA_PATH=chips/{}/metadata.rs",
chip_core_name
);
println!("cargo:rerun-if-changed=build.rs");

View File

@ -0,0 +1,80 @@
use core::marker::PhantomData;
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct RW;
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct R;
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct W;
mod sealed {
use super::*;
pub trait Access {}
impl Access for R {}
impl Access for W {}
impl Access for RW {}
}
pub trait Access: sealed::Access + Copy {}
impl Access for R {}
impl Access for W {}
impl Access for RW {}
pub trait Read: Access {}
impl Read for RW {}
impl Read for R {}
pub trait Write: Access {}
impl Write for RW {}
impl Write for W {}
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Reg<T: Copy, A: Access> {
ptr: *mut u8,
phantom: PhantomData<*mut (T, A)>,
}
unsafe impl<T: Copy, A: Access> Send for Reg<T, A> {}
unsafe impl<T: Copy, A: Access> Sync for Reg<T, A> {}
impl<T: Copy, A: Access> Reg<T, A> {
pub fn from_ptr(ptr: *mut u8) -> Self {
Self {
ptr,
phantom: PhantomData,
}
}
pub fn ptr(&self) -> *mut T {
self.ptr as _
}
}
impl<T: Copy, A: Read> Reg<T, A> {
pub unsafe fn read(&self) -> T {
(self.ptr as *mut T).read_volatile()
}
}
impl<T: Copy, A: Write> Reg<T, A> {
pub unsafe fn write_value(&self, val: T) {
(self.ptr as *mut T).write_volatile(val)
}
}
impl<T: Default + Copy, A: Write> Reg<T, A> {
pub unsafe fn write<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
let mut val = Default::default();
let res = f(&mut val);
self.write_value(val);
res
}
}
impl<T: Copy, A: Read + Write> Reg<T, A> {
pub unsafe fn modify<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
let mut val = self.read();
let res = f(&mut val);
self.write_value(val);
res
}
}

View File

@ -3,5 +3,13 @@
#![allow(unused)]
#![allow(non_camel_case_types)]
// GEN CUT HERE
include!(concat!(env!("OUT_DIR"), "/src/lib_inner.rs"));
pub mod common;
#[cfg(feature = "pac")]
include!(env!("STM32_METAPAC_PAC_PATH"));
#[cfg(feature = "metadata")]
pub mod metadata {
include!("metadata.rs");
include!(env!("STM32_METAPAC_METADATA_PATH"));
}