SeaOfNodes / Simple

A Simple showcase for the Sea-of-Nodes compiler IR
Apache License 2.0
397 stars 30 forks source link

pattern match with exhaust #143

Closed andypeng2015 closed 1 day ago

andypeng2015 commented 4 days ago

Hi, thanks for the effort to showcase the power of SoN IR, really appreciate it.

May I ask if a demo of pattern match with exhaust can be done in SoN IR? Thanks

cliffclick commented 2 days ago

I'm not sure what "pattern match with exhaust" is!? Certainly C2/HotSpot uses SoN IR, and certainly C2 compiles all of Java, including the Pattern & Match classes.

andypeng2015 commented 2 days ago

Sorry, I am talking about how to check if one of the branches is redundant in the match expression.

For example, in the following match expression in Rust, here we see the 4th pattern is redundant with the 1st, that branch will get an "unreachable" warning.

// x: (bool, Option<Foo>)
match x {
    (true, _) => {} // 1
    (false, Some(Foo::Bar)) => {} // 2
    (false, Some(_)) => {} // 3
    (true, None) => {} // 4
}

understood that in Java, we can implement switch with default, just wondering how to check branch redundancy in swith in SoN IR without default

void checkResult(Result result){                                     
    return switch (result) {                                                          
        case Success s -> System.out.println("ok");                                                
        case Failure f -> System.out.println("not ok");                                               
        default -> throw new IllegalArgumentException("Unexpected Input: " + result); 
    };                                                                                
}
thaliaarchi commented 1 day ago

@yorickpeterse wrote about implementing pattern matching in https://github.com/yorickpeterse/pattern-matching-in-rust after surveying the literature. It's currently used by Inko and Gleam, so you can also look there (both extend it in various ways).

Pattern matching and exhaustiveness analysis are orthogonal to Sea of Nodes, so I doubt they'd be added to Simple. Matches are lowered to a decision tree of ifs and bindings and the codegen doesn't require the analysis.

cliffclick commented 1 day ago

Yeah @thaliaarchi has it right, mostly orthogonal. Some simple patterns can be picked up by the type system "for free", in that they'd just happen without doing anything special. But past simple patterns... I'd do a custom analysis in both Simple and e.g. GCC

cliffclick commented 1 day ago

Closing as an issue, although happen to have more discussion.