devalang_wasm/engine/audio/interpreter/statements/
trigger.rs

1use crate::language::syntax::ast::{Statement, Value};
2/// Trigger statement handler
3use anyhow::Result;
4use std::collections::HashMap;
5
6/// Execute trigger statement
7///
8/// Triggers are used to conditionally execute a block of statements
9/// or emit events when specific conditions are met.
10///
11/// # Arguments
12/// * `trigger_name` - Name of the trigger to execute
13/// * `body` - Statements to execute when triggered
14/// * `context` - Current execution context (variables, etc.)
15///
16/// # Examples
17/// ```ignore
18/// // Trigger on MIDI note
19/// trigger "noteOn" {
20///     kick play
21/// }
22///
23/// // Trigger with condition
24/// trigger when $velocity > 0.5 {
25///     snare play
26/// }
27/// ```
28pub fn execute_trigger(
29    trigger_name: &str,
30    _body: &[Statement],
31    _context: &HashMap<String, Value>,
32) -> Result<()> {
33    // Validate trigger name
34    if trigger_name.is_empty() {
35        anyhow::bail!("Trigger name cannot be empty");
36    }
37
38    // For now, we execute the body statements immediately
39    // In a full implementation, this would register the trigger
40    // and execute it when the condition is met
41
42    // Log trigger execution
43    #[cfg(feature = "cli")]
44    {
45        if !_body.is_empty() {
46            eprintln!(
47                "Executing trigger '{}' with {} statement(s)",
48                trigger_name,
49                _body.len()
50            );
51        }
52    }
53
54    // Trigger body execution is handled by the interpreter's main loop
55    Ok(())
56}
57
58/// Check if a trigger condition is met
59pub fn check_trigger_condition(condition: &Value, context: &HashMap<String, Value>) -> bool {
60    // Simple condition evaluation
61    match condition {
62        Value::Number(n) => n > &0.0,
63        Value::String(s) => !s.is_empty(),
64        Value::Identifier(name) => {
65            // Check variable value
66            context
67                .get(name)
68                .map(|v| matches!(v, Value::Number(n) if n > &0.0))
69                .unwrap_or(false)
70        }
71        _ => false,
72    }
73}