geam-cli 0.2.1

Standalone command implementation for Geam
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
#[derive(Debug, Clone, PartialEq, Eq)]
struct RunnerComponent {
    field: String,
    type_path: String,
    initialization: ComponentInitialization,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum ComponentInitialization {
    Stdlib,
    Unit,
    SystemTime,
    Configured { package: String },
}

impl RunnerComponent {
    fn stdlib() -> Self {
        Self {
            field: "stdlib".to_owned(),
            type_path: "geam::gleam_stdlib::Component<CliIoSink>".to_owned(),
            initialization: ComponentInitialization::Stdlib,
        }
    }

    fn json() -> Self {
        Self {
            field: "json".to_owned(),
            type_path: "geam::gleam_json::Component".to_owned(),
            initialization: ComponentInitialization::Unit,
        }
    }

    fn time() -> Self {
        Self {
            field: "time".to_owned(),
            type_path: "geam::gleam_time::Component".to_owned(),
            initialization: ComponentInitialization::SystemTime,
        }
    }

    fn external(alias: String) -> Self {
        Self {
            field: alias.clone(),
            type_path: format!("{alias}::Component"),
            initialization: ComponentInitialization::Configured {
                package: provider_package(&alias).to_owned(),
            },
        }
    }

    fn store_field(&self) -> String {
        format!(
            "    {}: <{} as geam::HostProviderComponent>::Stores,\n",
            self.field, self.type_path,
        )
    }

    fn state_field(&self) -> String {
        format!(
            "    {}: <{} as geam::HostProviderComponent>::RunState,\n",
            self.field, self.type_path,
        )
    }

    fn profile(&self) -> String {
        format!(
            "\nimpl geam::HostComponentProfile<{type_path}> for Profile {{\n    fn component_stores(stores: &Self::ExternalStores) -> &<{type_path} as geam::HostProviderComponent>::Stores {{\n        &stores.{field}\n    }}\n\n    fn component_state(state: &mut Self::RunState) -> &mut <{type_path} as geam::HostProviderComponent>::RunState {{\n        &mut state.{field}\n    }}\n}}\n",
            type_path = self.type_path,
            field = self.field,
        )
    }

    fn registration(&self) -> String {
        format!(
            "    providers.extend(<{} as geam::HostProviderComponentRegistration<Profile>>::providers()?);\n",
            self.type_path,
        )
    }

    fn configuration_selection(&self) -> String {
        match &self.initialization {
            ComponentInitialization::Configured { package } => format!(
                "    let configuration_{field} = configurations.remove(\"{package}\").unwrap_or_else(geam::HostProviderConfiguration::empty);\n",
                field = self.field,
            ),
            ComponentInitialization::Stdlib
            | ComponentInitialization::Unit
            | ComponentInitialization::SystemTime => String::new(),
        }
    }

    fn configured_initialization(&self) -> String {
        match &self.initialization {
            ComponentInitialization::Configured { .. } => format!(
                "    let state_{field} = <{type_path} as geam::HostProviderComponentInitialization>::initialize(&configuration_{field})?;\n",
                field = self.field,
                type_path = self.type_path,
            ),
            ComponentInitialization::Stdlib
            | ComponentInitialization::Unit
            | ComponentInitialization::SystemTime => String::new(),
        }
    }

    fn capability_initialization(&self) -> String {
        let value = match &self.initialization {
            ComponentInitialization::Stdlib => {
                "geam::gleam_stdlib::GleamStdlibRunState::try_from_entropy_with_io(output.io_sink())?".to_owned()
            }
            ComponentInitialization::Unit => "()".to_owned(),
            ComponentInitialization::SystemTime => {
                "geam::gleam_time::SystemTimeSource".to_owned()
            }
            ComponentInitialization::Configured { .. } => return String::new(),
        };
        format!("    let state_{} = {value};\n", self.field)
    }

