rialo-build-lib 0.10.1

Shared library for Rialo program building logic
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{
    env,
    ffi::OsString,
    path::{Path, PathBuf},
    process::Command,
};

use anyhow::{Context, Result};

pub mod build_script;
pub mod compilation;
pub mod config;
pub mod detection;
mod riscv_builder;
mod solana_builder;
pub mod toolchain;
pub mod venus;

pub use config::{BuildFileConfig, BuildType, CompileFlags, RiscvConfig, SourceType};
pub use detection::{detect_program_type, ProgramType};
pub use riscv_builder::RiscvBuilder;
pub use solana_builder::SolanaBuilder;
pub use toolchain::{
    BuildSystemConfig, DownloadSource, GnuRiscvToolchain, RialoRustToolchain, RustSourceBuilder,
    S3StorageBackend, SourceBuildConfig, SourceBuildable, Toolchain, ToolchainConfig,
    ToolchainType,
};
pub use venus::{build_venus_workflow, is_venus_workflow};

/// Configuration for building a Rialo program
#[derive(Debug, Clone)]
pub struct BuildConfig {
    /// Path to the program directory to build
    pub program_path: PathBuf,
    /// Output directory for the built artifacts
    pub output_dir: PathBuf,
    /// Target directory for cargo build artifacts
    pub target_dir: PathBuf,
}

/// Validate that a program path exists and is a directory
///
/// Returns an error if the path does not exist or is not a directory.
/// This is used to provide consistent error messages across all builders.
pub fn validate_program_path(path: &std::path::Path) -> Result<()> {
    if !path.exists() {
        return Err(anyhow::anyhow!(
            "Program path does not exist: {}",
            path.display()
        ));
    }

    if !path.is_dir() {
        return Err(anyhow::anyhow!(
            "Program path is not a directory: {}",
            path.display()
        ));
    }

    Ok(())
}

const NESTED_CARGO_ENV_VARS_TO_REMOVE: &[&str] = &[
    "CARGO",
    "CARGO_MAKEFLAGS",
    "CARGO_BUILD_RUSTFLAGS",
    "CARGO_ENCODED_RUSTFLAGS",
    "RUSTC",
    "RUSTDOC",
    "RUSTC_WRAPPER",
    "RUSTC_WORKSPACE_WRAPPER",
    "RUSTUP_TOOLCHAIN",
];

/// Remove environment variables inherited from an outer Cargo invocation that
/// can corrupt a nested Cargo/rustup toolchain build.
pub fn sanitize_nested_cargo_env(command: &mut Command) {
    for key in NESTED_CARGO_ENV_VARS_TO_REMOVE {
        command.env_remove(key);
    }
}

/// Resolve the workspace root for a Cargo program directory.
pub fn workspace_root_for_program(program_path: &Path) -> Result<PathBuf> {
    let program_path = resolve_program_directory(program_path)?;
    let metadata = cargo_metadata::MetadataCommand::new()
        .manifest_path(program_path.join("Cargo.toml"))
        .no_deps()
        .exec()
        .with_context(|| {
            format!(
                "Failed to load Cargo metadata for {}",
                program_path.display()
            )
        })?;

    Ok(metadata.workspace_root.as_std_path().to_path_buf())
}

/// Resolve the target directory for a Cargo program with shared CLI/workspace
/// semantics.
///
/// Resolution order:
/// 1. Explicit override
/// 2. `CARGO_TARGET_DIR`
/// 3. `<workspace_root>/target`
///
/// Explicit overrides keep CLI semantics: relative paths are resolved against
/// the current working directory. Inherited `CARGO_TARGET_DIR` keeps Cargo
/// workspace semantics: relative paths are resolved against the program's
/// workspace root.
pub fn resolve_target_dir_for_program(
    program_path: &Path,
    target_dir_override: Option<&Path>,
) -> Result<PathBuf> {
    let program_path = resolve_program_directory(program_path)?;
    let workspace_root = workspace_root_for_program(&program_path)?;

    resolve_target_dir_with_inputs(
        &workspace_root,
        target_dir_override,
        env::var_os("CARGO_TARGET_DIR"),
    )
}

fn resolve_target_dir_with_inputs(
    workspace_root: &Path,
    target_dir_override: Option<&Path>,
    inherited_target_dir: Option<OsString>,
) -> Result<PathBuf> {
    if let Some(target_dir_override) = target_dir_override {
        return resolve_user_path(target_dir_override);
    }

    if let Some(inherited_target_dir) = inherited_target_dir.filter(|value| !value.is_empty()) {
        let inherited_target_dir = PathBuf::from(inherited_target_dir);
        if inherited_target_dir.is_absolute() {
            return Ok(inherited_target_dir);
        }

        return Ok(workspace_root.join(inherited_target_dir));
    }

    Ok(workspace_root.join("target"))
}

fn resolve_program_directory(program_path: &Path) -> Result<PathBuf> {
    let program_path = resolve_user_path(program_path)?;
    validate_program_path(&program_path)?;

    program_path
        .canonicalize()
        .with_context(|| format!("Failed to canonicalize {}", program_path.display()))
}

