summaryrefslogtreecommitdiff
path: root/audio/src/parse/parser.rs
blob: 989a6f1265cba957a10f619775fc0a3d78b10f72 (plain)
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
use std::{iter::Peekable, str::FromStr, vec::IntoIter};

use super::{
	Result,
	lexer::{Token, TokenKind},
	util::{SpanParserError, TokenError},
};
use crate::program::{ChanSpec, Instruction};
use TokenKind as K;

pub struct Parser<'s> {
	tokens: Peekable<IntoIter<Token<'s>>>,
	spec: Option<ChanSpec>,
	eof: Token<'s>,
}
impl<'s> Parser<'s> {
	pub fn new(tokens: Vec<Token<'s>>) -> Self {
		let eof = Token {
			span: tokens[tokens.len() - 1].span,
			content: "",
			kind: K::Eof,
		};
		Self {
			tokens: tokens.into_iter().peekable(),
			spec: None,
			eof,
		}
	}

	fn next(&mut self) -> Token<'s> {
		self.tokens.next().unwrap_or(self.eof)
	}

	fn peek(&mut self) -> Token<'s> {
		self.tokens.peek().cloned().unwrap_or(self.eof)
	}

	fn expect(&mut self, kind: TokenKind) -> Result<Token<'s>> {
		let token = self.next();
		if token.kind == kind {
			Ok(token)
		} else {
			token.token_err(format!("expected {kind}, got {}", token.kind))
		}
	}

	fn parse_int<T>(&mut self) -> Result<T>
	where
		T: FromStr,
		<T as FromStr>::Err: std::error::Error,
	{
		let token = self.expect(K::Integer)?;
		token.content.parse().span_err(token.span)
	}

	fn parse_note(&mut self) -> Result<u8> {
		if self.peek().kind == K::Integer {
			return self.parse_int();
		}

		let ident = self.expect(K::Identifier)?;
		let str = ident.content;
		let str_len = str.len();
		let last = str.chars().last().unwrap_or_default();

		let note_str = &str[..1];
		let note = match note_str {
			"a" => 80,
			"b" => 82,
			"c" => 83,
			"d" => 85,
			"e" => 87,
			"f" => 88,
			"g" => 90,
			_ => return ident.token_err("invalid note"),
		};

		let octave_str = if last.is_ascii_digit() {
			&str[1..str_len]
		} else {
			&str[1..str_len - 1]
		};
		let octave = if !octave_str.is_empty() {
			octave_str.parse().span_err(ident.span)?
		} else {
			4
		};

		let off = match last {
			'b' | 'f' => -1,
			'#' | 's' => 1,
			_ => 0,
		};

		let pitch_u32 = (note + octave * 12) + off;
		let pitch = u8::try_from(pitch_u32).span_err(ident.span)?;

		Ok(pitch)
	}

	fn parse_bool(&mut self) -> Result<bool> {
		let n = self.parse_int::<u8>()?;
		Ok(n > 0)
	}

	fn parse_chan_ins(&mut self) -> Result<Instruction> {
		let token = self.next();
		let Some(spec) = self.spec else {
			return token.token_err("missing channel specifier");
		};
		let ins = match token.kind {
			K::Volume => {
				let volume = self.parse_int()?;
				Instruction::SetVolume(spec, volume)
			}
			K::Pitch => {
				let pitch = self.parse_note()?;
				Instruction::SetPitch(spec, pitch)
			}
			K::DutyCycle if spec == ChanSpec::PulseA => {
				let cycle = self.parse_int()?;
				Instruction::SetPulseDutyA(cycle)
			}
			K::DutyCycle if spec == ChanSpec::PulseB => {
				let cycle = self.parse_int()?;
				Instruction::SetPulseDutyB(cycle)
			}
			K::DutyCycle => {
				return token.token_err("cannot set duty cycle for this channel");
			}
			K::Mode if spec == ChanSpec::Noise => {
				let mode = self.parse_bool()?;
				Instruction::SetNoiseMode(mode)
			}
			K::Mode => return token.token_err("cannot set mode for this channel"),
			_ => return token.token_err("invalid channel argument"),
		};
		Ok(ins)
	}

	fn parse_pause_len(&mut self) -> Result<Instruction> {
		self.next();
		let num = self.parse_int()?;
		Ok(Instruction::PauseLen(num))
	}

	fn parse_pause(&mut self) -> Result<Instruction> {
		self.next();
		let next = self.peek();
		let ins = if next.kind == K::Integer {
			let num = self.parse_int()?;
			Instruction::Pause(num)
		} else {
			Instruction::Pause(1)
		};
		Ok(ins)
	}

	fn parse_ins(&mut self) -> Result<Instruction> {
		let token = self.peek();
		let spec = self.spec.take();
		match token.kind {
			K::PulseA => {
				self.spec = Some(ChanSpec::PulseA);
				self.next();
				self.parse_chan_ins()
			}
			K::PulseB => {
				self.spec = Some(ChanSpec::PulseB);
				self.next();
				self.parse_chan_ins()
			}
			K::Triangle => {
				self.spec = Some(ChanSpec::Triangle);
				self.next();
				self.parse_chan_ins()
			}
			K::Noise => {
				self.spec = Some(ChanSpec::Noise);
				self.next();
				self.parse_chan_ins()
			}
			K::PauseLen => self.parse_pause_len(),
			K::Dash => self.parse_pause(),
			_ => {
				self.spec = spec;
				self.parse_chan_ins()
			}
		}
	}

	pub fn parse(&mut self) -> Result<Vec<Instruction>> {
		let mut prog = vec![];
		loop {
			let token = self.peek();
			match token.kind {
				K::Eof => break,
				K::LineSeparator => {
					self.next();
				}
				_ => prog.push(self.parse_ins()?),
			}
		}
		Ok(prog)
	}
}