smidr 1.1.0

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
// 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

//! Types and (de)serialization for `Smidr.toml`.
//!
//! This module owns the *shape* of the manifest file only - no filesystem
//! access beyond [`ManifestConfig::load`] and [`ManifestConfig::to_toml_string`],
//! and no process execution. Reading, validating, and acting on this data
//! is the job of [`crate::project`], [`crate::builder`], and
//! [`crate::toolchain`].

use crate::error::{BuildError, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::Path;

/// The full, typed contents of a `Smidr.toml` file.
#[derive(Deserialize, Serialize)]
pub struct ManifestConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project: Option<ProjectSection>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build: Option<BuildSection>,
    #[serde(default)]
    pub dependencies: BTreeMap<String, DependencySpec>,
    /// Optional `[workspace]` section: lets this same `Smidr.toml` also
    /// act as the root of a multi-project workspace, listing paths to
    /// member projects. A `Smidr.toml` is a normal single project unless
    /// this is present - this project doesn't (yet) support Cargo-style
    /// "virtual" workspace-only manifests without a `[project]` section.
    #[serde(default)]
    pub workspace: Option<WorkspacesConfig>,
    #[serde(default, skip_serializing_if = "ProfilesSection::is_empty")]
    pub profile: ProfilesSection,
    #[serde(default, rename = "bin", skip_serializing_if = "Vec::is_empty")]
    pub extra_bins: Vec<BinTarget>,
    #[serde(default, skip_serializing_if = "PathsConfig::is_empty")]
    pub paths: PathsConfig,
}

/// The `[project]` section: identifying metadata for the project.
#[derive(Deserialize, Serialize)]
pub struct ProjectSection {
    pub name: String,
    pub version: String,
    #[serde(rename = "type")]
    pub project_type: ProjectType,
    #[serde(default)]
    pub language: Language,
    #[serde(default, skip_serializing_if = "Option::is_none")]
pub c_standard: Option<CStandard>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cpp_standard: Option<CppStandard>,
    pub authors: Vec<String>,
    pub authors_email: Vec<String>,
    pub description: Option<String>,
    pub license: Option<String>,
    #[serde(default)]
    pub output_name: Option<String>,
}

/// The type of the project, either a binary, static library, or shared library.
#[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq, Eq, clap::ValueEnum)]
pub enum ProjectType {
    #[default]
    #[serde(rename = "bin")]
    #[value(name = "bin")]
    Binary,
    #[serde(rename = "static")]
    #[value(name = "static")]
    StaticLibrary,
    #[serde(rename = "dynamic")]
    #[value(name = "dynamic")]
    SharedLibrary,
}

#[derive(Debug, Clone, clap::ValueEnum, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Language {
    #[default]
    C,
    Cpp,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum LanguageStandard {
    C(CStandard),
    Cpp(CppStandard),
}

#[derive(Debug, Clone, clap::ValueEnum, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CStandard {
    C89,
    C90,
    C99,
    C11,
    #[default]
    C17,
    C23,
    Gnu99,
    Gnu11,
    Gnu17,
}

#[derive(Debug, Clone, clap::ValueEnum, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CppStandard {
    Cpp98,
    Cpp03,
    Cpp11,
    Cpp14,
    Cpp17,
    #[default]
    Cpp20,
    Cpp23,
    Cpp26,
}

/// `[workspace]` section - a list of paths to member projects, each with
/// its own `Smidr.toml`.
#[derive(Debug, Deserialize, Serialize)]
pub struct WorkspacesConfig {
    pub members: Vec<String>,
}

/// The `[build]` section: compiler and flag settings used by
/// [`crate::builder::build_project`].
#[derive(Deserialize, Serialize)]
pub struct BuildSection {
    pub compiler: CompilerKind,
    pub cflags: Vec<String>,
    pub libs: Vec<String>,
    #[serde(default)]
    pub linker_flags: Vec<String>,
}

/// One entry under `[dependencies]` - describes where a dependency's
/// source comes from and how to build it.
///
/// Exactly one of `git` or `path` must be set; see
/// [`crate::resolver::resolve`] for how that's validated.
#[derive(Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum DependencySpec {
    /// A version string for a system library, e.g. `zlib = "1.3"`.
    /// Resolved via a local search, then `pkg-config`.
    Version(String),
    /// A `git`, `path`, or build-system-configured dependency.
    Detailed {
        git: Option<String>,
        path: Option<String>,
        tag: Option<String>,
        branch: Option<String>,
        #[serde(default)]
        build_system: BuildSystemKind,
        #[serde(default)]
        build_commands: Vec<String>,
        #[serde(default)]
        extra_includes: Vec<String>,
        #[serde(default)]
        libs: Vec<String>,
    },
}

