1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3#![no_std]
4
5extern crate alloc;
6
7mod syntax;
8
9use alloc::{
10 collections::{BTreeMap, BTreeSet},
11 format,
12 string::String,
13 vec,
14 vec::Vec,
15};
16use core::fmt;
17use syntax::{Endpoint, Statement};
18use wavegraph_core::bytecode::{Op, VERSION};
19
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
23pub struct NodeSpec {
24 pub inputs: &'static [&'static str],
26 pub outputs: &'static [&'static str],
28}
29
30impl NodeSpec {
31 fn validate(self, kind: &str, line: usize) -> Result<(), CompileError> {
32 for (direction, ports) in [("inlet", self.inputs), ("outlet", self.outputs)] {
33 if ports.len() > usize::from(u8::MAX) {
34 return Err(CompileError::new(
35 line,
36 format!("'{kind}' exceeds 255 signal {direction}s"),
37 ));
38 }
39 for (index, name) in ports.iter().enumerate() {
40 if name.is_empty() || name.contains('#') || name.chars().any(char::is_whitespace) {
41 return Err(CompileError::new(
42 line,
43 format!("invalid {direction} name '{name}' on '{kind}'"),
44 ));
45 }
46 if ports[..index].contains(name) {
47 return Err(CompileError::new(
48 line,
49 format!("duplicate {direction} '{name}' on '{kind}'"),
50 ));
51 }
52 }
53 }
54 Ok(())
55 }
56}
57
58#[derive(Clone, Debug, Eq, PartialEq)]
60pub struct Node {
61 pub alias: String,
63 pub kind: String,
65 pub options: Vec<(String, String)>,
67 pub line: usize,
69}
70
71#[derive(Clone, Debug, Eq, PartialEq)]
73pub struct CompiledPatch {
74 pub nodes: Vec<Node>,
76 pub bytecode: Vec<u8>,
78 pub outputs: [u8; 2],
80}
81
82#[derive(Clone, Debug, Eq, PartialEq)]
84pub struct CompileError {
85 pub line: usize,
87 pub message: String,
89}
90
91impl CompileError {
92 fn new(line: usize, message: impl Into<String>) -> Self {
93 Self {
94 line,
95 message: message.into(),
96 }
97 }
98}
99
100impl fmt::Display for CompileError {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 write!(f, "line {}: {}", self.line, self.message)
103 }
104}
105
106impl core::error::Error for CompileError {}
107
108#[derive(Clone, Copy)]
109struct PortRef {
110 object: usize,
111 port: usize,
112}
113
114#[derive(Clone, Copy)]
115enum Instruction {
116 Native(u8),
117 Gain(u8),
118 Mix,
119}
120
121struct Object<'a> {
122 alias: &'a str,
123 line: usize,
124 spec: NodeSpec,
125 instruction: Instruction,
126 sources: Vec<Option<PortRef>>,
127}
128
129struct Wiring<'a> {
130 line: usize,
131 from: Endpoint<'a>,
132 to: Endpoint<'a>,
133}
134
135const GAIN: NodeSpec = NodeSpec {
136 inputs: &["in"],
137 outputs: &["out"],
138};
139const MIX: NodeSpec = NodeSpec {
140 inputs: &["left", "right"],
141 outputs: &["out"],
142};
143
144pub fn compile(
153 source: &str,
154 catalog: impl Fn(&str) -> Option<NodeSpec>,
155) -> Result<CompiledPatch, CompileError> {
156 let mut nodes = Vec::new();
157 let mut objects = Vec::new();
158 let mut ids = BTreeMap::new();
159 let mut connections = Vec::new();
160 let mut outputs = [None; 2];
161 let mut last_line = 1;
162
163 for (index, text) in source.lines().enumerate() {
164 let line = index.saturating_add(1);
165 last_line = line;
166 let Some(statement) = syntax::parse_line(text, line)? else {
167 continue;
168 };
169 let (alias, spec, instruction) = match statement {
170 Statement::Node {
171 alias,
172 kind,
173 options,
174 } => {
175 let id = u8::try_from(nodes.len())
176 .map_err(|_| CompileError::new(line, "patch exceeds 256 native nodes"))?;
177 let spec = catalog(kind).ok_or_else(|| {
178 CompileError::new(line, format!("unknown node type '{kind}'"))
179 })?;
180 spec.validate(kind, line)?;
181 nodes.push(bind_node(line, alias, kind, options)?);
182 (alias, spec, Instruction::Native(id))
183 }
184 Statement::Gain { alias, from, level } => {
185 connections.push(Wiring {
186 line,
187 from,
188 to: Endpoint { alias, port: "in" },
189 });
190 (alias, GAIN, Instruction::Gain(level))
191 }
192 Statement::Mix { alias, left, right } => {
193 connections.push(Wiring {
194 line,
195 from: left,
196 to: Endpoint {
197 alias,
198 port: "left",
199 },
200 });
201 connections.push(Wiring {
202 line,
203 from: right,
204 to: Endpoint {
205 alias,
206 port: "right",
207 },
208 });
209 (alias, MIX, Instruction::Mix)
210 }
211 Statement::Connect { from, to } => {
212 connections.push(Wiring { line, from, to });
213 continue;
214 }
215 Statement::Output { side, from } => {
216 let channel = usize::from(side == "right");
217 if outputs[channel].replace((line, from)).is_some() {
218 return Err(CompileError::new(line, format!("duplicate {side} output")));
219 }
220 continue;
221 }
222 };
223 if ids.insert(alias, objects.len()).is_some() {
224 return Err(CompileError::new(
225 line,
226 format!("duplicate object '{alias}'"),
227 ));
228 }
229 objects.push(Object {
230 alias,
231 line,
232 spec,
233 instruction,
234 sources: vec![None; spec.inputs.len()],
235 });
236 }
237
238 for Wiring { line, from, to } in connections {
239 let source = resolve_port(&objects, &ids, line, from, false)?;
240 let inlet = resolve_port(&objects, &ids, line, to, true)?;
241 if objects[inlet.object].sources[inlet.port]
242 .replace(source)
243 .is_some()
244 {
245 return Err(CompileError::new(
246 line,
247 format!("inlet '{}.{}' already connected", to.alias, to.port),
248 ));
249 }
250 }
251 let output_port = |index: usize, side: &str| {
252 let (line, port) = outputs[index]
253 .ok_or_else(|| CompileError::new(last_line, format!("missing {side} output")))?;
254 resolve_port(&objects, &ids, line, port, false)
255 };
256 let stereo = [output_port(0, "left")?, output_port(1, "right")?];
257 let (bytecode, bases) = schedule(&objects)?;
258 let bus = |source: PortRef| {
259 u8::try_from(bases[source.object].saturating_add(source.port)).map_err(|_| {
260 CompileError::new(
261 objects[source.object].line,
262 "patch exceeds 256 signal buses",
263 )
264 })
265 };
266 let outputs = [bus(stereo[0])?, bus(stereo[1])?];
267 Ok(CompiledPatch {
268 nodes,
269 bytecode,
270 outputs,
271 })
272}
273
274fn bind_node(
275 line: usize,
276 alias: &str,
277 kind: &str,
278 options: Vec<(&str, &str)>,
279) -> Result<Node, CompileError> {
280 let mut node = Node {
281 alias: alias.into(),
282 kind: kind.into(),
283 options: Vec::with_capacity(options.len()),
284 line,
285 };
286 for (key, value) in options {
287 if node.options.iter().any(|(name, _)| name == key) {
288 return Err(CompileError::new(line, format!("duplicate '{key}' option")));
289 }
290 node.options.push((key.into(), value.into()));
291 }
292 Ok(node)
293}
294
295fn resolve_port(
296 objects: &[Object<'_>],
297 ids: &BTreeMap<&str, usize>,
298 line: usize,
299 Endpoint { alias, port: name }: Endpoint<'_>,
300 inlet: bool,
301) -> Result<PortRef, CompileError> {
302 let &object = ids
303 .get(alias)
304 .ok_or_else(|| CompileError::new(line, format!("unknown object '{alias}'")))?;
305 let spec = objects[object].spec;
306 let (label, names) = if inlet {
307 ("inlet", spec.inputs)
308 } else {
309 ("outlet", spec.outputs)
310 };
311 let port = names.iter().position(|&p| p == name).ok_or_else(|| {
312 CompileError::new(line, format!("unknown signal {label} '{alias}.{name}'"))
313 })?;
314 Ok(PortRef { object, port })
315}
316
317fn schedule(objects: &[Object<'_>]) -> Result<(Vec<u8>, Vec<usize>), CompileError> {
320 let mut consumers = vec![Vec::new(); objects.len()];
321 let mut pending = Vec::with_capacity(objects.len());
322 let mut ready = BTreeSet::new();
323 for (id, object) in objects.iter().enumerate() {
324 for (name, source) in object.spec.inputs.iter().zip(&object.sources) {
325 let source = source.ok_or_else(|| {
326 CompileError::new(
327 object.line,
328 format!("unconnected inlet '{}.{name}'", object.alias),
329 )
330 })?;
331 consumers[source.object].push(id);
332 }
333 pending.push(object.sources.len());
334 if object.sources.is_empty() {
335 ready.insert(id);
336 }
337 }
338 let mut bases = vec![0usize; objects.len()];
339 let mut next_bus = 0usize;
340 let mut bytecode = vec![VERSION];
341 let mut encoded = [0; 4 + u8::MAX as usize];
343 while let Some(id) = ready.pop_first() {
344 let object = &objects[id];
345 let inputs = object
346 .sources
347 .iter()
348 .flatten()
349 .map(|source| {
350 u8::try_from(bases[source.object].saturating_add(source.port))
351 .map_err(|_| CompileError::new(object.line, "patch exceeds 256 signal buses"))
352 })
353 .collect::<Result<Vec<_>, _>>()?;
354 bases[id] = next_bus;
355 next_bus = next_bus.saturating_add(object.spec.outputs.len());
356 if next_bus > 256 {
357 return Err(CompileError::new(
358 object.line,
359 "patch exceeds 256 signal buses",
360 ));
361 }
362 let op = match object.instruction {
363 Instruction::Native(id) => {
364 let outputs = u8::try_from(object.spec.outputs.len()).map_err(|_| {
365 CompileError::new(object.line, "node exceeds 255 signal outlets")
366 })?;
367 Op::Call {
368 object: id,
369 inputs: &inputs,
370 outputs,
371 }
372 }
373 Instruction::Gain(level) => Op::Gain {
374 input: inputs[0],
375 level,
376 },
377 Instruction::Mix => Op::Mix {
378 left: inputs[0],
379 right: inputs[1],
380 },
381 };
382 let len = op.encode(&mut encoded).map_err(|error| {
383 CompileError::new(object.line, format!("cannot encode instruction: {error:?}"))
384 })?;
385 bytecode.extend_from_slice(&encoded[..len]);
386 for &dependent in &consumers[id] {
387 pending[dependent] = pending[dependent].saturating_sub(1);
388 if pending[dependent] == 0 {
389 ready.insert(dependent);
390 }
391 }
392 }
393 if let Some(id) = pending.iter().position(|&count| count > 0) {
394 let object = &objects[id];
395 return Err(CompileError::new(
396 object.line,
397 format!("signal cycle prevents scheduling '{}'", object.alias),
398 ));
399 }
400 Ok((bytecode, bases))
401}