smidr 1.2.1

Smidr is a cargo-inspired build tool for C/C++ projects, meant to bridge dependencies across different build systems into a single build.
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
// SPDX-License-Identifier: MIT OR Apache-2.0
// Copyright (c) 2026 Max-Mend
// This file is part of smidr: https://github.com/Max-Mend/smidr

//! Compiles and links a [`Project`]'s `.c` sources into a binary.
//!
//! This is the one module that ties everything else together: it reads
//! [`crate::config`] settings off a [`Project`], resolves a concrete
//! compiler binary, invokes it once per source file, and links the
//! results. Dependency include paths (`project.resolved_deps`) are
//! folded in, but the step that actually populates `resolved_deps` -
//! calling [`crate::resolver`] and [`crate::toolchain`] - isn't wired up
//! here yet (see the crate's roadmap).

use crate::compile_db::CompileCommand;
use crate::diagnostics::{parse_all, print_all};
use crate::error::Result;
use crate::project::Project;
use std::path::PathBuf;

/// Everything needed to invoke the compiler: which binary, which include
/// paths, and which extra flags.
pub struct CompileOptions {
    compiler: String,
    includes: Vec<PathBuf>,
    cflags: Vec<String>,
    dep_libs: Vec<String>,
    dep_lib_dirs: Vec<PathBuf>,
}

