Files
Doughlang/samples/usable.do
John e4c008bd4b doughlang: Expressions in patterns
ast:
- Document operators
- Parameterize Pat with Annotation
- Consolidate Path and Lit into "Value" (Expr)
- Consolidate NamedRecord/Namedtuple into PatOp::TypePrefixed
- Allow Pat<Pat,*> patterns
- Additional helper functions on Expr and Pat

lexer:
- Support inner-doc comment syntax `//!`
  - Cleans up `///` or `//!` prefix

parser:
- Make Parse::Prec `Default`
- Allow expression elision after `..`/`..=`
- Fix Parser::consume not updating elide_do state
- Add token splitting, to make `&&Expr` and `&&Pat` easier
- error: Embed Pat precedence in ParseError
2026-01-05 15:17:22 -05:00

67 lines
2.1 KiB
Plaintext

//! Sample doughlang code
enum Expr {
Atom (f64),
Op (char, [Expr]),
}
fn execute(expr: Expr) -> f64 {
match expr {
Expr::Atom(value) => value,
Expr::Op('*', [lhs, rhs]) => execute(lhs) * execute(rhs),
Expr::Op('/', [lhs, rhs]) => execute(lhs) / execute(rhs),
Expr::Op('%', [lhs, rhs]) => execute(lhs) % execute(rhs),
Expr::Op('+', [lhs, rhs]) => execute(lhs) + execute(rhs),
Expr::Op('-', [lhs, rhs]) => execute(lhs) - execute(rhs),
// Expr::Op('>', [lhs, rhs]) => (execute(lhs) as u64 >> execute(rhs) as u64) as f64,
// Expr::Op('<', [lhs, rhs]) => (execute(lhs) as u64 << execute(rhs) as u64) as f64,
Expr::Op('-', [lhs]) => - execute(lhs),
other => {
panic("Unknown operation: " + fmt(other))
}
}
}
/// Formats an expression to a string
fn fmt_expr(expr: Expr) -> str {
match expr {
Expr::Atom(value) => fmt(value),
Expr::Op(operator, [lhs, rhs]) => fmt('(', fmt_expr(lhs), ' ', operator, ' ', fmt_expr(rhs), ')'),
Expr::Op(operator, [rhs]) => fmt(operator, fmt_expr(rhs)),
_ => println("Unexpected expr: ", expr),
}
}
/// Prints an expression
fn print_expr(expr: Expr) {
println(fmt_expr(expr))
}
/// Parses expressions
fn parse(line: [char], power: i32) -> (Expr, [char]) {
fn map((expr, line): (Expr, [char]), f: fn(Expr) -> Expr) -> (Expr, [char]) {
(f(expr), line)
}
line = space(line);
let (lhs, line) = match line {
['0'..'9', ..] => number(line),
['(', ..rest] => match parse(rest, Power::None) {
(expr, [')', ..rest]) => (expr, rest),
(expr, rest) => panic(fmt("Expected ')', got ", expr, ", ", rest)),
},
[op, ..rest] => parse(rest, pre_bp(op)).map(|lhs| Expr::Op(op, [lhs])),
_ => panic("Unexpected end of input"),
};
while let [op, ..rest] = space(line) {
let (before, after) = inf_bp(op);
if before < power {
break;
};
(lhs, line) = parse(rest, after).map(|rhs| Expr::Op(op, [lhs, rhs]));
};
(lhs, line)
}