devela_base_alloc 0.26.0

base alloc shared functionality for devela
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
// devela::build::features
//
//! Features debugging and compile flags enabling for reflexion.
//
// NOTE: this file is shared between the build scripts in:
// - devela/build/main/
// - devela_base_core/build/

#[cfg(feature = "__dbg")]
use super::Build;
use std::{collections::HashSet, env, sync::OnceLock};

/// The set of enabled cargo features.
pub(crate) static ENABLED_CARGO_FEATURES: OnceLock<HashSet<String>> = OnceLock::new();
/// The set of enabled cfg flags.
pub(crate) static ENABLED_CFG_FLAGS: OnceLock<HashSet<String>> = OnceLock::new();

pub(crate) fn main() -> Result<(), std::io::Error> {
    println!("cargo:rerun-if-env-changed=CARGO_ENCODED_RUSTFLAGS");
    println!("cargo:rerun-if-env-changed=RUSTDOCFLAGS");

    #[cfg(feature = "__dbg")]
    Build::println_heading("Features:");

    /* Collect enabled cargo features from CARGO_FEATURE_* environment variables */

    ENABLED_CARGO_FEATURES.get_or_init(|| {
        let mut features = HashSet::new();
        for (key, _) in env::vars_os() {
            if let Some(feature) = key.to_str().and_then(|k| k.strip_prefix("CARGO_FEATURE_")) {
                features.insert(feature.to_lowercase());
            }
        }
        features
    });
    #[cfg(feature = "__dbg")]
    if let Some(f) = ENABLED_CARGO_FEATURES.get() {
        Build::println(format!("Active cargo features ({}): {:?}", f.len(), f));
    };
    // Enable reflection flags based on cargo features
    let _enabled_flags_from_features = reflection::set_ref_flags_from_cargo_features();
    #[cfg(feature = "__dbg")]
    {
        Build::println(format!(
            "Reflection flags auto-enabled by features ({}): {:?}",
            _enabled_flags_from_features.len(),
            _enabled_flags_from_features,
        ));
    }

    /* Collect *semantic* cfg names (`--cfg <name>`) from compiler flags */
    //
    // IMPORTANT:
    // - Build scripts receive raw compiler arguments, not parsed cfgs.
    // - We must explicitly extract `--cfg <name>` pairs.
    // - `cargo:rustc-cfg` only affects the current crate.
    // - For consistent behavior, we parse both
    //   - CARGO_ENCODED_RUSTFLAGS (build)
    //   - RUSTDOCFLAGS (docs)
    //
    // * NOTE on docs:
    // * - Changes to RUSTDOCFLAGS may not take effect immediately.
    // * - Cargo caches documentation builds, so previously compiled flags may persist.
    ENABLED_CFG_FLAGS.get_or_init(|| {
        let mut cfgs = HashSet::new();
        // rustc / cargo build
        if let Ok(value) = env::var("CARGO_ENCODED_RUSTFLAGS") {
            let mut it = value.split('\x1f');
            while let Some(arg) = it.next() {
                if arg == "--cfg" {
                    if let Some(name) = it.next() {
                        cfgs.insert(name.to_string());
                    }
                }
            }
        }
        // rustdoc
        if let Ok(value) = env::var("RUSTDOCFLAGS") {
            let mut it = value.split_whitespace();
            while let Some(arg) = it.next() {
                if arg == "--cfg" {
                    if let Some(name) = it.next() {
                        cfgs.insert(name.to_string());
                    }
                }
            }
        }
        cfgs
    });
    #[cfg(feature = "__dbg")]
    if let Some(f) = ENABLED_CFG_FLAGS.get() {
        // IMPROVE FIXME always shows as ""
        let filtered_flags: Vec<_> = f.iter().filter(|&f| f != "--cfg" && f != "-C").collect();
        // let filtered_flags: Vec<_> = f.iter().collect(); // SAME FOR THIS (TEMP)
        Build::println(format!(
            "Active compiler cfg flags ({}): {:?}",
            filtered_flags.len(),
            filtered_flags
        ));
    }
    // Enable reflection flags based on detected cfgs (`--cfg <name>`)
    let _enabled_flags_from_cfg_flags = reflection::set_ref_flags_from_cfg_flags();
    #[cfg(feature = "__dbg")]
    {
        Build::println(format!(
            "Flags auto-enabled by cfg flags ({}): {:?}",
            _enabled_flags_from_cfg_flags.len(),
            _enabled_flags_from_cfg_flags,
        ));
    }

    Ok(())
}

