1use std::marker::PhantomData;
10use std::path::Path;
11use std::sync::{Arc, OnceLock};
12
13use lensbench_core::{Error, Result, System};
14use schemars::JsonSchema;
15use serde::de::DeserializeOwned;
16use serde::Serialize;
17use serde_json::{Map, Value};
18
19#[derive(Debug, Clone, Copy)]
21pub struct Meta {
22 pub name: &'static str,
24 pub about: &'static str,
26 pub help: &'static str,
28}
29
30pub struct Cx<'a> {
32 pub system: &'a System,
34 pub source: Option<&'a dyn Source>,
36}
37
38impl<'a> Cx<'a> {
39 pub fn new(system: &'a System) -> Cx<'a> {
41 Cx {
42 system,
43 source: None,
44 }
45 }
46
47 pub fn source(&self) -> Result<&'a dyn Source> {
49 self.source.ok_or_else(|| {
50 Error::Invalid("this analysis needs the system file (how to read it)".into())
51 })
52 }
53}
54
55#[derive(Debug, Clone, Default)]
57pub struct Variant {
58 pub beam: Option<String>,
60 pub wavelengths: Option<Vec<f64>>,
62}
63
64pub trait Source {
66 fn is_project(&self) -> bool;
68 fn states(&self) -> Result<Vec<String>>;
70 fn beams(&self) -> Result<Vec<String>> {
72 Ok(Vec::new())
73 }
74 fn state(&self) -> Option<String>;
76 fn paths(&self) -> Result<Vec<String>>;
78 fn path(&self) -> Option<String>;
80 fn load(&self, v: &Variant, notes: &mut Vec<String>) -> Result<System>;
82 fn variant(&self, beam: &str, notes: &mut Vec<String>) -> Result<System> {
84 self.load(
85 &Variant {
86 beam: Some(beam.to_string()),
87 ..Default::default()
88 },
89 notes,
90 )
91 }
92 fn project_text(&self) -> Result<Option<String>>;
94 fn system_hash(&self, s: &System) -> Result<String>;
96}
97
98pub trait Analysis: Send + Sync + 'static {
100 type Params: DeserializeOwned + Serialize + JsonSchema + Default;
102 type Output: Serialize + JsonSchema + Send + Sync + 'static;
104 fn meta(&self) -> Meta;
105 fn run(&self, cx: &Cx<'_>, p: &Self::Params) -> Result<Self::Output>;
106 fn save(&self, _out: &Self::Output, _path: &Path) -> Option<Result<Saved>> {
108 None
109 }
110 fn run_to_file(&self, _cx: &Cx<'_>, _p: &Self::Params, _path: &Path) -> Option<Result<Saved>> {
113 None
114 }
115}
116
117pub enum Saved {
119 Json(Value),
121 Written(Value),
123}
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum ParamTy {
128 Count,
130 Int,
132 Num,
134 Flag,
136 Str,
138 Choice,
140 Nums,
142 Path,
144 Paths,
146 Json,
148}
149
150impl ParamTy {
151 pub fn as_str(self) -> &'static str {
153 match self {
154 ParamTy::Count => "count",
155 ParamTy::Int => "int",
156 ParamTy::Num => "num",
157 ParamTy::Flag => "flag",
158 ParamTy::Str => "str",
159 ParamTy::Choice => "choice",
160 ParamTy::Nums => "nums",
161 ParamTy::Path => "path",
162 ParamTy::Paths => "path",
163 ParamTy::Json => "json",
164 }
165 }
166}
167
168#[derive(Debug, Clone)]
170pub struct Param {
171 pub name: String,
173 pub ty: ParamTy,
174 pub default: Value,
176 pub optional: bool,
178 pub doc: String,
180 pub unit: String,
182 pub choices: Vec<String>,
184 pub min: Option<f64>,
186 pub len: Option<usize>,
188 pub write: bool,
190}
191
192impl Param {
193 pub fn required(&self) -> bool {
195 self.ty == ParamTy::Nums && !self.optional && self.default == Value::Array(Vec::new())
196 }
197
198 pub fn to_json(&self) -> Value {
200 let mut o = Map::new();
201 o.insert("name".into(), Value::from(self.name.clone()));
202 o.insert("type".into(), Value::from(self.ty.as_str()));
203 o.insert("default".into(), self.default.clone());
204 o.insert("unit".into(), Value::from(self.unit.clone()));
205 o.insert("doc".into(), Value::from(self.doc.clone()));
206 if !self.choices.is_empty() {
207 o.insert("choices".into(), Value::from(self.choices.clone()));
208 }
209 if let Some(n) = self.len {
210 o.insert("len".into(), Value::from(n));
211 }
212 if let Some(m) = self.min {
213 o.insert("min".into(), Value::from(m));
214 }
215 if self.ty == ParamTy::Paths {
216 o.insert("repeat".into(), Value::Bool(true));
217 }
218 if self.required() {
219 o.insert("required".into(), Value::Bool(true));
220 }
221 Value::Object(o)
222 }
223}
224
225pub trait DynAnalysis: Send + Sync {
227 fn meta(&self) -> Meta;
228 fn params_schema(&self) -> Value;
230 fn output_schema(&self) -> Value;
232 fn params(&self) -> Vec<Param>;
234 fn check_params(&self, params: &Value) -> Result<()>;
236 fn run_json(&self, cx: &Cx<'_>, params: &Value) -> Result<Value> {
238 Ok(self.run_save(cx, params, None)?.0)
239 }
240 fn run_save(
243 &self,
244 cx: &Cx<'_>,
245 params: &Value,
246 save: Option<&Path>,
247 ) -> Result<(Value, Option<Value>)>;
248 fn run_typed(&self, cx: &Cx<'_>, params: &Value) -> Result<Typed> {
251 Ok(Typed::json(self.meta().name, self.run_json(cx, params)?))
252 }
253}
254
255#[derive(Clone)]
259pub struct Typed {
260 name: &'static str,
261 value: Arc<dyn std::any::Any + Send + Sync>,
262 json: fn(&(dyn std::any::Any + Send + Sync), &str) -> Result<Value>,
263}
264
265impl Typed {
266 pub fn new<T: Serialize + Send + Sync + 'static>(name: &'static str, v: T) -> Typed {
268 Typed {
269 name,
270 value: Arc::new(v),
271 json: |x, name| {
272 let v = x
273 .downcast_ref::<T>()
274 .expect("the value has the type it was made with");
275 serde_json::to_value(v)
276 .map_err(|e| Error::Invalid(format!("results of {name}: {e}")))
277 },
278 }
279 }
280
281 pub fn json(name: &'static str, v: Value) -> Typed {
283 Typed::new(name, v)
284 }
285
286 pub fn name(&self) -> &'static str {
288 self.name
289 }
290
291 pub fn get<T: 'static>(&self) -> Option<&T> {
293 self.value.downcast_ref::<T>()
294 }
295
296 pub fn get_arc<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
298 self.value.clone().downcast::<T>().ok()
299 }
300
301 pub fn to_json(&self) -> Result<Value> {
303 (self.json)(&*self.value, self.name)
304 }
305}
306
307impl std::fmt::Debug for Typed {
308 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
309 f.debug_struct("Typed")
310 .field("name", &self.name)
311 .finish_non_exhaustive()
312 }
313}
314
315impl PartialEq for Typed {
317 fn eq(&self, o: &Typed) -> bool {
318 self.name == o.name
319 && (Arc::ptr_eq(&self.value, &o.value)
320 || matches!((self.to_json(), o.to_json()), (Ok(a), Ok(b)) if a == b))
321 }
322}
323
324struct Erased<A: Analysis>(A, PhantomData<fn() -> A>);
325
326impl<A: Analysis> Erased<A> {
327 fn parse(&self, params: &Value) -> Result<A::Params> {
328 match params {
329 Value::Null => Ok(A::Params::default()),
330 v => serde_json::from_value(v.clone())
331 .map_err(|e| Error::Invalid(format!("settings of {}: {e}", self.0.meta().name))),
332 }
333 }
334}
335
336fn schema_of<T: JsonSchema>() -> Value {
337 let g = schemars::generate::SchemaSettings::draft2020_12()
338 .with(|s| s.inline_subschemas = true)
339 .into_generator();
340 g.into_root_schema_for::<T>().to_value()
341}
342
343impl<A: Analysis> DynAnalysis for Erased<A> {
344 fn meta(&self) -> Meta {
345 self.0.meta()
346 }
347 fn params_schema(&self) -> Value {
348 schema_of::<A::Params>()
349 }
350 fn output_schema(&self) -> Value {
351 schema_of::<A::Output>()
352 }
353 fn params(&self) -> Vec<Param> {
354 let defaults = serde_json::to_value(A::Params::default()).unwrap_or(Value::Null);
355 params_of(&self.params_schema(), &defaults)
356 }
357 fn check_params(&self, params: &Value) -> Result<()> {
358 self.parse(params).map(|_| ())
359 }
360 fn run_typed(&self, cx: &Cx<'_>, params: &Value) -> Result<Typed> {
361 let p = self.parse(params)?;
362 Ok(Typed::new(self.0.meta().name, self.0.run(cx, &p)?))
363 }
364 fn run_save(
365 &self,
366 cx: &Cx<'_>,
367 params: &Value,
368 save: Option<&Path>,
369 ) -> Result<(Value, Option<Value>)> {
370 let p = self.parse(params)?;
371 if let Some(path) = save {
372 match self.0.run_to_file(cx, &p, path).transpose()? {
373 Some(Saved::Written(v)) => return Ok((v, None)),
374 Some(Saved::Json(v)) => {
375 let mut r = v.clone();
376 r["written"] = Value::from(path.display().to_string());
377 return Ok((r, Some(v)));
378 }
379 None => {}
380 }
381 }
382 let out = self.0.run(cx, &p)?;
383 let json = |o: &A::Output| {
384 serde_json::to_value(o)
385 .map_err(|e| Error::Invalid(format!("results of {}: {e}", self.0.meta().name)))
386 };
387 match save {
388 None => Ok((json(&out)?, None)),
389 Some(path) => match self.0.save(&out, path).transpose()? {
390 Some(Saved::Written(v)) => Ok((v, None)),
391 Some(Saved::Json(v)) => {
392 let mut r = v.clone();
393 r["written"] = Value::from(path.display().to_string());
394 Ok((r, Some(v)))
395 }
396 None => {
397 let v = json(&out)?;
398 Ok((v.clone(), Some(v)))
399 }
400 },
401 }
402 }
403}
404
405fn types(s: &Value) -> Vec<&str> {
407 match s.get("type") {
408 Some(Value::String(t)) => vec![t.as_str()],
409 Some(Value::Array(a)) => a
410 .iter()
411 .filter_map(Value::as_str)
412 .filter(|t| *t != "null")
413 .collect(),
414 _ => Vec::new(),
415 }
416}
417
418fn nullable(s: &Value) -> bool {
419 let in_type = match s.get("type") {
420 Some(Value::Array(a)) => a.iter().any(|t| t == "null"),
421 _ => false,
422 };
423 let null = Value::from("null");
424 in_type
425 || s.get("anyOf")
426 .and_then(Value::as_array)
427 .is_some_and(|a| a.iter().any(|x| x.get("type") == Some(&null)))
428}
429
430fn choices(s: &Value) -> Vec<String> {
432 if let Some(Value::Array(e)) = s.get("enum") {
433 return e
434 .iter()
435 .filter_map(Value::as_str)
436 .map(String::from)
437 .collect();
438 }
439 for k in ["oneOf", "anyOf"] {
440 if let Some(Value::Array(a)) = s.get(k) {
441 let c: Vec<String> = a
442 .iter()
443 .flat_map(|x| {
444 x.get("const")
445 .and_then(Value::as_str)
446 .map(|c| vec![c.to_string()])
447 .unwrap_or_else(|| choices(x))
448 })
449 .collect();
450 if !c.is_empty() {
451 return c;
452 }
453 }
454 }
455 Vec::new()
456}
457
458pub fn params_of(schema: &Value, defaults: &Value) -> Vec<Param> {
460 let Some(Value::Object(props)) = schema.get("properties") else {
461 return Vec::new();
462 };
463 props
464 .iter()
465 .map(|(name, s)| {
466 let t = types(s);
467 let ch = choices(s);
468 let ext = |k: &str| s.get(k).and_then(Value::as_str).unwrap_or("").to_string();
469 let item_ty = s.get("items").map(types).unwrap_or_default();
470 let ty = if ext("x-kind") == "json" {
471 ParamTy::Json
472 } else if ext("x-kind") == "path" {
473 if t.contains(&"array") {
474 ParamTy::Paths
475 } else {
476 ParamTy::Path
477 }
478 } else if !ch.is_empty() {
479 ParamTy::Choice
480 } else if t.contains(&"boolean") {
481 ParamTy::Flag
482 } else if t.contains(&"integer") {
483 if s.get("minimum")
484 .and_then(Value::as_f64)
485 .is_some_and(|m| m >= 0.0)
486 {
487 ParamTy::Count
488 } else {
489 ParamTy::Int
490 }
491 } else if t.contains(&"number") {
492 ParamTy::Num
493 } else if t.contains(&"array")
494 && item_ty.iter().any(|x| *x == "number" || *x == "integer")
495 {
496 ParamTy::Nums
497 } else {
498 ParamTy::Str
499 };
500 let len = match (s.get("minItems"), s.get("maxItems")) {
501 (Some(a), Some(b)) if a == b => a.as_u64().map(|n| n as usize),
502 _ => None,
503 };
504 let min = s.get("x-min").and_then(Value::as_f64);
506 Param {
507 name: name.clone(),
508 ty,
509 default: defaults.get(name).cloned().unwrap_or(Value::Null),
510 optional: nullable(s),
511 doc: ext("description"),
512 unit: ext("x-unit"),
513 choices: ch,
514 min,
515 len,
516 write: s.get("x-write").and_then(Value::as_bool).unwrap_or(false),
517 }
518 })
519 .collect()
520}
521
522#[derive(Clone, Default)]
524pub struct Analyses {
525 list: Vec<Arc<dyn DynAnalysis>>,
526}
527
528impl Analyses {
529 pub fn builtin() -> &'static Analyses {
531 static B: OnceLock<Analyses> = OnceLock::new();
532 B.get_or_init(|| {
533 let mut a = Analyses::default();
534 crate::defs::register(&mut a);
535 a
536 })
537 }
538
539 pub fn add<A: Analysis>(&mut self, a: A) {
541 let name = a.meta().name;
542 self.list.retain(|x| x.meta().name != name);
543 self.list.push(Arc::new(Erased(a, PhantomData)));
544 }
545
546 pub fn add_dyn(&mut self, a: Arc<dyn DynAnalysis>) {
548 let name = a.meta().name;
549 self.list.retain(|x| x.meta().name != name);
550 self.list.push(a);
551 }
552
553 pub fn get(&self, name: &str) -> Option<&Arc<dyn DynAnalysis>> {
554 self.list.iter().find(|a| a.meta().name == name)
555 }
556
557 pub fn iter(&self) -> impl Iterator<Item = &Arc<dyn DynAnalysis>> {
558 self.list.iter()
559 }
560}