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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/).

## [Unreleased]

- Fix special character escaping in generated documentation so that `&`, `<`
and `>` do not break the generated Rust docs while preserving HTML tags.
- Add `#[used]` to the generated interrupt vector table statics so they are not
dropped by the linker with lto
- Improve documentation for RISC-V settings file
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\\]");
}

Loading