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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
use std::borrow::Cow;

use crate::{
	block::BlockOrSingleStatement,
	declarations::variable::{VariableDeclaration, VariableDeclarationKeyword},
	ParseSettings, TSXKeyword, VariableField, VariableFieldInSourceCode, WithComment,
};
use visitable_derive::Visitable;

use super::{ASTNode, Expression, ParseResult, Span, TSXToken, Token, TokenReader};

#[derive(Debug, Clone, PartialEq, Eq, Visitable)]
#[cfg_attr(feature = "self-rust-tokenize", derive(self_rust_tokenize::SelfRustTokenize))]
pub struct ForLoopStatement {
	pub condition: ForLoopCondition,
	pub inner: BlockOrSingleStatement,
	pub position: Span,
}

impl ASTNode for ForLoopStatement {
	fn get_position(&self) -> Cow<Span> {
		Cow::Borrowed(&self.position)
	}

	fn from_reader(
		reader: &mut impl TokenReader<TSXToken, Span>,
		state: &mut crate::ParsingState,
		settings: &ParseSettings,
	) -> ParseResult<Self> {
		let start_pos = reader.expect_next(TSXToken::Keyword(TSXKeyword::For))?;
		let condition = ForLoopCondition::from_reader(reader, state, settings)?;
		let inner = BlockOrSingleStatement::from_reader(reader, state, settings)?;
		let position = start_pos.union(&inner.get_position());
		Ok(ForLoopStatement { condition, inner, position })
	}

	fn to_string_from_buffer<T: source_map::ToString>(
		&self,
		buf: &mut T,
		settings: &crate::ToStringSettingsAndData,
		depth: u8,
	) {
		buf.push_str("for");
		settings.0.add_gap(buf);
		self.condition.to_string_from_buffer(buf, settings, depth);
		settings.0.add_gap(buf);
		self.inner.to_string_from_buffer(buf, settings, depth + 1);
	}
}

#[derive(Debug, Clone, PartialEq, Eq, Visitable)]
#[cfg_attr(feature = "self-rust-tokenize", derive(self_rust_tokenize::SelfRustTokenize))]
pub enum ForLoopStatementInitializer {
	Statement(VariableDeclaration),
	Expression(Expression),
}

#[derive(Debug, Clone, PartialEq, Eq, Visitable)]
#[cfg_attr(feature = "self-rust-tokenize", derive(self_rust_tokenize::SelfRustTokenize))]
pub enum ForLoopCondition {
	ForOf {
		keyword: Option<VariableDeclarationKeyword>,
		variable: WithComment<VariableField<VariableFieldInSourceCode>>,
		// TODO box...?
		of: Expression,
	},
	ForIn {
		keyword: Option<VariableDeclarationKeyword>,
		variable: WithComment<VariableField<VariableFieldInSourceCode>>,
		// TODO box...?
		r#in: Expression,
	},
	Statements {
		initializer: Option<ForLoopStatementInitializer>,
		condition: Option<Expression>,
		afterthought: Option<Expression>,
	},
}

impl ASTNode for ForLoopCondition {
	fn get_position(&self) -> Cow<Span> {
		match self {
			ForLoopCondition::ForOf { keyword, variable, of: rhs }
			| ForLoopCondition::ForIn { keyword, variable, r#in: rhs } => Cow::Owned(
				keyword
					.as_ref()
					.map(VariableDeclarationKeyword::get_position)
					.map(Cow::Borrowed)
					.unwrap_or_else(|| variable.get_position())
					.union(&rhs.get_position()),
			),
			ForLoopCondition::Statements { initializer, condition: _, afterthought } => {
				let initializer_position = match initializer.as_ref().expect("TODO what about None")
				{
					ForLoopStatementInitializer::Statement(stmt) => stmt.get_position(),
					ForLoopStatementInitializer::Expression(expr) => expr.get_position(),
				};
				Cow::Owned(
					initializer_position.union(
						&afterthought.as_ref().expect("TODO what about None").get_position(),
					),
				)
			}
		}
	}

