wavegraph-compiler 0.1.0

Compile named textual audio patches to WaveGraph signal bytecode
Documentation
#![doc = include_str!("../README.md")]
#![forbid(unsafe_code)]
#![no_std]

extern crate alloc;

mod syntax;

use alloc::{
    collections::{BTreeMap, BTreeSet},
    format,
    string::String,
    vec,
    vec::Vec,
};
use core::fmt;
use syntax::{Endpoint, Statement};
use wavegraph_core::bytecode::{Op, VERSION};

/// Signal inlet and outlet names in the order declared by a native processor.
/// Names must be distinct within each direction and addressable as patch tokens.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct NodeSpec {
    /// Signal inlet names, excluding message ports.
    pub inputs: &'static [&'static str],
    /// Signal outlet names, excluding message ports.
    pub outputs: &'static [&'static str],
}

impl NodeSpec {
    fn validate(self, kind: &str, line: usize) -> Result<(), CompileError> {
        for (direction, ports) in [("inlet", self.inputs), ("outlet", self.outputs)] {
            if ports.len() > usize::from(u8::MAX) {
                return Err(CompileError::new(
                    line,
                    format!("'{kind}' exceeds 255 signal {direction}s"),
                ));
            }
            for (index, name) in ports.iter().enumerate() {
                if name.is_empty() || name.contains('#') || name.chars().any(char::is_whitespace) {
                    return Err(CompileError::new(
                        line,
                        format!("invalid {direction} name '{name}' on '{kind}'"),
                    ));
                }
                if ports[..index].contains(name) {
                    return Err(CompileError::new(
                        line,
                        format!("duplicate {direction} '{name}' on '{kind}'"),
                    ));
                }
            }
        }
        Ok(())
    }
}

/// One native instance in the compiled program's object table.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Node {
    /// Name used in connections.
    pub alias: String,
    /// Processor type in the host's catalog.
    pub kind: String,
    /// Type-specific constructor options, in source order.
    pub options: Vec<(String, String)>,
    /// One-based source line for errors instantiating this processor.
    pub line: usize,
}

/// A signal schedule and the host bindings needed to run it.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CompiledPatch {
    /// Object table in declaration order. Bytecode calls index this table.
    pub nodes: Vec<Node>,
    /// Signal bytecode, including its version byte.
    pub bytecode: Vec<u8>,
    /// Left and right physical output bus IDs.
    pub outputs: [u8; 2],
}

/// An error in a patch source file.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CompileError {
    /// One-based source line, or the end of the file for a missing declaration.
    pub line: usize,
    /// Description of what could not be compiled.
    pub message: String,
}

impl CompileError {
    fn new(line: usize, message: impl Into<String>) -> Self {
        Self {
            line,
            message: message.into(),
        }
    }
}

impl fmt::Display for CompileError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "line {}: {}", self.line, self.message)
    }
}

impl core::error::Error for CompileError {}

#[derive(Clone, Copy)]
struct PortRef {
    object: usize,
    port: usize,
}

#[derive(Clone, Copy)]
enum Instruction {
    Native(u8),
    Gain(u8),
    Mix,
}

struct Object<'a> {
    alias: &'a str,
    line: usize,
    spec: NodeSpec,
    instruction: Instruction,
    sources: Vec<Option<PortRef>>,
}

struct Wiring<'a> {
    line: usize,
    from: Endpoint<'a>,
    to: Endpoint<'a>,
}

const GAIN: NodeSpec = NodeSpec {
    inputs: &["in"],
    outputs: &["out"],
};
const MIX: NodeSpec = NodeSpec {
    inputs: &["left", "right"],
    outputs: &["out"],
};

