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
use themelios::types::Game;
use themelios::lookup::Lookup;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Space {
	None,
	Space,
	Newline,
}

pub struct Context<'a> {
	pub game: Game,
	pub decompile: bool,
	indent: usize,
	space: Space,
	pub lookup: &'a dyn Lookup,
	out: String,
}

impl<'a> Context<'a> {
	pub fn new(game: Game, lookup: Option<&'a dyn Lookup>) -> Self {
		Self {
			game,
			decompile: true,
			indent: 0,
			space: Space::None,
			lookup: lookup.unwrap_or_else(|| themelios::lookup::default_for(game)),
			out: String::new(),
		}
	}

	pub fn flat(mut self) -> Self {
		self.decompile = false;
		self
	}

	pub fn finish(self) -> String {
		self.out
	}
}

impl<'a> Context<'a> {
	fn put_space(&mut self) {
		match self.space {
			Space::None => {}
			Space::Space => {
				self.out.push(' ');
			}
			Space::Newline => {
				for _ in 0..self.indent {
					self.out.push('\t');
				}
			}
		}
		self.space = Space::None;
	}

	pub fn space(&mut self) -> &mut Self {
		self.space = Space::Space;
		self
	}

	pub fn no_space(&mut self) -> &mut Self {
		self.space = Space::None;
		self
	}

	pub fn kw(&mut self, arg: &str) -> &mut Self {
		self.put_space();
		self.out.push_str(arg);
		self.space();
		self
	}

	pub fn pre(&mut self, arg: &str) -> &mut Self {
		self.put_space();
		self.out.push_str(arg);
		self
	}

	pub fn suf(&mut self, arg: &str) -> &mut Self {
		self.out.push_str(arg);
		self.space();
		self
	}

	pub fn line(&mut self) -> &mut Self {
		self.out.push('\n');
		self.space = Space::Newline;
		self
	}

	pub fn is_line(&self) -> bool {
		self.space == Space::Newline
	}

	pub fn write_fmt(&mut self, args: std::fmt::Arguments<'_>) {
		self.put_space();
		std::fmt::Write::write_fmt(&mut self.out, args).unwrap();
	}

	pub fn indent<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
		self.indent += 1;
		let v = f(self);
		self.indent -= 1;
		v
	}
}