Skip to main content

bast3st_eval/evaluation/
process_spec.rs

1use std::fmt::Debug;
2
3use itertools::Itertools;
4use scratch_test_model::{Id, ProjectDoc};
5use tokio::task::JoinError;
6
7use crate::{
8    Features, LogPfx, Messages,
9    evaluation::{
10        Context, Effects, FatalRunError, PCategory, PSpec, ParamData, SelectableSource, WithNotice,
11        initial_block::{InitialBlockAmbiguity, find_initial_block},
12        report::{ReportBuilder, WithSpec},
13        single_evaluation::EvalSignal,
14    },
15    spec::{Bast3StSpec, MapKey, Numeric, PrimitiveValue, RealMapping, RuntimeValue, SpecHooks},
16};
17
18#[derive(Debug, thiserror::Error)]
19pub enum SpecRunError {
20    #[error("join: {_0}")]
21    Join(#[from] JoinError),
22    #[error("run: {_0}")]
23    FatalRun(#[from] WithNotice<FatalRunError>),
24    #[error("initial-block: {_0}")]
25    InitialBlock(#[from] InitialBlockAmbiguity),
26}
27
28fn get_blockcount_map(doc: &ProjectDoc) -> (RealMapping, (RuntimeValue, RealMapping)) {
29    let base_counts = doc.ids_with_opcodes().map(|(_, unit)| unit).counts();
30    let total = RuntimeValue::from(Numeric::Int(
31        base_counts
32            .values()
33            .sum::<usize>()
34            .try_into()
35            .unwrap_or(i64::MAX),
36    ));
37    let by_opcode: RealMapping = base_counts
38        .iter()
39        .map(|(key, count)| {
40            (
41                MapKey::Str(key.to_string().into()),
42                RuntimeValue::Prim(PrimitiveValue::Number(Numeric::Int(
43                    (*count).try_into().unwrap_or(i64::MAX),
44                ))),
45            )
46        })
47        .collect::<RealMapping>()
48        .with_default(Ok(0.into()));
49
50    let blockcount = RealMapping::from_iter(vec![
51        ("total".into(), total.clone()),
52        ("opcode".into(), RuntimeValue::from(by_opcode.clone())),
53    ]);
54    (blockcount, (total, by_opcode))
55}
56
57impl PSpec {
58    pub async fn new<'a, Fallback: SelectableSource + Clone + 'static>(
59        report_builder: ReportBuilder<'a, Fallback, WithSpec>,
60        doc: ProjectDoc,
61        initial_block: Option<Id>,
62    ) -> Result<PSpec, SpecRunError> {
63        let initial_block = initial_block
64            .map(Ok)
65            .unwrap_or_else(|| find_initial_block(&doc).cloned())?;
66        let (ctx, (log_pfx, param_my, fallback, spec)) = report_builder.build(doc, initial_block);
67        Self::inner_new(&ctx, log_pfx, spec, param_my, fallback).await
68    }
69
70    async fn inner_new<Fallback: SelectableSource + Clone + 'static>(
71        ctx: &Context,
72        log_pfx: impl Into<LogPfx>,
73        spec: &Bast3StSpec,
74        param_my: Option<impl Into<RealMapping>>,
75        fallback: Fallback,
76    ) -> Result<PSpec, SpecRunError> {
77        let log_pfx = log_pfx.into();
78        let (blockcount, _) = get_blockcount_map(ctx.doc());
79        let doc =
80            RealMapping::from_iter(vec![("blockcount".into(), RuntimeValue::from(blockcount))]);
81        let all =
82            RealMapping::from_iter(vec![("doc".into(), doc.into())].into_iter().chain(
83                param_my.map(|param_my| ("my".into(), RuntimeValue::from(param_my.into()))),
84            ));
85
86        let stats = ParamData::from(all);
87        Self::new_with_effects(ctx, log_pfx, spec, (stats, fallback)).await
88    }
89
90    async fn new_with_effects<Fallback: SelectableSource + Clone + 'static>(
91        ctx: &Context,
92        log_pfx: LogPfx,
93        spec: &Bast3StSpec,
94        fallback: Fallback,
95    ) -> Result<PSpec, SpecRunError> {
96        let mut categories = vec![];
97        let mut eft = Effects::default();
98
99        let (before_all_categories, sig) = spec
100            .hooks()
101            .before_all_categories()
102            .run_all(
103                ctx,
104                log_pfx.join("before-all-cat"),
105                &mut eft,
106                Features::PermittedFEAT_SpecHook,
107                &fallback,
108            )
109            .await;
110        match sig {
111            Some(EvalSignal::EndTest(_)) | None => {} // not relevant
112        }
113
114        // take "current"-level messages for spec, don't move this line
115        let mut messages: Messages<Bast3StSpec> = eft.take_messages();
116        {
117            let mut cat_futures = vec![];
118            {
119                let frozen_effects = std::sync::Arc::new(eft.clone());
120                let log_pfx = log_pfx.join("cat");
121                for (index, cat) in spec.categories().iter().enumerate() {
122                    let cat = cat.clone();
123                    let source = (frozen_effects.clone(), fallback.clone());
124                    let ctx = ctx.clone();
125                    let log_pfx = log_pfx.join(index);
126                    cat_futures.push(tokio::spawn(async move {
127                        PCategory::new(&ctx, log_pfx, &cat, source).await
128                    }));
129                }
130            }
131            for cat_future in cat_futures {
132                let (cat, cat_effects) = cat_future.await??.into_parts();
133                eft.append(cat_effects);
134                categories.push(cat);
135            }
136        }
137
138        let (after_all_categories, sig) = spec
139            .hooks()
140            .after_all_categories()
141            .run_all(
142                ctx,
143                log_pfx.join("after-all-cat"),
144                &mut eft,
145                Features::PermittedFEAT_SpecHook,
146                fallback,
147            )
148            .await;
149        match sig {
150            Some(EvalSignal::EndTest(_)) | None => {} // not relevant
151        }
152        messages.extend(eft.take_messages());
153
154        let (flags, notice) = eft.take_rest();
155        Ok(PSpec {
156            title: spec.title().clone().into(),
157            description: spec.description().clone().map(|x| x.into()),
158            messages,
159            categories,
160            hooks: SpecHooks {
161                before_all_categories,
162                after_all_categories,
163            },
164            flags,
165            notice,
166        })
167    }
168}