/// Compile every `.c` file in `project` and link them into a binary at
/// `target/bin/<project-name>`.
///
/// Steps: resolve a compiler ([`compiler_binary`]), compile each source
/// file to `target/<name>.o`, then link all object files together. A
/// `compile_commands.json` (recording the exact command used for each
/// file) is written to the project root once all files have compiled
/// successfully.
///
/// # Errors
/// Returns [`crate::error::BuildError::CompilerNotFound`] if no usable
/// compiler is found, [`crate::error::BuildError::Compile`] if a source
/// file fails to compile, or [`crate::error::BuildError::Link`] if the
/// final link step fails.
pub fn build_project(project: &Project, release: bool, verbose: bool, dry_run: bool) -> Result<()> {
    let project_section = project.config.project.as_ref().ok_or_else(|| {
        crate::error::BuildError::Dependency {
            name: project.root.display().to_string(),
            reason: "cannot build: Smidr.toml has no [project] section (this is a workspace root)".to_string(),
        }
    })?;
    let build_section = project.config.build.as_ref().ok_or_else(|| {
        crate::error::BuildError::Dependency {
            name: project.root.display().to_string(),
            reason: "cannot build: Smidr.toml has no [build] section".to_string(),
        }
    })?;

    let sources = project.source_files()?;
    project.header_files()?;

    let profile_dir = if release { "release" } else { "debug" };
    let build_dir = project.build_dir.join(profile_dir);
    std::fs::create_dir_all(&build_dir)?;

    let compiler = compiler_binary(&build_section.compiler, &project_section.language)?;
    println!("Using compiler: {}", compiler);

    let profile = if release {
        project.config.get_release_profile()
    } else {
        project.config.get_debug_profile()
    };

    let mut opts = CompileOptions {
        compiler: compiler.to_string(),
        includes: {
            let mut incs = vec![project.root.join(
                project.config.paths.include.as_deref().unwrap_or("include")
            )];
            incs.extend(project.config.paths.custom.values().map(|p| project.root.join(p)));
            incs
        },
        cflags: build_section.cflags.clone(),
        dep_libs: Vec::new(),
        dep_lib_dirs: Vec::new(),
    };

    for (_name, output) in &project.resolved_deps {
        opts.includes.extend(output.include_dirs.clone());
        opts.dep_lib_dirs.extend(output.lib_dirs.clone());
        opts.dep_libs.extend(output.libs.clone());
    }

    let mut object_files: Vec<PathBuf> = Vec::new();
    let mut compile_commands: Vec<CompileCommand> = Vec::new();

    for src in sources {
        let file_stem = src.file_stem().unwrap().to_str().unwrap();
        let obj_path = build_dir.join(format!("{}.o", file_stem));

        let mut cmd = std::process::Command::new(&opts.compiler);
        cmd.arg("-c").arg(&src).arg("-o").arg(&obj_path);
        cmd.args(
            &opts
                .includes
                .iter()
                .map(|p| format!("-I{}", p.display()))
                .collect::<Vec<_>>(),
        );
        cmd.args(&opts.cflags);
        cmd.arg(match profile.opt_level {
            crate::config::OptLevel::None => "-O0",
            crate::config::OptLevel::Speed => "-O2",
            crate::config::OptLevel::Size => "-Os",
            crate::config::OptLevel::Max => "-O3",
        });
        if profile.debug_symbols {
            cmd.arg("-g");
        }
        let std_flag = match project_section.language {
            crate::config::Language::C => format!(
                "-std={}",
                project_section.c_standard.clone().unwrap_or_default()
            ),
            crate::config::Language::Cpp => format!(
                "-std={}",
                project_section.cpp_standard.as_ref()
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| crate::config::CppStandard::default().to_string())
            ),
        };
        cmd.arg(std_flag);

        // Recording the actual command used for this specific file -
        // doing it before .output(), while cmd is still available for formatting,
        // and after all arguments have been added.
        let command_str = format!("{:?}", cmd);

        if verbose || dry_run {
            println!("   $ {}", command_str);
        }

        if dry_run {
            compile_commands.push(CompileCommand {
                directory: project.root.display().to_string(),
                file: src.display().to_string(),
                command: command_str,
                output: obj_path.display().to_string(),
            });
            object_files.push(obj_path);
            continue;
        }

        let output = cmd.output()?;
        let stderr = String::from_utf8_lossy(&output.stderr);
        let diagnostics = parse_all(&stderr);

        if !diagnostics.is_empty() {
            print_all(&diagnostics);
        }

        if !output.status.success() {
            let error_detail = if diagnostics.is_empty() {
                stderr.to_string()
            } else {
                "See error details above...".to_string()
            };

            return Err(crate::error::BuildError::Compile(
                src.display().to_string(),
                error_detail,
            ));
        }

        compile_commands.push(CompileCommand {
            directory: project.root.display().to_string(),
            file: src.display().to_string(),
            command: command_str,
            output: obj_path.display().to_string(),
        });

        object_files.push(obj_path);
    }

    crate::compile_db::write(
        &compile_commands,
        &project.root.join("compile_commands.json"),
    )?;

    let output_name = project_section.output_name();

    std::fs::create_dir_all(build_dir.join("bin"))?;

    // Linking based on project type
    match project_section.project_type {
        // Binary
        crate::config::ProjectType::Binary => {
            let binary_name = if cfg!(windows) {
                format!("{}.exe", output_name)
            } else {
                output_name.to_string()
            };
            let binary_path = build_dir.join("bin").join(binary_name);

            let mut link_cmd = std::process::Command::new(&opts.compiler);
            link_cmd.args(&object_files);
            link_cmd.arg("-o").arg(&binary_path);
            link_cmd.args(opts.dep_lib_dirs.iter().map(|p| format!("-L{}", p.display())));
            link_cmd.args(opts.dep_libs.iter().map(|l| format!("-l{}", l)));
            link_cmd.args(build_section.libs.iter().map(|l| format!("-l{}", l)));
            link_cmd.args(&build_section.linker_flags);
            if profile.lto { link_cmd.arg("-flto"); }
            if profile.strip { link_cmd.arg("-s"); }

            if verbose || dry_run {
                println!("   $ {:?}", link_cmd);
            }
            if dry_run {
                return Ok(());
            }

            let output = link_cmd.output()?;
            if !output.status.success() {
                return Err(crate::error::BuildError::Link(
                    String::from_utf8_lossy(&output.stderr).to_string(),
                ));
            }
        }

        // Static library
        crate::config::ProjectType::StaticLibrary => {
            let lib_ext = if cfg!(windows) { "lib" } else { "a" };
            let lib_path = build_dir.join("bin").join(format!("lib{}.{}", output_name, lib_ext));

            let mut ar_cmd = std::process::Command::new("ar");
            ar_cmd.arg("rcs").arg(&lib_path).args(&object_files);

            let output = ar_cmd.output()?;
            if !output.status.success() {
                return Err(crate::error::BuildError::Link(
                    String::from_utf8_lossy(&output.stderr).to_string(),
                ));
            }
        }

        // Shared library
        crate::config::ProjectType::SharedLibrary => {
            let lib_ext = if cfg!(windows) { "dll" } else { "so" };
            let lib_path = build_dir.join("bin").join(format!("lib{}.{}", output_name, lib_ext));

            let mut link_cmd = std::process::Command::new(&opts.compiler);
            link_cmd.arg("-shared").args(&object_files);
            link_cmd.arg("-o").arg(&lib_path);
            link_cmd.args(opts.dep_lib_dirs.iter().map(|p| format!("-L{}", p.display())));
            link_cmd.args(opts.dep_libs.iter().map(|l| format!("-l{}", l)));
            link_cmd.args(build_section.libs.iter().map(|l| format!("-l{}", l)));
            link_cmd.args(&build_section.linker_flags);

            let output = link_cmd.output()?;
            if !output.status.success() {
                return Err(crate::error::BuildError::Link(
                    String::from_utf8_lossy(&output.stderr).to_string(),
                ));
            }
        }
    }

    Ok(())
}

