r/Compilers • u/ApprehensivePipe1584 • 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
View all comments
Show parent comment
1
u/ApprehensivePipe1584 Oct 29 '26
I don't find it too hard to read. everything in main is just normal C/C++ style syntax plus rust-style match, Patterns are just defining names like an enum + struct style tags, and fits statements are literally just
thing if (cond);
like math. you just put the name of the parameter that is being checked (self in these cases) which is a pointer to the type (MS*/C*) then you just do normal conditions. its like inline if statements. thing if cond, like cases blocks in math, which is a big left brace then value if thing,...
such as:
⎧ 1, if x > 0
f(x) = ⎨ 0, if x = 0
⎩ -1, if x < 0