use std::fmt::{self, Write};
use crate::{
Attribute, Block, DocComment, Format, Formatter, RenderOptions, Statement, StorageClass, Type,
declare_with, has_annotations, write_annotations,
};
use tamacro::DisplayFromFormat;
#[derive(Debug, Clone, DisplayFromFormat)]
pub struct Function {
pub name: String,
pub params: Vec<Parameter>,
pub ret: Type,
pub is_inline: bool,
pub storage: StorageClass,
pub body: Option<Block>,
pub attrs: Vec<Attribute>,
pub raw_attrs: Vec<String>,
pub doc: Option<DocComment>,
}
impl Function {
pub fn new(name: String, ret: Type) -> FunctionBuilder {
FunctionBuilder::new(name, ret)
}
pub fn to_prototype(&self) -> Function {
let mut proto = self.clone();
proto.body = None;
proto
}
pub fn is_prototype(&self) -> bool {
self.body.is_none()
}
}
impl Format for Function {
fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
if let Some(doc) = &self.doc {
doc.format(fmt)?;
}
if has_annotations(&self.raw_attrs, &self.attrs) {
write_annotations(fmt, &self.raw_attrs, &self.attrs)?;
write!(fmt, " ")?;
}
if let Some(kw) = self.storage.keyword() {
write!(fmt, "{kw} ")?;
}
if self.is_inline {
write!(fmt, "inline ")?;
}
let params = if self.params.is_empty() {
"void".to_string()
} else {
self.params
.iter()
.map(|p| p.render_with(fmt.options()))
.collect::<Vec<_>>()
.join(", ")
};
write!(
fmt,
"{}",
declare_with(
&self.ret,
&format!("{}({})", self.name, params),
fmt.options()
)
)?;
match &self.body {
Some(body) => {
fmt.block(|fmt| body.format(fmt))?;
writeln!(fmt)
}
None => writeln!(fmt, ";"),
}
}
}
pub struct FunctionBuilder {
name: String,
params: Vec<Parameter>,
ret: Type,
is_inline: bool,
storage: StorageClass,
body: Option<Block>,
attrs: Vec<Attribute>,
raw_attrs: Vec<String>,
doc: Option<DocComment>,
}
impl FunctionBuilder {
pub fn new(name: String, ret: Type) -> Self {
Self {
name,
ret,
params: vec![],
is_inline: false,
storage: StorageClass::None,
body: None,
attrs: vec![],
raw_attrs: vec![],
doc: None,
}
}
pub fn new_with_str(name: &str, ret: Type) -> Self {
Self::new(name.to_string(), ret)
}
pub fn doc(mut self, doc: DocComment) -> Self {
self.doc = Some(doc);
self
}
pub fn make_inline(mut self) -> Self {
self.is_inline = true;
self
}
pub fn make_static(mut self) -> Self {
self.storage = StorageClass::Static;
self
}
pub fn make_extern(mut self) -> Self {
self.storage = StorageClass::Extern;
self
}
pub fn storage(mut self, storage: StorageClass) -> Self {
self.storage = storage;
self
}
pub fn body(mut self, body: Block) -> Self {
self.body = Some(body);
self
}
pub fn statement(mut self, stmt: Statement) -> Self {
self.body
.get_or_insert_with(|| Block::new().build())
.stmts
.push(stmt);
self
}
pub fn new_line(mut self) -> Self {
self.body
.get_or_insert_with(|| Block::new().build())
.stmts
.push(Statement::NewLine);
self
}
pub fn param(mut self, param: Parameter) -> Self {
self.params.push(param);
self
}
pub fn params(mut self, params: Vec<Parameter>) -> Self {
self.params = params;
self
}
pub fn attr(mut self, attr: Attribute) -> Self {
self.attrs.push(attr);
self
}
pub fn attrs(mut self, attrs: Vec<Attribute>) -> Self {
self.attrs = attrs;
self
}
pub fn raw_attr(mut self, token: &str) -> Self {
self.raw_attrs.push(token.to_string());
self
}
pub fn raw_attrs(mut self, tokens: Vec<String>) -> Self {
self.raw_attrs = tokens;
self
}
pub fn build(self) -> Function {
Function {
name: self.name,
ret: self.ret,
params: self.params,
is_inline: self.is_inline,
storage: self.storage,
body: self.body,
attrs: self.attrs,
raw_attrs: self.raw_attrs,
doc: self.doc,
}
}
}
#[derive(Debug, Clone, DisplayFromFormat)]
pub struct Parameter {
pub name: String,
pub t: Type,
pub attrs: Vec<Attribute>,
pub raw_attrs: Vec<String>,
}
impl Parameter {
pub fn new(name: String, t: Type) -> ParameterBuilder {
ParameterBuilder::new(name, t)
}
}
pub struct ParameterBuilder {
name: String,
t: Type,
attrs: Vec<Attribute>,
raw_attrs: Vec<String>,
}
impl ParameterBuilder {
pub fn new(name: String, t: Type) -> Self {
Self {
name,
t,
attrs: vec![],
raw_attrs: vec![],
}
}
pub fn new_with_str(name: &str, t: Type) -> Self {
Self::new(name.to_string(), t)
}
pub fn attr(mut self, attr: Attribute) -> Self {
self.attrs.push(attr);
self
}
pub fn attrs(mut self, attrs: Vec<Attribute>) -> Self {
self.attrs = attrs;
self
}
pub fn raw_attr(mut self, token: &str) -> Self {
self.raw_attrs.push(token.to_string());
self
}
pub fn raw_attrs(mut self, tokens: Vec<String>) -> Self {
self.raw_attrs = tokens;
self
}
pub fn build(self) -> Parameter {
Parameter {
name: self.name,
t: self.t,
attrs: self.attrs,
raw_attrs: self.raw_attrs,
}
}
}
impl Parameter {
pub fn declarator(&self) -> String {
self.declarator_with(RenderOptions::default())
}
pub fn declarator_with(&self, opts: RenderOptions) -> String {
declare_with(&self.t, &self.name, opts)
}
pub fn render(&self, style: crate::AttrStyle) -> String {
self.render_with(RenderOptions {
attr_style: style,
..Default::default()
})
}
pub fn render_with(&self, opts: RenderOptions) -> String {
crate::render(self, opts)
}
}
impl Format for Parameter {
fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
if has_annotations(&self.raw_attrs, &self.attrs) {
write_annotations(fmt, &self.raw_attrs, &self.attrs)?;
write!(fmt, " ")?;
}
write!(fmt, "{}", declare_with(&self.t, &self.name, fmt.options()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::*;
#[test]
fn function() {
let f = FunctionBuilder::new_with_str("some_function", Type::new(BaseType::Double).build())
.make_inline()
.param(
ParameterBuilder::new_with_str("val", Type::new(BaseType::Double).build()).build(),
)
.body(
Block::new()
.statement(Statement::Return(Some(Expr::Binary {
left: Box::new(Expr::Double(1.23)),
op: BinOp::Add,
right: Box::new(Expr::Ident("val".to_string())),
})))
.build(),
)
.build();
let res = r#"inline double some_function(double val) {
return 1.23 + val;
}
"#;
assert_eq!(f.to_string(), res);
}
#[test]
fn prototype() {
let proto = FunctionBuilder::new_with_str("foo", Type::new(BaseType::Void).build()).build();
assert_eq!(proto.to_string(), "void foo(void);\n");
}
#[test]
fn empty_definition() {
let empty = FunctionBuilder::new_with_str("arse", Type::new(BaseType::Void).build())
.body(Block::new().build())
.build();
assert_eq!(empty.to_string(), "void arse(void) {\n}\n");
}
#[test]
fn extern_prototype() {
let ext = FunctionBuilder::new_with_str("lol", Type::new(BaseType::Int).build())
.make_extern()
.build();
assert_eq!(ext.to_string(), "extern int lol(void);\n");
}
#[test]
fn static_inline_definition() {
let f = FunctionBuilder::new_with_str("x", Type::new(BaseType::Int).build())
.make_static()
.make_inline()
.body(
Block::new()
.statement(Statement::Return(Some(Expr::Int(0))))
.build(),
)
.build();
assert_eq!(
f.to_string(),
"static inline int x(void) {\n return 0;\n}\n"
);
}
#[test]
fn storage_class_is_mutually_exclusive() {
let f = FunctionBuilder::new_with_str("f", Type::new(BaseType::Int).build())
.make_static()
.make_extern()
.build();
assert_eq!(f.storage, StorageClass::Extern);
assert_eq!(f.to_string(), "extern int f(void);\n");
let g = FunctionBuilder::new_with_str("g", Type::new(BaseType::Int).build())
.make_extern()
.make_static()
.build();
assert_eq!(g.storage, StorageClass::Static);
assert_eq!(g.to_string(), "static int g(void);\n");
}
}