/// Build `project` (via [`build_project`]) and then execute the
/// resulting binary, forwarding its exit status.
///
/// # Errors
/// Propagates any error from [`build_project`]. Returns
/// [`crate::error::BuildError::CommandFailed`] if the binary itself
/// exits with a non-zero status.
pub fn run_project(project: &Project, release: bool, verbose: bool, dry_run: bool) -> Result<()> {
    build_project(project, release, verbose, dry_run)?;

    if dry_run {
        println!("Dry run: skipping execution.");
        return Ok(());
    }

    let project_section = project.config.project.as_ref().ok_or_else(|| {
        crate::error::BuildError::Dependency {
            name: project.root.display().to_string(),
            reason: "cannot run: Smidr.toml has no [project] section".to_string(),
        }
    })?;
    let profile_dir = if release { "release" } else { "debug" };

    let output_name = project_section.output_name.as_ref().unwrap_or(&project_section.name);
    let binary_name = if cfg!(windows) {
        format!("{}.exe", output_name)
    } else {
        output_name.clone()
    };

    let binary_path = project.build_dir.join(profile_dir).join("bin").join(binary_name);

    println!("Running: {}", binary_path.display());
    let status = std::process::Command::new(&binary_path).status()?;

    if !status.success() {
        return Err(crate::error::BuildError::CommandFailed {
            cmd: binary_path.display().to_string(),
            code: status.code(),
        });
    }

    Ok(())
}

/// Remove build artifacts from a project.
///
/// # Errors
/// Propagates any error from [`std::fs::remove_dir_all`].
pub fn clean_project(project: &Project) -> Result<()> {
    if project.build_dir.exists() {
        std::fs::remove_dir_all(&project.build_dir)?;
        println!("Cleaned: {}", project.build_dir.display());
    } else {
        println!("Nothing to clean.");
    }
    Ok(())
}

pub fn rebuild_project(project: &Project, release: bool, verbose: bool, dry_run: bool) -> Result<()> {
    clean_project(project)?;
    build_project(project, release, verbose, dry_run)
}

