ecma_syntax_cat/
function.rs1use crate::identifier::Identifier;
5use crate::pattern::Pattern;
6use crate::statement::Statement;
7
8#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct Function {
14 id: Option<Identifier>,
15 params: Vec<Pattern>,
16 body: Vec<Statement>,
17 is_async: bool,
18 is_generator: bool,
19}
20
21impl Function {
22 #[must_use]
24 pub fn new(
25 id: Option<Identifier>,
26 params: Vec<Pattern>,
27 body: Vec<Statement>,
28 is_async: bool,
29 is_generator: bool,
30 ) -> Self {
31 Self {
32 id,
33 params,
34 body,
35 is_async,
36 is_generator,
37 }
38 }
39
40 #[must_use]
43 pub fn id(&self) -> Option<&Identifier> {
44 self.id.as_ref()
45 }
46
47 #[must_use]
49 pub fn params(&self) -> &[Pattern] {
50 &self.params
51 }
52
53 #[must_use]
55 pub fn body(&self) -> &[Statement] {
56 &self.body
57 }
58
59 #[must_use]
61 pub fn is_async(&self) -> bool {
62 self.is_async
63 }
64
65 #[must_use]
67 pub fn is_generator(&self) -> bool {
68 self.is_generator
69 }
70}
71
72impl std::fmt::Display for Function {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 if self.is_async {
75 f.write_str("async ")?;
76 }
77 f.write_str("function")?;
78 if self.is_generator {
79 f.write_str("*")?;
80 }
81 if let Some(name) = &self.id {
82 write!(f, " {name}")?;
83 }
84 let params = self
85 .params
86 .iter()
87 .map(|p| format!("{p}"))
88 .collect::<Vec<_>>()
89 .join(", ");
90 write!(f, "({params}) {{ ... }}")
91 }
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
97pub enum ArrowBody {
98 Expression(Box<crate::expression::Expression>),
100 Block(Vec<Statement>),
102}
103
104#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct ArrowFunction {
107 params: Vec<Pattern>,
108 body: ArrowBody,
109 is_async: bool,
110}
111
112impl ArrowFunction {
113 #[must_use]
115 pub fn new(params: Vec<Pattern>, body: ArrowBody, is_async: bool) -> Self {
116 Self {
117 params,
118 body,
119 is_async,
120 }
121 }
122
123 #[must_use]
125 pub fn params(&self) -> &[Pattern] {
126 &self.params
127 }
128
129 #[must_use]
131 pub fn body(&self) -> &ArrowBody {
132 &self.body
133 }
134
135 #[must_use]
137 pub fn is_async(&self) -> bool {
138 self.is_async
139 }
140}
141
142impl std::fmt::Display for ArrowFunction {
143 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144 if self.is_async {
145 f.write_str("async ")?;
146 }
147 let params = self
148 .params
149 .iter()
150 .map(|p| format!("{p}"))
151 .collect::<Vec<_>>()
152 .join(", ");
153 write!(f, "({params}) => ")?;
154 match &self.body {
155 ArrowBody::Expression(expr) => write!(f, "{expr}"),
156 ArrowBody::Block(_) => f.write_str("{ ... }"),
157 }
158 }
159}