/// The `[profile]` section in Smidr.toml. (All fields optional)
#[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq, Eq)]
pub struct ProfilesSection {
    pub debug: Option<ProfileSection>,
    pub release: Option<ProfileSection>,
}

/// The `[profile.debug]` and `[profile.release]` sections in Smidr.toml. (All fields optional)
#[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq, Eq)]
pub struct ProfileSection {
    pub opt_level: Option<OptLevel>,
    pub warnings: Option<WarningLevel>,
    pub debug_symbols: Option<bool>,
    pub lto: Option<bool>,
    pub strip: Option<bool>,
}

/// The effective, fully-resolved settings for a build profile - every
/// field filled in, either from the user's `[profile.debug]`/
/// `[profile.release]` in `Smidr.toml`, or from the profile's built-in
/// defaults. This is what `builder::build_project` actually reads;
/// [`ProfileSection`] (all-`Option`) is only the on-disk, possibly-partial
/// representation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResolvedProfile {
    pub opt_level: OptLevel,
    pub warnings: WarningLevel,
    pub debug_symbols: bool,
    pub lto: bool,
    pub strip: bool,
}

/// Optimization level for the build.
#[derive(Debug, Clone, Copy, Deserialize, Serialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum OptLevel {
    #[default]
    None,   // -O0
    Speed,  // -O2
    Size,   // -Os
    Max,    // -O3
}

/// Compiler warning level, translated into concrete flags by
/// `builder.rs` (`-Wall -Wextra`, plus `-Werror -Wpedantic` for `Strict`).
#[derive(Debug, Clone, Copy, Deserialize, Serialize, Default, PartialEq, Eq)]
pub enum WarningLevel {
    None,
    #[default]
    Standard,
    Strict,
}

#[derive(Deserialize, Serialize)]
pub struct BinTarget {
    pub name: String,
    pub path: String,
}

/// Which build system to use for a dependency. `Auto` probes the
/// dependency's source directory and picks the best match - see
/// [`crate::toolchain::resolve_builder`] for the detection order and
/// priority when more than one candidate is found.
#[derive(Debug, Deserialize, Serialize, Default, PartialEq, Eq, Clone)]
#[serde(rename_all = "lowercase")]
pub enum BuildSystemKind {
    #[default]
    Auto,
    Cmake,
    Meson,
    Make,
    Custom,
}

/// Which C compiler to use. `Auto` probes for a working compiler on
/// `PATH` - see `builder::compiler_binary` for the detection order.
#[derive(Deserialize, Serialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum CompilerKind {
    #[default]
    Auto,
    Gcc,
    Tcc,
    Clang,
}

#[derive(Debug, Deserialize, Serialize, Default)]
pub struct PathsConfig {
    #[serde(default)]
    pub src_dir: Option<String>,
    #[serde(default)]
    pub include: Option<String>,
    /// Additional named source directories, compiled alongside `src_dir`
    /// (e.g. `core = "core"`, `platform = "platform"`).
    #[serde(flatten)]
    pub custom: BTreeMap<String, String>,
}

impl ManifestConfig {
    /// Read and parse `Smidr.toml` from `project_dir`.
    ///
    /// # Errors
    /// Returns [`BuildError::ManifestNotFound`] if no `Smidr.toml` exists
    /// in `project_dir`, or [`BuildError::TomlDe`] if it exists but fails
    /// to parse.
    pub fn load(project_dir: &Path) -> Result<Self> {
        let manifest_path = project_dir.join("Smidr.toml");

        if !manifest_path.exists() {
            return Err(BuildError::ManifestNotFound(manifest_path));
        }

        let text = std::fs::read_to_string(&manifest_path)?;
        let config: ManifestConfig = toml::from_str(&text)?;

        Ok(config)
    }

    /// Serialize this config back into a pretty-printed TOML string, for
    /// writing out a freshly scaffolded `Smidr.toml` 
    /// (see [`crate::project::Project::init`]).
    pub fn to_toml_string(&self) -> Result<String> {
        Ok(toml::to_string_pretty(self)?)
    }

