Skip to main content

mago_type_syntax/cst/
conditional.rs

1use mago_span::HasSpan;
2use mago_span::Span;
3
4use crate::cst::Type;
5use crate::cst::keyword::Keyword;
6
7#[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
8#[cfg_attr(feature = "serde", derive(serde::Serialize))]
9pub struct ConditionalType<'arena> {
10    pub subject: &'arena Type<'arena>,
11    pub is: Keyword<'arena>,
12    pub not: Option<Keyword<'arena>>,
13    pub target: &'arena Type<'arena>,
14    pub question_mark: Span,
15    pub then: &'arena Type<'arena>,
16    pub colon: Span,
17    pub otherwise: &'arena Type<'arena>,
18}
19
20impl ConditionalType<'_> {
21    #[must_use]
22    pub fn is_negated(&self) -> bool {
23        self.not.is_some()
24    }
25}
26
27impl HasSpan for ConditionalType<'_> {
28    fn span(&self) -> Span {
29        self.subject.span().join(self.otherwise.span())
30    }
31}
32
33impl std::fmt::Display for ConditionalType<'_> {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        write!(
36            f,
37            "{} {}{} {} ? {} : {}",
38            self.subject,
39            self.is,
40            self.not.as_ref().map(|k| format!(" {k}")).unwrap_or_default(),
41            self.target,
42            self.then,
43            self.otherwise
44        )
45    }
46}