1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
use super::Node;
use gc::{Finalize, Trace};
use std::fmt;
use crate::syntax::ast::node::StatementList;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Trace, Finalize, PartialEq)]
pub struct Case {
condition: Node,
body: StatementList,
}
impl Case {
pub fn condition(&self) -> &Node {
&self.condition
}
pub fn body(&self) -> &StatementList {
&self.body
}
pub fn new<C, B>(condition: C, body: B) -> Self
where
C: Into<Node>,
B: Into<StatementList>,
{
Self {
condition: condition.into(),
body: body.into(),
}
}
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Trace, Finalize, PartialEq)]
pub struct Switch {
val: Box<Node>,
cases: Box<[Case]>,
default: Option<Box<Node>>,
}
impl Switch {
pub fn val(&self) -> &Node {
&self.val
}
pub fn cases(&self) -> &[Case] {
&self.cases
}
pub fn default(&self) -> Option<&Node> {
self.default.as_ref().map(Box::as_ref)
}
pub fn new<V, C>(val: V, cases: C, default: Option<V>) -> Self
where
V: Into<Node>,
C: Into<Box<[Case]>>,
{
Self {
val: Box::new(val.into()),
cases: cases.into(),
default: default.map(V::into).map(Box::new),
}
}
pub(super) fn display(&self, f: &mut fmt::Formatter<'_>, indent: usize) -> fmt::Result {
writeln!(f, "switch ({}) {{", self.val())?;
for e in self.cases().iter() {
writeln!(f, "{}case {}:", indent, e.condition())?;
e.body().display(f, indent)?;
}
if self.default().is_some() {
writeln!(f, "{}default:", indent)?;
self.default().as_ref().unwrap().display(f, indent + 1)?;
}
writeln!(f, "{}}}", indent)
}
}
impl fmt::Display for Switch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.display(f, 0)
}
}
impl From<Switch> for Node {
fn from(switch: Switch) -> Self {
Self::Switch(switch)
}
}