/// Format project source and header files with clang-format.
///
/// # Errors
/// Returns [crate::error::BuildError::CompilerNotFound] if
/// clang-format isn't on PATH. Returns
/// [crate::error::BuildError::CommandFailed] if clang-format exits
/// with a non-zero status.
pub fn fmt_project(project: &Project) -> Result<()> {
    if !command_exists("clang-format") {
        return Err(crate::error::BuildError::ToolNotFound {
            tool: "clang-format".to_string(),
            hint: "Install it via your package manager (e.g. `apt install clang-format`)."
                .to_string(),
        });
    }

    let files = project.formattable_files()?;
    if files.is_empty() {
        println!("Nothing to format.");
        return Ok(());
    }

    let mut cmd = std::process::Command::new("clang-format");
    cmd.arg("-i");
    cmd.args(&files);

    let status = cmd.status()?;
    if !status.success() {
        return Err(crate::error::BuildError::CommandFailed {
            cmd: "clang-format".to_string(),
            code: status.code(),
        });
    }

    println!("Formatted {} file(s).", files.len());
    Ok(())
}

/// Resolve a [`crate::config::CompilerKind`] into an actual compiler
/// binary name, verifying it's runnable rather than trusting the config
/// blindly.
///
/// An explicit choice (`Gcc`/`Tcc`/`Clang`) is checked against the system
/// before use - better to fail clearly here than have the compiler
/// invocation fail later with a confusing "command not found".
/// `Auto` tries, in priority order: `clang`, `tcc`, the system `cc`,
/// then `gcc` as a last resort.
///
/// # Errors
/// Returns [`crate::error::BuildError::CompilerNotFound`] if the
/// requested compiler (or, for `Auto`, none of the candidates) is found
/// on `PATH`.
fn compiler_binary(kind: &crate::config::CompilerKind, language: &crate::config::Language) -> Result<&'static str> {
    use crate::config::{CompilerKind, Language};

    let candidates: &[&str] = match (kind, language) {
        (CompilerKind::Gcc, Language::C) => &["gcc"],
        (CompilerKind::Gcc, Language::Cpp) => &["g++"],
        (CompilerKind::Clang, Language::C) => &["clang"],
        (CompilerKind::Clang, Language::Cpp) => &["clang++"],
        (CompilerKind::Tcc, _) => &["tcc"],
        (CompilerKind::Auto, Language::C) => &["clang", "tcc", "cc", "gcc"],
        (CompilerKind::Auto, Language::Cpp) => &["clang++", "g++"],
    };

    for candidate in candidates {
        if command_exists(candidate) {
            return Ok(candidate);
        }
    }
    Err(crate::error::BuildError::CompilerNotFound(candidates.join(", ")))
}

/// Check whether `name` is a runnable compiler on `PATH`, by attempting
/// to run `<name> --version` and discarding its output.
fn command_exists(name: &str) -> bool {
    std::process::Command::new(name)
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .map(|status| status.success())
        .unwrap_or(false)
}

pub fn lint_project(project: &Project) -> Result<()> {
    let project_section = project.config.project.as_ref().ok_or_else(|| {
        crate::error::BuildError::Dependency {
            name: project.root.display().to_string(),
            reason: "cannot lint: Smidr.toml has no [project] section".to_string(),
        }
    })?;

    let files = project.source_files()?;

    let clang_binary = match project_section.language {
        crate::config::Language::C => "clang",
        crate::config::Language::Cpp => "clang++",
    };

    let mut cmd = std::process::Command::new(clang_binary);
    cmd.arg("-fsyntax-only");
    cmd.args(&files);

    let status = cmd.status()?;
    if !status.success() {
        return Err(crate::error::BuildError::CommandFailed {
            cmd: clang_binary.to_string(),
            code: status.code(),
        });
    }

    println!("Linted {} file(s).", files.len());
    Ok(())
}

pub fn update_project() -> Result<()> {
    let status = std::process::Command::new("cargo")
        .args(["install", "smidr", "--force"])
        .status()?;

    if !status.success() {
        return Err(crate::error::BuildError::CompilerNotFound(
            "cargo".to_string(),
        ));
    }

    println!("Smidr updated successfully!");
    
    Ok(())
}