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
use std::borrow::Cow;

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

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

#[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(VariableStatement),
	Expression(Expression),
}

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

impl ASTNode for ForLoopCondition {
	fn get_position(&self) -> Cow<Span> {
		todo!()
	}

	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;
				false
			}
		});

		let condition = match next.map(|Token(tok, _)| tok) {
			Some(TSXToken::Keyword(TSXKeyword::Of)) => {
				let keyword = VariableKeyword::from_reader(reader.next().unwrap())?;
				let variable = ASTNode::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 = VariableKeyword::from_reader(reader.next().unwrap())?;
				let variable = ASTNode::from_reader(reader, state, settings)?;
				reader.expect_next(TSXToken::Keyword(TSXKeyword::In))?;
				let in_condition = Expression::from_reader(reader, state, settings)?;
				Self::ForIn { variable, keyword, in_condition }
			}
			_ => {
				let initializer = if let Some(Token(
					TSXToken::Keyword(TSXKeyword::Const | TSXKeyword::Let | TSXKeyword::Var),
					_,
				)) = reader.peek()
				{
					VariableStatement::from_reader(reader, state, settings)
						.map(ForLoopStatementInitializer::Statement)
				} else {
					Expression::from_reader(reader, state, settings)
						.map(ForLoopStatementInitializer::Expression)
				}?;
				reader.expect_next(TSXToken::SemiColon)?;
				let condition = Expression::from_reader(reader, state, settings)?;
				reader.expect_next(TSXToken::SemiColon)?;
				let final_expression = Expression::from_reader(reader, state, settings)?;
				Self::Statements { initializer, condition, final_expression }
			}
		};
		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 } => {
				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, in_condition } => {
				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 ");
				in_condition.to_string_from_buffer(buf, settings, depth);
			}
			Self::Statements { initializer, condition, final_expression } => {
				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(';');
				settings.0.add_gap(buf);
				condition.to_string_from_buffer(buf, settings, depth);
				buf.push(';');
				settings.0.add_gap(buf);
				final_expression.to_string_from_buffer(buf, settings, depth);
			}
		}
		buf.push(')');
	}
}