pub(crate) fn resolve_user_path(path: &Path) -> Result<PathBuf> {
    if path.is_absolute() {
        return Ok(path.to_path_buf());
    }

    Ok(env::current_dir()
        .context("Failed to determine current working directory")?
        .join(path))
}

/// RISC-V target architecture
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RiscvTarget {
    /// RV32I base integer instruction set
    Rv32i,
    /// RV32IM with integer multiply/divide
    Rv32im,
    /// RV64GC general purpose (includes IMAFD + Zicsr + Zifencei + C extensions)
    Rv64gc,
    /// Rialo custom target (riscv64emac-solana-solana) with custom Rust toolchain
    #[default]
    RialoCustom,
}

impl RiscvTarget {
    /// Get the target triple string for cargo
    pub fn as_target_triple(&self) -> &str {
        match self {
            RiscvTarget::Rv32i => "riscv32i-unknown-none-elf",
            RiscvTarget::Rv32im => "riscv32im-unknown-none-elf",
            RiscvTarget::Rv64gc => "riscv64gc-unknown-none-elf",
            RiscvTarget::RialoCustom => "riscv64emac-solana-solana",
        }
    }

    /// Get the -march flag for gcc
    pub fn as_march(&self) -> &str {
        match self {
            RiscvTarget::Rv32i => "rv32i",
            RiscvTarget::Rv32im => "rv32im",
            RiscvTarget::Rv64gc => "rv64gc",
            RiscvTarget::RialoCustom => "rv64gc", // Fallback for C compilation
        }
    }

    /// Get the -mabi flag for gcc
    pub fn as_mabi(&self) -> &str {
        match self {
            RiscvTarget::Rv32i | RiscvTarget::Rv32im => "ilp32",
            RiscvTarget::Rv64gc | RiscvTarget::RialoCustom => "lp64d",
        }
    }

    /// Check if this target requires the Rialo custom Rust toolchain
    pub fn requires_rialo_toolchain(&self) -> bool {
        matches!(self, RiscvTarget::RialoCustom)
    }
}

/// Builder-specific configuration
#[derive(Debug, Clone)]
pub enum BuilderConfig {
    /// Configuration for the Solana builder
    Solana {},
    /// Configuration for the RISC-V builder
    Riscv {
        /// Toolchain version (optional, uses default if not specified)
        toolchain_version: Option<String>,
        /// Target architecture
        target: RiscvTarget,
    },
}

/// Result of a build operation
#[derive(Debug, serde::Serialize)]
pub struct BuildResult {
    /// The package name that was built
    pub package_name: String,
    /// The output directory where artifacts were placed
    pub output_dir: PathBuf,
    /// The program binary file
    pub program_binary: PathBuf,
    /// The program keypair file (optional, Solana-specific)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub program_keypair: Option<PathBuf>,
}

/// Trait for building Rialo programs
pub trait ProgramBuilder {
    /// Validate that the builder can be used (e.g., check dependencies)
    fn validate(&self) -> Result<()>;
    /// Build a program using the given configuration
    fn build(&self, config: &BuildConfig) -> Result<BuildResult>;
}

/// Create a builder based on the builder config
pub fn create_builder(builder_config: &BuilderConfig) -> Result<Box<dyn ProgramBuilder>> {
    match builder_config {
        BuilderConfig::Solana {} => Ok(Box::new(SolanaBuilder::default())),
        BuilderConfig::Riscv {
            toolchain_version,
            target,
        } => {
            let builder = if let Some(version) = toolchain_version {
                RiscvBuilder::with_version(version, *target)?
            } else {
                RiscvBuilder::new(*target)?
            };
            Ok(Box::new(builder))
        }
    }
}

/// Build a single Rialo program using the default builder
pub fn build_program(config: &BuildConfig) -> Result<BuildResult> {
    let builder = create_builder(&BuilderConfig::Solana {})?;
    builder.validate()?;
    builder.build(config)
}

/// Automatically detect the builder configuration based on the program directory
///
/// This function will:
/// 1. Look for a rialo-build.toml configuration file
/// 2. If not found or set to "auto", detect the program type
/// 3. Return the appropriate BuilderConfig
pub fn auto_detect_builder(program_path: &std::path::Path) -> Result<BuilderConfig> {
    // Try to load configuration file
    let file_config = BuildFileConfig::from_directory(program_path)?;

    // If we have a config file with explicit build type, use it
    if let Some(config) = &file_config {
        if let Some(build_type) = config.build_type {
            match build_type {
                BuildType::Solana => return Ok(BuilderConfig::Solana {}),
                BuildType::Riscv => {
                    let target = config
                        .riscv
                        .as_ref()
                        .and_then(|r| r.target)
                        .unwrap_or_default();

                    let toolchain_version = config
                        .riscv
                        .as_ref()
                        .and_then(|r| r.toolchain_version.clone());

                    return Ok(BuilderConfig::Riscv {
                        toolchain_version,
                        target,
                    });
                }
                BuildType::Auto => {
                    // Continue to auto-detection
                }
            }
        }
    }

    // Auto-detect based on program contents
    let program_type = detect_program_type(program_path)?;

    match program_type {
        ProgramType::Solana => Ok(BuilderConfig::Solana {}),
        ProgramType::RiscvC | ProgramType::RiscvRust => {
            // Use config file settings if available, otherwise use defaults
            let target = file_config
                .as_ref()
                .and_then(|c| c.riscv.as_ref())
                .and_then(|r| r.target)
                .unwrap_or_default();

            let toolchain_version = file_config
                .as_ref()
                .and_then(|c| c.riscv.as_ref())
                .and_then(|r| r.toolchain_version.clone());

            Ok(BuilderConfig::Riscv {
                toolchain_version,
                target,
            })
        }
    }
}

