ccgo 3.8.4

A high-performance C++ cross-platform build CLI
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
use std::collections::HashMap;

use anyhow::{bail, Result};

use crate::commands::build::LinkType;
use crate::config::{
    Linkage, MergeStrategy, ProfileCmake, ProfileConfig, ProfileDepLinkage,
    ProfilePlatformConfig,
};

/// Resolved (post-inheritance) cmake flags for a single scope.
#[derive(Debug, Clone, Default)]
pub struct ResolvedCmake {
    pub arguments: Vec<String>,
    pub c_flags: Vec<String>,
    pub cpp_flags: Vec<String>,
}

/// Resolved dep-linkage hints from a profile scope.
#[derive(Debug, Clone, Default)]
pub struct ResolvedDepLinkage {
    pub default: Option<Linkage>,
    pub on_shared: Option<Linkage>,
    pub on_static: Option<Linkage>,
}

/// Fully-resolved profile after inheritance chain expansion.
#[derive(Debug, Clone, Default)]
pub struct ResolvedProfile {
    pub name: Option<String>,
    pub release: Option<bool>,
    pub link_type: Option<LinkType>,
    pub jobs: Option<u32>,
    pub cmake: ResolvedCmake,
    pub features: Vec<String>,
    pub dep_linkage: ResolvedDepLinkage,
    /// Per-platform cmake flags, keyed by lowercase platform name.
    pub platform_cmake: HashMap<String, ResolvedCmake>,
    /// Per-platform dep linkage, keyed by lowercase platform name.
    pub platform_dep_linkage: HashMap<String, ResolvedDepLinkage>,
}

/// Build a map that includes built-in profiles alongside user-defined ones.
///
/// Built-in profiles (`debug`, `release`) carry a fixed `release` bool.  When
/// the user redefines one of these names to add cmake flags or dep-linkage hints,
/// they almost never want to lose that bool.  So instead of a blind overwrite we
/// preserve the built-in `release` field unless the user explicitly set one.
fn build_full_profiles(
    user_profiles: &HashMap<String, ProfileConfig>,
) -> HashMap<String, ProfileConfig> {
    let builtin_release_for = |name: &str| -> Option<bool> {
        match name {
            "debug" => Some(false),
            "release" => Some(true),
            _ => None,
        }
    };

    let mut map = HashMap::new();
    map.insert("debug".to_string(), ProfileConfig { release: Some(false), ..Default::default() });
    map.insert("release".to_string(), ProfileConfig { release: Some(true), ..Default::default() });

    for (k, v) in user_profiles {
        let entry = if let Some(builtin_release) = builtin_release_for(k) {
            // Preserve the built-in `release` bool when the user didn't set one.
            ProfileConfig {
                release: v.release.or(Some(builtin_release)),
                ..v.clone()
            }
        } else {
            v.clone()
        };
        map.insert(k.clone(), entry);
    }
    map
}

/// Expand the single-inheritance chain for `name` into a list ordered
/// [furthest ancestor, …, direct parent, name].
fn expand_chain<'a>(
    name: &'a str,
    profiles: &'a HashMap<String, ProfileConfig>,
) -> Result<Vec<&'a str>> {
    let mut chain: Vec<&str> = Vec::new();
    let mut visited: std::collections::HashSet<&str> = std::collections::HashSet::new();
    let mut cursor = name;
    loop {
        if !visited.insert(cursor) {
            bail!("profile inheritance cycle detected: '{cursor}' appears twice in chain");
        }
        chain.push(cursor);
        match profiles.get(cursor).and_then(|p| p.inherits.as_deref()) {
            Some(parent) => cursor = parent,
            None => break,
        }
    }
    chain.reverse();
    Ok(chain)
}

fn apply_cmake(acc: &mut ResolvedCmake, layer: &ProfileCmake) {
    match layer.merge {
        MergeStrategy::Replace => {
            acc.arguments = layer.arguments.clone();
            acc.c_flags = layer.c_flags.clone();
            acc.cpp_flags = layer.cpp_flags.clone();
        }
        MergeStrategy::Extend => {
            acc.arguments.extend_from_slice(&layer.arguments);
            acc.c_flags.extend_from_slice(&layer.c_flags);
            acc.cpp_flags.extend_from_slice(&layer.cpp_flags);
        }
    }
}

fn apply_dep_linkage(acc: &mut ResolvedDepLinkage, layer: &ProfileDepLinkage) {
    if layer.default.is_some() {
        acc.default = layer.default;
    }
    if layer.on_shared.is_some() {
        acc.on_shared = layer.on_shared;
    }
    if layer.on_static.is_some() {
        acc.on_static = layer.on_static;
    }
}