    fn state_initializer(&self) -> String {
        format!("        {}: state_{},\n", self.field, self.field)
    }
}

fn runner_components(provider_aliases: &[String]) -> Vec<RunnerComponent> {
    let mut provider_aliases = provider_aliases.to_vec();
    provider_aliases.sort();
    provider_aliases.dedup();

    [
        RunnerComponent::stdlib(),
        RunnerComponent::json(),
        RunnerComponent::time(),
    ]
    .into_iter()
    .chain(provider_aliases.into_iter().map(RunnerComponent::external))
    .collect()
}

pub(super) fn render_source(provider_aliases: &[String]) -> String {
    let components = runner_components(provider_aliases);
    let store_fields = components
        .iter()
        .map(RunnerComponent::store_field)
        .collect::<String>();
    let state_fields = components
        .iter()
        .map(RunnerComponent::state_field)
        .collect::<String>();
    let component_profiles = components
        .iter()
        .map(RunnerComponent::profile)
        .collect::<String>();
    let component_registrations = components
        .iter()
        .map(RunnerComponent::registration)
        .collect::<String>();
    let configuration_selections = components
        .iter()
        .map(RunnerComponent::configuration_selection)
        .collect::<String>();
    let configured_initializations = components
        .iter()
        .map(RunnerComponent::configured_initialization)
        .collect::<String>();
    let capability_initializations = components
        .iter()
        .map(RunnerComponent::capability_initialization)
        .collect::<String>();
    let state_initializers = components
        .iter()
        .map(RunnerComponent::state_initializer)
        .collect::<String>();
    let configuration_mutability = if components.iter().any(|component| {
        matches!(
            component.initialization,
            ComponentInitialization::Configured { .. }
        )
    }) {
        "mut "
    } else {
        ""
    };

    RUNNER_TEMPLATE
        .replace("__STORE_FIELDS__", &store_fields)
        .replace("__STATE_FIELDS__", &state_fields)
        .replace("__COMPONENT_PROFILES__", &component_profiles)
        .replace("__COMPONENT_REGISTRATIONS__", &component_registrations)
        .replace("__CONFIGURATION_SELECTIONS__", &configuration_selections)
        .replace(
            "__CONFIGURED_INITIALIZATIONS__",
            &configured_initializations,
        )
        .replace(
            "__CAPABILITY_INITIALIZATIONS__",
            &capability_initializations,
        )
        .replace("__STATE_INITIALIZERS__", &state_initializers)
        .replace("__CONFIGURATION_MUTABILITY__", configuration_mutability)
}

fn provider_package(alias: &str) -> &str {
    alias.strip_prefix("geam_provider_").unwrap_or(alias)
}

const RUNNER_TEMPLATE: &str = r#"// Generated by Geam. Do not edit.

#[derive(Default)]
struct Stores {
__STORE_FIELDS__}

struct RunState {
__STATE_FIELDS__}

struct Profile;

impl geam::HostProfile for Profile {
    type RunState = RunState;
    type ExternalStores = Stores;
}

__COMPONENT_PROFILES__

impl geam::gleam_stdlib::GleamStdlibHostProfile for Profile {
    type Io = CliIoSink;
}

impl geam::gleam_time::GleamTimeHostProfile for Profile {
    type Source = geam::gleam_time::SystemTimeSource;
}

fn host_providers() -> Result<geam::HostProviderSet<Profile>, geam::HostRegistrationError> {
    let mut providers = Vec::new();
__COMPONENT_REGISTRATIONS__    geam::HostProviderSet::with_providers(Vec::<geam::HostModule<Profile>>::new(), providers)
}

fn check(project_root: String, module: String) -> Result<(), Box<dyn std::error::Error>> {
    let typed = geam::compile_typed_host_project(project_root, module, host_providers()?)?;
    let plan = geam::plan_host_program(typed)?;
    let _execution = geam::HostedExecution::try_from_module_plan(plan)?;
    Ok(())
}

fn run_project(
    project_root: String,
    module: String,
    configuration_arguments: impl Iterator<Item = String>,
) -> Result<(), Box<dyn std::error::Error>> {
    let typed = geam::compile_typed_host_project(project_root, module, host_providers()?)?;
    let __CONFIGURATION_MUTABILITY__configurations = load_configurations(configuration_arguments)?;
__CONFIGURATION_SELECTIONS__    if let Some(package) = configurations.keys().next() {
        return Err(invalid_data(format!("no selected provider accepts configuration for Gleam package {package}")).into());
    }
__CONFIGURED_INITIALIZATIONS__    let output = SharedOutput::new();
__CAPABILITY_INITIALIZATIONS__
    let mut state = RunState {
__STATE_INITIALIZERS__    };
    let plan = geam::plan_host_program(typed)?;
    let execution = geam::HostedExecution::try_from_module_plan(plan)?;
    let mut echo = output.echo_sink();
    let execution_result = execution.run_main(&mut state, &mut echo);
    output.finish()?;
    execution_result?;
    Ok(())
}

fn load_configurations(
    arguments: impl Iterator<Item = String>,
) -> Result<std::collections::BTreeMap<String, geam::HostProviderConfiguration>, Box<dyn std::error::Error>> {
    let mut configurations = std::collections::BTreeMap::new();
    for argument in arguments {
        let Some((package, path)) = argument.split_once('=') else {
            return Err(invalid_data("expected provider configuration argument PACKAGE=PATH").into());
        };
        let configuration = read_configuration(path)?;
        if configurations.insert(package.to_owned(), configuration).is_some() {
            return Err(invalid_data(format!("provider configuration for {package} was supplied more than once")).into());
        }
    }
    Ok(configurations)
}

fn read_configuration(path: &str) -> Result<geam::HostProviderConfiguration, Box<dyn std::error::Error>> {
    let source = std::fs::read_to_string(path).map_err(|error| {
        std::io::Error::new(error.kind(), format!("failed to read provider configuration {path}: {error}"))
    })?;
    let table = toml::from_str::<toml::Table>(&source).map_err(|error| {
        invalid_data(format!("invalid provider configuration {path}: {error}"))
    })?;
    configuration_from_table(table)
}

fn configuration_from_table(
    table: toml::Table,
) -> Result<geam::HostProviderConfiguration, Box<dyn std::error::Error>> {
    let values = table
        .into_iter()
        .map(|(key, value)| configuration_value(value).map(|value| (key.into(), value)))
        .collect::<Result<_, _>>()?;
    Ok(geam::HostProviderConfiguration::new(values))
}

fn configuration_value(
    value: toml::Value,
) -> Result<geam::HostProviderConfigurationValue, Box<dyn std::error::Error>> {
    Ok(match value {
        toml::Value::String(value) => geam::HostProviderConfigurationValue::String(value.into()),
        toml::Value::Integer(value) => geam::HostProviderConfigurationValue::Integer(value),
        toml::Value::Float(value) => geam::HostProviderConfigurationValue::Float(value),
        toml::Value::Boolean(value) => geam::HostProviderConfigurationValue::Bool(value),
        toml::Value::Array(values) => geam::HostProviderConfigurationValue::Array(
            values
                .into_iter()
                .map(configuration_value)
                .collect::<Result<_, _>>()?,
        ),
        toml::Value::Table(value) => {
            geam::HostProviderConfigurationValue::Table(configuration_from_table(value)?)
        }
        toml::Value::Datetime(value) => {
            return Err(invalid_data(format!("TOML datetime configuration values are unsupported: {value}")).into());
        }
    })
}

#[derive(Clone)]
struct SharedOutput {
    failure: std::rc::Rc<std::cell::RefCell<Option<std::io::Error>>>,
}

impl SharedOutput {
    fn new() -> Self {
        Self {
            failure: std::rc::Rc::new(std::cell::RefCell::new(None)),
        }
    }

