buildlang 1.15.0

BuildLang (buildc): an effects-oriented compiler with a verified C path, shader output, experimental backends, opt-in linear types, and re-checkable accountability + scientific-runtime receipts
Documentation
// ===============================================================================
// BUILDLANG CODE GENERATOR - BACKENDS
// ===============================================================================
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2022-2026 Zain Dana Harper.
// ===============================================================================

//! Code generation backends.
//!
//! Each backend takes MIR and produces target-specific output.

pub mod arm64;
pub mod arm64_enc;
pub mod c;
pub mod glsl;
pub mod hlsl;
pub mod llvm;
pub mod rust;
pub mod spirv;
pub mod wasm;
pub mod wasm_bin;
pub mod x86_64;
pub mod x86_64_enc;
pub mod x86_64_exe;
pub mod x86_64_exe_asm;
pub mod x86_64_exe_obj;
mod x86_64_exe_ops;

use std::{fmt, str::FromStr};
use thiserror::Error;

use super::ir::MirModule;
use super::GeneratedCode;

/// Target platform for code generation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Target {
    /// C transpilation (portable).
    C,
    /// x86-64 native code.
    X86_64,
    /// x86-64 Windows executable (PE32+), written without outside tools.
    X86_64Pe,
    /// x86-64 Linux executable (ELF64), written without outside tools.
    X86_64Elf,
    /// ARM64/AArch64 native code.
    Arm64,
    /// WebAssembly.
    Wasm,
    /// SPIR-V for GPU.
    SpirV,
    /// LLVM IR (for optimization and multi-target).
    LlvmIr,
    /// HLSL for DirectX / ReShade.
    Hlsl,
    /// GLSL for OpenGL / Vulkan shader source.
    Glsl,
    /// Rust source code.
    Rust,
}

impl Target {
    /// Get the default file extension for this target.
    pub fn extension(&self) -> &'static str {
        match self {
            Target::C => "c",
            Target::X86_64 | Target::Arm64 => "o",
            Target::X86_64Pe => "exe",
            Target::X86_64Elf => "out",
            Target::Wasm => "wasm",
            Target::SpirV => "spv",
            Target::LlvmIr => "ll",
            Target::Hlsl => "hlsl",
            Target::Glsl => "glsl",
            Target::Rust => "rs",
        }
    }

    /// Get the pointer size in bits for this target.
    pub fn pointer_size(&self) -> u32 {
        match self {
            Target::C => 64, // Assume 64-bit
            Target::X86_64 | Target::X86_64Pe | Target::X86_64Elf => 64,
            Target::Arm64 => 64,
            Target::Wasm => 32, // wasm32
            Target::SpirV => 64,
            Target::LlvmIr => 64,              // Default to 64-bit
            Target::Hlsl | Target::Glsl => 32, // GPU
            Target::Rust => 64,
        }
    }

    /// Check if this is a native code target.
    pub fn is_native(&self) -> bool {
        matches!(
            self,
            Target::X86_64 | Target::X86_64Pe | Target::X86_64Elf | Target::Arm64
        )
    }

    /// Check if this is an intermediate representation target.
    pub fn is_ir(&self) -> bool {
        matches!(self, Target::LlvmIr)
    }
}

impl fmt::Display for Target {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Target::C => write!(f, "c"),
            Target::X86_64 => write!(f, "x86_64"),
            Target::X86_64Pe => write!(f, "x86_64-windows"),
            Target::X86_64Elf => write!(f, "x86_64-linux"),
            Target::Arm64 => write!(f, "arm64"),
            Target::Wasm => write!(f, "wasm"),
            Target::SpirV => write!(f, "spirv"),
            Target::LlvmIr => write!(f, "llvm-ir"),
            Target::Hlsl => write!(f, "hlsl"),
            Target::Glsl => write!(f, "glsl"),
            Target::Rust => write!(f, "rust"),
        }
    }
}

/// Runtime stdio policy for generated programs.
///
/// `Native` preserves the host C runtime's normal text-mode behavior. On
/// Windows that means `\n` emitted through stdio is translated to CRLF.
/// `PortableLf` is a C-backend-only mode that keeps generated stdout/stderr
/// bytes stable by disabling Windows CRT text translation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StdioMode {
    /// Preserve the platform's native C stdio behavior.
    Native,
    /// Emit LF bytes on stdout/stderr across platforms.
    PortableLf,
}

impl StdioMode {
    pub fn as_str(self) -> &'static str {
        match self {
            StdioMode::Native => "native",
            StdioMode::PortableLf => "portable-lf",
        }
    }

    pub fn is_native(self) -> bool {
        self == StdioMode::Native
    }
}

impl Default for StdioMode {
    fn default() -> Self {
        StdioMode::Native
    }
}

impl fmt::Display for StdioMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for StdioMode {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "native" => Ok(StdioMode::Native),
            "portable-lf" => Ok(StdioMode::PortableLf),
            other => Err(format!(
                "unknown stdio mode '{other}'. Supported: native, portable-lf"
            )),
        }
    }
}

/// Code generation error.
#[derive(Debug, Clone, Error)]
pub enum CodegenError {
    /// Internal error.
    #[error("internal error: {0}")]
    Internal(String),

    /// Unsupported feature.
    #[error("unsupported feature: {0}")]
    Unsupported(String),

    /// Invalid MIR.
    #[error("invalid MIR: {0}")]
    InvalidMir(String),

    /// Type error.
    #[error("type error: {0}")]
    TypeError(String),

    /// Missing function.
    #[error("missing function: {0}")]
    MissingFunction(String),

    /// Missing type.
    #[error("missing type: {0}")]
    MissingType(String),

    /// A program the type checker accepted but the backend cannot compile,
    /// reported in BuildLang terms. `location` is a byte range in the entry
    /// source when the construct could be found there; `help` is a fix hint.
    #[error("{message}")]
    Rejected {
        message: String,
        location: Option<(u32, u32)>,
        help: Option<String>,
    },
}

/// Result type for code generation.
pub type CodegenResult<T> = Result<T, CodegenError>;

/// Trait for code generation backends.
pub trait Backend {
    /// Generate code from MIR.
    fn generate(&mut self, mir: &MirModule) -> CodegenResult<GeneratedCode>;

    /// Get the target for this backend.
    fn target(&self) -> Target;
}