1use std::fmt;2use std::ops::Deref;3use std::rc::Rc;45use jrsonnet_gcmodule::Acyclic;6use jrsonnet_interner::IStr;78#[derive(Clone, Acyclic, Debug, PartialEq, Eq)]9pub enum ParamName {10 Unnamed,11 Named(IStr),12}13impl ParamName {14 pub fn as_str(&self) -> Option<&str> {15 match self {16 ParamName::Unnamed => None,17 ParamName::Named(istr) => Some(istr),18 }19 }20 pub fn is_anonymous(&self) -> bool {21 matches!(self, Self::Unnamed)22 }23 pub fn is_named(&self) -> bool {24 matches!(self, Self::Named(_))25 }26}27impl PartialEq<IStr> for ParamName {28 fn eq(&self, other: &IStr) -> bool {29 match self {30 ParamName::Unnamed => false,31 ParamName::Named(istr) => istr == other,32 }33 }34}3536impl fmt::Display for ParamName {37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {38 match &self {39 Self::Named(v) => write!(f, "{v}"),40 Self::Unnamed => write!(f, "<unnamed>"),41 }42 }43}4445#[derive(Clone, Copy, Debug, Acyclic, PartialEq, Eq)]46pub enum ParamDefault {47 None,48 Exists,49 Literal(&'static str),50}51impl ParamDefault {52 pub const fn exists(is_exists: bool) -> Self {53 if is_exists {54 Self::Exists55 } else {56 Self::None57 }58 }59}60impl fmt::Display for ParamDefault {61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {62 match self {63 ParamDefault::None => Ok(()),64 ParamDefault::Exists => write!(f, " = <default>"),65 ParamDefault::Literal(lit) => write!(f, " = {lit}"),66 }67 }68}6970#[derive(Clone, Acyclic, Debug, PartialEq, Eq)]71pub struct ParamParse {72 name: ParamName,73 default: ParamDefault,74}75impl ParamParse {76 pub fn new(name: ParamName, default: ParamDefault) -> Self {77 Self { name, default }78 }79 80 pub fn name(&self) -> &ParamName {81 &self.name82 }83 pub fn default(&self) -> ParamDefault {84 self.default85 }86 pub fn has_default(&self) -> bool {87 !matches!(self.default, ParamDefault::None)88 }89}90impl fmt::Display for ParamParse {91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {92 write!(f, "{}{}", self.name, self.default)93 }94}9596#[derive(Debug, Clone, Acyclic, PartialEq, Eq)]97pub struct FunctionSignature(Rc<[ParamParse]>);98impl Deref for FunctionSignature {99 type Target = [ParamParse];100101 fn deref(&self) -> &Self::Target {102 &self.0103 }104}105106thread_local! {107 static EMPTY_SIGNATURE: FunctionSignature = FunctionSignature::new([].into());108}109110impl FunctionSignature {111 pub fn new(v: Rc<[ParamParse]>) -> Self {112 Self(v)113 }114 pub fn empty() -> Self {115 EMPTY_SIGNATURE.with(|p| p.clone())116 }117}118impl fmt::Display for FunctionSignature {119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {120 if self.0.is_empty() {121 return write!(f, "(/*no arguments*/)");122 }123 write!(f, "(")?;124 for (i, par) in self.0.iter().enumerate() {125 if i != 0 {126 write!(f, ", ")?;127 }128 write!(f, "{par}")?;129 }130 write!(f, ")")131 }132}