/// Compile source text against a catalog of available processor types.
///
/// The host supplies named signal ports and interprets the type-specific
/// options on each returned node. Patch compilation runs outside the audio loop.
///
/// # Errors
/// Rejects malformed declarations, missing or ambiguous bindings, cycles, and
/// graphs exceeding the bytecode format limits.
pub fn compile(
    source: &str,
    catalog: impl Fn(&str) -> Option<NodeSpec>,
) -> Result<CompiledPatch, CompileError> {
    let mut nodes = Vec::new();
    let mut objects = Vec::new();
    let mut ids = BTreeMap::new();
    let mut connections = Vec::new();
    let mut outputs = [None; 2];
    let mut last_line = 1;

    for (index, text) in source.lines().enumerate() {
        let line = index.saturating_add(1);
        last_line = line;
        let Some(statement) = syntax::parse_line(text, line)? else {
            continue;
        };
        let (alias, spec, instruction) = match statement {
            Statement::Node {
                alias,
                kind,
                options,
            } => {
                let id = u8::try_from(nodes.len())
                    .map_err(|_| CompileError::new(line, "patch exceeds 256 native nodes"))?;
                let spec = catalog(kind).ok_or_else(|| {
                    CompileError::new(line, format!("unknown node type '{kind}'"))
                })?;
                spec.validate(kind, line)?;
                nodes.push(bind_node(line, alias, kind, options)?);
                (alias, spec, Instruction::Native(id))
            }
            Statement::Gain { alias, from, level } => {
                connections.push(Wiring {
                    line,
                    from,
                    to: Endpoint { alias, port: "in" },
                });
                (alias, GAIN, Instruction::Gain(level))
            }
            Statement::Mix { alias, left, right } => {
                connections.push(Wiring {
                    line,
                    from: left,
                    to: Endpoint {
                        alias,
                        port: "left",
                    },
                });
                connections.push(Wiring {
                    line,
                    from: right,
                    to: Endpoint {
                        alias,
                        port: "right",
                    },
                });
                (alias, MIX, Instruction::Mix)
            }
            Statement::Connect { from, to } => {
                connections.push(Wiring { line, from, to });
                continue;
            }
            Statement::Output { side, from } => {
                let channel = usize::from(side == "right");
                if outputs[channel].replace((line, from)).is_some() {
                    return Err(CompileError::new(line, format!("duplicate {side} output")));
                }
                continue;
            }
        };
        if ids.insert(alias, objects.len()).is_some() {
            return Err(CompileError::new(
                line,
                format!("duplicate object '{alias}'"),
            ));
        }
        objects.push(Object {
            alias,
            line,
            spec,
            instruction,
            sources: vec![None; spec.inputs.len()],
        });
    }

    for Wiring { line, from, to } in connections {
        let source = resolve_port(&objects, &ids, line, from, false)?;
        let inlet = resolve_port(&objects, &ids, line, to, true)?;
        if objects[inlet.object].sources[inlet.port]
            .replace(source)
            .is_some()
        {
            return Err(CompileError::new(
                line,
                format!("inlet '{}.{}' already connected", to.alias, to.port),
            ));
        }
    }
    let output_port = |index: usize, side: &str| {
        let (line, port) = outputs[index]
            .ok_or_else(|| CompileError::new(last_line, format!("missing {side} output")))?;
        resolve_port(&objects, &ids, line, port, false)
    };
    let stereo = [output_port(0, "left")?, output_port(1, "right")?];
    let (bytecode, bases) = schedule(&objects)?;
    let bus = |source: PortRef| {
        u8::try_from(bases[source.object].saturating_add(source.port)).map_err(|_| {
            CompileError::new(
                objects[source.object].line,
                "patch exceeds 256 signal buses",
            )
        })
    };
    let outputs = [bus(stereo[0])?, bus(stereo[1])?];
    Ok(CompiledPatch {
        nodes,
        bytecode,
        outputs,
    })
}

fn bind_node(
    line: usize,
    alias: &str,
    kind: &str,
    options: Vec<(&str, &str)>,
) -> Result<Node, CompileError> {
    let mut node = Node {
        alias: alias.into(),
        kind: kind.into(),
        options: Vec::with_capacity(options.len()),
        line,
    };
    for (key, value) in options {
        if node.options.iter().any(|(name, _)| name == key) {
            return Err(CompileError::new(line, format!("duplicate '{key}' option")));
        }
        node.options.push((key.into(), value.into()));
    }
    Ok(node)
}