	fn from_reader(
		reader: &mut impl TokenReader<TSXToken, Span>,
		state: &mut crate::ParsingState,
		settings: &ParseSettings,
	) -> ParseResult<Self> {
		reader.expect_next(TSXToken::OpenParentheses)?;
		// Figure out if after variable declaration there exists a "=", "in" or a "of"
		let mut destructuring_depth = 0;
		let mut ate_variable_specifier = false;
		let next = reader
			.scan(|token, _| {
				if ate_variable_specifier {
					match token {
						TSXToken::OpenBrace | TSXToken::OpenBracket => destructuring_depth += 1,
						TSXToken::CloseBrace | TSXToken::CloseBracket => destructuring_depth -= 1,
						_ => {}
					}
					destructuring_depth == 0
				} else {
					ate_variable_specifier = true;
					!VariableDeclarationKeyword::is_token_variable_keyword(token)
				}
			})
			.map(|Token(tok, _)| tok);

		let condition = match next {
			Some(TSXToken::Keyword(TSXKeyword::Of)) => {
				let keyword = if let Some(token) =
					reader.conditional_next(VariableDeclarationKeyword::is_token_variable_keyword)
				{
					Some(VariableDeclarationKeyword::from_reader(token).unwrap())
				} else {
					None
				};

				let variable =
					WithComment::<VariableField<_>>::from_reader(reader, state, settings)?;
				reader.expect_next(TSXToken::Keyword(TSXKeyword::Of))?;
				let of = Expression::from_reader(reader, state, settings)?;
				Self::ForOf { variable, keyword, of }
			}
			Some(TSXToken::Keyword(TSXKeyword::In)) => {
				let keyword = if let Some(token) =
					reader.conditional_next(VariableDeclarationKeyword::is_token_variable_keyword)
				{
					Some(VariableDeclarationKeyword::from_reader(token).unwrap())
				} else {
					None
				};

				let variable =
					WithComment::<VariableField<_>>::from_reader(reader, state, settings)?;
				reader.expect_next(TSXToken::Keyword(TSXKeyword::In))?;
				let r#in = Expression::from_reader(reader, state, settings)?;
				Self::ForIn { variable, keyword, r#in }
			}
			_ => {
				let peek = reader.peek();
				let initializer = if let Some(Token(
					TSXToken::Keyword(TSXKeyword::Const | TSXKeyword::Let | TSXKeyword::Var),
					_,
				)) = peek
				{
					let declaration = VariableDeclaration::from_reader(reader, state, settings)?;
					Some(ForLoopStatementInitializer::Statement(declaration))
				} else if let Some(Token(TSXToken::SemiColon, _)) = peek {
					None
				} else {
					let expr = Expression::from_reader(reader, state, settings)?;
					Some(ForLoopStatementInitializer::Expression(expr))
				};
				reader.expect_next(TSXToken::SemiColon)?;
				let condition = if !matches!(reader.peek(), Some(Token(TSXToken::SemiColon, _))) {
					Some(Expression::from_reader(reader, state, settings)?)
				} else {
					None
				};
				reader.expect_next(TSXToken::SemiColon)?;
				let afterthought =
					if !matches!(reader.peek(), Some(Token(TSXToken::CloseParentheses, _))) {
						Some(Expression::from_reader(reader, state, settings)?)
					} else {
						None
					};
				Self::Statements { initializer, condition, afterthought }
			}
		};
		reader.expect_next(TSXToken::CloseParentheses)?;
		Ok(condition)
	}

	fn to_string_from_buffer<T: source_map::ToString>(
		&self,
		buf: &mut T,
		settings: &crate::ToStringSettingsAndData,
		depth: u8,
	) {
		buf.push('(');
		match self {
			Self::ForOf { keyword, variable, of } => {
				if let Some(keyword) = keyword {
					buf.push_str(keyword.as_str());
				}
				variable.to_string_from_buffer(buf, settings, depth);
				// TODO whitespace here if variable is array of object destructuring
				buf.push_str(" of ");
				of.to_string_from_buffer(buf, settings, depth);
			}
			Self::ForIn { keyword, variable, r#in } => {
				if let Some(keyword) = keyword {
					buf.push_str(keyword.as_str());
				}
				variable.to_string_from_buffer(buf, settings, depth);
				// TODO whitespace here if variable is array of object destructuring
				buf.push_str(" in ");
				r#in.to_string_from_buffer(buf, settings, depth);
			}
			Self::Statements { initializer, condition, afterthought } => {
				if let Some(initializer) = initializer {
					match initializer {
						ForLoopStatementInitializer::Statement(stmt) => {
							stmt.to_string_from_buffer(buf, settings, depth)
						}
						ForLoopStatementInitializer::Expression(expr) => {
							expr.to_string_from_buffer(buf, settings, depth);
						}
					}
				}
				buf.push(';');
				if let Some(condition) = condition {
					settings.0.add_gap(buf);
					condition.to_string_from_buffer(buf, settings, depth);
				}
				buf.push(';');
				if let Some(afterthought) = afterthought {
					settings.0.add_gap(buf);
					afterthought.to_string_from_buffer(buf, settings, depth);
				}
			}
		}
		buf.push(')');
	}
}

#[cfg(test)]
mod tests {
	use super::ForLoopCondition;
	use crate::assert_matches_ast;

	#[test]
	fn condition_without_variable_keyword() {
		assert_matches_ast!("(k in x)", ForLoopCondition::ForIn { .. })
	}
}