    fn io_sink(&self) -> CliIoSink {
        CliIoSink {
            output: self.clone(),
        }
    }

    fn echo_sink(&self) -> CliEchoSink {
        CliEchoSink {
            output: self.clone(),
        }
    }

    fn write(&self, stream: OutputStream, text: &str) {
        if self.failure.borrow().is_some() {
            return;
        }
        let result = match stream {
            OutputStream::Stdout => write_stdout(text),
            OutputStream::Stderr => write_stderr(text),
        };
        if let Err(error) = result {
            *self.failure.borrow_mut() = Some(error);
        }
    }

    fn finish(&self) -> Result<(), std::io::Error> {
        match self.failure.borrow_mut().take() {
            Some(error) => Err(error),
            None => Ok(()),
        }
    }
}

enum OutputStream {
    Stdout,
    Stderr,
}

struct CliIoSink {
    output: SharedOutput,
}

impl geam::gleam_stdlib::IoSink for CliIoSink {
    fn emit(&mut self, output: geam::gleam_stdlib::IoOutput) {
        let stream = match output.stream() {
            geam::gleam_stdlib::IoStream::Stdout => OutputStream::Stdout,
            geam::gleam_stdlib::IoStream::Stderr => OutputStream::Stderr,
        };
        self.output.write(stream, output.text().as_str());
    }
}

struct CliEchoSink {
    output: SharedOutput,
}

impl geam::EchoSink for CliEchoSink {
    fn emit(&mut self, output: geam::EchoOutput) {
        let mut text = output.to_string();
        text.push('\n');
        self.output.write(OutputStream::Stderr, &text);
    }
}

fn write_stdout(text: &str) -> Result<(), std::io::Error> {
    let stdout = std::io::stdout();
    let mut stdout = stdout.lock();
    std::io::Write::write_all(&mut stdout, text.as_bytes())?;
    std::io::Write::flush(&mut stdout)
}

fn write_stderr(text: &str) -> Result<(), std::io::Error> {
    let stderr = std::io::stderr();
    let mut stderr = stderr.lock();
    std::io::Write::write_all(&mut stderr, text.as_bytes())?;
    std::io::Write::flush(&mut stderr)
}

fn entry() -> Result<(), Box<dyn std::error::Error>> {
    let mut arguments = std::env::args().skip(1);
    let mode = arguments.next().ok_or_else(invalid_arguments)?;
    let project_root = arguments.next().ok_or_else(invalid_arguments)?;
    let module = arguments.next().ok_or_else(invalid_arguments)?;
    match mode.as_str() {
        "check" if arguments.next().is_none() => check(project_root, module),
        "run" => run_project(project_root, module, arguments),
        _ => Err(invalid_arguments().into()),
    }
}

fn main() -> std::process::ExitCode {
    match entry() {
        Ok(()) => std::process::ExitCode::SUCCESS,
        Err(error) => {
            eprintln!("geam runner: {error}");
            std::process::ExitCode::FAILURE
        }
    }
}

fn invalid_arguments() -> std::io::Error {
    invalid_data("expected internal runner arguments: check|run PROJECT_ROOT MODULE [PACKAGE=PATH ...]")
}

fn invalid_data(reason: impl Into<String>) -> std::io::Error {
    std::io::Error::new(std::io::ErrorKind::InvalidInput, reason.into())
}
"#;

#[cfg(test)]
mod tests {
    use super::{ComponentInitialization, RunnerComponent, render_source, runner_components};