fn resolve_port(
    objects: &[Object<'_>],
    ids: &BTreeMap<&str, usize>,
    line: usize,
    Endpoint { alias, port: name }: Endpoint<'_>,
    inlet: bool,
) -> Result<PortRef, CompileError> {
    let &object = ids
        .get(alias)
        .ok_or_else(|| CompileError::new(line, format!("unknown object '{alias}'")))?;
    let spec = objects[object].spec;
    let (label, names) = if inlet {
        ("inlet", spec.inputs)
    } else {
        ("outlet", spec.outputs)
    };
    let port = names.iter().position(|&p| p == name).ok_or_else(|| {
        CompileError::new(line, format!("unknown signal {label} '{alias}.{name}'"))
    })?;
    Ok(PortRef { object, port })
}

// Kahn's algorithm with declaration order as its tie breaker. Object IDs stay
// fixed even when a forward connection changes the execution order.
fn schedule(objects: &[Object<'_>]) -> Result<(Vec<u8>, Vec<usize>), CompileError> {
    let mut consumers = vec![Vec::new(); objects.len()];
    let mut pending = Vec::with_capacity(objects.len());
    let mut ready = BTreeSet::new();
    for (id, object) in objects.iter().enumerate() {
        for (name, source) in object.spec.inputs.iter().zip(&object.sources) {
            let source = source.ok_or_else(|| {
                CompileError::new(
                    object.line,
                    format!("unconnected inlet '{}.{name}'", object.alias),
                )
            })?;
            consumers[source.object].push(id);
        }
        pending.push(object.sources.len());
        if object.sources.is_empty() {
            ready.insert(id);
        }
    }
    let mut bases = vec![0usize; objects.len()];
    let mut next_bus = 0usize;
    let mut bytecode = vec![VERSION];
    // A CALL has a four-byte header and up to 255 one-byte input bus IDs.
    let mut encoded = [0; 4 + u8::MAX as usize];
    while let Some(id) = ready.pop_first() {
        let object = &objects[id];
        let inputs = object
            .sources
            .iter()
            .flatten()
            .map(|source| {
                u8::try_from(bases[source.object].saturating_add(source.port))
                    .map_err(|_| CompileError::new(object.line, "patch exceeds 256 signal buses"))
            })
            .collect::<Result<Vec<_>, _>>()?;
        bases[id] = next_bus;
        next_bus = next_bus.saturating_add(object.spec.outputs.len());
        if next_bus > 256 {
            return Err(CompileError::new(
                object.line,
                "patch exceeds 256 signal buses",
            ));
        }
        let op = match object.instruction {
            Instruction::Native(id) => {
                let outputs = u8::try_from(object.spec.outputs.len()).map_err(|_| {
                    CompileError::new(object.line, "node exceeds 255 signal outlets")
                })?;
                Op::Call {
                    object: id,
                    inputs: &inputs,
                    outputs,
                }
            }
            Instruction::Gain(level) => Op::Gain {
                input: inputs[0],
                level,
            },
            Instruction::Mix => Op::Mix {
                left: inputs[0],
                right: inputs[1],
            },
        };
        let len = op.encode(&mut encoded).map_err(|error| {
            CompileError::new(object.line, format!("cannot encode instruction: {error:?}"))
        })?;
        bytecode.extend_from_slice(&encoded[..len]);
        for &dependent in &consumers[id] {
            pending[dependent] = pending[dependent].saturating_sub(1);
            if pending[dependent] == 0 {
                ready.insert(dependent);
            }
        }
    }
    if let Some(id) = pending.iter().position(|&count| count > 0) {
        let object = &objects[id];
        return Err(CompileError::new(
            object.line,
            format!("signal cycle prevents scheduling '{}'", object.alias),
        ));
    }
    Ok((bytecode, bases))
}