/// Sets configuration options for reflection, based on enabled features.
//
// https://doc.rust-lang.org/reference/conditional-compilation.html#set-configuration-options
#[rustfmt::skip]
mod reflection {
    use super::{ENABLED_CARGO_FEATURES, ENABLED_CFG_FLAGS};

    /* FLAGS
   -------------------------------------------------------------------------
   - Each `FlagsFlags` entry maps `cfg_flags` (required for activation)
     to `auto_flags` (which get enabled when any `cfg_flags` is present).

   - Important: Auto-enabled flags **do not propagate recursively**.
     If a flag (e.g., `nightly_stable`) has its own dependent flags,
     it must be explicitly included in the `cfg_flags` list of the parent
     (e.g., `nightly` must list `nightly_stable` if its children should be active).
    */

    /// Associates a set of automatically enabled flags with a set of `cfg` flags.
    pub struct FlagsFlags<'a> {
        /// Flags that are enabled when any of the `cfg_flags` are present.
        auto_flags: &'a [&'a str],
        /// `cfg` flags that trigger the corresponding `auto_flags`.
        cfg_flags: &'a [&'a str],
    }

    // In sync with ./Cargo.toml, ./docs/nightly.md && ./src/index.rs
    pub const FLAGS_NIGHTLY: FlagsFlags = FlagsFlags {
        auto_flags: &[
            "nightly_unstable",
                // "nightly_autodiff", // FLAG_DISABLED
                "nightly_allocator", "nightly_become", "nightly_coro",
                "nightly_doc", "nightly_float", "nightly_simd",
            //
            "nightly_stable",
                "nightly_stable_1_95", "nightly_stable_1_96", "nightly_stable_1_97",
                "nightly_stable_later",
        ],
        cfg_flags: &["nightly"],
    };
        pub const FLAGS_NIGHTLY_UNSTABLE: FlagsFlags = FlagsFlags {
            auto_flags: &[
                // "nightly_autodiff", // FLAG_DISABLED
                "nightly_allocator", "nightly_become", "nightly_coro",
                "nightly_doc", "nightly_float", "nightly_simd",
            ],
            cfg_flags: &["nightly_stable"],
        };
        pub const FLAGS_NIGHTLY_STABLE: FlagsFlags = FlagsFlags {
            auto_flags: &[
                "nightly_stable_1_95", "nightly_stable_1_96", "nightly_stable_1_97",
                "nightly_stable_later",
            ],
            cfg_flags: &["nightly_stable"],
        };
        pub const FLAGS_NIGHTLY_REFLECT: FlagsFlags = FlagsFlags {
            auto_flags: &["nightly··"],
            cfg_flags: &[ "nightly",
                "nightly_unstable",
                    // "nightly_autodiff", // FLAG_DISABLED
                    "nightly_allocator", "nightly_coro",
                    "nightly_doc", "nightly_float", "nightly_simd",
                //
                "nightly_stable",
                    "nightly_stable_1_95", "nightly_stable_1_96", "nightly_stable_1_97",
                    "nightly_stable_later",
            ],
        };

    /* FEATURES
   -------------------------------------------------------------------------
   - Each `FlagsFeatures` entry maps `features` (required for activation)
     to `ref_flags` (which get enabled when any `features` are present).

   - Features propagate **transitively**—enabling a feature activates all its
     direct and indirect flags. (e.g., enabling `"sys"` also enables `"mem"` and,
     through it, `"mem··"`, even though `"mem··"` isn't directly enabled in `"sys"`).
    */

    /// Associates a set of reflection flags with a set of `cfg` features.
    pub struct FlagsFeatures<'a> {
        /// Reflection flags enabled when any of the `features` are present.
        ref_flags: &'a [&'a str],
        /// Cargo features that trigger the corresponding `ref_flags`.
        features: &'a [&'a str],
    }

    /* # miscellaneous */

    pub const DEVELOPMENT: FlagsFeatures = FlagsFeatures {
        ref_flags: &[],
        features: &[
            "__dbg",
            "__exclude_test",
            "__force_miri_dst",
            "__publish",
            "__std",
            // "default",
            // "_default",
            "_docs", "_docs_nodeps", "_docs_min",
            "_max", "_maxest",
        ]
    };

    pub const ENVIRONMENT: FlagsFeatures = FlagsFeatures {
        ref_flags: &[],
        features: &["std", "alloc", "no_std"]
    };

    // In sync with ./Cargo.toml::[un][safe][st] & ./src/index.rs::safety
    pub const SAFE: FlagsFeatures = FlagsFeatures {
        ref_flags: &["safe··"],
        features: &[
            "safest",
            "safe",
            "safe_base",
            "safe_build",
            "safe_code",
            "safe_data",
            "safe_geom",
            "safe_lang",
            "safe_media",
                "safe_audio",
                "safe_font",
                "safe_visual", "safe_color", "safe_draw", "safe_image",
            "safe_num",
            "safe_org",
            "safe_phys",
                "safe_time",
            "safe_run",
            "safe_sys",
                "safe_io", "safe_mem",
            "safe_text",
            "safe_ui",
            "safe_work",
        ]
    };
    pub const UNSAFE: FlagsFeatures = FlagsFeatures {
        ref_flags: &["unsafe··"],
        features: &[
            "unsafe", // [11]
            "unsafe_array", "unsafe_ffi", "unsafe_hint", "unsafe_layout",
            "unsafe_niche", "unsafe_ptr", "unsafe_slice", "unsafe_str",
            "unsafe_sync", "unsafe_syscall", "unsafe_thread",
        ]
    };

    // In sync with ../Cargo.toml::dep_all & ../src/_dep.rs
    pub const DEPENDENCY: FlagsFeatures = FlagsFeatures {
        ref_flags: &["dep··"],
        features: &include!["./dep_all"],
    };

    /* # modules */

    pub const CODE: FlagsFeatures = FlagsFeatures {
        ref_flags: &["code··"],
        features: &["code"]
    };
    pub const DATA: FlagsFeatures = FlagsFeatures {
        ref_flags: &["data··"],
        features: &["data", "hash"]
    };
    pub const GEOM: FlagsFeatures = FlagsFeatures {
        ref_flags: &["geom··"],
        features: &["geom", "shape"]
    };
    pub const LANG: FlagsFeatures = FlagsFeatures {
        ref_flags: &["lang··"],
        features: &["lang", "glsl", "js"]
    };
        pub const FFI: FlagsFeatures = FlagsFeatures {
            ref_flags: &["ffi··"],
            features: &["glsl", "js"]
        };
    pub const MEDIA: FlagsFeatures = FlagsFeatures {
        ref_flags: &["media··"],
        features: &["media",
            "audio",
            "font",
            "visual", "color", "draw", "image",
        ]
    };
        pub const VISUAL: FlagsFeatures = FlagsFeatures {
            ref_flags: &["visual··"],
            features: &["visual", "color", "draw", "image"]
        };
    pub const NUM: FlagsFeatures = FlagsFeatures {
        ref_flags: &["num··"],
        features: &["num", "lin", "int", "rand"]
    };
    pub const ORG: FlagsFeatures = FlagsFeatures {
        ref_flags: &["org··"],
        features: &["org"]
    };
    pub const PHYS: FlagsFeatures = FlagsFeatures {
        ref_flags: &["phys··"],
        features: &["phys", "time", "unit", "wave"]
    };
    pub const RUN: FlagsFeatures = FlagsFeatures {
        ref_flags: &["run··"],
        features: &["run"]
    };
    pub const SYS: FlagsFeatures = FlagsFeatures {
        ref_flags: &["sys··"],
        features: &["sys", "io",
            "mem", "bit",
            /* os: */ "linux", "term", "windows"]
    };
        // RETHINK:
        pub const MEM: FlagsFeatures = FlagsFeatures {
            ref_flags: &["mem··"],
            features: &["mem", "bit"]
        };
    pub const TEXT: FlagsFeatures = FlagsFeatures {
        ref_flags: &["text··"],
        features: &["text", "grapheme", "translit"]
    };
    pub const UI: FlagsFeatures = FlagsFeatures {
        ref_flags: &["ui··"],
        features: &[
            "ui", "event", "layout",
        ]
    };
    pub const VITA: FlagsFeatures = FlagsFeatures {
        ref_flags: &["vita··"],
        features: &["vita"]
    };
    pub const WORK: FlagsFeatures = FlagsFeatures {
        ref_flags: &["work··"],
        features: &["work", "process", "sync", "thread"]
    };

    /* # capabilities */

    /* ## code */

    pub const UNROLL: FlagsFeatures = FlagsFeatures {
        ref_flags: &[],
        features: &[
            "_unroll", "_unroll_128", "_unroll_256", "_unroll_512", "_unroll_1024", "_unroll_2048",
        ]
    };

    /* ## data */

    pub const TUPLE: FlagsFeatures = FlagsFeatures {
        ref_flags: &[],
        features: &["_tuple", "_tuple_24", "_tuple_36", "_tuple_48", "_tuple_72"]
    };

    // ### collections
    pub const DESTAQUE: FlagsFeatures = FlagsFeatures {
        ref_flags: &["_destaque··"],
        features: &["_destaque_u8", "_destaque_u16", "_destaque_u32", "_destaque_usize"]
    };
    pub const GRAPH: FlagsFeatures = FlagsFeatures {
        ref_flags: &["_graph··"],
        features: &["_graph_u8", "_graph_u16", "_graph_u32", "_graph_usize"]
    };
    pub const NODE: FlagsFeatures = FlagsFeatures {
        ref_flags: &["_node··"],
        features: &["_node_u8", "_node_u16", "_node_u32", "_node_usize"]
    };
    pub const STACK: FlagsFeatures = FlagsFeatures {
        ref_flags: &["_stack··"],
        features: &["_stack_u8", "_stack_u16", "_stack_u32", "_stack_usize"] };


    // function helpers
    // -------------------------------------------------------------------------

    /* cargo features */

    /// Sets the reflection flags for all the corresponding enabled cargo features from the list.
    ///
    /// This is the list of the constants defined above.
    pub(super) fn set_ref_flags_from_cargo_features() -> Vec<String> {
        let mut enabled_ref_flags = Vec::new();

        for ff in [
            /* development */

            DEVELOPMENT,
            ENVIRONMENT,
            SAFE, UNSAFE,
            DEPENDENCY,

            /* modules */

            CODE,
            DATA,
            GEOM,
            LANG, FFI,
            MEDIA, VISUAL,
            NUM,
            ORG,
            PHYS,
            RUN,
            SYS, MEM,
            TEXT,
            UI,
            VITA,
            WORK,

            /* capabilities */

            // code
            UNROLL,
            // data
            TUPLE,
            DESTAQUE, GRAPH, NODE, STACK, // collections

        ] { set_flags_dbg_features(ff.ref_flags, ff.features, &mut enabled_ref_flags); }

        enabled_ref_flags
    }
    /// Sets reflection flags if some **FEATURES** are enabled.
    ///
    /// - flag_names: The name of the reflection flag to set if any feature is enabled.
    /// - features:   The cargo features names to check.
    fn set_flags_dbg_features(ref_flags: &[&str], features: &[&str], enabled: &mut Vec<String>) {
        let is_enabled = features.iter().any(|&f| ENABLED_CARGO_FEATURES.get().unwrap().contains(f));
        if is_enabled {
            for flag in ref_flags {
                println!("cargo:rustc-cfg={flag}");
                enabled.push(flag.to_string());
            }
        }
    }

    /* cfg flags */

    /// Sets automatic flags, based on enabled cfg flags.
    pub(super) fn set_ref_flags_from_cfg_flags() -> Vec<String> {
        let mut enabled_ref_flags = Vec::new();
        for ff in [
            FLAGS_NIGHTLY, FLAGS_NIGHTLY_UNSTABLE, FLAGS_NIGHTLY_STABLE, FLAGS_NIGHTLY_REFLECT,
        ] {
            set_flags_dbg_flags(ff.auto_flags, ff.cfg_flags, &mut enabled_ref_flags);
        }
        enabled_ref_flags
    }
    /// Sets automatic flags if some **FLAGS** are enabled.
    ///
    /// - flag_names: The name of the reflection flag to set if any cfg flag is enabled.
    /// - cfg_flags:   The cfg flags names to check.
    fn set_flags_dbg_flags(ref_flags: &[&str], cfg_flags: &[&str], enabled: &mut Vec<String>) {
        let is_enabled = cfg_flags.iter().any(|&f| ENABLED_CFG_FLAGS.get().unwrap().contains(f));
        if is_enabled {
            for flag in ref_flags {
                println!("cargo:rustc-cfg={flag}");
                enabled.push(flag.to_string());
            }
        }
    }
}