synthphonia/parser/
config.rs1use std::collections::{HashMap, BTreeMap};
2
3use itertools::Itertools;
4use pest::iterators::Pair;
5
6use crate::{expr::Expr, galloc::AllocForCharIter, parser::problem::new_custom_error_span, value::{ConstValue, Value}};
7
8use super::problem::{Error, FunSig, Rule};
9use derive_more::{From, DebugCustom};
10
11#[derive(From, Clone, PartialEq, Eq, Hash, Default)]
12pub struct Config(BTreeMap<String, ConstValue>);
14
15impl Config {
16 pub fn new() -> Self {
18 Config(BTreeMap::new())
19 }
20 pub fn parse(pair: Pair<'_, Rule>) -> Result<Self, Error> {
22 assert!(pair.as_rule() == Rule::config);
23 let span = pair.as_span();
24 let hash: Result<BTreeMap<String, ConstValue>, Error> = pair.into_inner().map(|x| {
25 let [sym, v] : [Pair<'_, Rule>; 2] = x.into_inner().collect_vec().try_into().map_err(|_| new_custom_error_span("Expecting [(key value),*]".into(), span))?;
26 match v.as_rule() {
27 Rule::value => Ok((sym.as_str().into(), ConstValue::parse(v)?)),
28 Rule::symbol => Ok((sym.as_str().into(), ConstValue::Str(v.as_str().chars().galloc_collect_str()))),
29 Rule::expr => Ok((sym.as_str().into(), ConstValue::Expr(Expr::parse(v, None).unwrap()))),
30 _ => panic!(),
31 }
32 }).collect();
33 Ok(hash?.into())
34 }
35 pub fn get_str(&self, name: &str) -> Option<&'static str> {
37 self.0.get(name).and_then(|x| x.as_str())
38 }
39 pub fn get_i64(&self, name: &str) -> Option<i64> {
42 self.0.get(name).and_then(|x| x.as_i64())
43 }
44 pub fn get_usize(&self, name: &str) -> Option<usize> {
46 self.0.get(name).and_then(|x| x.as_usize())
47 }
48 pub fn get_bool(&self, name: &str) -> Option<bool> {
50 self.0.get(name).and_then(|x| x.as_bool())
51 }
52 pub fn get_expr(&self, name: &str) -> Option<&'static Expr> {
54 self.0.get(name).and_then(|x| x.as_expr())
55 }
56 pub fn merge(&mut self, other: Self) {
59 self.0.extend(other.0);
60 }
61}
62
63impl std::fmt::Debug for Config {
64 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67 for (k, v) in self.0.iter() {
68 write!(f, " #{}:{}", k, v)?
69 }
70 Ok(())
71 }
72}
73
74
75
76