    #[test]
    fn renders_static_profiles_and_initialization_in_sorted_component_order() {
        let aliases = [
            "geam_provider_zeta".to_owned(),
            "geam_provider_alpha".to_owned(),
            "geam_provider_alpha".to_owned(),
        ];
        assert_eq!(
            runner_components(&aliases),
            [
                RunnerComponent {
                    field: "stdlib".to_owned(),
                    type_path: "geam::gleam_stdlib::Component<CliIoSink>".to_owned(),
                    initialization: ComponentInitialization::Stdlib,
                },
                RunnerComponent {
                    field: "json".to_owned(),
                    type_path: "geam::gleam_json::Component".to_owned(),
                    initialization: ComponentInitialization::Unit,
                },
                RunnerComponent {
                    field: "time".to_owned(),
                    type_path: "geam::gleam_time::Component".to_owned(),
                    initialization: ComponentInitialization::SystemTime,
                },
                RunnerComponent {
                    field: "geam_provider_alpha".to_owned(),
                    type_path: "geam_provider_alpha::Component".to_owned(),
                    initialization: ComponentInitialization::Configured {
                        package: "alpha".to_owned(),
                    },
                },
                RunnerComponent {
                    field: "geam_provider_zeta".to_owned(),
                    type_path: "geam_provider_zeta::Component".to_owned(),
                    initialization: ComponentInitialization::Configured {
                        package: "zeta".to_owned(),
                    },
                },
            ],
        );

        let source = render_source(&aliases);

        assert!(source.starts_with("// Generated by Geam. Do not edit.\n"));
        for field in [
            "stdlib",
            "json",
            "time",
            "geam_provider_alpha",
            "geam_provider_zeta",
        ] {
            assert_eq!(source.matches(&format!("    {field}: <")).count(), 2);
        }
        assert!(source.contains("impl geam::gleam_stdlib::GleamStdlibHostProfile for Profile"));
        assert!(source.contains("impl geam::gleam_time::GleamTimeHostProfile for Profile"));

        let type_paths = [
            "geam::gleam_stdlib::Component<CliIoSink>",
            "geam::gleam_json::Component",
            "geam::gleam_time::Component",
            "geam_provider_alpha::Component",
            "geam_provider_zeta::Component",
        ];
        let mut previous_profile = 0;
        let mut previous_registration = 0;
        for type_path in type_paths {
            let profile = source
                .find(&format!(
                    "impl geam::HostComponentProfile<{type_path}> for Profile"
                ))
                .expect("component profile should render");
            let registration = source
                .find(&format!(
                    "<{type_path} as geam::HostProviderComponentRegistration<Profile>>::providers()?"
                ))
                .expect("component registration should render");
            assert!(profile > previous_profile);
            assert!(registration > previous_registration);
            previous_profile = profile;
            previous_registration = registration;
        }
        assert!(!source.contains("geam::gleam_stdlib::host_providers::<Profile>()"));
        assert!(!source.contains("geam::gleam_json::host_providers::<Profile>()"));
        assert!(!source.contains("geam::gleam_time::host_providers::<Profile>()"));

        let alpha_initialization = source
            .find("let state_geam_provider_alpha")
            .expect("alpha state should initialize");
        let zeta_initialization = source
            .find("let state_geam_provider_zeta")
            .expect("zeta state should initialize");
        let output_initialization = source
            .find("let output = SharedOutput::new();")
            .expect("shared output should initialize");
        assert!(alpha_initialization < zeta_initialization);
        assert!(zeta_initialization < output_initialization);

        let mut previous_initialization = output_initialization;
        for field in ["stdlib", "json", "time"] {
            let initialization = source
                .find(&format!("let state_{field}"))
                .expect("runner capability should initialize");
            assert!(initialization > previous_initialization);
            previous_initialization = initialization;
        }
        assert!(source.contains(
            "let state_stdlib = geam::gleam_stdlib::GleamStdlibRunState::try_from_entropy_with_io(output.io_sink())?;"
        ));
        assert!(source.contains("let state_json = ();"));
        assert!(source.contains("let state_time = geam::gleam_time::SystemTimeSource;"));
        assert!(
            source.contains("let execution_result = execution.run_main(&mut state, &mut echo);")
        );
        assert_eq!(
            source,
            render_source(&[
                "geam_provider_alpha".to_owned(),
                "geam_provider_zeta".to_owned(),
            ])
        );
    }
}