/// Build a program with automatic builder detection
pub fn build_program_auto(config: &BuildConfig) -> Result<BuildResult> {
    let builder_config = auto_detect_builder(&config.program_path)?;
    let builder = create_builder(&builder_config)?;
    builder.validate()?;
    builder.build(config)
}

#[cfg(test)]
mod tests {
    use std::{collections::BTreeMap, ffi::OsString, path::PathBuf, process::Command};

    use super::{
        resolve_target_dir_with_inputs, sanitize_nested_cargo_env, workspace_root_for_program,
    };

    #[test]
    fn resolve_target_dir_prefers_explicit_override() {
        let workspace = create_workspace().unwrap();
        let explicit_target_dir = workspace.root.join("explicit-target");

        let target_dir = resolve_target_dir_with_inputs(
            &workspace.root,
            Some(explicit_target_dir.as_path()),
            Some(OsString::from("ignored-by-override")),
        )
        .unwrap();

        assert_eq!(target_dir, explicit_target_dir);
    }

    #[test]
    fn resolve_target_dir_honors_absolute_inherited_target_dir() {
        let workspace = create_workspace().unwrap();
        let absolute_target_dir = workspace.root.join("absolute-target");

        let target_dir = resolve_target_dir_with_inputs(
            &workspace.root,
            None,
            Some(absolute_target_dir.clone().into_os_string()),
        )
        .unwrap();

        assert_eq!(target_dir, absolute_target_dir);
    }

    #[test]
    fn resolve_target_dir_normalizes_relative_inherited_target_dir_against_workspace_root() {
        let workspace = create_workspace().unwrap();

        let target_dir = resolve_target_dir_with_inputs(
            &workspace.root,
            None,
            Some(OsString::from("target-rel")),
        )
        .unwrap();

        assert_eq!(target_dir, workspace.root.join("target-rel"));
    }

    #[test]
    fn resolve_target_dir_falls_back_to_workspace_target_directory() {
        let workspace = create_workspace().unwrap();

        let target_dir = resolve_target_dir_with_inputs(&workspace.root, None, None).unwrap();

        assert_eq!(target_dir, workspace.root.join("target"));
    }

    #[test]
    fn workspace_root_for_program_uses_cargo_metadata() {
        let workspace = create_workspace().unwrap();

        let workspace_root = workspace_root_for_program(&workspace.program_dir).unwrap();

        assert_eq!(workspace_root, workspace.root.canonicalize().unwrap());
    }

    #[test]
    fn sanitize_nested_cargo_env_removes_only_problematic_vars() {
        let mut command = Command::new("cargo");
        command.env("HOME", "/tmp/rialo-home");
        command.env("RUSTC", "bad-rustc");
        command.env("RUSTUP_TOOLCHAIN", "bad-toolchain");
        command.env("CARGO_MAKEFLAGS", "bad-jobserver");

        sanitize_nested_cargo_env(&mut command);

        let envs: BTreeMap<OsString, Option<OsString>> = command
            .get_envs()
            .map(|(key, value)| (key.to_os_string(), value.map(|value| value.to_os_string())))
            .collect();

        assert_eq!(
            envs.get(&OsString::from("HOME")),
            Some(&Some(OsString::from("/tmp/rialo-home")))
        );
        assert_eq!(envs.get(&OsString::from("RUSTC")), Some(&None));
        assert_eq!(envs.get(&OsString::from("RUSTUP_TOOLCHAIN")), Some(&None));
        assert_eq!(envs.get(&OsString::from("CARGO_MAKEFLAGS")), Some(&None));
    }

    fn create_workspace() -> anyhow::Result<TestWorkspace> {
        let root = tempfile::tempdir()?;
        let root_path = root.path().to_path_buf();
        let program_dir = root_path.join("program");
        let src_dir = program_dir.join("src");

        std::fs::create_dir_all(&src_dir)?;
        std::fs::write(
            root_path.join("Cargo.toml"),
            "[workspace]\nmembers = [\"program\"]\nresolver = \"2\"\n",
        )?;
        std::fs::write(
            program_dir.join("Cargo.toml"),
            "[package]\nname = \"example-program\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )?;
        std::fs::write(src_dir.join("lib.rs"), "pub fn example() {}\n")?;

        Ok(TestWorkspace {
            _root: root,
            root: root_path,
            program_dir,
        })
    }

    struct TestWorkspace {
        _root: tempfile::TempDir,
        root: PathBuf,
        program_dir: PathBuf,
    }
}