    /// Returns the effective release profile, using defaults if not specified.
    pub fn get_release_profile(&self) -> ResolvedProfile {
        let user_profile = self.profile.release.as_ref();
        ResolvedProfile {
            opt_level: user_profile
                .and_then(|p| p.opt_level)
                .unwrap_or(OptLevel::Max),
            warnings: user_profile
                .and_then(|p| p.warnings)
                .unwrap_or(WarningLevel::Strict),
            debug_symbols: user_profile
                .and_then(|p| p.debug_symbols)
                .unwrap_or(false),
            lto: user_profile.and_then(|p| p.lto).unwrap_or(true),
            strip: user_profile.and_then(|p| p.strip).unwrap_or(false),
        }
    }

    /// Returns the effective debug profile, using defaults if not specified.
    pub fn get_debug_profile(&self) -> ResolvedProfile {
        let user_profile = self.profile.debug.as_ref();
        ResolvedProfile {
            opt_level: user_profile
                .and_then(|p| p.opt_level)
                .unwrap_or(OptLevel::None),
            warnings: user_profile
                .and_then(|p| p.warnings)
                .unwrap_or(WarningLevel::Standard),
            debug_symbols: user_profile
                .and_then(|p| p.debug_symbols)
                .unwrap_or(true),
            lto: user_profile.and_then(|p| p.lto).unwrap_or(false),
            strip: user_profile.and_then(|p| p.strip).unwrap_or(false),
        }
    }
}

impl ProjectSection {
    /// Returns the explicit `output_name` if configured, falling back to the project `name`.
    pub fn output_name(&self) -> &str {
        self.output_name.as_deref().unwrap_or(&self.name)
    }
}

impl ProfilesSection {
    /// Returns `true` if no profile settings are specified (both `debug` and `release` are `None`).
    ///
    /// This is used by `toml::to_string_pretty` to decide whether to serialize the `profile` field
    pub fn is_empty(&self) -> bool {
        self.debug.is_none() && self.release.is_none()
    }
}

impl PathsConfig {
    /// Returns `true` if no path settings are specified (all fields are `None` or empty).
    pub fn is_empty(&self) -> bool {
        self.src_dir.is_none() && self.include.is_none() && self.custom.is_empty()
    }
}

//region LanguageStandard Implementations
impl Default for LanguageStandard {
    fn default() -> Self {
        LanguageStandard::C(CStandard::default())
    }
}

impl From<CStandard> for LanguageStandard {
    fn from(std: CStandard) -> Self {
        LanguageStandard::C(std)
    }
}

impl From<CppStandard> for LanguageStandard {
    fn from(std: CppStandard) -> Self {
        LanguageStandard::Cpp(std)
    }
}

impl LanguageStandard {
    pub fn language(&self) -> Language {
        match self {
            LanguageStandard::C(_) => Language::C,
            LanguageStandard::Cpp(_) => Language::Cpp,
        }
    }

    pub fn c_standard(&self) -> Option<CStandard> {
        match self {
            LanguageStandard::C(std) => Some(std.clone()),
            LanguageStandard::Cpp(_) => None,
        }
    }

    pub fn cpp_standard(&self) -> Option<CppStandard> {
        match self {
            LanguageStandard::C(_) => None,
            LanguageStandard::Cpp(std) => Some(std.clone()),
        }
    }
}

impl std::str::FromStr for LanguageStandard {
    type Err = String;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        use clap::ValueEnum;

        if let Ok(c) = CStandard::from_str(s, true) {
            return Ok(LanguageStandard::C(c));
        }
        if let Ok(cpp) = CppStandard::from_str(s, true) {
            return Ok(LanguageStandard::Cpp(cpp));
        }
        Err(format!("invalid language standard: '{}'", s))
    }
}

// Implementation of the Display trait for CStandard, used for printing the CStandard enum to a string.
impl std::fmt::Display for CStandard {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            CStandard::C89 => "c89",
            CStandard::C90 => "c90",
            CStandard::C99 => "c99",
            CStandard::C11 => "c11",
            CStandard::C17 => "c17",
            CStandard::C23 => "c23",
            CStandard::Gnu99 => "gnu99",
            CStandard::Gnu11 => "gnu11",
            CStandard::Gnu17 => "gnu17",
        };
        f.write_str(s)
    }
}

// Implementation of the Display trait for CppStandard, used for printing the CppStandard enum to a string.
impl std::fmt::Display for CppStandard {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            CppStandard::Cpp98 => "c++98",
            CppStandard::Cpp03 => "c++03",
            CppStandard::Cpp11 => "c++11",
            CppStandard::Cpp14 => "c++14",
            CppStandard::Cpp17 => "c++17",
            CppStandard::Cpp20 => "c++20",
            CppStandard::Cpp23 => "c++23",
            CppStandard::Cpp26 => "c++26",
        };
        f.write_str(s)
    }
}