use std::fmt::{self, Display, Write};
use crate::{Doc, Expr, Formatter, Type};
#[derive(Debug, Clone)]
pub struct FunctionParam {
name: String,
ty: Type,
doc: Option<Doc>,
}
impl FunctionParam {
pub fn new(name: &str, ty: Type) -> Self {
Self::with_string(String::from(name), ty)
}
pub fn with_string(name: String, ty: Type) -> Self {
FunctionParam { name, ty, doc: None }
}
pub fn name(&self) -> &str {
&self.name
}
pub fn type_ref(&self) -> &Type {
&self.ty
}
pub fn to_type(&self) -> Type {
self.ty.clone()
}
pub fn to_expr(&self) -> Expr {
Expr::Variable {
name: self.name.clone(),
ty: self.ty.clone(),
}
}
pub fn push_doc_str(&mut self, doc: &str) -> &mut Self {
if let Some(d) = &mut self.doc {
d.add_text(doc);
} else {
self.doc = Some(Doc::with_str(doc));
}
self
}
pub fn doc(&mut self, doc: Doc) -> &mut Self {
self.doc = Some(doc);
self
}
pub fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
self.ty.fmt(fmt)?;
write!(fmt, " {}", self.name)
}
}
impl Display for FunctionParam {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut ret = String::new();
self.fmt(&mut Formatter::new(&mut ret)).unwrap();
write!(f, "{ret}")
}
}
#[derive(Debug, Clone)]
pub struct MethodParam {
name: String,
default: Option<String>,
ty: Type,
doc: Option<Doc>,
}
impl MethodParam {
pub fn new(name: &str, ty: Type) -> Self {
MethodParam {
name: String::from(name),
default: None,
ty,
doc: None,
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn type_ref(&self) -> &Type {
&self.ty
}
pub fn to_type(&self) -> Type {
self.ty.clone()
}
pub fn to_expr(&self) -> Expr {
Expr::Variable {
name: self.name.clone(),
ty: self.ty.clone(),
}
}
pub fn doc_str(&mut self, doc: &str) -> &mut Self {
if let Some(d) = &mut self.doc {
d.add_text(doc);
} else {
self.doc = Some(Doc::with_str(doc));
}
self
}
pub fn doc(&mut self, doc: Doc) -> &mut Self {
self.doc = Some(doc);
self
}
pub fn set_default_value(&mut self, val: &str) -> &mut Self {
self.default = Some(String::from(val));
self
}
pub fn do_fmt(&self, fmt: &mut Formatter<'_>, decl_only: bool) -> fmt::Result {
self.ty.fmt(fmt)?;
write!(fmt, " {}", self.name)?;
if let Some(s) = &self.default {
if decl_only {
write!(fmt, " = {s}")?;
}
}
Ok(())
}
pub fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
self.do_fmt(fmt, false)
}
}
impl Display for MethodParam {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut ret = String::new();
self.fmt(&mut Formatter::new(&mut ret)).unwrap();
write!(f, "{ret}")
}
}