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
use legion::{systems::Runnable, Resources, World};

use crate::{
    codegen, compile,
    hooks::{Continuation, Ctx, Hooks},
    lowering, parse, type_check, BuildContext, FeatureFlags,
};

/// Execute the `rune build` process.
pub fn build(ctx: BuildContext) -> (World, Resources) {
    struct NopHooks;
    impl Hooks for NopHooks {}

    build_with_hooks(ctx, FeatureFlags::production(), &mut NopHooks)
}

/// Execute the `rune build` process, passing in custom [`Hooks`] which will
/// be fired after each phase.
pub fn build_with_hooks(
    ctx: BuildContext,
    features: FeatureFlags,
    hooks: &mut dyn Hooks,
) -> (World, Resources) {
    let mut world = World::default();
    let mut res = Resources::default();

    res.insert(ctx);
    res.insert(features);

    if hooks.before_parse(&mut c(&mut world, &mut res))
        != Continuation::Continue
    {
        return (world, res);
    }

    log::debug!("Beginning the \"parse\" phase");
    parse::phase().run(&mut world, &mut res);

    if hooks.after_parse(&mut c(&mut world, &mut res)) != Continuation::Continue
    {
        return (world, res);
    }

    log::debug!("Beginning the \"lowering\" phase");
    lowering::phase().run(&mut world, &mut res);

    if hooks.after_lowering(&mut c(&mut world, &mut res))
        != Continuation::Continue
    {
        return (world, res);
    }

    log::debug!("Beginning the \"type_check\" phase");
    type_check::phase().run(&mut world, &mut res);

    if hooks.after_type_checking(&mut c(&mut world, &mut res))
        != Continuation::Continue
    {
        return (world, res);
    }

    log::debug!("Beginning the \"codegen\" phase");
    codegen::phase().run(&mut world, &mut res);

    if hooks.after_codegen(&mut c(&mut world, &mut res))
        != Continuation::Continue
    {
        return (world, res);
    }

    compile::phase().run(&mut world, &mut res);

    if hooks.after_compile(&mut c(&mut world, &mut res))
        != Continuation::Continue
    {
        return (world, res);
    }

    (world, res)
}

/// A group of operations which make up a single "phase" in the build process.
pub struct Phase(legion::systems::Builder);

impl Phase {
    pub(crate) fn new() -> Self { Phase(legion::Schedule::builder()) }

    pub(crate) fn with_setup(
        mut setup: impl FnMut(&mut Resources) + 'static,
    ) -> Self {
        let mut phase = Phase::new();
        phase.0.add_thread_local_fn(move |_, res| setup(res));

        phase
    }

    pub(crate) fn and_then<F, R>(mut self, run_system: F) -> Self
    where
        R: legion::systems::ParallelRunnable + 'static,
        F: FnOnce() -> R,
    {
        self.0
            .add_system(TracingRunnable {
                runnable: run_system(),
                name: std::any::type_name::<F>(),
            })
            .flush();

        self
    }

    /// Execute the phase, updating the [`World`].
    pub fn run(&mut self, world: &mut World, resources: &mut Resources) {
        self.0.build().execute(world, resources);
    }
}

/// A wrapper around some [`Runnable`] which logs whenever it starts.
struct TracingRunnable<R> {
    runnable: R,
    name: &'static str,
}

impl<R: Runnable> Runnable for TracingRunnable<R> {
    fn name(&self) -> Option<&legion::systems::SystemId> {
        self.runnable.name()
    }

    fn reads(
        &self,
    ) -> (
        &[legion::systems::ResourceTypeId],
        &[legion::storage::ComponentTypeId],
    ) {
        self.runnable.reads()
    }

    fn writes(
        &self,
    ) -> (
        &[legion::systems::ResourceTypeId],
        &[legion::storage::ComponentTypeId],
    ) {
        self.runnable.writes()
    }

    fn prepare(&mut self, world: &World) { self.runnable.prepare(world); }

    fn accesses_archetypes(&self) -> &legion::world::ArchetypeAccess {
        self.runnable.accesses_archetypes()
    }

    unsafe fn run_unsafe(
        &mut self,
        world: &World,
        resources: &legion::systems::UnsafeResources,
    ) {
        let pretty_name = self
            .name
            .trim_start_matches(env!("CARGO_CRATE_NAME"))
            .trim_end_matches("_system")
            .trim_end_matches("::run")
            .trim_matches(':');
        log::debug!("Starting the \"{}\" pass", pretty_name);

        self.runnable.run_unsafe(world, resources);
    }

    fn command_buffer_mut(
        &mut self,
        world: legion::world::WorldId,
    ) -> Option<&mut legion::systems::CommandBuffer> {
        self.runnable.command_buffer_mut(world)
    }
}

fn c<'world, 'res>(
    world: &'world mut World,
    res: &'res mut Resources,
) -> Ctx<'world, 'res> {
    Ctx { world, res }
}

#[cfg(test)]
#[cfg(never)]
mod tests {
    use indexmap::IndexMap;

    use super::*;

    #[test]
    fn detect_pipeline_cycle() {
        let src = r#"
image: runicos/base
version: 1

pipeline:
  audio:
    proc-block: "hotg-ai/rune#proc_blocks/fft"
    inputs:
    - model
    outputs:
    - type: i16
      dimensions: [16000]

  fft:
    proc-block: "hotg-ai/rune#proc_blocks/fft"
    inputs:
    - audio
    outputs:
    - type: i8
      dimensions: [1960]

  model:
    model: "./model.tflite"
    inputs:
    - fft
    outputs:
    - type: i8
      dimensions: [6]
            "#;
        let doc = Document::parse(src).unwrap();
        let mut diags = Diagnostics::new();

        let _ = crate::analyse(doc, &mut diags);

        assert!(diags.has_errors());
        let errors: Vec<_> = diags
            .iter_severity(codespan_reporting::diagnostic::Severity::Error)
            .collect();
        assert_eq!(errors.len(), 1);
        let diag = errors[0];
        assert_eq!(diag.message, "Cycle detected when checking \"audio\"");
        assert!(diag.notes[0].contains("model"));
        assert!(diag.notes[1].contains("fft"));
        assert_eq!(
            diag.notes[2],
            "... which receives input from \"audio\", completing the cycle."
        );
    }
}