Skip to main content

vibelang_std/
lib.rs

1//! VibeLang Standard Library.
2//!
3//! This crate provides the standard library of `.vibe` files for VibeLang,
4//! including drums, bass, leads, pads, effects, and music theory utilities.
5//!
6//! # Usage
7//!
8//! The standard library is typically accessed via import paths in `.vibe` files:
9//!
10//! ```vibe
11//! import "stdlib/drums/kicks/kick_808.vibe";
12//! import "stdlib/effects/reverb.vibe";
13//! ```
14//!
15//! # Directory Structure
16//!
17//! - `stdlib/drums/` - Drum sounds (kicks, snares, hihats, claps, percussion, cymbals)
18//! - `stdlib/bass/` - Bass sounds (sub, acid, pluck, reese, wobble)
19//! - `stdlib/leads/` - Lead synths (pluck, stabs, synth)
20//! - `stdlib/pads/` - Pad textures (ambient, lush)
21//! - `stdlib/textures/` - Ambient textures (ambient, drone)
22//! - `stdlib/effects/` - Audio effects (delay, reverb, distortion, filters, etc.)
23//! - `stdlib/fx/` - Sound design elements (impacts, risers, subdrops, sweeps)
24//! - `stdlib/theory/` - Music theory tools (scales, chords, progressions, etc.)
25//!
26//! # Installation
27//!
28//! When installed via `cargo install vibelang-cli`, the stdlib is automatically
29//! extracted to `~/.local/share/vibelang/stdlib/` (Linux/macOS) or the equivalent
30//! user data directory on Windows.
31
32use include_dir::{include_dir, Dir};
33use std::path::PathBuf;
34use std::sync::OnceLock;
35
36/// Embedded stdlib directory (compiled into the binary)
37static STDLIB_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/stdlib");
38
39/// Cached stdlib path
40static STDLIB_PATH: OnceLock<PathBuf> = OnceLock::new();
41
42/// Get the path to the stdlib directory.
43///
44/// On first call, this will extract the embedded stdlib files to the user's
45/// data directory if they don't already exist. Subsequent calls return the
46/// cached path.
47///
48/// The stdlib is extracted to:
49/// - Linux: `~/.local/share/vibelang/stdlib/`
50/// - macOS: `~/Library/Application Support/vibelang/stdlib/`
51/// - Windows: `C:\Users\<User>\AppData\Roaming\vibelang\stdlib\`
52///
53/// If the data directory is unavailable, falls back to `~/vibelang/stdlib/`.
54pub fn stdlib_path() -> &'static str {
55    STDLIB_PATH
56        .get_or_init(|| {
57            let path = get_stdlib_install_path();
58            ensure_stdlib_extracted(&path);
59            path
60        })
61        .to_str()
62        .unwrap_or(".")
63}
64
65/// Get the installation path for the stdlib.
66fn get_stdlib_install_path() -> PathBuf {
67    dirs::data_dir()
68        .or_else(|| {
69            // Fallback to home directory if data_dir is not available
70            // (avoids hardcoding platform-specific paths like .local/share)
71            dirs::home_dir()
72        })
73        .unwrap_or_else(|| PathBuf::from("."))
74        .join("vibelang")
75        .join("stdlib")
76}
77
78/// Ensure the stdlib is extracted to the target path.
79fn ensure_stdlib_extracted(target_path: &PathBuf) {
80    // Check if stdlib already exists and has content
81    if target_path.exists() && target_path.join("index.vibe").exists() {
82        // Stdlib already extracted, check version
83        let version_file = target_path.join(".version");
84        let current_version = env!("CARGO_PKG_VERSION");
85
86        if let Ok(installed_version) = std::fs::read_to_string(&version_file) {
87            if installed_version.trim() == current_version {
88                // Same version, no need to re-extract
89                return;
90            }
91        }
92
93        // Different version or no version file, re-extract
94        eprintln!(
95            "Updating stdlib to version {} in {}",
96            current_version,
97            target_path.display()
98        );
99    } else {
100        eprintln!("Extracting stdlib to {}", target_path.display());
101    }
102
103    // Extract the embedded stdlib
104    if let Err(e) = extract_stdlib(target_path) {
105        eprintln!("Warning: Failed to extract stdlib: {}", e);
106        eprintln!("You may need to manually specify stdlib path with -I flag");
107    }
108}
109
110/// Extract the embedded stdlib to the target directory.
111fn extract_stdlib(target_path: &PathBuf) -> std::io::Result<()> {
112    // Create the target directory
113    std::fs::create_dir_all(target_path)?;
114
115    // Extract all files recursively
116    extract_dir(&STDLIB_DIR, target_path)?;
117
118    // Write version file
119    let version_file = target_path.join(".version");
120    std::fs::write(version_file, env!("CARGO_PKG_VERSION"))?;
121
122    eprintln!("Stdlib extracted successfully");
123    Ok(())
124}
125
126/// Recursively extract a directory.
127fn extract_dir(dir: &Dir, target_path: &PathBuf) -> std::io::Result<()> {
128    // Extract files in this directory
129    for file in dir.files() {
130        let file_path = target_path.join(file.path());
131
132        // Create parent directories if needed
133        if let Some(parent) = file_path.parent() {
134            std::fs::create_dir_all(parent)?;
135        }
136
137        std::fs::write(&file_path, file.contents())?;
138    }
139
140    // Recursively extract subdirectories
141    for subdir in dir.dirs() {
142        extract_dir(subdir, target_path)?;
143    }
144
145    Ok(())
146}
147
148/// List of all available stdlib categories.
149pub const CATEGORIES: &[&str] = &[
150    "drums",
151    "bass",
152    "leads",
153    "pads",
154    "textures",
155    "effects",
156    "fx",
157    "theory",
158    "modulators",
159];
160
161/// Get the embedded stdlib directory for direct access.
162///
163/// This can be used to list files or read content without extracting.
164pub fn embedded_stdlib() -> &'static Dir<'static> {
165    &STDLIB_DIR
166}
167
168/// Get all stdlib files as a HashMap of path -> content.
169///
170/// This is useful for WASM where filesystem access is not available.
171/// The paths are relative to the stdlib root (e.g., "drums/kicks/kick_808.vibe").
172pub fn get_stdlib_files() -> std::collections::HashMap<String, String> {
173    let mut files = std::collections::HashMap::new();
174    collect_files_recursive(&STDLIB_DIR, &mut files);
175    files
176}
177
178/// Recursively collect all files from a directory.
179fn collect_files_recursive(dir: &Dir, files: &mut std::collections::HashMap<String, String>) {
180    // Collect files in this directory
181    for file in dir.files() {
182        if let Some(path) = file.path().to_str() {
183            // Only include .vibe files
184            if path.ends_with(".vibe") {
185                if let Some(content) = file.contents_utf8() {
186                    files.insert(path.to_string(), content.to_string());
187                }
188            }
189        }
190    }
191
192    // Recursively collect from subdirectories
193    for subdir in dir.dirs() {
194        collect_files_recursive(subdir, files);
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201
202    #[test]
203    fn test_stdlib_path_returns_string() {
204        let path = stdlib_path();
205        assert!(!path.is_empty());
206    }
207
208    #[test]
209    fn test_embedded_stdlib_has_content() {
210        let dir = embedded_stdlib();
211        // Should have at least some files
212        assert!(dir.files().count() > 0 || dir.dirs().count() > 0);
213    }
214
215    #[test]
216    fn test_get_stdlib_files_paths() {
217        let files = get_stdlib_files();
218        println!("Found {} stdlib files:", files.len());
219        for path in files.keys().take(20) {
220            println!("  - {}", path);
221        }
222        assert!(!files.is_empty(), "Should have stdlib files");
223    }
224}