Skip to content

Some unsolicited Rust advice #13

@nickdrozd

Description

@nickdrozd

In your validator code, you call unwrap a lot. Specifically, 463 times.

One common case is this:

                Rule {
                    init_config: Config::from_str("0^inf 1 0 0 B> 0").unwrap(),
                    final_config: Config::from_str("0^inf 1^n+1 0 0 B> 0").unwrap(),
                    proof: Proof::Simple(vec![
                        // 0^inf 1 00 B> 0  ->  0^inf 1^n+2 00 B> 0
                        rule_step(2, &[("n", "n")]),
                    ]),
                },

Need to convert hard-coded strings into Config objects. Current method is to use

impl FromStr for Config {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> { /*...*/ }
}

FromStr can fail, so either need to check errors (lol) or unwrap. But these are strings that you have personally written and know to be correct. So error handling is pointless.

What I would suggest doing instead is something like this:

impl From<&str> for Config {
    fn from(s: &str) -> Self { /*...*/ }
}

This will allow for nicer calls:

                Rule {
                    init_config: "0^inf 1 0 0 B> 0".into(),
                    final_config: "0^inf 1^n+1 0 0 B> 0".into(),
                    proof: Proof::Simple(vec![
                        // 0^inf 1 00 B> 0  ->  0^inf 1^n+2 00 B> 0
                        rule_step(2, &[("n", "n")]),
                    ]),
                },

Applies across the board to all these types.

In some cases it could also be nice to specify with macros. For example, Variable::from_str("x").unwrap() could be replaced with a macro like var!("x"). Lots of ways this could be done. Basic idea is to work up a validator specification language that minimizes the involvement of low-level Rust junk (f2("n".parse().unwrap(), "b".parse().unwrap()), etc).

I would be happy to help out if you are interested. ChatGPT is also extremely useful for writing macros. Of course, feel free to ignore all of this :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions