Skip to main content

midenc_session/options/
printing.rs

1use alloc::{
2    borrow::Cow,
3    format,
4    string::{String, ToString},
5};
6use core::str::FromStr;
7
8/// ColorChoice represents the color preferences of an end user.
9///
10/// The `Default` implementation for this type will select `Auto`, which tries
11/// to do the right thing based on the current environment.
12///
13/// The `FromStr` implementation for this type converts a lowercase kebab-case
14/// string of the variant name to the corresponding variant. Any other string
15/// results in an error.
16#[derive(Default, Debug, Clone, PartialEq, Eq)]
17pub enum IrFilter {
18    /// Apply to any IR
19    #[default]
20    Any,
21    /// Apply to any operation that implements `Symbol`, optionally restricted with a specific
22    /// string that the name of the symbol must contain
23    Symbol(Option<Cow<'static, str>>),
24    /// Apply to a specific operation, given by its dialect and opcode
25    Op {
26        dialect: midenc_hir_symbol::Symbol,
27        op: midenc_hir_symbol::Symbol,
28    },
29}
30
31impl FromStr for IrFilter {
32    type Err = String;
33
34    fn from_str(s: &str) -> Result<Self, Self::Err> {
35        match s.split_once(':') {
36            Some(("symbol", "" | "*")) => Ok(Self::Symbol(None)),
37            Some(("symbol", pattern)) => Ok(Self::Symbol(Some(pattern.to_string().into()))),
38            Some(("op", name)) => match name.split_once(".") {
39                Some((dialect, op)) => Ok(Self::Op {
40                    dialect: midenc_hir_symbol::Symbol::intern(dialect),
41                    op: midenc_hir_symbol::Symbol::intern(op),
42                }),
43                None => Err(format!(
44                    "invalid operation name '{name}': must be dialect-qualified, e.g. \
45                     `dialect.{name}`"
46                )),
47            },
48            Some((ty, _)) => {
49                Err(format!("unrecognized filter type '{ty}': expected `symbol` or `op`"))
50            }
51            None if s == "any" => Ok(Self::Any),
52            None => Err(format!(
53                "unrecognized filter '{s}': expected `symbol:<pattern|*>`, \
54                 `op:<dialect>.<opcode>`, or `any`"
55            )),
56        }
57    }
58}