Skip to content
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
1 change: 1 addition & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ pub struct Config {
pub settings_file: Option<PathBuf>,
/// Chip-specific settings
pub settings: Settings,
pub strict_safe_access: bool,
}

impl Config {
Expand Down
11 changes: 9 additions & 2 deletions src/generate/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,14 @@ pub fn render(d: &Device, config: &Config, device_x: &mut String) -> Result<Toke
}

let generic_file = include_str!("generic.rs");
let generic_reg_file = include_str!("generic_reg_vcell.rs");
let generic_reg_file = include_str!("generic_reg_vcell.rs");
let write_safety = if config.strict_safe_access {
"pub unsafe"
} else {
"pub"
};
let generic_reg_file = generic_reg_file.replace("_WRITE_SAFETY_", write_safety);

let generic_atomic_file = include_str!("generic_atomic.rs");
if config.generic_mod {
let mut file = File::create(
Expand Down Expand Up @@ -166,7 +173,7 @@ pub fn render(d: &Device, config: &Config, device_x: &mut String) -> Result<Toke
}
} else {
let mut tokens = syn::parse_file(generic_file)?.into_token_stream();
syn::parse_file(generic_reg_file)?.to_tokens(&mut tokens);
syn::parse_file(&generic_reg_file)?.to_tokens(&mut tokens);
if config.atomics {
if let Some(atomics_feature) = config.atomics_feature.as_ref() {
quote!(#[cfg(feature = #atomics_feature)]).to_tokens(&mut tokens);
Expand Down
2 changes: 2 additions & 0 deletions src/generate/generic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@ pub trait IsEnum: FieldSpec {}
///
/// Registers marked with `Writable` can be also be `modify`'ed.
pub trait Readable: RegisterSpec {}
/// Trait implemented by readable registers with side effects to enable the `read` method.
pub trait ReadableSideEffect: RegisterSpec {}

/// Trait implemented by writeable registers.
///
Expand Down
24 changes: 20 additions & 4 deletions src/generate/generic_reg_vcell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,21 @@ impl<REG: Readable> Reg<REG> {
}
}

impl<REG: ReadableSideEffect> Reg<REG> {
/// Reads the contents of a `ReadableSideEffect` register.
///
/// # Safety
///
/// Reading this register has side effects.
#[inline(always)]
pub unsafe fn read(&self) -> R<REG> {
R {
bits: self.register.get(),
_reg: marker::PhantomData,
}
}
}

impl<REG: Resettable + Writable> Reg<REG> {
/// Writes the reset value to `Writable` register.
///
Expand Down Expand Up @@ -74,7 +89,7 @@ impl<REG: Resettable + Writable> Reg<REG> {
/// ```
/// In the latter case, other fields will be set to their reset value.
#[inline(always)]
pub fn write<F>(&self, f: F) -> REG::Ux
_WRITE_SAFETY_ fn write<F>(&self, f: F) -> REG::Ux
where
F: FnOnce(&mut W<REG>) -> &mut W<REG>,
{
Expand Down Expand Up @@ -117,7 +132,7 @@ impl<REG: Resettable + Writable> Reg<REG> {
/// let state = periph.reg.write_and(|w| State::set(w.field1()));
/// ```
#[inline(always)]
pub fn from_write<F, T>(&self, f: F) -> T
_WRITE_SAFETY_ fn from_write<F, T>(&self, f: F) -> T
where
F: FnOnce(&mut W<REG>) -> T,
{
Expand Down Expand Up @@ -208,7 +223,7 @@ impl<REG: Readable + Writable> Reg<REG> {
/// ```
/// Other fields will have the value they had before the call to `modify`.
#[inline(always)]
pub fn modify<F>(&self, f: F) -> REG::Ux
_WRITE_SAFETY_ fn modify<F>(&self, f: F) -> REG::Ux
where
for<'w> F: FnOnce(&R<REG>, &'w mut W<REG>) -> &'w mut W<REG>,
{
Expand All @@ -228,6 +243,7 @@ impl<REG: Readable + Writable> Reg<REG> {
value
}


/// Modifies the contents of the register by reading and then writing it
/// and produces a value.
///
Expand Down Expand Up @@ -260,7 +276,7 @@ impl<REG: Readable + Writable> Reg<REG> {
/// ```
/// Other fields will have the value they had before the call to `modify`.
#[inline(always)]
pub fn from_modify<F, T>(&self, f: F) -> T
_WRITE_SAFETY_ fn from_modify<F, T>(&self, f: F) -> T
where
for<'w> F: FnOnce(&R<REG>, &'w mut W<REG>) -> T,
{
Expand Down
13 changes: 11 additions & 2 deletions src/generate/register.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,10 +385,19 @@ pub fn render_register_mod(
});

if can_read {
let doc = format!("`read()` method returns [`{mod_ty}::R`](R) reader structure",);
let is_side_effect = register.read_action.is_some() && config.strict_safe_access;
let (trait_name, read_safety_doc) = if is_side_effect {
(quote!(ReadableSideEffect), " (unsafe)")
} else {
(quote!(Readable), "")
};

let doc = format!(
"`read()` method returns [`{mod_ty}::R`](R) reader structure{read_safety_doc}",
);
mod_items.extend(quote! {
#[doc = #doc]
impl crate::Readable for #regspec_ty {}
impl crate::#trait_name for #regspec_ty {}
});
}
if can_write {
Expand Down
7 changes: 7 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,13 @@ Ignore this option if you are not building your own FPGA based soft-cores."),
.action(ArgAction::Set)
.value_parser(["off", "error", "warn", "info", "debug", "trace"]),
)
.arg(
Arg::new("strict_safe_access")
.long("strict-safe-access")
.help("Marks all write accesses and read accesses with side effects as unsafe")
.action(ArgAction::SetTrue),
)

.version(concat!(
env!("CARGO_PKG_VERSION"),
include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt"))
Expand Down
44 changes: 41 additions & 3 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ use syn::{
punctuated::Punctuated, token::PathSep, Lit, LitInt, PathArguments, PathSegment, Type, TypePath,
};

use regex::Regex;
use std::sync::OnceLock;


use anyhow::{anyhow, Result};

pub const BITS_PER_BYTE: u32 = 8;
Expand Down Expand Up @@ -177,13 +181,35 @@ pub fn escape_brackets(s: &str) -> String {
})
}

static TAG_RE: OnceLock<Regex> = OnceLock::new();

/// Escape basic html tags and brackets
pub fn escape_special_chars(s: &str) -> Cow<'_, str> {
if s.contains('[') {
escape_brackets(s).into()
let tag_re= TAG_RE.get_or_init(|| Regex::new(r"<[^>]+>|&[a-zA-Z0-9#]+;").unwrap());

if !s.contains('[') && !s.contains('&') && !s.contains('<') && !s.contains('>') {
return s.into();
}

let mut last_end = 0;
let mut escaped = String::new();

for mat in tag_re.find_iter(s) {
let part = &s[last_end..mat.start()];
escaped.push_str(&part.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;"));
escaped.push_str(mat.as_str());
last_end = mat.end();
}
let remaining = &s[last_end..];

escaped.push_str(&remaining.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;"));

if escaped.contains('[') {
escape_brackets(&escaped).into()
} else {
s.into()
escaped.into()
}

}

pub fn name_of<T: FullName>(maybe_array: &MaybeArray<T>, ignore_group: bool) -> String {
Expand Down Expand Up @@ -513,3 +539,15 @@ fn pascalcase() {
assert_eq!(to_pascal_case("FOO_BAR_1_2"), "FooBar1_2");
assert_eq!(to_pascal_case("FOO_BAR_1_2_"), "FooBar1_2_");
}

#[test]
fn test_escape_special_chars() {

assert_eq!(escape_special_chars("Enable & disable"), "Enable &amp; disable");
assert_eq!(escape_special_chars("Wait < 10"), "Wait &lt; 10");
assert_eq!(escape_special_chars("This is <b>bold</b>"), "This is <b>bold</b>");
assert_eq!(escape_special_chars("Use <div class=\"foo\">"), "Use <div class=\"foo\">");
assert_eq!(escape_special_chars("A &amp; B"), "A &amp; B");
assert_eq!(escape_special_chars("Array[0]"), "Array\\[0\\]");
}

4 changes: 4 additions & 0 deletions svd2rust-regress/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ pub enum Manufacturer {
RaspberryPi,
Renesas,
Unknown,
GigaDevice,
WCH,
}

impl Manufacturer {
Expand All @@ -51,6 +53,8 @@ impl Manufacturer {
Renesas,
TexasInstruments,
Espressif,
GigaDevice,
WCH,
]
}
}
Expand Down
6 changes: 5 additions & 1 deletion svd2rust-regress/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,11 @@
mfgr: SiFive
chip: fu540
svd_url: https://raw.githubusercontent.com/riscv-rust/fu540-pac/master/fu540.svd

- arch: riscv
mfgr: WCH
chip: ch32v30x
svd_url: https://raw.githubusercontent.com/ch32-rs/ch32v30x/main/ch32v30x.svd

# SiliconLabs
- arch: cortex-m
mfgr: SiliconLabs
Expand Down
Loading