fn apply_scalar_fields(resolved: &mut ResolvedProfile, cfg: &ProfileConfig) {
    if let Some(v) = cfg.release {
        resolved.release = Some(v);
    }
    if let Some(ref v) = cfg.link_type {
        resolved.link_type = Some(v.clone());
    }
    if let Some(v) = cfg.jobs {
        resolved.jobs = Some(v);
    }
    if let Some(ref v) = cfg.name {
        resolved.name = Some(v.clone());
    }

    if let Some(ref feat) = cfg.features {
        match feat.merge {
            MergeStrategy::Replace => resolved.features = feat.list.clone(),
            MergeStrategy::Extend => resolved.features.extend_from_slice(&feat.list),
        }
    }

    if let Some(ref cmake) = cfg.cmake {
        apply_cmake(&mut resolved.cmake, cmake);
    }

    if let Some(ref dl) = cfg.dep_linkage {
        apply_dep_linkage(&mut resolved.dep_linkage, dl);
    }
}

fn apply_platform_configs(resolved: &mut ResolvedProfile, cfg: &ProfileConfig) {
    let plat_configs: [(&str, Option<&ProfilePlatformConfig>); 6] = [
        ("android", cfg.platforms.as_ref().and_then(|p| p.android.as_ref())),
        ("ios", cfg.platforms.as_ref().and_then(|p| p.ios.as_ref())),
        ("macos", cfg.platforms.as_ref().and_then(|p| p.macos.as_ref())),
        ("windows", cfg.platforms.as_ref().and_then(|p| p.windows.as_ref())),
        ("linux", cfg.platforms.as_ref().and_then(|p| p.linux.as_ref())),
        ("ohos", cfg.platforms.as_ref().and_then(|p| p.ohos.as_ref())),
    ];
    for (plat_name, plat_cfg) in &plat_configs {
        let Some(pc) = plat_cfg else { continue };
        let Some(ref build) = pc.build else { continue };

        if let Some(ref cmake) = build.cmake {
            let acc = resolved.platform_cmake.entry(plat_name.to_string()).or_default();
            apply_cmake(acc, cmake);
        }
        if let Some(ref dl) = build.dep_linkage {
            let acc = resolved
                .platform_dep_linkage
                .entry(plat_name.to_string())
                .or_default();
            apply_dep_linkage(acc, dl);
        }
    }
}

