use std::fmt::{self, Write};
use crate::{Expr, Format, Formatter, RenderOptions};
use tamacro::DisplayFromFormat;
#[derive(Debug, Clone, DisplayFromFormat)]
pub enum BaseType {
Void,
Double,
Float,
Char,
Int,
UInt8,
UInt16,
UInt32,
UInt64,
Int8,
Int16,
Int32,
Int64,
Size,
UIntPtr,
Bool,
Enum(String),
Struct(String),
Union(String),
TypeDef(String),
}
impl BaseType {
pub fn new_uint(bits: u8) -> Self {
use BaseType::*;
match bits {
8 => UInt8,
16 => UInt16,
32 => UInt32,
64 => UInt64,
_ => UInt64,
}
}
pub fn new_int(bits: u8) -> Self {
use BaseType::*;
match bits {
8 => Int8,
16 => Int16,
32 => Int32,
64 => Int64,
_ => Int64,
}
}
pub fn is_integer(&self) -> bool {
use BaseType::*;
matches!(
self,
Int | UInt8
| UInt16
| UInt32
| UInt64
| Int8
| Int16
| Int32
| Int64
| Size
| UIntPtr
| Bool
| Char
)
}
pub fn is_tag_type(&self) -> bool {
use BaseType::*;
matches!(self, Enum(_) | Struct(_) | Union(_) | TypeDef(_))
}
}
impl Format for BaseType {
fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
use BaseType::*;
match self {
Void => write!(fmt, "void"),
Double => write!(fmt, "double"),
Float => write!(fmt, "float"),
Char => write!(fmt, "char"),
Int => write!(fmt, "int"),
UInt8 => write!(fmt, "uint8_t"),
UInt16 => write!(fmt, "uint16_t"),
UInt32 => write!(fmt, "uint32_t"),
UInt64 => write!(fmt, "uint64_t"),
Int8 => write!(fmt, "int8_t"),
Int16 => write!(fmt, "int16_t"),
Int32 => write!(fmt, "int32_t"),
Int64 => write!(fmt, "int64_t"),
Size => write!(fmt, "size_t"),
UIntPtr => write!(fmt, "uintptr_t"),
Bool => write!(fmt, "bool"),
Enum(s) => write!(fmt, "enum {s}"),
Struct(s) => write!(fmt, "struct {s}"),
Union(s) => write!(fmt, "union {s}"),
TypeDef(s) => write!(fmt, "{s}"),
}
}
}
#[derive(Debug, Clone, Copy, DisplayFromFormat)]
pub enum TypeQualifier {
Volatile,
Const,
}
impl Format for TypeQualifier {
fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
use TypeQualifier::*;
match self {
Volatile => write!(fmt, "volatile"),
Const => write!(fmt, "const"),
}
}
}
#[derive(Debug, Clone, DisplayFromFormat)]
pub enum Type {
Base {
base: BaseType,
quals: Vec<TypeQualifier>,
},
Pointer {
quals: Vec<TypeQualifier>,
to: Box<Type>,
},
Array {
size: Option<Box<Expr>>,
of: Box<Type>,
},
Function {
ret: Box<Type>,
params: Vec<Type>,
variadic: bool,
},
Raw(String),
}
pub fn declare(ty: &Type, inner: &str) -> String {
declare_with(ty, inner, RenderOptions::default())
}
pub fn declare_with(ty: &Type, inner: &str, opts: RenderOptions) -> String {
match ty {
Type::Base { base, quals } => {
let q = quals_prefix(quals);
if inner.is_empty() {
format!("{q}{base}")
} else if inner.starts_with('[') {
format!("{q}{base}{inner}")
} else {
format!("{q}{base} {inner}")
}
}
Type::Pointer { quals, to } => {
let pq = quals_prefix(quals);
let star = format!("*{pq}{inner}");
let next = match to.as_ref() {
Type::Array { .. } | Type::Function { .. } => format!("({star})"),
_ => star,
};
declare_with(to, &next, opts)
}
Type::Array { size, of } => {
let sz = size
.as_ref()
.map(|e| crate::render(&**e, opts))
.unwrap_or_default();
declare_with(of, &format!("{inner}[{sz}]"), opts)
}
Type::Function {
ret,
params,
variadic,
} => {
let mut parts: Vec<String> = params.iter().map(|p| declare_with(p, "", opts)).collect();
if *variadic {
parts.push("...".to_string());
}
let params_str = if parts.is_empty() {
"void".to_string()
} else {
parts.join(", ")
};
declare_with(ret, &format!("{inner}({params_str})"), opts)
}
Type::Raw(spelling) => {
if inner.is_empty() {
spelling.clone()
} else if inner.starts_with('[') {
format!("{spelling}{inner}")
} else {
format!("{spelling} {inner}")
}
}
}
}
fn quals_prefix(quals: &[TypeQualifier]) -> String {
let mut out = String::new();
for q in quals {
out.push_str(&q.to_string());
out.push(' ');
}
out
}
impl Type {
pub fn new(base: BaseType) -> TypeBuilder {
TypeBuilder::new(base)
}
pub fn base(base: BaseType) -> Type {
Type::Base {
base,
quals: vec![],
}
}
pub fn base_qualified(base: BaseType, quals: Vec<TypeQualifier>) -> Type {
Type::Base { base, quals }
}
pub fn ptr(to: Type) -> Type {
Type::Pointer {
quals: vec![],
to: Box::new(to),
}
}
pub fn const_ptr(to: Type) -> Type {
Type::Pointer {
quals: vec![TypeQualifier::Const],
to: Box::new(to),
}
}
pub fn array(of: Type, size: Option<Expr>) -> Type {
Type::Array {
size: size.map(Box::new),
of: Box::new(of),
}
}
pub fn func(ret: Type, params: Vec<Type>, variadic: bool) -> Type {
Type::Function {
ret: Box::new(ret),
params,
variadic,
}
}
pub fn raw(spelling: impl Into<String>) -> Type {
Type::Raw(spelling.into())
}
pub fn declarator(&self, name: &str) -> String {
declare(self, name)
}
pub fn is_array(&self) -> bool {
matches!(self, Type::Array { .. })
}
}
impl Format for Type {
fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
write!(fmt, "{}", declare_with(self, "", fmt.options()))
}
}
pub struct TypeBuilder {
base: BaseType,
qualifiers: Vec<TypeQualifier>,
pointers: u8,
array: usize,
}
impl TypeBuilder {
pub fn new(base: BaseType) -> Self {
Self {
base,
qualifiers: vec![],
pointers: 0,
array: 0,
}
}
pub fn type_qualifier(mut self, q: TypeQualifier) -> Self {
self.qualifiers.push(q);
self
}
pub fn make_volatile(self) -> Self {
self.type_qualifier(TypeQualifier::Volatile)
}
pub fn make_const(self) -> Self {
self.type_qualifier(TypeQualifier::Const)
}
pub fn make_pointer(mut self) -> Self {
self.pointers += 1;
self
}
pub fn make_array(mut self, size: usize) -> Self {
self.array = size;
self
}
pub fn build(self) -> Type {
let mut ty = Type::Base {
base: self.base,
quals: self.qualifiers,
};
for _ in 0..self.pointers {
ty = Type::Pointer {
quals: vec![],
to: Box::new(ty),
};
}
if self.array != 0 {
ty = Type::Array {
size: Some(Box::new(Expr::Int(self.array as i64))),
of: Box::new(ty),
};
}
ty
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn base_type() {
use BaseType::*;
assert_eq!(Void.to_string(), "void");
assert_eq!(Double.to_string(), "double");
assert_eq!(Float.to_string(), "float");
assert_eq!(Char.to_string(), "char");
assert_eq!(Int.to_string(), "int");
assert_eq!(UInt8.to_string(), "uint8_t");
assert_eq!(UInt16.to_string(), "uint16_t");
assert_eq!(UInt32.to_string(), "uint32_t");
assert_eq!(UInt64.to_string(), "uint64_t");
assert_eq!(Int8.to_string(), "int8_t");
assert_eq!(Int16.to_string(), "int16_t");
assert_eq!(Int32.to_string(), "int32_t");
assert_eq!(Int64.to_string(), "int64_t");
assert_eq!(Size.to_string(), "size_t");
assert_eq!(UIntPtr.to_string(), "uintptr_t");
assert_eq!(Bool.to_string(), "bool");
assert_eq!(Enum("abc".to_string()).to_string(), "enum abc");
assert_eq!(Struct("abc".to_string()).to_string(), "struct abc");
assert_eq!(Union("abc".to_string()).to_string(), "union abc");
assert_eq!(TypeDef("abc".to_string()).to_string(), "abc");
}
#[test]
fn t() {
use BaseType::*;
let mut t = Type::new(Void).build();
assert_eq!(t.to_string(), "void");
t = Type::new(Void).make_pointer().make_pointer().build();
assert_eq!(t.to_string(), "void **");
t = Type::new(Void)
.make_pointer()
.make_pointer()
.make_const()
.build();
assert_eq!(t.to_string(), "const void **");
t = Type::new(Void)
.make_pointer()
.make_const()
.make_array(10)
.build();
assert_eq!(t.to_string(), "const void *[10]");
assert!(t.is_array())
}
#[test]
fn declarator_named() {
use BaseType::*;
let t = Type::ptr(Type::base(Int));
assert_eq!(t.declarator("x"), "int *x");
let t = Type::array(Type::ptr(Type::base(Int)), Some(Expr::Int(10)));
assert_eq!(t.declarator("a"), "int *a[10]");
let t = Type::ptr(Type::array(Type::base(Int), Some(Expr::Int(10))));
assert_eq!(t.declarator("p"), "int (*p)[10]");
let t = Type::ptr(Type::func(
Type::base(Void),
vec![Type::base(Int), Type::base(Char)],
false,
));
assert_eq!(t.declarator("cb"), "void (*cb)(int, char)");
let t = Type::const_ptr(Type::base_qualified(Char, vec![TypeQualifier::Const]));
assert_eq!(t.declarator("p"), "const char *const p");
let t = Type::array(Type::base(Int), None);
assert_eq!(t.declarator("data"), "int data[]");
}
#[test]
fn raw_type() {
let t = Type::raw("_Atomic(int)");
assert_eq!(t.declarator("counter"), "_Atomic(int) counter");
assert_eq!(t.to_string(), "_Atomic(int)");
let p = Type::ptr(Type::raw("__m128"));
assert_eq!(p.declarator("v"), "__m128 *v");
}
#[test]
fn array_size_respects_render_options() {
use crate::render;
use BaseType::Int;
let t = Type::array(Type::base(Int), Some(Expr::new_alignof(Type::base(Int))));
assert_eq!(t.to_string(), "int[_Alignof(int)]");
let c23 = render(
&t,
RenderOptions {
c23_keywords: true,
..Default::default()
},
);
assert_eq!(c23, "int[alignof(int)]");
assert_eq!(declare(&t, "xs"), "int xs[_Alignof(int)]");
}
}