use std::fmt::{self, Write};
use crate::escape::escape_c_str;
use crate::{AttrStyle, Format, Formatter};
use tamacro::DisplayFromFormat;
#[derive(Debug, Clone, PartialEq, Eq, DisplayFromFormat)]
pub struct Attribute {
pub namespace: Option<String>,
pub name: String,
pub args: Vec<String>,
}
impl Attribute {
pub fn new(name: impl Into<String>, args: Vec<String>) -> Self {
Self {
namespace: None,
name: name.into(),
args,
}
}
pub fn gnu(name: impl Into<String>, args: Vec<String>) -> Self {
Self {
namespace: Some("gnu".to_string()),
name: name.into(),
args,
}
}
pub fn packed() -> Self {
Self::gnu("packed", vec![])
}
pub fn aligned(n: u64) -> Self {
Self::gnu("aligned", vec![n.to_string()])
}
pub fn noreturn() -> Self {
Self::gnu("noreturn", vec![])
}
pub fn always_inline() -> Self {
Self::gnu("always_inline", vec![])
}
pub fn weak() -> Self {
Self::gnu("weak", vec![])
}
pub fn section(name: &str) -> Self {
Self::gnu("section", vec![quote(name)])
}
pub fn visibility(kind: &str) -> Self {
Self::gnu("visibility", vec![quote(kind)])
}
pub fn deprecated() -> Self {
Self::gnu("deprecated", vec![])
}
pub fn deprecated_msg(message: &str) -> Self {
Self::gnu("deprecated", vec![quote(message)])
}
pub fn unused() -> Self {
Self::gnu("unused", vec![])
}
pub fn used() -> Self {
Self::gnu("used", vec![])
}
pub fn cleanup(func: &str) -> Self {
Self::gnu("cleanup", vec![func.to_string()])
}
pub fn format(archetype: &str, string_index: u64, first_to_check: u64) -> Self {
Self::gnu(
"format",
vec![
archetype.to_string(),
string_index.to_string(),
first_to_check.to_string(),
],
)
}
fn entry(&self, style: AttrStyle) -> String {
let mut out = String::new();
if style == AttrStyle::C23
&& let Some(ns) = &self.namespace {
out.push_str(ns);
out.push_str("::");
}
out.push_str(&self.name);
if !self.args.is_empty() {
out.push('(');
out.push_str(&self.args.join(", "));
out.push(')');
}
out
}
}
impl Format for Attribute {
fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
let s = format_attrs(std::slice::from_ref(self), fmt.attr_style());
write!(fmt, "{s}")
}
}
fn quote(s: &str) -> String {
format!("\"{}\"", escape_c_str(s))
}
pub fn format_attrs(attrs: &[Attribute], style: AttrStyle) -> String {
if attrs.is_empty() {
return String::new();
}
let entries = attrs
.iter()
.map(|a| a.entry(style))
.collect::<Vec<_>>()
.join(", ");
match style {
AttrStyle::Gnu => format!("__attribute__(({entries}))"),
AttrStyle::C23 => format!("[[{entries}]]"),
}
}
pub fn format_annotations(raw: &[String], typed: &[Attribute], style: AttrStyle) -> String {
let typed = format_attrs(typed, style);
match (raw.is_empty(), typed.is_empty()) {
(true, true) => String::new(),
(false, true) => raw.join(" "),
(true, false) => typed,
(false, false) => format!("{} {typed}", raw.join(" ")),
}
}
pub fn has_annotations(raw: &[String], typed: &[Attribute]) -> bool {
!raw.is_empty() || !typed.is_empty()
}
pub fn write_attrs(fmt: &mut Formatter<'_>, attrs: &[Attribute]) -> fmt::Result {
let s = format_attrs(attrs, fmt.attr_style());
if !s.is_empty() {
write!(fmt, "{s}")?;
}
Ok(())
}
pub fn write_annotations(
fmt: &mut Formatter<'_>,
raw: &[String],
typed: &[Attribute],
) -> fmt::Result {
let s = format_annotations(raw, typed, fmt.attr_style());
if !s.is_empty() {
write!(fmt, "{s}")?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn gnu_and_c23_spelling() {
let attrs = vec![Attribute::packed(), Attribute::aligned(16)];
assert_eq!(
format_attrs(&attrs, AttrStyle::Gnu),
"__attribute__((packed, aligned(16)))"
);
assert_eq!(
format_attrs(&attrs, AttrStyle::C23),
"[[gnu::packed, gnu::aligned(16)]]"
);
}
#[test]
fn string_and_numeric_args() {
assert_eq!(
format_attrs(&[Attribute::section(".boot")], AttrStyle::Gnu),
"__attribute__((section(\".boot\")))"
);
assert_eq!(
format_attrs(&[Attribute::format("printf", 1, 2)], AttrStyle::Gnu),
"__attribute__((format(printf, 1, 2)))"
);
assert_eq!(
format_attrs(&[Attribute::deprecated_msg("use bar")], AttrStyle::C23),
"[[gnu::deprecated(\"use bar\")]]"
);
}
#[test]
fn plain_and_empty() {
assert_eq!(
format_attrs(&[Attribute::new("nodiscard", vec![])], AttrStyle::C23),
"[[nodiscard]]"
);
assert_eq!(format_attrs(&[], AttrStyle::Gnu), "");
}
#[test]
fn format_impl_uses_ambient_style() {
use crate::{RenderOptions, render};
let a = Attribute::packed();
assert_eq!(a.to_string(), "__attribute__((packed))");
let c23 = render(
&a,
RenderOptions {
attr_style: AttrStyle::C23,
..Default::default()
},
);
assert_eq!(c23, "[[gnu::packed]]");
}
#[test]
fn formatter_writers_match_string_form() {
use crate::{Formatter, RenderOptions};
let raw = vec!["MYLANG_EXPORT".to_string()];
let typed = vec![Attribute::noreturn()];
assert!(has_annotations(&raw, &typed));
assert!(!has_annotations(&[], &[]));
let mut buf = String::new();
{
let mut fmt = Formatter::new(&mut buf);
write_annotations(&mut fmt, &raw, &typed).unwrap();
}
assert_eq!(buf, format_annotations(&raw, &typed, AttrStyle::Gnu));
assert_eq!(buf, "MYLANG_EXPORT __attribute__((noreturn))");
let mut buf = String::new();
{
let mut fmt = Formatter::with_options(
&mut buf,
RenderOptions {
attr_style: AttrStyle::C23,
..Default::default()
},
);
write_attrs(&mut fmt, &typed).unwrap();
}
assert_eq!(buf, "[[gnu::noreturn]]");
let mut buf = String::new();
{
let mut fmt = Formatter::new(&mut buf);
write_annotations(&mut fmt, &[], &[]).unwrap();
}
assert_eq!(buf, "");
}
}