bock 1.0.0

The Bock language compiler and CLI — feature-declarative, target-agnostic programming language with AI-native transpilation
//! Embedded standard-library sources for the v1 core (`core.*`).
//!
//! The Bock core standard library ships *embedded in the `bock` binary* as
//! Bock source. Each core module is plain Bock source (its public surface),
//! compiled through the exact same multi-file pipeline as user code: the CLI
//! commands (`check`, `build`, `run`) prepend the parsed core sources to the
//! parsed-files set before the user-file loop, so a core module's
//! `module core.<name>` declaration lands in the
//! [`bock_air::registry::ModuleRegistry`] before any user module resolves
//! `use core.<name>.{...}` against it — with no special-casing in the name
//! resolver or type checker.
//!
//! # Embedding
//!
//! The embedded set is produced at compile time by the crate's `build.rs`,
//! which walks `stdlib/core/**/*.bock` and emits a `&[(logical_path, source)]`
//! table baked into the binary via `include_str!`. As a result a built `bock`
//! resolves `core.*` with no filesystem access — from any working directory,
//! inside or outside the repo. To add a core module, drop its source under
//! `stdlib/core/<name>/<name>.bock`; the build script picks it up automatically.
//!
//! # `$BOCK_STDLIB` override (dev-only)
//!
//! When the `BOCK_STDLIB` environment variable is set, [`core_sources`] reads
//! the core sources from that directory on disk (walking `<dir>/**/*.bock`)
//! instead of using the embedded copy. This lets compiler developers iterate
//! on stdlib sources without a rebuild. The override is intentionally
//! undocumented for end users.

use std::path::{Path, PathBuf};

/// One embedded core-stdlib source: its logical (repo-relative) path and the
/// source text itself.
pub struct StdlibSource {
    /// Repo-relative logical path, used only for diagnostic rendering.
    pub logical_path: PathBuf,
    /// The Bock source text of the module.
    pub source: String,
}

/// The embedded core sources, generated by `build.rs` from `stdlib/core/**`.
///
/// Each entry is `(logical_path, source_text)`. The logical path is the
/// repo-relative `stdlib/core/...` path (for diagnostic rendering); the source
/// text is baked in via `include_str!`.
const EMBEDDED: &[(&str, &str)] = include!(concat!(env!("OUT_DIR"), "/stdlib_embedded.rs"));

/// Returns every embedded core-stdlib source, in a deterministic order.
///
/// When `BOCK_STDLIB` is set, the sources are read from that directory on disk
/// instead (dev-only override); see the module docs. Each returned
/// [`StdlibSource`] flows through the same parse -> dependency-sort -> compile
/// pipeline as user files, landing in the registry before user modules.
#[must_use]
pub fn core_sources() -> Vec<StdlibSource> {
    if let Some(dir) = std::env::var_os("BOCK_STDLIB") {
        return core_sources_from_disk(&PathBuf::from(dir));
    }

    EMBEDDED
        .iter()
        .map(|(logical, source)| StdlibSource {
            logical_path: PathBuf::from(logical),
            source: (*source).to_string(),
        })
        .collect()
}

/// Reads the core sources from a `$BOCK_STDLIB` directory on disk.
///
/// Walks `<dir>/**/*.bock` and assigns each file a logical path of
/// `stdlib/<relative-to-dir>` so diagnostics render against a stable,
/// repo-shaped location. Sources are returned in sorted order for determinism.
fn core_sources_from_disk(dir: &Path) -> Vec<StdlibSource> {
    let mut found: Vec<(String, PathBuf)> = Vec::new();
    collect_disk_sources(dir, dir, &mut found);
    found.sort_by(|a, b| a.0.cmp(&b.0));

    found
        .into_iter()
        .filter_map(|(rel, abs)| {
            std::fs::read_to_string(&abs)
                .ok()
                .map(|source| StdlibSource {
                    logical_path: PathBuf::from("stdlib").join(rel),
                    source,
                })
        })
        .collect()
}

/// Recursively collect `*.bock` files under `dir`, recording each as
/// `(path_relative_to_root, absolute_path)`.
fn collect_disk_sources(root: &Path, dir: &Path, out: &mut Vec<(String, PathBuf)>) {
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return,
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            collect_disk_sources(root, &path, out);
        } else if path.extension().and_then(|e| e.to_str()) == Some("bock") {
            if let Ok(rel) = path.strip_prefix(root) {
                let rel = rel.to_string_lossy().replace('\\', "/");
                out.push((rel, path));
            }
        }
    }
}