/// Resolve a named profile from the profile map.
///
/// Returns `Err` if:
/// - `name` is not found in `profiles` (and is not a built-in name)
/// - a cycle is detected in the inheritance chain
/// - a profile referenced in `inherits` doesn't exist
///
/// Built-in profiles (`debug`, `release`) are synthesized; no declaration needed.
pub fn resolve_profile(
    name: &str,
    user_profiles: &HashMap<String, ProfileConfig>,
) -> Result<ResolvedProfile> {
    let full = build_full_profiles(user_profiles);

    if !full.contains_key(name) {
        bail!("profile '{name}' not found in CCGO.toml");
    }

    let chain = expand_chain(name, &full)?;

    let mut resolved = ResolvedProfile::default();
    for node_name in &chain {
        let cfg = match full.get(*node_name) {
            Some(c) => c,
            None => bail!("profile '{node_name}' referenced in inherits chain but not defined"),
        };
        apply_scalar_fields(&mut resolved, cfg);
        apply_platform_configs(&mut resolved, cfg);
    }

    Ok(resolved)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{
        Linkage, MergeStrategy, ProfileCmake, ProfileConfig, ProfileDepLinkage, ProfileListField,
        ProfilePlatformBuild, ProfilePlatformConfig, ProfilePlatforms,
    };

    fn profiles_from(pairs: &[(&str, ProfileConfig)]) -> HashMap<String, ProfileConfig> {
        pairs.iter().map(|(k, v)| (k.to_string(), v.clone())).collect()
    }

    #[test]
    fn builtin_debug_resolves() {
        let profs = HashMap::new();
        let r = resolve_profile("debug", &profs).unwrap();
        assert_eq!(r.release, Some(false));
    }

    #[test]
    fn builtin_release_resolves() {
        let profs = HashMap::new();
        let r = resolve_profile("release", &profs).unwrap();
        assert_eq!(r.release, Some(true));
    }

    #[test]
    fn unknown_profile_errors() {
        let profs = HashMap::new();
        assert!(resolve_profile("nope", &profs).is_err());
    }

    #[test]
    fn cycle_detected() {
        let a = ProfileConfig {
            inherits: Some("b".to_string()),
            ..Default::default()
        };
        let b = ProfileConfig {
            inherits: Some("a".to_string()),
            ..Default::default()
        };
        let profs = profiles_from(&[("a", a), ("b", b)]);
        assert!(resolve_profile("a", &profs).is_err());
    }

    #[test]
    fn scalar_fields_inherited_and_overridable() {
        let base = ProfileConfig {
            release: Some(false),
            jobs: Some(2),
            ..Default::default()
        };

        let child = ProfileConfig {
            inherits: Some("base".to_string()),
            jobs: Some(8),
            ..Default::default()
        };

        let profs = profiles_from(&[("base", base), ("child", child)]);
        let r = resolve_profile("child", &profs).unwrap();
        assert_eq!(r.release, Some(false));
        assert_eq!(r.jobs, Some(8));
    }

    #[test]
    fn cmake_replace_strategy() {
        let base = ProfileConfig {
            cmake: Some(ProfileCmake {
            merge: MergeStrategy::Replace,
            arguments: vec!["-DA=1".to_string()],
            ..Default::default()
        }),
            ..Default::default()
        };

        let child = ProfileConfig {
            inherits: Some("base".to_string()),
            cmake: Some(ProfileCmake {
            merge: MergeStrategy::Replace,
            arguments: vec!["-DB=2".to_string()],
            ..Default::default()
        }),
            ..Default::default()
        };

        let profs = profiles_from(&[("base", base), ("child", child)]);
        let r = resolve_profile("child", &profs).unwrap();
        assert_eq!(r.cmake.arguments, vec!["-DB=2"]);
    }

    #[test]
    fn cmake_extend_strategy() {
        let base = ProfileConfig {
            cmake: Some(ProfileCmake {
            merge: MergeStrategy::Replace,
            arguments: vec!["-DA=1".to_string()],
            ..Default::default()
        }),
            ..Default::default()
        };

        let child = ProfileConfig {
            inherits: Some("base".to_string()),
            cmake: Some(ProfileCmake {
            merge: MergeStrategy::Extend,
            arguments: vec!["-DB=2".to_string()],
            ..Default::default()
        }),
            ..Default::default()
        };

        let profs = profiles_from(&[("base", base), ("child", child)]);
        let r = resolve_profile("child", &profs).unwrap();
        assert_eq!(r.cmake.arguments, vec!["-DA=1", "-DB=2"]);
    }

    #[test]
    fn features_extend_strategy() {
        let base = ProfileConfig {
            features: Some(ProfileListField {
            merge: MergeStrategy::Replace,
            list: vec!["a".to_string()],
        }),
            ..Default::default()
        };

        let child = ProfileConfig {
            inherits: Some("base".to_string()),
            features: Some(ProfileListField {
            merge: MergeStrategy::Extend,
            list: vec!["b".to_string()],
        }),
            ..Default::default()
        };

        let profs = profiles_from(&[("base", base), ("child", child)]);
        let r = resolve_profile("child", &profs).unwrap();
        assert_eq!(r.features, vec!["a", "b"]);
    }

    #[test]
    fn platform_cmake_resolved() {
        let prof = ProfileConfig {
            platforms: Some(ProfilePlatforms {
            android: Some(ProfilePlatformConfig {
                build: Some(ProfilePlatformBuild {
                    cmake: Some(ProfileCmake {
                        merge: MergeStrategy::Replace,
                        arguments: vec!["-DANDROID_ARM_NEON=TRUE".to_string()],
                        ..Default::default()
                    }),
                    dep_linkage: None,
                }),
            }),
            ..Default::default()
        }),
            ..Default::default()
        };
        let profs = profiles_from(&[("android_neon", prof)]);
        let r = resolve_profile("android_neon", &profs).unwrap();
        let android_cmake = r.platform_cmake.get("android").unwrap();
        assert_eq!(android_cmake.arguments, vec!["-DANDROID_ARM_NEON=TRUE"]);
    }

    #[test]
    fn dep_linkage_last_wins() {
        let base = ProfileConfig {
            dep_linkage: Some(ProfileDepLinkage {
            default: Some(Linkage::StaticEmbedded),
            on_shared: None,
            on_static: None,
        }),
            ..Default::default()
        };

        let child = ProfileConfig {
            inherits: Some("base".to_string()),
            dep_linkage: Some(ProfileDepLinkage {
            default: Some(Linkage::SharedExternal),
            on_shared: None,
            on_static: None,
        }),
            ..Default::default()
        };

        let profs = profiles_from(&[("base", base), ("child", child)]);
        let r = resolve_profile("child", &profs).unwrap();
        assert_eq!(r.dep_linkage.default, Some(Linkage::SharedExternal));
    }

    #[test]
    fn inherits_builtin_debug() {
        let child = ProfileConfig {
            inherits: Some("debug".to_string()),
            jobs: Some(4),
            ..Default::default()
        };

        let profs = profiles_from(&[("mysanitize", child)]);
        let r = resolve_profile("mysanitize", &profs).unwrap();
        assert_eq!(r.release, Some(false)); // inherited from builtin debug
        assert_eq!(r.jobs, Some(4));
    }
}