Files
2026-11-19 04:54:17 -06:00

628 lines
24 KiB
Plaintext

#! @file types.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the parsing of types: names and paths with their type arguments,
#! references, arrays, `type_of`, and the type parameters of declarations.
module sakura::analyzer;
#! What may follow the segments of a path as type arguments.
enum parser::args {
plain, #! Nothing, as in imports.
types, #! Type arguments after `<`, as in `box<i64>`.
values, #! Type arguments after `::<`, as in `box::<i64>`.
}
#! A type, as `&mut T`, `*u8`, `T[4]`, `def(T): U`, or `std::list<T>`, which
#! is also what follows `as` and `is`, so `x as i32 | y` remains a bitwise or.
#! @param this The parser.
#! @returns The type's node, or an `error` node.
def parser::type_expr(&mut this): u32 {
return this.error_here() if !this.enter();
# What `as` and `is` take goes on with the expression's `?`, not a type's.
val chooses := !this.plain_type;
this.plain_type = false;
val argument := this.type_argument;
this.type_argument = false;
# `C ? A : B` chooses by a constant: a name or a path, which `!` may deny, a
# call, or an expression in parentheses, as `(N > 4) ? A : B`.
var condition: u32 = 0;
var made: u32 = 0;
if chooses && this.check(tk::negate) {
val token := this.index;
this.advance();
condition = this.make_node(nk::unary, token, this.condition_name(this.type_name()));
if !this.check(tk::quest) {
this.fail(ec::token, "Expected `?`: a type is chosen by a constant, as `!MUTABLE ? &T : &mut T`.");
}
made = condition;
} else if chooses && this.check(tk::lparen) && this.chooses_type(0) {
val angled := this.angled;
this.angled = false;
condition = this.pratt(parser::bp::ternary, true);
this.angled = angled;
made = condition;
} else if chooses && this.check(tk::name) && this.call_chooses_type() {
# A call is a condition too, as `small(N) ? A : B`.
val angled := this.angled;
this.angled = false;
condition = this.pratt(parser::bp::ternary, true);
this.angled = angled;
made = condition;
} else if this.check(tk::star) || this.check(tk::bitand) {
val kind := this.check(tk::star) ? nk::type_ptr : nk::type_ref;
val token := this.index;
this.advance();
val mutable := this.accept(tk::kw_mut);
# What `as` and `is` take stays plain within it, as `x as *T != null`.
this.plain_type = !chooses;
made = this.make_node(kind, token, this.type_expr(), parser::bit(mutable, nf::mutable));
} else {
made = this.type_postfix();
if chooses && this.check(tk::quest) && this.syntax.node_kinds[made] == nk::type_name && parser::begins_type(this.peek(1)) {
condition = this.condition_name(made);
} else if chooses && this.syntax.node_kinds[made] == nk::type_name && parser::continues_condition(this.kind)
&& (!argument || this.condition_chooses_type()) {
# A test of a type is a condition too, as `T is reference ? T::target : T`,
# and so is a name compared, as `N == 4`, or joined, as `M && N == 4`.
condition = this.condition_after(this.condition_name(made));
if !this.check(tk::quest) {
this.fail(ec::token, "Expected `?`: a condition chooses a type, as `T is reference ? T::target : T`.");
}
made = condition;
}
}
if condition != 0 && this.check(tk::quest) {
made = this.type_cond(condition);
}
this.leave();
return made;
}
#! `C ? A : B`, from the `?`: the type `A` where the constant `C` holds, and `B`
#! where it does not, as `MUTABLE ? &mut T : &T`.
#! @param this The parser.
#! @param condition The condition's node.
#! @returns The `type_cond` node.
def parser::type_cond(&mut this, condition: u32): u32 {
val token := this.index;
this.advance();
val then := this.type_expr();
this.expect(tk::colon, "Expected `:` between the types `?` chooses from, as `MUTABLE ? &mut T : &T`.");
val other := this.type_expr();
return this.make_node(nk::type_cond, token, condition, this.make_record(then, other));
}
#! A name read as a type that is a type's condition instead, as `MUTABLE` of
#! `MUTABLE ? &mut T : &T`: the name or path of a constant, as an expression.
#! @param this The parser.
#! @param made The `type_name` node.
#! @returns The node, now a `name` or `path`.
def parser::condition_name(&mut this, made: u32): u32 {
if this.syntax.node_kinds[made] == nk::type_name {
this.syntax.node_kinds[made] = this.syntax.node_lefts[made] == 0 ? nk::name : nk::path;
}
return made;
}
#! The rest of a condition a type is chosen by that begins with a name read as
#! a type, as `T is pointer && T::target is integer` of `T is pointer &&
#! T::target is integer ? T::target : u8`: what operators follow it, up to its
#! `?`.
#! @param this The parser.
#! @param left The name's node, now a `name` or `path`.
#! @returns The condition's node.
def parser::condition_after(&mut this, left: u32): u32 {
val angled := this.angled;
this.angled = false;
var made := left;
while true {
val power := this.power(made);
break if power as u32 <= parser::bp::ternary as u32;
made = this.infix(made, power, true);
}
this.angled = angled;
return made;
}
#! Whether a token after a name read as a type goes on with a condition a
#! type is chosen by, which nothing a type is goes on with: `is`, `==`, `!=`,
#! `&&`, or `||`. A comparison by `<` or `>` is written in parentheses, as
#! `(N > 4) ? A : B`, since those are a type's arguments.
#! @param kind The token's kind.
#! @returns Whether it does.
def parser::continues_condition(kind: tk): bool {
return kind == tk::kw_is || kind == tk::equals || kind == tk::noteq || kind == tk::logand || kind == tk::logor;
}
#! Whether what follows a name read as a type among type arguments goes on
#! with a condition a type is chosen by, up to a `?` a type follows, as `is
#! reference ? T::target : T`, where `T is integer ? 4 : 8` is a constant. The
#! condition compares by no `<` or `>`, so those are brackets.
#! @param this The parser.
#! @returns Whether it does.
def parser::condition_chooses_type(&this): bool {
var depth: u32 = 0;
var ahead: u32 = 0;
while ahead < 1024 {
val kind := this.peek(ahead);
return false if kind == tk::eof || kind == tk::semicolon || kind == tk::lbrace || kind == tk::rbrace;
if kind == tk::lparen || kind == tk::lbracket || kind == tk::less {
depth++;
} else if kind == tk::rparen || kind == tk::rbracket || kind == tk::more {
return false if depth == 0;
depth--;
} else if kind == tk::rshift {
return false if depth < 2;
depth -= 2;
} else if depth == 0 && (kind == tk::comma || kind == tk::assign) {
return false;
} else if depth == 0 && kind == tk::quest {
return parser::begins_type(this.peek(ahead + 1));
}
ahead++;
}
return false;
}
#! Whether a token begins a type, so a `?` before it chooses between types.
#! @param kind The token's kind.
#! @returns Whether it does.
def parser::begins_type(kind: tk): bool {
return kind == tk::name || kind == tk::star || kind == tk::bitand || kind == tk::kw_def
|| kind == tk::lparen || kind == tk::kw_match || kind == tk::negate;
}
#! Whether what begins with the `(` a number of tokens ahead is the condition
#! a type is chosen by: a `?` a type follows comes after it, outside any
#! parentheses, before anything ends a type, as `(N > 4) ? A : B`, where `(N >
#! 4) ? 8 : 4` is a value. The condition may go on past it, as `(A || B) && (C
#! || D) ? X : Y`, or `small(N) && M ? A : B` from a call's `(`, but compares by
#! `<` or `>` only within parentheses, since `>` ends type arguments.
#! @param this The parser.
#! @param start How many tokens ahead the `(` is.
#! @returns Whether it does.
def parser::chooses_type(&this, start: u32): bool {
var depth: u32 = 0;
var ahead := start;
while ahead < start + 1024 {
val kind := this.peek(ahead);
return false if kind == tk::eof || kind == tk::semicolon || kind == tk::lbrace || kind == tk::rbrace;
if kind == tk::lparen {
depth++;
} else if kind == tk::rparen {
return false if depth == 0;
depth--;
} else if depth == 0 {
return parser::begins_type(this.peek(ahead + 1)) if kind == tk::quest;
return false if kind == tk::comma || kind == tk::assign || kind == tk::colon || kind == tk::more
|| kind == tk::moreeq || kind == tk::rshift || kind == tk::arrow || kind == tk::rbracket;
}
ahead++;
}
return false;
}
#! Whether the name at the current token begins a call that is the condition
#! a type is chosen by, or begins it, as `small(N) ? u32 : u64`: a name or a
#! path, which may give type arguments after `::<`, then its arguments in
#! parentheses, as `chooses_type` reads them.
#! @param this The parser.
#! @returns Whether it does.
def parser::call_chooses_type(&this): bool {
var ahead: u32 = 1;
while this.peek(ahead) == tk::scope {
if this.peek(ahead + 1) == tk::name {
ahead += 2;
continue;
}
return false if this.peek(ahead + 1) != tk::less;
ahead += 2;
var depth: u32 = 1;
while depth != 0 && ahead < 256 {
val kind := this.peek(ahead);
return false if kind == tk::eof || kind == tk::semicolon || kind == tk::lbrace || kind == tk::rbrace;
if kind == tk::less {
depth++;
} else if kind == tk::more {
depth--;
} else if kind == tk::rshift {
return false if depth < 2;
depth -= 2;
}
ahead++;
}
}
return this.peek(ahead) == tk::lparen && this.chooses_type(ahead);
}
#! A type followed by the lengths of fixed arrays of it, as `T[4][2]`, or a
#! pack followed by the index of one of its types, as `Ts...[0]`, a `type_fixed`
#! node whose token is the `...`.
#! @param this The parser.
#! @returns The type's node, a `type_fixed` node where lengths follow.
def parser::type_postfix(&mut this): u32 {
var made := this.type_primary();
while this.check(tk::lbracket) || (this.check(tk::spread) && this.peek(1) == tk::lbracket) {
val token := this.index;
if this.check(tk::spread) {
this.advance();
this.advance();
val index := this.expression();
this.expect(tk::rbracket, "Expected `]` after the index of the pack's type.");
made = this.make_node(nk::type_fixed, token, made, index);
continue;
}
this.advance();
if this.check(tk::rbracket) {
this.report(ec::token,
"Expected the number of elements, as `T[4]`: a run of elements whose number is not known is a `std::list<T>`, and a view of one a `slice<T>`.");
}
val length := this.expression();
this.expect(tk::rbracket, "Expected `]` after the number of elements.");
made = this.make_node(nk::type_fixed, token, made, length);
}
return made;
}
#! A type that `...` may follow: a function type's last parameter, which takes
#! any number of arguments, as `def(i64...): i64`, or is a pack, as `def(Ts...):
#! R`, and a pack passed on among type arguments, as `box<i64, Ts...>`.
#! @param this The parser.
#! @returns The type's node, or a `type_spread` of it.
def parser::spread_type(&mut this): u32 {
val made := this.type_expr();
return made if !this.check(tk::spread);
val token := this.index;
this.advance();
return this.make_node(nk::type_spread, token, made);
}
def parser::type_primary(&mut this): u32 {
# A function type, as `def(int, str): bool`, whose result takes everything
# after it.
if this.check(tk::kw_def) {
val token := this.index;
this.advance();
this.expect(tk::lparen, "Expected `(` to begin the parameter types.");
val params := this.list(parser::item::param_type, tk::rparen, "Expected `)` to close the parameter types.");
this.expect(tk::colon, "Expected `:` followed by the return type.");
return this.make_node(nk::type_func, token, params, this.type_expr());
}
if this.accept(tk::lparen) {
val made := this.type_expr();
this.expect(tk::rparen, "Expected `)` to close the type.");
return made;
}
# `match const T { pointer => T::target, else => T }` is the type its first arm
# whose trait or type `T` fits gives.
if this.check(tk::kw_match) {
val token := this.index;
this.advance();
this.expect(tk::kw_const, "Expected `const` after `match`: a type is chosen by `match const T { ... }`.");
val subject := this.type_expr();
if !this.accept(tk::lbrace) {
this.fail(ec::token, "Expected `{` to begin the arms of the match.");
return this.make_node(nk::type_match, token, subject);
}
val arms := this.list(parser::item::type_arm, tk::rbrace, "Expected `,` between the arms, or `}` to close the match.");
return this.make_node(nk::type_match, token, subject, arms);
}
# `type_of(d)` is the type of what a declaration known while compiling declares.
if this.check_word(names::type_of_id) && this.peek(1) == tk::lparen {
val token := this.index;
this.advance();
this.advance();
val declaration := this.expression();
this.expect(tk::rparen, "Expected `)` after the declaration whose type it is.");
return this.make_node(nk::type_of, token, declaration);
}
return this.type_name();
}
#! A named type, as `std::list<T>`, made of its segments. One of a single
#! segment without type arguments, as `u8`, holds no run: its token names it.
#! @param this The parser.
#! @returns The `type_name` node.
def parser::type_name(&mut this): u32 {
if !this.check(tk::name) {
this.fail(ec::kind, "Expected a type name.");
return this.error_here();
}
val token := this.index;
if this.peek(1) != tk::less && this.peek(1) != tk::scope {
this.advance();
return this.make_node(nk::type_name, token);
}
return this.make_node(nk::type_name, token, this.segments(parser::args::types));
}
#! A path, as `std::io`, of segments without type arguments. One of a single
#! segment holds no run: its token names it.
#! @param this The parser.
#! @returns The `path` node.
def parser::path(&mut this): u32 {
val token := this.index;
if this.check(tk::name) && this.peek(1) != tk::scope {
this.advance();
return this.make_node(nk::path, token);
}
return this.make_node(nk::path, token, this.segments(parser::args::plain));
}
#! The segments of a path, as `a::b::c`, each of which may take type arguments,
#! as `res<i64>::ok` in a type, or `res::<i64>::ok` in an expression.
#! @param this The parser.
#! @param args How type arguments are written after each segment, if at all.
#! @returns The run of `segment` nodes.
def parser::segments(&mut this, args: parser::args): u32 {
val mark := this.mark;
while true {
if !this.check(tk::name) {
this.fail(ec::ident, "Expected an identifier in the path.");
break;
}
val token := this.index;
var types: u32 = 0;
this.advance();
if args == parser::args::types && this.check(tk::less) {
types = this.type_args();
} else if args == parser::args::values && this.at_value_args() {
this.advance();
types = this.type_args();
}
this.push(this.make_node(nk::segment, token, types));
break if !this.accept(tk::scope);
}
return this.make_run(mark);
}
#! Whether type arguments follow a name in an expression, written `::<` so that
#! a `<` alone always compares.
#! @param this The parser.
#! @returns Whether they do.
def parser::at_value_args(&this): bool {
return this.check(tk::scope) && this.peek(1) == tk::less;
}
#! The type arguments `<T, U>`, from the current `<`. After `as` and `is`, a `<`
#! always begins type arguments, so a comparison there needs parentheses.
#! @param this The parser.
#! @returns The run of types.
def parser::type_args(&mut this): u32 {
val open := this.index;
val angled := this.angled;
this.angled = false;
this.advance();
val mark := this.mark;
while true {
this.push(this.type_arg());
break if !this.accept(tk::comma);
}
this.angled = angled;
val types := this.make_run(mark);
this.close_angle(this.follows_cast(open)
? "Expected `>` to close the type arguments. A `<` after the type of `as` or `is` begins type arguments, so put a comparison in parentheses, as `(n as i64) < limit`."
: "Expected `>` to close the type arguments.");
return types;
}
#! Whether the name at the current token begins what is given type arguments
#! after `::<`, as `size_of::<T>()`, which no type is.
#! @param this The parser.
#! @returns Whether it does.
def parser::names_generic_call(&this): bool {
var ahead: u32 = 1;
while this.peek(ahead) == tk::scope {
return true if this.peek(ahead + 1) == tk::less;
return false if this.peek(ahead + 1) != tk::name;
ahead += 2;
}
return false;
}
#! A type argument: a type, or the value a constant parameter is given, a
#! literal, a name, or an expression of them, as `buffer<u8, 64>` or
#! `grid<N * 2>`. A name alone is read as a type, which the checker takes as the
#! constant it names where the parameter is one. `(` begins a value, unless a
#! type that needs one does, and so does a name given type arguments after
#! `::<`, as `buffer<u8, size_of::<T>()>`.
#! @param this The parser.
#! @returns The type's or the value's node.
def parser::type_arg(&mut this): u32 {
val next := this.peek(1);
val value := match this.kind {
tk::signed, tk::unsigned, tk::float, tk::char, tk::string, tk::istring, tk::istring_beg,
tk::kw_true, tk::kw_false, tk::kw_null, tk::minus, tk::negate, tk::bitnot, tk::lbracket => true,
tk::lparen => next != tk::star && next != tk::bitand && next != tk::kw_def && !this.chooses_type(0),
tk::name => this.names_generic_call(),
else => false
};
return this.constant_arg(0) if value;
this.type_argument = true;
val made := this.spread_type();
return made if this.syntax.node_kinds[made] != nk::type_name || !this.continues_value();
# The name is the expression's first operand: a name of one segment, or a path.
this.syntax.node_kinds[made] = this.syntax.node_lefts[made] == 0 ? nk::name : nk::path;
return this.constant_arg(made);
}
#! Whether what follows a name read as a type goes on with an expression, so the
#! name began a constant argument, as `N` does in `grid<N * 2>`. `>` closes the
#! arguments, so a comparison is put in parentheses.
#! @param this The parser.
#! @returns Whether it does.
def parser::continues_value(&this): bool {
return match this.kind {
tk::lparen, tk::lbrace, tk::dot, tk::quest, tk::kw_as, tk::kw_is => true,
tk::more, tk::moreeq, tk::rshift, tk::rshifteq, tk::comma => false,
else => token_powers[this.kind as u64] as u32 > parser::bp::assign as u32
};
}
#! A constant argument, which is an expression, going on from the name already
#! read as a type where one was.
#! @param this The parser.
#! @param primed The `name` or `path` the expression begins with, or 0.
#! @returns The expression's node.
def parser::constant_arg(&mut this, primed: u32): u32 {
val angled := this.angled;
this.angled = true;
var made: u32 = 0;
if primed == 0 {
made = this.expression();
} else {
made = primed;
# A struct literal of the name, as `point { x = 1 }`.
if this.check(tk::lbrace) {
this.syntax.node_kinds[made] = nk::type_name;
made = this.make_node(nk::construct, this.index, made, this.field_list());
}
while true {
val power := this.power(made);
break if power == parser::bp::none;
made = this.infix(made, power, true);
}
}
this.angled = angled;
return made;
}
#! A pattern parameter, `def(A, Ts...): R`, from the current `def`: a type
#! parameter for each of the parameter types it names, the last of which may be
#! a pack, and one for its result.
#! @param this The parser.
#! @returns The `type_pattern` node.
def parser::type_pattern(&mut this): u32 {
val token := this.index;
this.advance();
this.expect(tk::lparen, "Expected `(` to begin the pattern's parameter types, as `def(Ts...): R`.");
val mark := this.mark;
while !this.check(tk::rparen) && !this.check(tk::eof) {
if !this.check(tk::name) {
this.fail(ec::ident, "Expected the name of a type parameter the pattern's parameter type is, as `T` of `def(T): R`.");
break;
}
val name := this.index;
this.advance();
val packed := this.accept(tk::spread);
if packed && !this.check(tk::rparen) {
this.report_at(name, ec::token, "A pack takes every parameter type after those before it, so it is the last.");
}
this.push(this.make_node(nk::type_param, name, 0, parser::bit(packed, nf::packed)));
break if !this.accept(tk::comma);
}
val params := this.make_run(mark);
this.expect(tk::rparen, "Expected `)` to close the pattern's parameter types.");
this.expect(tk::colon, "Expected `:` followed by the name of the type parameter the result is, as `R` of `def(Ts...): R`.");
var result: u32 = 0;
if this.check(tk::name) {
result = this.make_node(nk::type_param, this.index, 0, 0);
this.advance();
} else {
this.fail(ec::ident, "Expected the name of the type parameter the result is, as `R` of `def(Ts...): R`.");
}
return this.make_node(nk::type_pattern, token, params, result);
}
#! A pattern parameter, `L[N]`, from the current `[` after the name of its
#! element's type parameter: that, and a constant parameter for its length.
#! @param this The parser.
#! @param token The name of the element's type parameter.
#! @returns The `array_pattern` node.
def parser::array_pattern(&mut this, token: u32): u32 {
val element := this.make_node(nk::type_param, token, 0, 0);
this.advance();
var length: u32 = 0;
if this.check(tk::name) {
length = this.make_node(nk::const_param, this.index, 0, 0);
this.advance();
} else {
this.fail(ec::ident, "Expected the name of the constant parameter the length is, as `N` of `L[N]`.");
}
this.expect(tk::rbracket, "Expected `]` to close the pattern, as `L[N]`.");
return this.make_node(nk::array_pattern, token, element, length);
}
#! The type parameters `<T, Us...>` of a declaration, from the current `<`,
#! whose bounds are given in a `where` clause after its signature, which gives
#! them to the `type_param` nodes.
#! @param this The parser.
#! @returns The run of `type_param` nodes.
def parser::type_params(&mut this): u32 {
this.advance();
val mark := this.mark;
while true {
# `def(Ts...): R` is given a function type, and names its parameters' types
# and its result's.
if this.check(tk::kw_def) {
this.push(this.type_pattern());
break if !this.accept(tk::comma);
continue;
}
# `const N: u64` stands for a value each instance is given, of the type written.
val valued := this.accept(tk::kw_const);
if !this.check(tk::name) {
this.fail(ec::ident, valued ? "Expected the name of a constant parameter, as `const N: u64`." : "Expected the name of a type parameter.");
break;
}
val token := this.index;
this.advance();
# `L[N]` is given a fixed array, and names its element's type and its length.
if !valued && this.check(tk::lbracket) {
this.push(this.array_pattern(token));
break if !this.accept(tk::comma);
continue;
}
if valued {
if this.accept(tk::spread) {
this.report_at(token, ec::token, "A constant parameter stands for one value, so it is not a pack.");
}
this.expect(tk::colon, "Expected `:` followed by the type of the constant, as `const N: u64`.");
this.push(this.make_node(nk::const_param, token, 0, this.type_expr()));
break if !this.accept(tk::comma);
continue;
}
# `Ts...` is a pack, standing for any number of types, which comes last.
val packed := this.accept(tk::spread);
if packed && !this.at(tt::angle) {
this.report_at(token, ec::token,
"A pack takes every type argument after the type parameters before it, so it is the last.");
}
this.push(this.make_node(nk::type_param, token, 0, parser::bit(packed, nf::packed)));
break if !this.accept(tk::comma);
}
val params := this.make_run(mark);
this.close_angle("Expected `>` to close the type parameters.");
return params;
}