uiua 0.18.1

A stack-based array programming language
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
use std::{
    cell::RefCell,
    collections::{HashMap, hash_map::Entry},
    f64::consts::TAU,
    path::{Path, PathBuf},
    sync::{Arc, LazyLock, OnceLock},
};

use ecow::EcoVec;
use rand::prelude::*;

use crate::{
    Array, Boxed, PrimDocFragment, SysBackend, Uiua, Value, WILDCARD_NAN, media,
    parse_doc_line_fragments,
};

/// The definition of a shadowable constant
pub struct ConstantDef {
    /// The constant's name
    pub name: &'static str,
    /// The constant's class
    pub class: ConstClass,
    /// The constant's value
    pub value: LazyLock<ConstantValue>,
    /// The constant's documentation
    pub doc: LazyLock<String>,
    /// The suggested replacement because of deprecation
    pub deprecation: Option<&'static str>,
}

impl ConstantDef {
    /// Get the constant's documentation
    pub fn doc(&self) -> &str {
        &self.doc
    }
    /// Get the constant's documentation as fragments
    pub fn doc_frags(&self) -> Vec<PrimDocFragment> {
        parse_doc_line_fragments(self.doc())
    }
    /// Check if the constant is deprecated
    pub fn is_deprecated(&self) -> bool {
        self.deprecation.is_some()
    }
}

/// The value of a shadowable constant
pub enum ConstantValue {
    /// A static value that is always the same
    Static(Value),
    /// A big constant
    Big(BigConstant),
    /// The music constant
    Music,
    /// Bad Apple!! audio
    BadAppleAudio,
    /// The path of the current source file relative to the current working directory
    ThisFile,
    /// The name of the current source file
    ThisFileName,
    /// The name of the directory containing the current source file
    ThisFileDir,
    /// The compile-time working directory
    WorkingDir,
}

/// Identifier for a constant that's kind of big
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BigConstant {
    /// The Uiua386 font
    Uiua386,
    /// An elevation map of the world
    Elevation,
    /// A gif representing the Bad Apple!! video
    BadAppleGif,
    /// Audio for the Amen break
    Amen,
}

impl ConstantValue {
    /// Resolve the constant to a value
    pub(crate) fn resolve(
        &self,
        current_file_path: Option<&Path>,
        backend: Arc<dyn SysBackend>,
    ) -> Result<Value, String> {
        let current_file_path = current_file_path.map(|p| {
            let mut path = PathBuf::new();
            for comp in p.components() {
                path.push(comp);
            }
            path
        });
        Ok(match self {
            ConstantValue::Static(val) => val.clone(),
            &ConstantValue::Big(big) => {
                thread_local! {
                    static CACHE: RefCell<HashMap<BigConstant, Value>> = Default::default();
                }
                CACHE.with(|cache| -> Result<_, String> {
                    let mut cache = cache.borrow_mut();
                    Ok(match cache.entry(big) {
                        Entry::Occupied(e) => e.get().clone(),
                        Entry::Vacant(e) => {
                            let bytes = backend.big_constant(big)?;
                            e.insert(match big {
                                BigConstant::Uiua386 => bytes.into_owned().into(),
                                BigConstant::Elevation => {
                                    media::image_bytes_to_array(&bytes, true, false)?.into()
                                }
                                BigConstant::BadAppleGif => {
                                    let (_, mut val) = media::gif_bytes_to_value_gray(&bytes)?;
                                    let Value::Byte(_) = &mut val else {
                                        return Err(
                                            "Bad Apple gif data is not properly rounded to 0 or 1"
                                                .into(),
                                        );
                                    };
                                    val
                                }
                                BigConstant::Amen => {
                                    let (samples, sr) =
                                        media::array_from_wav_bytes(&bytes).unwrap();
                                    let new_row_count = (samples.row_count() as f64
                                        * backend.audio_sample_rate() as f64
                                        / sr as f64)
                                        .round()
                                        as usize;
                                    samples.keep_scalar_real_impl(new_row_count).into()
                                }
                            })
                            .clone()
                        }
                    })
                })?
            }
            ConstantValue::Music => {
                static MUSIC: OnceLock<Value> = OnceLock::new();
                MUSIC
                    .get_or_init(|| music_constant(backend.as_ref()))
                    .clone()
            }
            ConstantValue::BadAppleAudio => {
                static MUSIC: OnceLock<Value> = OnceLock::new();
                MUSIC
                    .get_or_init(|| {
                        let mut env = Uiua::with_backend(backend);
                        env.run_str(include_str!("assets/bad_apple.ua")).unwrap();
                        env.pop("samples").unwrap()
                    })
                    .clone()
            }
            ConstantValue::ThisFile => {
                current_file_path.map_or_else(|| "".into(), |p| p.display().to_string().into())
            }
            ConstantValue::ThisFileName => current_file_path
                .and_then(|p| p.file_name().map(|f| f.to_string_lossy().into_owned()))
                .unwrap_or_default()
                .into(),
            ConstantValue::ThisFileDir => {
                let mut path = current_file_path
                    .and_then(|p| p.parent().map(|f| f.display().to_string()))
                    .unwrap_or_default();
                if path.is_empty() {
                    path = ".".into();
                }
                path.into()
            }
            ConstantValue::WorkingDir => std::env::current_dir()
                .unwrap_or_default()
                .display()
                .to_string()
                .into(),
        })
    }
}

