Files
sakurac/analyzer/parser/expressions.sakura
T
2026-11-19 04:54:17 -06:00

350 lines
13 KiB
Plaintext

#! @file expressions.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the expression parser, a Pratt parser, which reads each operator
#! by the binding power `token_powers` gives it. Prefix and postfix operators,
#! casts, `is` tests, ternaries, `else` fallbacks, calls, indexes, and members
#! are each parsed here.
module sakura::analyzer;
#! How tightly each operator binds, loosest first. An operator continues an
#! expression only where it binds tighter than what the expression began under.
enum parser::bp : u32 {
none, #! Nothing has begun.
assign, #! `=`, `+=`, and the rest, which group to the right.
fallback, #! `x else y`, which groups to the right.
ternary, #! `c ? a : b`, which groups to the right.
range, #! `a..b` and `a..=b`.
logor, #! `||`
logand, #! `&&`
bitor, #! `|`
bitxor, #! `^`
bitand, #! `&`
equality, #! `==` and `!=`
compare, #! `<`, `<=`, `>`, and `>=`
shift, #! `<<` and `>>`
sum, #! `+` and `-`
product, #! `*`, `/`, and `%`
cast, #! `as` and `is`, after a prefix operator's operand, so `-x as u8` is `(-x) as u8`.
prefix, #! What a prefix operator applies to.
postfix, #! Calls, indexing, members, `++`, and `--`.
}
#! An expression, where struct literals are allowed.
#! @param this The parser.
#! @returns The expression's node, or an `error` node.
def parser::expression(&mut this): u32 {
return this.pratt(parser::bp::none, true);
}
#! The expression of a condition, or of what a `for` loop or `match` takes,
#! where `{` begins the block after it rather than a struct literal.
#! @param this The parser.
#! @returns The expression's node, or an `error` node.
def parser::condition_expr(&mut this): u32 {
return this.pratt(parser::bp::none, false);
}
#! Parses an expression by precedence climbing: an operand, then each operator
#! binding tighter than `min` with what it applies to.
#! @param this The parser.
#! @param min The power an operator must bind tighter than to be taken.
#! @param structs Whether a name followed by `{` is a struct literal, which it
#! is not in conditions, so that `if x {` opens the block. It
#! is passed down rather than kept on the parser, so nothing
#! has to put it back.
#! @returns The expression's node, or an `error` node.
def parser::pratt(&mut this, min: parser::bp, structs: bool): u32 {
return this.error_here() if !this.enter();
var left := this.prefix(structs);
while true {
val power := this.power(left);
break if power as u32 <= min as u32;
left = this.infix(left, power, structs);
}
this.leave();
return left;
}
#! How tightly the current token binds as an operator after `left`, or `none`
#! where it ends the expression.
#! @param this The parser.
#! @param left The operand before the token.
#! @returns The power.
def parser::power(&this, left: u32): parser::bp {
val power := token_powers[this.kind as u64];
# `else =>` is the last arm of a match, not a fallback, and `::<` gives type
# arguments only to what a call gives, as `value_of(d)::<i64>`.
return parser::bp::none if this.check(tk::kw_else) && this.peek(1) == tk::arrow;
# Within type arguments, `>` closes them, and nothing is assigned.
if this.angled {
val kind := this.kind;
return parser::bp::none if kind == tk::more || kind == tk::moreeq || kind == tk::rshift || kind == tk::rshifteq
|| power == parser::bp::assign;
}
return parser::bp::none if this.check(tk::scope) && (this.syntax.node_kinds[left] != nk::call || this.peek(1) != tk::less);
return power;
}
#! An operand: a prefix operator and what it applies to, or a primary.
#! @param this The parser.
#! @param structs Whether a name followed by `{` is a struct literal.
#! @returns The operand's node, or an `error` node.
def parser::prefix(&mut this, structs: bool): u32 {
val token := this.index;
match this.kind {
tk::minus, tk::negate, tk::bitnot, tk::increment, tk::decrement, tk::star => {
this.advance();
return this.make_node(nk::unary, token, this.pratt(parser::bp::prefix, structs));
}
tk::bitand => {
this.advance();
val mutable := this.accept(tk::kw_mut);
val operand := this.pratt(parser::bp::prefix, structs);
return this.make_node(nk::reference, token, operand, parser::bit(mutable, nf::mutable));
}
else => return this.primary(structs);
}
return this.primary(structs);
}
#! The operator at the current token applied to `left`, which binds as tightly
#! as `power`. What follows an operator grouping to the right is parsed under
#! the power just below its own, so another of it continues there.
#! @param this The parser.
#! @param left The operand before the operator.
#! @param power How tightly the operator binds.
#! @param structs Whether a name followed by `{` is a struct literal.
#! @returns The node of the operator applied.
def parser::infix(&mut this, left: u32, power: parser::bp, structs: bool): u32 {
val token := this.index;
match power {
parser::bp::assign => {
this.advance();
return this.make_node(nk::assign, token, left, this.pratt(parser::bp::none, structs));
}
parser::bp::fallback => return this.fallback(left, structs);
parser::bp::ternary => return this.ternary(left, structs);
parser::bp::cast => return this.check(tk::kw_as) ? this.cast_to(left) : this.is_test(left);
parser::bp::postfix => return this.postfix(left);
parser::bp::range => {
this.advance();
return this.make_node(nk::range, token, left, this.pratt(power, structs));
}
else => {
this.advance();
return this.make_node(nk::binary, token, left, this.pratt(power, structs));
}
}
return left;
}
#! `value else fallback`, which takes what a result or a maybe holds, or else
#! what stands in for it: `else (e)` names the error, and a block standing in
#! must leave, where an expression gives the value instead.
#! @param this The parser.
#! @param value The node of the value before `else`.
#! @param structs Whether a name followed by `{` is a struct literal.
#! @returns The `fallback` node.
def parser::fallback(&mut this, value: u32, structs: bool): u32 {
val token := this.index;
this.advance();
# `(e)` names the error only before the block standing in, so `else (x)`
# anywhere else is the value `x`.
var error: u32 = 0;
if this.check(tk::lparen) && this.peek(1) == tk::name && this.peek(2) == tk::rparen && this.peek(3) == tk::lbrace {
this.advance();
error = this.name_node("Expected the name of the error.");
this.advance();
}
val other := this.check(tk::lbrace)
? this.block()
: this.pratt(parser::bp::assign, structs);
return this.make_node(nk::fallback, token, value, this.make_record(error, other));
}
#! `cond ? then : else`. The branch taken where the condition holds ends at
#! `:`, so it may be a fallback, as `ok ? parse(text) else 0 : 1`.
#! @param this The parser.
#! @param condition The condition's node.
#! @param structs Whether a name followed by `{` is a struct literal.
#! @returns The `ternary` node.
def parser::ternary(&mut this, condition: u32, structs: bool): u32 {
val token := this.index;
this.advance();
val then := this.pratt(parser::bp::assign, structs);
this.expect(tk::colon, "Expected `:` between the ternary branches.");
val other := this.pratt(parser::bp::fallback, structs);
return this.make_node(nk::ternary, token, condition, this.make_record(then, other));
}
#! `x as T`.
#! @param this The parser.
#! @param value The node of the value converted.
#! @returns The `cast` node.
def parser::cast_to(&mut this, value: u32): u32 {
val token := this.index;
this.advance();
if this.check(tk::kw_not) {
this.fail(ec::token,
"`not` follows `is`, which it denies; `as` converts a value and has nothing to deny.");
}
this.plain_type = true;
val target := this.type_expr();
return this.make_node(nk::cast, token, value, target);
}
#! `x is T`, `x is not field(value)`, and `x is (d)`.
#! @param this The parser.
#! @param value The node of what is tested.
#! @returns The `is_test` node.
def parser::is_test(&mut this, value: u32): u32 {
val token := this.index;
this.advance();
# `x is not T` denies the test, which saves writing `!(x is T)`.
var flags := parser::bit(this.accept(tk::kw_not), nf::negated);
# `x is (d)` names the field of a union a declaration known while compiling
# describes, as `x is field` would.
if this.accept(tk::lparen) {
val named := this.expression();
this.expect(tk::rparen, "Expected `)` after the declaration naming the field.");
flags |= nf::computed as u32;
return this.make_node(nk::is_test, token, value, this.make_record(named, 0, flags));
}
this.plain_type = true;
val target := this.type_expr();
# `x is field(value)` names what the field holds, as an arm of a match does.
var binding: u32 = 0;
if this.accept(tk::lparen) {
binding = this.binding();
this.expect(tk::rparen, "Expected `)` after the name of the value.");
}
return this.make_node(nk::is_test, token, value, this.make_record(target, binding, flags));
}
#! The name given what a field holds, as `value` of `is field(value)`. `&name`
#! and `&mut name` refer to the field where the union holds it, rather than
#! naming a copy of what it holds.
#! @param this The parser.
#! @returns The `name` or `reference` node, or an `error` node.
def parser::binding(&mut this): u32 {
val detail := "Expected the name to give the value the field holds, as `is field(value)`.";
return this.name_node(detail) if !this.check(tk::bitand);
val token := this.index;
this.advance();
val mutable := this.accept(tk::kw_mut);
return this.make_node(nk::reference, token, this.name_node(detail), parser::bit(mutable, nf::mutable));
}
#! One postfix operator applied to `left`: a call, indexing or slicing, a
#! member, type arguments, `++`, or `--`.
#! @param this The parser.
#! @param left The operand.
#! @returns The node of the operator applied.
def parser::postfix(&mut this, left: u32): u32 {
val token := this.index;
match this.kind {
tk::lparen => {
this.advance();
val args := this.list(parser::item::argument, tk::rparen, "Expected `)` to close the arguments.");
return this.make_node(nk::call, token, left, args);
}
tk::lbracket => return this.subscript(left);
tk::dot => return this.member(left);
tk::scope => {
this.advance();
return this.make_node(nk::type_args, token, left, this.type_args());
}
else => {
this.advance();
return this.make_node(nk::postfix, token, left);
}
}
return left;
}
#! `xs[i]`, or a slice, `xs[a:n]`, either of whose bounds may be left out.
#! @param this The parser.
#! @param object The node of what is indexed.
#! @returns The `index` or `slice` node.
def parser::subscript(&mut this, object: u32): u32 {
val token := this.index;
val angled := this.angled;
this.angled = false;
this.advance();
val start := this.check(tk::colon) ? 0 : this.expression();
if !this.accept(tk::colon) {
this.expect(tk::rbracket, "Expected `]` to close the index.");
this.angled = angled;
return this.make_node(nk::index, token, object, start);
}
val count := this.check(tk::rbracket) ? 0 : this.expression();
this.expect(tk::rbracket, "Expected `]` to close the slice.");
this.angled = angled;
return this.make_node(nk::slice, token, object, this.make_record(start, count));
}
#! `x.name`, `x.name::<T>`, or `x.(d)`, which names the member a declaration
#! known while compiling describes.
#! @param this The parser.
#! @param object The node of the value.
#! @returns The `member` or `member_of` node.
def parser::member(&mut this, object: u32): u32 {
val token := this.index;
this.advance();
if this.accept(tk::lparen) {
val named := this.expression();
this.expect(tk::rparen, "Expected `)` after the declaration naming the member.");
return this.make_node(nk::member_of, token, object, named);
}
if !this.check(tk::name) {
this.fail(ec::ident, "Expected a member name after `.`.");
return object;
}
val name := this.index;
this.advance();
var types: u32 = 0;
if this.at_value_args() {
this.advance();
types = this.type_args();
}
return this.make_node(nk::member, name, object, types);
}
#! An argument of a call. `...xs` spreads a view or a pack into the arguments,
#! and is only an argument.
#! @param this The parser.
#! @returns The argument's node.
def parser::argument(&mut this): u32 {
return this.expression() if !this.check(tk::spread);
val token := this.index;
this.advance();
return this.make_node(nk::unary, token, this.expression());
}