r/Compilers • • Oct 25 '26

Patterns

I've been making a programming language for a while now, and just came up with this idea for a feature i'm bout to implement. Patterns.

   pattern P {
    N;
    T(int, int);
    S {
        int x;
        int y;
    };
}
struct MS {
    int x;
}
class C {
    C() {}
    int y;
}
MS fits P(self) {
    N if (self->x == 0);
    T(self->x, -self->x) if (self->x < 10);
    S {
        x: self->x;
        y: 0;
    } if (self->x < 20);
    default N;
}
C fits P(self) {
    default N;
}
int main() {
    C c = C();
    c.y = 0;
    MS ms = {19};
    match (c) {
        P.N => `qout("Worked");
        default => `qout("Failed");
    }
    match (ms) {
        P.S {x, y} => `qout("Worked");
        default => `qout("Failed");
    }
    return 0;
} 

Basically, making user types have the ability to have custom behavior + extraction in match stmts, beyond just enums & integer types

8 Upvotes

33 comments sorted by

View all comments

Show parent comment

3

u/ApprehensivePipe1584 Oct 25 '26

Basically, my `match` only matches on integers & enums, so this allows your own non-enum types to interop with `match`, such as a heap wrapper like this
```
pattern Valid {
Valid(void *);
Invalid;
}
class MyHeapWrapper {
private void *data;
bool isValid() {...}
...
}
MyHeapWrapper fits Valid(heap) {
Valid(heap->data) if (heap.isValid());
default Invalid;
}
```
then you could just
```
match (myheap) {
Valid.Valid(data) => ...handle
Valid.Invalid => ...error
}
```
or like, in a game you could have for example
```
pattern Active {
Active;
Idle;
Off;
}
class Player {
...
}
Player fits Active(p) {
Active if (!p.is_dead);
default Off;
}
```
Which not only avoids neding to for example track a PlayerState enum and manually set it, but also allows for easier encapsulation, etc. And also it allows you to make multiple types of the same pattern, like a physics render that has a global pattern for like physics states and can share matching. Also, it's compiel time only and takes up no data, compared to storing enums. Not sure if theres a difference between it and enums except it has more options for tags (sruct tags), it allows you to avoid storing just a random enum in your class (e.g. for cache line purposes), less public fields, and it providing a shared interface automatically instead of manually setting state and providing like a setEnumState method and nonsense.