impl<T> From<T> for ConstantValue
where
    T: Into<Value>,
{
    fn from(val: T) -> Self {
        ConstantValue::Static(val.into())
    }
}

macro_rules! constant {
    ($(
        $(#[doc = $doc:literal])+
        (
            $(#[$attr:meta])*
            $name:literal,
            $class:ident,
            $value:expr
            $(, deprecated($deprecation:literal))?
        )
    ),* $(,)?) => {
        const COUNT: usize = {
            let mut count = 0;
            $(
                $(#[$attr])*
                {
                    _ = $name;
                    count += 1;
                }
            )*
            count
        };
        /// The list of all shadowable constants
        #[allow(path_statements)]
        pub static CONSTANTS: [ConstantDef; COUNT] =
            [$(
                $(#[$attr])*
                ConstantDef {
                    name: $name,
                    value: LazyLock::new(|| {$value.into()}),
                    class: ConstClass::$class,
                    doc: LazyLock::new(|| {
                        let mut s = String::new();
                        $(
                            s.push_str($doc.trim());
                            s.push('\n');
                        )*
                        s.pop();
                        s
                    }),
                    deprecation: { None::<&'static str> $(; Some($deprecation))? }
                },
            )*];
    };
}

/// Kinds of shadowable constants
#[allow(missing_docs)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ConstClass {
    Math,
    External,
    Time,
    Media,
    System,
    Color,
    Spatial,
    Flags,
    Fun,
}

constant!(
    /// Euler's constant
    ("e", Math, std::f64::consts::E),
    /// The golden ratio phi
    ("φ", Math, 1.618_033_988_749_895_f64),
    /// The Euler-Mascheroni constant
    ("γ", Math, 0.577_215_664_901_532_9_f64),
    /// The real complex unit
    ("r", Math, crate::Complex::ONE),
    /// The imaginary unit
    ("i", Math, crate::Complex::I),
    /// IEEE 754-2008's `NaN`
    ("NaN", Math, f64::NAN),
    /// The wildcard `NaN` value that equals any other number
    ("W", Math, WILDCARD_NAN),
    /// The maximum integer that can be represented exactly
    ("MaxInt", Math, 2f64.powi(53)),
    /// The machine epsilon for Uiua numbers
    ///
    /// It is the difference between 1 and the next larger representable number.
    ("ε", Math, f64::EPSILON),
    /// 1-dimensional adjacent neighbors offsets
    ("A₁", Spatial, [1, -1]),
    /// 2-dimensional adjacent neighbors offsets
    ("A₂", Spatial, [[0, 1], [1, 0], [0, -1], [-1, 0]]),
    /// 3-dimensional adjacent neighbors offsets
    ("A₃", Spatial, [[0, 1, 0], [1, 0, 0], [0, -1, 0], [-1, 0, 0], [0, 0, 1], [0, 0, -1]]),
    /// 2-dimensional corner neighbors offsets
    ("C₂", Spatial, [[1, 1], [1, -1], [-1, -1], [-1, 1]]),
    /// 3-dimensional corner neighbors offsets
    ("C₃", Spatial, [
        [1, 1, 1], [1, -1, 1], [-1, -1, 1], [-1, 1, 1],
        [1, 1, -1], [1, -1, -1], [-1, -1, -1], [-1, 1, -1]
    ]),
    /// 3-dimensional edge neighbors offsets
    ("E₃", Spatial, [
        [1, 1, 0], [1, -1, 0], [-1, -1, 0], [-1, 1, 0],
        [0, 1, 1], [1, 0, 1], [0, -1, 1], [-1, 0, 1],
        [0, 1, -1], [1, 0, -1], [0, -1, -1], [-1, 0, -1]
    ]),
    /// A string identifying the operating system
    ("Os", System, std::env::consts::OS, deprecated("Use the os function instead")),
    /// A string identifying family of the operating system
    ("Family", System, std::env::consts::FAMILY, deprecated("Use the osfamily function instead")),
    /// A string identifying the architecture of the CPU
    ("Arch", System, std::env::consts::ARCH, deprecated("Use the arch function instead")),
    /// The executable file extension
    ("ExeExt", System, std::env::consts::EXE_EXTENSION, deprecated("Use the exeext function instead")),
    /// The file extension for shared libraries
    ("DllExt", System, std::env::consts::DLL_EXTENSION, deprecated("Use the dllext function instead")),
    /// The primary path separator character
    ("Sep", System, std::path::MAIN_SEPARATOR, deprecated("Use the pathsep function instead")),
    /// The path of the current source file relative to `WorkingDir`
    ("ThisFile", System, ConstantValue::ThisFile),
    /// The name of the current source file
    ("ThisFileName", System, ConstantValue::ThisFileName),
    /// The name of the directory containing the current source file
    ("ThisFileDir", System, ConstantValue::ThisFileDir),
    /// The compile-time working directory
    ("WorkingDir", System, ConstantValue::WorkingDir),
    /// The number of processors available
    ("NumProcs", System, num_cpus::get() as f64, deprecated("Use the numprocs function instead")),
    /// A boolean `true` value for use in `json`
    ("True", External, Array::json_bool(true)),
    /// A boolean `false` value for use in `json`
    ("False", External, Array::json_bool(false)),
    /// A NULL pointer for use in `&ffi`
    ("NULL", External, Value::null()),
    /// The hexadecimal digits
    ("HexDigits", Math, "0123456789abcdef"),
    /// The days of the week
    (
        "Days",
        Time,
        [
            "Sunday",
            "Monday",
            "Tuesday",
            "Wednesday",
            "Thursday",
            "Friday",
            "Saturday"
        ]
        .as_slice()
    ),
    /// The months of the year
    (
        "Months",
        Time,
        [
            "January",
            "February",
            "March",
            "April",
            "May",
            "June",
            "July",
            "August",
            "September",
            "October",
            "November",
            "December"
        ]
        .as_slice()
    ),
    /// The number of days in each month in a non-leap year
    (
        "MonthDays",
        Time,
        [31u8, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    ),
    /// The number of days in each month in a leap year
    (
        "LeapMonthDays",
        Time,
        [31u8, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    ),
    /// The color white
    ("White", Color, [1.0, 1.0, 1.0]),
    /// The color black
    ("Black", Color, [0.0, 0.0, 0.0]),
    /// The color red
    ("Red", Color, [1.0, 0.0, 0.0]),
    /// The color orange
    ("Orange", Color, [1.0, 0.5, 0.0]),
    /// The color yellow
    ("Yellow", Color, [1.0, 1.0, 0.0]),
    /// The color green
    ("Green", Color, [0.0, 1.0, 0.0]),
    /// The color cyan
    ("Cyan", Color, [0.0, 1.0, 1.0]),
    /// The color blue
    ("Blue", Color, [0.0, 0.0, 1.0]),
    /// The color purple
    ("Purple", Color, [0.5, 0.0, 1.0]),
    /// The color magenta
    ("Magenta", Color, [1.0, 0.0, 1.0]),
    /// The planets of the solar system
    (
        "Planets",
        Fun,
        ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"].as_slice()
    ),
    /// Symbols for each of the planets
    (
        "PlanetSymbols",
        Fun,
        ['', '', '🜨', '', '', '', '', '']
    ),
    /// The signs of the zodiac
    (
        "Zodiac",
        Fun,
        [
            "Aries",
            "Taurus",
            "Gemini",
            "Cancer",
            "Leo",
            "Virgo",
            "Libra",
            "Scorpio",
            "Sagittarius",
            "Capricorn",
            "Aquarius",
            "Pisces"
        ]
        .as_slice()
    ),
    /// The symbols of the zodiac
    (
        "ZodiacSymbols",
        Fun,
        ['', '', '', '', '', '', '', '', '', '', '', '']
    ),
    /// The suits of a standard deck of playing cards
    ("Suits", Fun, ['', '', '', '']),
    /// The ranks of a standard deck of playing cards
    (
        "Cards",
        Fun,
        ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"].as_slice()
    ),
    /// The symbols of the standard chess pieces
    (
        "Chess",
        Fun,
        Array::new(
            [2, 6],
            ['', '', '', '', '', '', '', '', '', '', '', '']
        )
    ),
    /// The phases of the moon
    ("Moon", Fun, "🌑🌒🌓🌔🌕🌖🌗🌘"),
    /// Skin color modifiers for emoji
    ("Skin", Fun, "🏻🏼🏽🏾🏿"),
    /// People emoji
    ("People", Fun, "👨👩👦👧"),
    /// Emoji hair components
    ("Hair", Fun, "🦰🦱🦲🦳"),
    /// Names of each of the chemical elements
    (
        "Elements",
        Fun,
        [
            "Hydrogen", "Helium", "Lithium", "Beryllium", "Boron", "Carbon", "Nitrogen", "Oxygen", "Fluorine", "Neon", "Sodium", "Magnesium", "Aluminium",
            "Silicon", "Phosphorus", "Sulfur", "Chlorine", "Argon", "Potassium", "Calcium", "Scandium", "Titanium", "Vanadium", "Chromium", "Manganese",
            "Iron", "Cobalt", "Nickel", "Copper", "Zinc", "Gallium", "Germanium", "Arsenic", "Selenium", "Bromine", "Krypton", "Rubidium", "Strontium",
            "Yttrium", "Zirconium", "Niobium", "Molybdenum", "Technetium", "Ruthenium", "Rhodium", "Palladium", "Silver", "Cadmium", "Indium", "Tin",
            "Antimony", "Tellurium", "Iodine", "Xenon", "Cesium", "Barium", "Lanthanum", "Cerium", "Praseodymium", "Neodymium", "Promethium", "Samarium",
            "Europium", "Gadolinium", "Terbium", "Dysprosium", "Holmium", "Erbium", "Thulium", "Ytterbium", "Lutetium", "Hafnium", "Tantalum", "Tungsten",
            "Rhenium", "Osmium", "Iridium", "Platinum", "Gold", "Mercury", "Thallium", "Lead", "Bismuth", "Polonium", "Astatine", "Radon", "Francium",
            "Radium", "Actinium", "Thorium", "Protactinium", "Uranium", "Neptunium", "Plutonium", "Americium", "Curium", "Berkelium", "Californium",
            "Einsteinium", "Fermium", "Mendelevium", "Nobelium", "Lawrencium", "Rutherfordium", "Dubnium", "Seaborgium", "Bohrium", "Hassium", "Meitnerium",
            "Darmstadtium", "Roentgenium", "Copernicium", "Nihonium", "Flerovium", "Moscovium", "Livermorium", "Tennessine", "Oganesson"
        ].as_slice()
    ),
    /// Symbols for each of the chemical elements
    (
        "ElementSymbols",
        Fun,
        [
            "H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca", "Sc", "Ti", "V",
            "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru", "Rh",
            "Pd", "Ag", "Cd", "In", "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho",
            "Er", "Tm", "Yb", "Lu", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au", "Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac",
            "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es", "Fm", "Md", "No", "Lr", "Rf", "Db", "Sg", "Bh", "Hs", "Mt", "Ds", "Rg",
            "Cn", "Nh", "Fl", "Mc", "Lv", "Ts", "Og"
        ].as_slice()
    ),
    /// The Uiua logo
    (#[cfg(feature = "image")] "Logo", Media, media::image_bytes_to_array(include_bytes!("assets/uiua-logo-512.png"), false, true).unwrap()),
    /// Ethically sourced Lena picture
    /// Morten Rieger Hannemose
    /// 2019
    /// https://mortenhannemose.github.io/lena/
    (#[cfg(feature = "image")] "Lena", Media, media::image_bytes_to_array(include_bytes!("assets/lena.jpg"), false, false).unwrap()),
    /// Depth map for Lena picture
    (#[cfg(feature = "image")] "LenaDepth", Media, media::image_bytes_to_array(include_bytes!("assets/lena-depth.png"), true, false).unwrap()),
    /// A picture of two cats
    ///
    /// Their names are Murphy and Louie
    (#[cfg(feature = "image")] "Cats", Media, media::image_bytes_to_array(include_bytes!("assets/cats.webp"), false, false).unwrap()),
    /// Depth map for the cats
    (#[cfg(feature = "image")] "CatsDepth", Media, media::image_bytes_to_array(include_bytes!("assets/cats-depth.png"), true, false).unwrap()),
    /// An elevation map of the world
    ///
    /// Sea level is at 0.562
    (#[cfg(feature = "image")] "Elevation", Media, ConstantValue::Big(BigConstant::Elevation)),
    /// Sample music data
    ("Music", Media, ConstantValue::Music),
    /// Amen break
    ///
    /// Thank you Gregory Coleman 🙏
    ("Amen", Media, ConstantValue::Big(BigConstant::Amen)),
    /// Audio for Bad Apple!! (WIP)
    ("Bad", Media, ConstantValue::BadAppleAudio),
    /// Frames for Bad Apple!! at 24fps
    ("Apple", Media, ConstantValue::Big(BigConstant::BadAppleGif)),
    /// Lorem Ipsum text
    ("Lorem", Media, "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."),
    /// Rainbow flag colors
    ("Rainbow", Flags, [[0.894, 0.012, 0.012], [1.0, 0.647, 0.173], [1.0, 1.0, 0.255], [0.0, 0.502, 0.094], [0.0, 0.0, 0.976], [0.525, 0.0, 0.49]]),
    /// Lesbian flag colors
    ("Lesbian", Flags, [[0.831, 0.173, 0.0], [0.992, 0.596, 0.333], [1.0, 1.0, 1.0], [0.82, 0.38, 0.635], [0.635, 0.004, 0.38]]),
    /// Gay flag colors
    ("Gay", Flags, [[0.031, 0.55, 0.44], [0.149, 0.808, 0.667], [0.596, 0.91, 0.757], [1.0, 1.0, 1.0], [0.482, 0.678, 0.886], [0.314, 0.286, 0.8], [0.239, 0.102, 0.471]]),
    /// Bi flag colors
    ("Bi", Flags, [[0.839, 0.008, 0.439], [0.839, 0.008, 0.439], [0.608, 0.31, 0.588], [0.0, 0.22, 0.659], [0.0, 0.22, 0.659]]),
    /// Trans flag colors
    ("Trans", Flags, [[0.357, 0.808, 0.98], [0.961, 0.663, 0.722], [1.0, 1.0, 1.0], [0.961, 0.663, 0.722], [0.357, 0.808, 0.98]]),
    /// Pan flag colors
    ("Pan", Flags, [[1.0, 0.129, 0.549], [1.0, 0.847, 0.0], [0.129, 0.694, 1.0]]),
    /// Ace flag colors
    ("Ace", Flags, [[0.0, 0.0, 0.0], [0.639, 0.639, 0.639], [1.0, 1.0, 1.0], [0.502, 0.0, 0.502]]),
    /// Aro flag colors
    ("Aro", Flags, [[0.239, 0.647, 0.259], [0.655, 0.827, 0.475], [1.0, 1.0, 1.0], [0.663, 0.663, 0.663], [0.0, 0.0, 0.0]]),
    /// Aroace flag colors
    ("AroAce", Flags, [[0.937, 0.565, 0.027], [0.965, 0.827, 0.09], [1.0, 1.0, 1.0], [0.271, 0.737, 0.933], [0.118, 0.247, 0.329]]),
    /// Enby flag colors
    ("Enby", Flags, [[0.988, 0.957, 0.204], [1.0, 1.0, 1.0], [0.612, 0.349, 0.82], [0.173, 0.173, 0.173]]),
    /// Genderfluid flag colors
    ("Fluid", Flags, [[1.0, 0.463, 0.643], [1.0, 1.0, 1.0], [0.753, 0.067, 0.843], [0.0, 0.0, 0.0], [0.184, 0.235, 0.745]]),
    /// Genderqueer flag colors
    ("Queer", Flags, [[0.71, 0.494, 0.863], [1.0, 1.0, 1.0], [0.29, 0.506, 0.137]]),
    /// Agender flag colors
    ("Agender", Flags, [[0.0; 3], [0.74, 0.77, 0.78], [1.0; 3], [0.72, 0.96, 0.52], [1.0; 3], [0.74, 0.77, 0.78], [0.0; 3],]),
    /// All pride flags
    ("PrideFlags", Flags, {
        CONSTANTS
            .iter()
            .skip_while(|def| def.name != "Rainbow")
            .take_while(|def| def.name != "PrideFlags")
            .map(|def| match &*def.value {
                ConstantValue::Static(val) => val.clone(),
                _ => unreachable!()
            })
            .map(Boxed).collect::<Array<Boxed>>()
    }),
    /// All pride flag names
    ("PrideFlagNames", Flags, {
        CONSTANTS
            .iter()
            .skip_while(|def| def.name != "Rainbow")
            .take_while(|def| def.name != "PrideFlags")
            .map(|def| def.name.to_string())
            .collect::<Value>()
    }),
);

fn music_constant(backend: &dyn SysBackend) -> Value {
    const TEMPO: f64 = 128.0;
    const BEAT: f64 = 60.0 / TEMPO;
    const C4: f64 = 261.63;
    const B3: f64 = 246.94;
    const G3: f64 = 196.00;
    const E3: f64 = 164.81;
    const C2: f64 = 65.41;
    const D2: f64 = 73.42;
    const E2: f64 = 82.41;
    const G2: f64 = 98.00;
    #[rustfmt::skip]
    let down = [
        C4, C4, C4, C4, B3, B3, B3, B3, G3, G3, G3, G3, E3, E3, E3, E3,
        C4, C4, B3, B3, G3, G3, E3, E3, C4, C4, B3, B3, G3, G3, E3, E3,
        C4, C4, C4, C4, B3, B3, B3, B3, G3, G3, G3, G3, E3, E3, E3, E3,
        C4, B3, G3, E3, C4, B3, G3, E3, C4, B3, G3, E3, C4, B3, G3, E3,
    ];
    #[rustfmt::skip]
    let up = [
        E3, G3, B3, C4, E3, G3, B3, C4, E3, G3, B3, C4, E3, G3, B3, C4,
        E3, E3, E3, E3, G3, G3, G3, G3, B3, B3, B3, B3, C4, C4, C4, C4,
        E3, E3, G3, G3, B3, B3, C4, C4, E3, E3, G3, G3, B3, B3, C4, C4,
        E3, E3, E3, E3, G3, G3, G3, G3, B3, B3, B3, B3, C4, C4, C4, C4,
    ];
    let mut melody = Vec::with_capacity(down.len() * 2 + up.len() * 2);
    melody.extend(down);
    // melody.extend(down);
    melody.extend(up);
    // melody.extend(up);
    let harmony = [C2, D2, E2, G2];
    let mut hat_mask = Vec::new();
    let mut hat_bits: u64 = 0xbeef_babe;
    for _ in 0..32 {
        hat_mask.push((hat_bits & 1) as f64);
        hat_bits >>= 1;
    }
    let mut rng = SmallRng::seed_from_u64(0);
    let sr = backend.audio_sample_rate();
    (0..(BEAT * 2.0 * 16.0 * sr as f64) as usize)
        .map(|s| {
            let secs = s as f64 / sr as f64;
            let beat = secs / BEAT;

            let m = melody[(4.0 * beat) as usize % melody.len()];
            let h = harmony[(beat / 4.0) as usize % harmony.len()];

            let m = (1.0 - (m * secs % 1.0) * 2.0) / 3.0; // Saw wave
            let h = if (h * secs % 1.0) < 0.5 { 1.0 } else { -1.0 } / 3.0; // Square wave
            let kick = ((secs % BEAT).powf(0.4) * 40.0 * TAU).sin();
            let hat = 0.3
                * rng.random_range(-1.0..=1.0)
                * hat_mask[(4.0 * beat) as usize % 32]
                * (0.0..=0.1).contains(&(secs % (BEAT / 4.0) / (BEAT / 4.0))) as u8 as f64;
            let snare = 0.5
                * rng.random_range(-1.0..=1.0)
                * ((0.5..=0.6).contains(&(secs % (2.0 * BEAT) / (2.0 * BEAT))) as u8 as f64);

            0.5 * (m + h + kick + hat + snare)
        })
        .collect::<EcoVec<_>>()
        .into()
}