Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-12-06 13:52:57 -06:00
commit 528ccf1523
782 files changed
+145156

No files matched your search

+118
View File
@@ -0,0 +1,118 @@
#! @file arithmetic.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the traits of arithmetic: one for each operator, asking for the
#! method `+`, `-`, `*`, `/`, `%`, or a prefix `-` calls between values of one
#! type, and `additive` and `multiplicative`, which gather those that add and
#! those that multiply, and which every number has.
module core;
#! A type whose values add to another of the type, giving one more.
#!
#! `a + b` calls `add`, and `a += b` writes what it gives over `a`. A type has
#! `+` by declaring the method, whether or not it names this trait, and may
#! declare others taking other types, as `instant::add(&this, by: &duration)`.
#! The trait is what generic code asks for to add two values of a type. Numbers
#! are addable without declaring anything.
pub trait addable {
#! Adds another value to this one, as `+` does.
#! @param this The value to add to.
#! @param other The value to add.
#! @returns The sum.
def add(&this, other: &self): self;
}
#! A type whose values subtract from another of the type, giving one more.
#!
#! `a - b` calls `sub`, and `a -= b` writes what it gives over `a`. A type has
#! `-` by declaring the method, and may declare others taking or giving other
#! types, as `instant::sub(&this, since: &instant): duration`. The trait is
#! what generic code asks for to subtract two values of a type. Numbers are
#! subtractable without declaring anything.
pub trait subtractable {
#! Subtracts another value from this one, as `-` does.
#! @param this The value to subtract from.
#! @param other The value to subtract.
#! @returns The difference.
def sub(&this, other: &self): self;
}
#! A type whose values multiply by another of the type, giving one more.
#!
#! `a * b` calls `mul`, and `a *= b` writes what it gives over `a`. A type has
#! `*` by declaring the method, and may declare others taking other types, as
#! `vec2::mul(&this, by: &f64)`. The trait is what generic code asks for to
#! multiply two values of a type, as two matrices. Numbers are multipliable
#! without declaring anything.
pub trait multipliable {
#! Multiplies this value by another, as `*` does.
#! @param this The value to multiply.
#! @param other The value to multiply by.
#! @returns The product.
def mul(&this, other: &self): self;
}
#! A type whose values divide by another of the type, giving one more.
#!
#! `a / b` calls `div`, and `a /= b` writes what it gives over `a`. A type has
#! `/` by declaring the method, and may declare others taking other types, as
#! `duration::div(&this, by: &i64)`. The trait is what generic code asks for to
#! divide two values of a type. Numbers are divisible without declaring
#! anything.
pub trait divisible {
#! Divides this value by another, as `/` does.
#! @param this The value to divide.
#! @param other The value to divide by.
#! @returns The quotient.
def div(&this, other: &self): self;
}
#! A type whose values leave a remainder when divided by another of the type.
#!
#! `a % b` calls `rem`, and `a %= b` writes what it gives over `a`. A type has
#! `%` by declaring the method. The trait is what generic code asks for to take
#! the remainder of two values of a type. Numbers are modular without declaring
#! anything.
pub trait modular {
#! The remainder of dividing this value by another, as `%` gives it.
#! @param this The value to divide.
#! @param other The value to divide by.
#! @returns The remainder.
def rem(&this, other: &self): self;
}
#! A type whose values negate, giving another of the type.
#!
#! `-a` calls `negate`. A type has it by declaring the method. The trait is
#! what generic code asks for to negate a value. Numbers are negatable without
#! declaring anything.
pub trait negatable {
#! Negates this value, as `-x` does.
#! @param this The value to negate.
#! @returns The negated value.
def negate(&this): self;
}
#! A type whose values add, subtract, and negate, all as one type: lengths of
#! time, vectors, matrices, amounts of money.
#!
#! It composes `addable`, `subtractable`, and `negatable`, which give `+`, `-`,
#! and `-x`, beside `equatable`. It asks for no multiplication, since two
#! lengths of time have no product. Numbers are additive without declaring
#! anything.
#!
#! Within a generic bounded by it, a constant does not stand for a value, as it
#! does under `numeric`: a length of time is no number.
pub trait additive : equatable, addable, subtractable, negatable {}
#! A type whose values multiply, as one type: matrices, and whatever is
#! numeric.
#!
#! It composes `multipliable`, which gives `*`, beside `equatable`. It asks for
#! no division, since not every matrix divides another. Numbers are
#! multiplicative without declaring anything.
pub trait multiplicative : equatable, multipliable {}
+140
View File
@@ -0,0 +1,140 @@
#! @file comparison.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the traits comparing values: `equatable`, which `==` calls, with
#! `equals`, which compares two values through it; `ordered`, which gives values
#! an order, as numbers, enums, and pointers have; and `hashable`, which hashes
#! values, as a dictionary's keys are, with `hash` and `mix`, which hash values
#! and fold words into a hash.
module core;
#! A type whose values can be compared for equality, by a method comparing a
#! value with another of the same type.
#!
#! A type that is `equatable` is compared by `==` and `!=`, which call its
#! `equals`, and the method can be called by name too.
pub trait equatable {
#! Compares this value with another of the same type.
#! @param this The value to compare against.
#! @param other The value to compare with.
#! @returns Whether the two are equal.
def equals(&this, other: &self): bool;
}
#! Compares two values of the same type through its `equals`, as `==` does.
#! @tparam T The type of the values.
#! @param first The value to compare against.
#! @param second The value to compare with.
#! @returns Whether the two are equal.
#! @remarks A type that is not `equatable` is an error where it is compared, as
#! it is with `==`, since its bytes may differ where its values do not,
#! as the padding between fields does.
pub def equals<T>(first: &T, second: &T): bool {
if const !(T is equatable) {
compile_error("`equals` compares values through `equatable`, which this type does not implement, as `==` does.");
}
return first.equals(second);
}
#! A type whose values have an order.
#!
#! `compare` gives a negative number when `this` comes before `other`, zero when
#! they are equal, and a positive number when it comes after. `<`, `<=`, `>`,
#! and `>=` between two values of the type call it, as `==` calls `equals`,
#! which an ordered type also gives, so the two always agree. Numbers, enums,
#! and pointers are ordered without declaring anything.
pub trait ordered : equatable {
#! Compares this value with another of the same type, for their order.
#! @param this The value to compare against.
#! @param other The value to compare with.
#! @returns A negative number where this value comes first, zero where they
#! are equal, and a positive number where it comes after.
def compare(&this, other: &self): i64;
}
#! A type whose values can be hashed into a `u64`, as a dictionary's keys are.
#!
#! Equal values must hash alike, and values that differ should hash differently
#! as often as possible.
pub trait hashable {
#! Hashes this value.
#! @param this The value to hash.
#! @returns Its hash code, which equal values share.
def hash(&this): u64;
}
#! Shortcut function for hashing a value, providing a 64-bit hashed value.
#! @tparam T The type of the value.
#! @param item The object to hash.
#! @returns The hash value of the object, from its `hash`.
#! @remarks A type that is not `hashable` is an error where it is hashed, since
#! its bytes may differ where its values do not, as the padding between
#! fields does, and equal values must hash alike.
pub def hash<T>(item: &T): u64 {
if const !(T is hashable) {
compile_error("`hash` hashes values through `hashable`, which this type does not implement.");
}
return item.hash();
}
# Hashes bytes a word at a time, the last few as one word read without passing
# their end, so that equal bytes always hash alike.
def hash_bytes(data: *u8, len: u64): u64 {
var code := len;
var at := data;
var left := len;
while left >= 8 {
code = mix(code, *(at as *u64));
at = at + 8;
left = left - 8;
}
if left >= 4 {
return mix(code, (*(at as *u32) as u64) | ((*((at + left - 4) as *u32) as u64) << 32));
}
if left >= 2 {
return mix(code, (*(at as *u16) as u64) | ((*((at + left - 2) as *u16) as u64) << 16));
}
if left == 1 {
return mix(code, *at as u64);
}
return code;
}
#! Packs two 32-bit numbers into one word, the first in its high half, as a key
#! naming a pair, such as a type and a trait, is made for a dictionary.
#! @param high The number held in the high half.
#! @param low The number held in the low half.
#! @returns The word, which `pair_high` and `pair_low` take apart, and which no
#! other pair packs into.
pub def pair_key(high: u32, low: u32): u64 {
return (high as u64 << 32) | low as u64;
}
#! The number held in the high half of a word `pair_key` packed.
#! @param key The word.
#! @returns The first number given to `pair_key`.
pub def pair_high(key: u64): u32 {
return (key >> 32) as u32;
}
#! The number held in the low half of a word `pair_key` packed.
#! @param key The word.
#! @returns The second number given to `pair_key`.
pub def pair_low(key: u64): u32 {
return (key & 0xFFFFFFFF) as u32;
}
#! Folds a word into a hash code, as hashing a value made of several does for
#! each.
#! @param code The hash code so far.
#! @param value The word to fold in.
#! @returns The new hash code.
pub def mix(code: u64, value: u64): u64 {
var bits := code ^ value;
bits *= 0x9E3779B97F4A7C15;
return bits ^ (bits >> 29);
}
+143
View File
@@ -0,0 +1,143 @@
#! @file containers.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the traits a container implements to lend its elements: `indexable`
#! and `assignable`, which let it be written `d[key]` to read and to write, the
#! way the language already writes a fixed array, a pointer, and a view;
#! `spannable` and `sliceable`, which lend a view of its elements that reads and
#! one that writes, and let it be written `x[a:n]` to take them, as a view is;
#! and `extendable`, which has values appended to it, as an
#! iterator's `into` appends each element it gives.
module core;
#! Defines that a type is indexed by a key, giving the element it holds there to
#! read.
#!
#! `d[key]` is `d.at(key)`: the reference the accessor gives, which is read and
#! bound as any reference is, so indexing copies nothing. `val e := d[key]`
#! refers to the element, and `val e: V = d[key]` copies it. A type whose
#! elements are written where they are is `assignable` too, which adds the
#! accessor that writes. One that is only ever read is read through `at(&this)`
#! however it is held, so writing an element of it is an error where it is
#! written.
#!
#! The accessor is expected to stop a checked program where the key is one the
#! value does not hold, as indexing a fixed array outside its length does, with
#! a contract, as `expects(key < this._len)`: one that is not checked trusts the
#! key, as C does. A
#! key that may be one the value does not hold in a program that is right is
#! asked of a `get` the type gives beside this trait, returning `maybe<&V>`, as
#! each container of std's does.
#!
#! Traits are satisfied by shape, as they are everywhere else, so a type with
#! `at` is indexable whether or not it names the trait. Naming it is still worth
#! doing: it says the type means to be indexed, and it is what a `where` clause
#! bounds a type parameter by.
#! @tparam K The type of the keys it is indexed by.
#! @tparam V The type of the elements it holds.
pub trait indexable<K, V> {
#! Reaches the element held at a key, to read it.
#! @param this The value to index.
#! @param key The key of the element.
#! @returns The element.
#! @remarks A key the value does not hold stops a checked program.
def at(&this, key: K): &V;
}
#! Defines that a type is indexed by a key and written there too: the half of
#! indexing that writes, which a type adds to `indexable` where its elements
#! may be changed in place.
#!
#! There are then two accessors, both named `at`: the one `indexable` asks for,
#! taking `&this` and giving a `&V`, and this one, taking `&mut this` and giving
#! a `&mut V`. The receiver chooses between them, so a value that can be written
#! is given the element to write, and one that cannot is given it only to read.
#! Both are given the same key, and both stop a checked program where the key
#! is one the value does not hold.
#!
#! Generic code bounded by it writes `d[key] = value` and `d[key] += 1`, which a
#! bound of `indexable` alone does not let it, and `position_mutator` writes
#! each element of what is indexed by position through it.
#! @tparam K The type of the keys it is indexed by.
#! @tparam V The type of the elements it holds.
pub trait assignable<K, V> : indexable<K, V> {
#! Reaches the element held at a key, to write it.
#! @param this The value to index.
#! @param key The key of the element.
#! @returns The element.
#! @remarks A key the value does not hold stops a checked program.
def at(&mut this, key: K): &mut V;
}
#! A type that lends a view of the elements it holds, as a `string` lends its
#! text and a container its elements.
#!
#! `x[start:count]` is `T::span_of(&x, start, count)`, the way the language
#! already slices a fixed array, a pointer, and a view: `count` elements from
#! `start`, as a `span<T>`. A type whose elements are written where they are is
#! `sliceable` too, and a value of it that can be written is sliced through
#! `slice_of` instead. Either bound may be left out, which gives it as `span_of`
#! takes it by default: the start as 0, and the count as `~0u`, which stands for
#! every element after the start, so `x[2:]` is all but the first two and `x[:]`
#! is all of them.
#!
#! Generic code bounded by it reads the elements of whatever it is given through
#! `span_of`, as `C::span_of(c)` for all of them, or `c[a:n]`. A container lends
#! the whole view as its `span` property too, as `v.span`, which is what code
#! that knows its type reads.
#!
#! A type gives `span_of` the same defaults, so a call leaving them out calls it
#! as it calls the trait's, and is expected to stop a checked program where the
#! start or the count reaches past its last element, as slicing a fixed array
#! does. Slicing the whole view does both, as `whole[start:]` where `count` is
#! `~0u`, and `whole[start:count]` where it isn't.
#! @tparam T The type of the elements.
pub trait spannable<T> {
#! Lends a view of elements of a value, without copying them.
#! @param other The value to view.
#! @param start The index of the first element viewed.
#! @param count How many elements are viewed, or `~0u` for every one after
#! the start.
#! @returns The view, which is only good until the value changes or closes.
#! @remarks A start or count past the last element stops a checked program.
def span_of(other: &self, start: u64 = 0, count: u64 = ~0u): span<T>;
}
#! A type that lends a writable view of the elements it holds, as a container
#! lends one of its elements.
#!
#! `x[start:count]` is `T::slice_of(&mut x, start, count)` where `x` can be
#! written, as a `slice<T>` that writes the elements where they are, and
#! `T::span_of(&x, start, count)` where it cannot. The bounds are given and left
#! out as `spannable` says.
#!
#! Generic code bounded by it writes the elements of whatever it is given
#! through `slice_of`, as `C::slice_of(c)` for all of them, or `c[a:n]` of a
#! `c` that can be written. A container lends the whole view as its `slice`
#! property too, as `v.slice`, which only a value that can be written reads.
#! @tparam T The type of the elements.
pub trait sliceable<T> {
#! Lends a writable view of elements of a value, without copying them.
#! @param other The value to view, which can be written.
#! @param start The index of the first element viewed.
#! @param count How many elements are viewed, or `~0u` for every one after
#! the start.
#! @returns The view, which writes the elements where they are, and is only
#! good until the value changes or closes.
#! @remarks A start or count past the last element stops a checked program.
def slice_of(other: &mut self, start: u64 = 0, count: u64 = ~0u): slice<T>;
}
#! A container values are appended to one at a time, as a `vector` takes its
#! elements and a `string` its text.
#! @tparam T The type of what is appended.
pub trait extendable<T> {
#! Appends a value, after those the container holds.
#! @param this The container.
#! @param value The value, which the container then owns.
def append(&mut this, value: T): void;
}
+71
View File
@@ -0,0 +1,71 @@
#! @file functions.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the traits of functions: `invokable`, which a type implements to be
#! called as a function is, `f(args)`, and which every function is, and
#! `signature`, which the compiler gives every function type, and which names
#! what a function takes and what it gives.
module core;
#! What is called as a function of a signature: a function value, the address of
#! a C function, or a value of a type with an `invoke` taking the arguments.
#!
#! The trait is given the signature whole, as `invokable<def(i64, bool): u8>`,
#! whose parameter types it names `Ts` and whose result `R`, so `invoke` takes a
#! parameter of each of the types, as `def adder::invoke(&mut this, a: i64, b:
#! bool): u8` does. A variadic signature, as `def(i64...): i64`, asks for a
#! variadic `invoke`. Generic code over any signature names it through a type
#! parameter bounded by `signature`, as `invokable<F>`.
#!
#! A call of a value whose type is no function, `f(1, true)`, calls its `invoke`,
#! as `f.invoke(1, true)`, by the rules a method's call has: the overloads are
#! chosen between as they are, and one taking `&mut this` is called on what can be
#! written. Any type with an `invoke` is called so, whether or not it names this
#! trait, which bounds generic code taking functions and callable values alike:
#!
#! ```sakura
#! def twice<F>(f: &mut F, x: i64): i64 where F: invokable<def(i64): i64> {
#! return f(f(x));
#! }
#! ```
#!
#! A function value, and the address of a C function, have an `invoke` the
#! compiler gives them, which calls them, so each is `invokable` of its own type.
#! An `invoke` taking `&this` meets the trait too, since what can be written can
#! be read.
#! @tparam Ts The types of the arguments it is called with.
#! @tparam R The type it gives.
pub trait invokable<def(Ts...): R> {
#! Calls it with the arguments, as `f(args)` does.
#! @param this The value called.
#! @param args The arguments, one of each of the signature's parameter types.
#! @returns What the call gives.
def invoke(&mut this, args: Ts...): R;
}
#! A function type, as `def(i64, bool): u8`, a variadic one, as `def(i64...):
#! i64`, or the address of a C function, as `cfn<def(i32): void>`.
#!
#! Generic code bounded by it names the parts of the type it is given: `F::result`
#! is what a function of it gives, and `F::params` the types it takes, as a pack,
#! so `args: F::params...` takes the arguments it does. A variadic function's
#! pack ends in the type of the values its last parameter takes, so a parameter
#! of the pack is variadic too.
#!
#! A pattern parameter, as `def(Ts...): R` of `invokable`, is given a signature
#! whole: `invokable<F>` where `F: signature` names `F::params` and `F::result`
#! as `Ts` and `R`.
#!
#! The compiler decides what is a signature, so no type implements it.
pub trait signature {
#! What a function of the type gives.
type result;
#! The types a function of the type takes, as a pack, which only the compiler
#! gives.
type params...;
}
+691
View File
@@ -0,0 +1,691 @@
#! @file iteration.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the traits of iteration, and the iterators any container may lend:
#! `iter`, which gives elements one at a time and which a `for` loop walks, with
#! the adapters making one iterator of another and the consumers walking one to
#! its end as its defaults; `sized_iterator`, which knows how many elements it
#! has left; `backward_iterator`, which also walks from its far end; `iterable`,
#! which lends an iterator over the elements a container holds; and
#! `positions_iterator` and `position_mutator`, which read and write the
#! elements of whatever is indexed by position, so a container need not write
#! iterators of its own.
module core;
#! Gives elements one at a time, as `some` of each while there are more and
#! `none` once there are no more.
#!
#! `for x in it` walks an iterator where it is, calling `next` until it gives
#! `none`, so one that a loop stops early carries on from there in the next. An
#! iterator that is `owning` and that a loop is given as a value, rather than as
#! a variable, is closed where the loop ends, however it ends.
#!
#! A type naming the trait has its defaults: the adapters, which make an
#! iterator of it, as `v.iter().filter(odd).map(square)`, and the consumers,
#! which walk it to its end, or until they know their answer, as `.sum()`. Each
#! is compiled for the type, so what it calls of the type is called directly. An
#! adapter moves the iterator it is called on into what it makes, which closes
#! it where that closes, so `it.map(f)` leaves `it` walked to its end.
#!
#! It is named as the types the syntax makes are, short, leaving `iterator` to
#! the type a container lends, as `vector<T>::iterator`.
#! @tparam T The type of what it gives.
pub trait iter<T> {
#! Gives the next element, or `none` once there are no more.
#! @param this The iterator to advance.
#! @returns Maybe the next element; otherwise, `nothing`.
def next(&mut this): maybe<T>;
#! Gives what a function makes of each element.
#! @tparam U What the function gives.
#! @tparam F The function, a lambda, or anything `invokable`.
#! @param this The iterator, moved into what is made.
#! @param f The function, called on each element as it is given.
#! @returns The iterator of what it makes.
def map<U, F>(&mut this, f: F): mapped<T, U, self, F> where F: invokable<def(T): U> {
return mapped::<T, U, self, F> { _from = move(this), _f = move(&mut f) };
}
#! Gives each element a test passes.
#! @tparam F The test.
#! @param this The iterator, moved into what is made.
#! @param test The test, given a reference to each element.
#! @returns The iterator of those that pass.
def filter<F>(&mut this, test: F): filtered<T, self, F> where F: invokable<def(&T): bool> {
return filtered::<T, self, F> { _from = move(this), _test = move(&mut test) };
}
#! Gives what a function makes of each element where it makes something, as
#! `some`.
#! @tparam U What the function may give.
#! @tparam F The function.
#! @param this The iterator, moved into what is made.
#! @param f The function, called on each element.
#! @returns The iterator of what it makes.
def filter_map<U, F>(&mut this, f: F): filter_mapped<T, U, self, F> where F: invokable<def(T): maybe<U>> {
return filter_mapped::<T, U, self, F> { _from = move(this), _f = move(&mut f) };
}
#! Gives each element with its index, counting from 0, as a `pair`.
#! @param this The iterator, moved into what is made.
#! @returns The iterator of pairs.
def enumerate(&mut this): enumerated<T, self> {
return enumerated::<T, self> { _from = move(this), _at = 0 };
}
#! Gives the elements of this iterator and another side by side, as a `pair`,
#! until either ends.
#! @tparam U What the other gives.
#! @tparam J The other iterator.
#! @param this The iterator, moved into what is made.
#! @param other The other iterator, moved into what is made.
#! @returns The iterator of pairs.
def zip<U, J>(&mut this, other: J): zipped<T, U, self, J> where J: iter<U> {
return zipped::<T, U, self, J> { _from = move(this), _other = move(&mut other) };
}
#! Gives this iterator's elements, then another's.
#! @tparam J The other iterator, giving what this one gives.
#! @param this The iterator, moved into what is made.
#! @param other The other iterator, moved into what is made.
#! @returns The iterator of both.
def chain<J>(&mut this, other: J): chained<T, self, J> where J: iter<T> {
return chained::<T, self, J> { _first = move(this), _second = move(&mut other), _on_second = false };
}
#! Gives the first elements, up to a count.
#! @param this The iterator, moved into what is made.
#! @param n How many to give at most.
#! @returns The iterator of those.
def take(&mut this, n: u64): taken<T, self> {
return taken::<T, self> { _from = move(this), _left = n };
}
#! Gives the elements after the first, up to a count, which it passes over.
#! @param this The iterator, moved into what is made.
#! @param n How many to pass over.
#! @returns The iterator of the rest.
def skip(&mut this, n: u64): skipped<T, self> {
return skipped::<T, self> { _from = move(this), _skip = n };
}
#! Gives the elements while a test passes them, ending at the first it does
#! not.
#! @tparam F The test.
#! @param this The iterator, moved into what is made.
#! @param test The test, given a reference to each element.
#! @returns The iterator of the run that passes.
def take_while<F>(&mut this, test: F): taken_while<T, self, F> where F: invokable<def(&T): bool> {
return taken_while::<T, self, F> { _from = move(this), _test = move(&mut test), _done = false };
}
#! Gives the elements from the first a test does not pass on, passing over
#! those before it.
#! @tparam F The test.
#! @param this The iterator, moved into what is made.
#! @param test The test, given a reference to each element.
#! @returns The iterator of the rest.
def skip_while<F>(&mut this, test: F): skipped_while<T, self, F> where F: invokable<def(&T): bool> {
return skipped_while::<T, self, F> { _from = move(this), _test = move(&mut test), _past = false };
}
#! Gives every `n`th element, the first included.
#! @param this The iterator, moved into what is made.
#! @param n How far apart the elements given are, at least 1.
#! @returns The iterator of those.
def step(&mut this, n: u64): stepped<T, self> {
if n == 0 {
fault("An iterator steps by 0, which is no step.");
}
return stepped::<T, self> { _from = move(this), _by = n, _first = true };
}
#! Gives the elements from the far end.
#! @param this The iterator, moved into what is made.
#! @returns The iterator walking backward.
def rev(&mut this): reversed<T, self> where self: backward_iterator<T> {
return reversed::<T, self> { _from = move(this) };
}
#! Gives the elements, and looks at the next before it is given, by `peek`.
#! @param this The iterator, moved into what is made.
#! @returns The iterator that peeks.
def peekable(&mut this): peeking<T, self> {
return peeking::<T, self> { _from = move(this), _held = nothing {} };
}
#! Gives the elements of each iterator a function makes of each element.
#! @tparam U What the iterators it makes give.
#! @tparam J The iterators it makes.
#! @tparam F The function.
#! @param this The iterator, moved into what is made.
#! @param f The function, called on each element.
#! @returns The iterator of what each gives, in turn.
def flat_map<U, J, F>(&mut this, f: F): flat_mapped<T, U, self, J, F>
where F: invokable<def(T): J> where J: iter<U> {
return flat_mapped::<T, U, self, J, F> { _from = move(this), _f = move(&mut f), _inner = nothing {} };
}
#! Gives a copy of what each reference it gives refers to, of what closes
#! nothing.
#! @tparam X What the references refer to.
#! @param this The iterator of references, moved into what is made.
#! @returns The iterator of copies.
def copied<X>(&mut this): copying<X, self> where self: iter<&X> {
return copying::<X, self> { _from = move(this) };
}
#! Gives the elements as they are, after calling a function on each.
#! @tparam F The function.
#! @param this The iterator, moved into what is made.
#! @param f The function, given a reference to each element.
#! @returns The iterator.
def inspect<F>(&mut this, f: F): inspected<T, self, F> where F: invokable<def(&T): void> {
return inspected::<T, self, F> { _from = move(this), _f = move(&mut f) };
}
#! Walks to the end, counting the elements.
#! @param this The iterator.
#! @returns How many it gave.
def count(&mut this): u64 {
var n: u64 = 0;
while this.next() is some(x) {
n++;
}
return n;
}
#! Walks to the end, adding the elements up.
#! @param this The iterator, of numbers.
#! @returns The sum, or 0 where it gives none.
def sum(&mut this): T where T: numeric {
var total: T = 0;
while this.next() is some(x) {
total += x;
}
return total;
}
#! Walks to the end, multiplying the elements together.
#! @param this The iterator, of numbers.
#! @returns The product, or 1 where it gives none.
def product(&mut this): T where T: numeric {
var total: T = 1;
while this.next() is some(x) {
total *= x;
}
return total;
}
#! Walks to the end, folding each element into a value: `f(f(start, x0), x1)`
#! and on.
#! @tparam A The value.
#! @tparam F The function folding each in.
#! @param this The iterator.
#! @param start The value before any element is folded in.
#! @param f The function, given the value so far and the element.
#! @returns The value once every element is folded in.
def fold<A, F>(&mut this, start: A, f: F): A where F: invokable<def(A, T): A> {
var made := move(&mut start);
while this.next() is some(x) {
made = f(move(&mut made), move(&mut x));
}
return made;
}
#! Walks to the end, folding the elements into the first: `f(f(x0, x1), x2)`
#! and on.
#! @tparam F The function folding each in.
#! @param this The iterator.
#! @param f The function, given the value so far and the element.
#! @returns Maybe the value; otherwise, `nothing` where it gives no elements.
def reduce<F>(&mut this, f: F): maybe<T> where F: invokable<def(T, T): T> {
var first := this.next();
if first is not some(&mut start) {
return nothing {};
}
var made := move(start);
while this.next() is some(x) {
made = f(move(&mut made), move(&mut x));
}
return made;
}
#! Whether a test passes any element, walking until one does.
#! @tparam F The test.
#! @param this The iterator.
#! @param test The test, given a reference to each element.
#! @returns Whether it passes one.
def any<F>(&mut this, test: F): bool where F: invokable<def(&T): bool> {
while this.next() is some(x) {
return true if test(&x);
}
return false;
}
#! Whether a test passes every element, walking until one fails it.
#! @tparam F The test.
#! @param this The iterator.
#! @param test The test, given a reference to each element.
#! @returns Whether it passes all of them, as it does where there are none.
def all<F>(&mut this, test: F): bool where F: invokable<def(&T): bool> {
while this.next() is some(x) {
return false if !test(&x);
}
return true;
}
#! The first element a test passes, walking until it finds one.
#! @tparam F The test.
#! @param this The iterator.
#! @param test The test, given a reference to each element.
#! @returns Maybe the element; otherwise, `nothing`.
def find<F>(&mut this, test: F): maybe<T> where F: invokable<def(&T): bool> {
while this.next() is some(x) {
return move(&mut x) if test(&x);
}
return nothing {};
}
#! The index of the first element a test passes, counting from 0, walking
#! until it finds one.
#! @tparam F The test.
#! @param this The iterator.
#! @param test The test, given a reference to each element.
#! @returns Maybe the index; otherwise, `nothing`.
def position<F>(&mut this, test: F): maybe<u64> where F: invokable<def(&T): bool> {
var at: u64 = 0;
while this.next() is some(x) {
return at if test(&x);
at++;
}
return nothing {};
}
#! Walks to the end, keeping the least element, the first of those equally
#! least.
#! @param this The iterator, of what is ordered.
#! @returns Maybe the least; otherwise, `nothing` where it gives none.
def min(&mut this): maybe<T> where T: ordered {
var first := this.next();
if first is not some(&mut start) {
return nothing {};
}
var best := move(start);
while this.next() is some(x) {
if x < best {
best = move(&mut x);
}
}
return best;
}
#! Walks to the end, keeping the greatest element, the last of those equally
#! greatest.
#! @param this The iterator, of what is ordered.
#! @returns Maybe the greatest; otherwise, `nothing` where it gives none.
def max(&mut this): maybe<T> where T: ordered {
var first := this.next();
if first is not some(&mut start) {
return nothing {};
}
var best := move(start);
while this.next() is some(x) {
if !(x < best) {
best = move(&mut x);
}
}
return best;
}
#! Walks to the end, keeping the least element as an order says, the first of
#! those equally least.
#! @tparam F The order.
#! @param this The iterator.
#! @param order Whether one element comes before another.
#! @returns Maybe the least; otherwise, `nothing` where it gives none.
def min_by<F>(&mut this, order: F): maybe<T> where F: invokable<def(&T, &T): bool> {
var first := this.next();
if first is not some(&mut start) {
return nothing {};
}
var best := move(start);
while this.next() is some(x) {
if order(&x, &best) {
best = move(&mut x);
}
}
return best;
}
#! Walks to the end, keeping the greatest element as an order says, the last
#! of those equally greatest.
#! @tparam F The order.
#! @param this The iterator.
#! @param order Whether one element comes before another.
#! @returns Maybe the greatest; otherwise, `nothing` where it gives none.
def max_by<F>(&mut this, order: F): maybe<T> where F: invokable<def(&T, &T): bool> {
var first := this.next();
if first is not some(&mut start) {
return nothing {};
}
var best := move(start);
while this.next() is some(x) {
if !order(&x, &best) {
best = move(&mut x);
}
}
return best;
}
#! Walks to the end, keeping the element whose key is least, the first of
#! those equally least.
#! @tparam K The key, which is ordered.
#! @tparam F The function giving the key.
#! @param this The iterator.
#! @param key The function, given a reference to each element.
#! @returns Maybe the element; otherwise, `nothing` where it gives none.
def min_by_key<K, F>(&mut this, key: F): maybe<T> where F: invokable<def(&T): K> where K: ordered {
var first := this.next();
if first is not some(&mut start) {
return nothing {};
}
var best := move(start);
var least := key(&best);
while this.next() is some(x) {
var made := key(&x);
if made < least {
best = move(&mut x);
least = move(&mut made);
}
}
return best;
}
#! Walks to the end, keeping the element whose key is greatest, the last of
#! those equally greatest.
#! @tparam K The key, which is ordered.
#! @tparam F The function giving the key.
#! @param this The iterator.
#! @param key The function, given a reference to each element.
#! @returns Maybe the element; otherwise, `nothing` where it gives none.
def max_by_key<K, F>(&mut this, key: F): maybe<T> where F: invokable<def(&T): K> where K: ordered {
var first := this.next();
if first is not some(&mut start) {
return nothing {};
}
var best := move(start);
var most := key(&best);
while this.next() is some(x) {
var made := key(&x);
if !(made < most) {
best = move(&mut x);
most = move(&mut made);
}
}
return best;
}
#! The last element: from the far end where the iterator walks backward,
#! and otherwise by walking to the end.
#! @param this The iterator.
#! @returns Maybe the last element; otherwise, `nothing` where it gives none.
def last(&mut this): maybe<T> {
if const self is backward_iterator<T> {
return this.next_back();
}
var kept: maybe<T> = nothing {};
while this.next() is some(x) {
kept = move(&mut x);
}
return kept;
}
#! The element `n` along, counting from 0, passing over those before it.
#! @param this The iterator.
#! @param n How many to pass over first.
#! @returns Maybe the element; otherwise, `nothing` where it gives fewer.
def nth(&mut this, n: u64): maybe<T> {
var left := n;
while left != 0 {
return nothing {} if this.next() is not some(x);
left--;
}
return this.next();
}
#! Walks to the end, calling a function on each element.
#! @tparam F The function.
#! @param this The iterator.
#! @param f The function, given each element.
def for_each<F>(&mut this, f: F): void where F: invokable<def(T): void> {
while this.next() is some(x) {
f(move(&mut x));
}
}
#! Walks to the end, collecting the elements into a vector, which is given
#! room for them all at once where the iterator knows how many it has left.
#! @param this The iterator.
#! @returns The vector.
def to_vector(&mut this): vector<T> {
var made := vector::<T>::new();
if const self is sized_iterator<T> {
made.reserve(this.remaining());
}
while this.next() is some(x) {
made.append(move(&mut x));
}
return made;
}
#! Walks to the end, joining the text of the elements, as `$"{x}"` writes
#! each, with text between each two.
#! @param this The iterator.
#! @param between What is written between each two elements.
#! @returns The text.
def to_string(&mut this, between: strview): string {
var made := string::new(nothing {});
var first := true;
while this.next() is some(x) {
if !first {
made.append(between);
}
first = false;
val text := $"{x}";
made.append(text.span);
}
return made;
}
#! Walks to the end, appending each element to a container, as a `vector`, a
#! `string`, or anything `extendable` is.
#! @tparam C The container.
#! @param this The iterator.
#! @param target The container, which keeps what it held before.
def into<C>(&mut this, target: &mut C): void where C: extendable<T> {
while this.next() is some(x) {
target.append(move(&mut x));
}
}
}
#! An iterator that knows how many elements it has left, as a view, a range,
#! and the containers' iterators do, so collecting it makes room for them at
#! once.
#! @tparam T The type of what it gives.
pub trait sized_iterator<T> : iter<T> {
#! How many elements it has left to give.
#! @param this The iterator.
#! @returns How many.
def remaining(&this): u64;
}
#! An iterator that also walks from its far end, until the two ends meet, as a
#! view, a range, a `deque`, and a `chain` do, which `rev` and `last` take.
#! @tparam T The type of what it gives.
pub trait backward_iterator<T> : iter<T> {
#! Gives the element at the far end, or `none` once the ends have met.
#! @param this The iterator.
#! @returns Maybe the last element left; otherwise, `nothing`.
def next_back(&mut this): maybe<T>;
}
#! Lends an iterator over the elements it holds, as references to them.
#!
#! `for x in c` calls `iter(&this)` once and walks what it gives, copying each
#! element, and `for &x in c` refers to each instead. `for &mut x in c` calls
#! `iter(&mut this)`, which a container whose elements may be changed in place
#! gives, and which one that only reads leaves out. What `iter` gives is closed
#! where the loop ends, however it ends, where it is `owning`.
#!
#! The iterator types are asked of the container: an `iterator`, which only
#! reads, and a `mutator`, which writes, as `type list<T>::iterator = ...;`, so
#! generic code names them through a bound, as `C::iterator` where
#! `C: iterable<T>`. A container lends them as properties of the same names too,
#! as `v.iterator`. A container indexed by position need write neither, since
#! `positions_iterator` and `position_mutator` walk it through its `at`.
#!
#! Within the container, as within this trait, `iterator` names the type it
#! lends, so the trait is `iter` there, as `where I: iter<T>`.
#! @tparam T The type of the elements, which the iterators give references to.
pub trait iterable<T> {
#! What `iter(&this)` gives, which gives references that read the elements.
type iterator: iter<&T>;
#! What `iter(&mut this)` gives, which gives references that write them.
@optional
type mutator: iter<&mut T>;
#! Lends an iterator that reads the elements.
#! @param this The container to iterate.
#! @returns The iterator, which refers into the container.
def iter(&this): iterator;
#! Lends an iterator that writes the elements where they are.
#! @param this The container to iterate.
#! @returns The iterator, which refers into the container.
@optional
def iter(&mut this): mutator;
}
#! Walks the elements of whatever is indexed by position, from `0` up to a
#! length, giving a reference that reads each in turn through its `at`, from
#! either end. It is the `iterator` of a container that has no faster way to
#! walk its elements, as a ring buffer, whose elements are not one run, so the
#! container writes none of its own: `type ring<T>::iterator =
#! positions_iterator<ring<T>, T>;`.
#!
#! It refers to the container rather than to its elements, so it is only good
#! while the container stays where it is and holds at least as many elements.
#! @tparam C The container, indexed by position.
#! @tparam T The type of its elements.
pub struct positions_iterator<C, T> : sized_iterator<&T>, backward_iterator<&T> where C: indexable<u64, T> {
var _of: *C;
var _at: u64;
var _left: u64;
}
#! Makes an iterator over the elements of a container, from position `0` up to
#! a length.
#! @param of The container, which the iterator refers to.
#! @param length How many elements it gives, which the container holds.
#! @returns The iterator.
pub def positions_iterator<C, T>::over(of: &C, length: u64): positions_iterator<C, T> {
return positions_iterator::<C, T> { _of = &of, _at = 0, _left = length };
}
#! Gives the next element of the container.
#! @param this The iterator to advance.
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
pub def positions_iterator<C, T>::next(&mut this): maybe<&T> {
if this._left == 0 {
return nothing {};
}
val here := this._at;
this._at = here + 1;
this._left = this._left - 1;
return &(*this._of)[here];
}
#! How many elements the iterator has left to give.
#! @param this The iterator.
#! @returns How many.
pub def positions_iterator<C, T>::remaining(&this): u64 {
return this._left;
}
#! Gives the last element the iterator has left, from the far end.
#! @param this The iterator to advance from its far end.
#! @returns Maybe a reference to the element; otherwise, `nothing`.
pub def positions_iterator<C, T>::next_back(&mut this): maybe<&T> {
if this._left == 0 {
return nothing {};
}
this._left = this._left - 1;
return &(*this._of)[this._at + this._left];
}
#! Walks the elements of whatever is indexed by position and written there,
#! from `0` up to a length, giving a reference that writes each in turn through
#! its `at`, from either end. It is the `mutator` of a container that has no
#! faster way to walk its elements, as `positions_iterator` is its `iterator`.
#!
#! It refers to the container rather than to its elements, so it is only good
#! while the container stays where it is and holds at least as many elements.
#! @tparam C The container, indexed by position and written there.
#! @tparam T The type of its elements.
pub struct position_mutator<C, T> : sized_iterator<&mut T>, backward_iterator<&mut T> where C: assignable<u64, T> {
var _of: *mut C;
var _at: u64;
var _left: u64;
}
#! Makes an iterator writing the elements of a container, from position `0` up
#! to a length.
#! @param of The container, which the iterator refers to.
#! @param length How many elements it gives, which the container holds.
#! @returns The iterator.
pub def position_mutator<C, T>::over(of: &mut C, length: u64): position_mutator<C, T> {
return position_mutator::<C, T> { _of = &mut of, _at = 0, _left = length };
}
#! Gives the next element of the container, to be written.
#! @param this The iterator to advance.
#! @returns Maybe a reference to the next element; otherwise, `nothing`.
pub def position_mutator<C, T>::next(&mut this): maybe<&mut T> {
if this._left == 0 {
return nothing {};
}
val here := this._at;
this._at = here + 1;
this._left = this._left - 1;
return &mut (*this._of)[here];
}
#! How many elements the iterator has left to give.
#! @param this The iterator.
#! @returns How many.
pub def position_mutator<C, T>::remaining(&this): u64 {
return this._left;
}
#! Gives the last element the iterator has left, from the far end, to be
#! written.
#! @param this The iterator to advance from its far end.
#! @returns Maybe a reference to the element; otherwise, `nothing`.
pub def position_mutator<C, T>::next_back(&mut this): maybe<&mut T> {
if this._left == 0 {
return nothing {};
}
this._left = this._left - 1;
return &mut (*this._of)[this._at + this._left];
}
+267
View File
@@ -0,0 +1,267 @@
#! @file kinds.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the traits saying what kind of value a type's are: `numeric`, which
#! a type implements to have all of arithmetic, and which every number has, and
#! those the compiler gives: `integer` and `real`, with the functions parsing
#! each from text, `ordinal`, which every integer type and every enum is,
#! `zeroable`, which every type with a zero value is, and those naming the parts
#! of a type, as `signature` does a function's: `pointer`, `reference`, `array`,
#! and `generic`.
module core;
#! A type with arithmetic.
#!
#! It composes `additive` and `multiplicative`, and `divisible` and `modular`
#! beside them, so it asks for `add`, `sub`, `mul`, `div`, `rem`, and `negate`
#! between two values of the type, with their `equals`. `+`, `-`, `*`, `/`, and
#! `%` call them, the compound assignments such as `+=` call them too, and `-x`
#! calls `negate`. Numbers are numeric without declaring anything. It does not
#! ask for an order, so vectors and matrices can be numeric; write
#! `where T: numeric, ordered` for both.
#!
#! A type has each operator by the method that gives it, so one that means only
#! some of them declares only those, and satisfies the smaller traits this one
#! composes.
#!
#! Within a generic bounded by it, a constant such as `x + 1`, and `as` between
#! numbers, work where `T` is a number and are errors in an instance where it is
#! not.
pub trait numeric : additive, multiplicative, divisible, modular {}
#! An integer type, signed or unsigned, of any width.
#!
#! A type parameter bounded by `integer` has what numbers have, as `numeric` and
#! `ordered` give, along with bitwise operators, shifts, and indexing, and it is
#! `ordinal`. The compiler decides what is an integer, so no other type can
#! implement it.
pub trait integer {}
#! Reads the text as a signed 64-bit integer, in decimal or with a `0x`, `0o`,
#! or `0b` prefix, where `_` may separate digits.
#! @param this The text to read, which may start with `-` or `+`.
#! @returns The integer, or why the text is not one.
pub def integer::parse<T>(text: strview):
result<T, failure> where T : integer
{
var at := 0u;
var neg := false;
if text.length > 0 {
neg = text[0] == '-';
at = (text[0] == '+' || neg) as uint;
}
var base := 10u;
if text.length > at + 1 && text[at] == '0' {
val marker := text[at + 1];
if marker == 'x' || marker == 'X' { base = 16; } else
if marker == 'o' || marker == 'O' { base = 8; } else
if marker == 'b' || marker == 'B' { base = 2; }
if base != 10 { at += 2; }
}
return failure { $"`{text}` has no digits" }
if at >= text.length;
const signed := 0x8000000000000000u;
const unsigned := 0x7FFFFFFFFFFFFFFFu;
val limit := neg ? signed : unsigned;
var magnitude := 0u;
for byte in text[at:] {
continue if byte == '_';
val digit := byte.digit_value;
return failure { $"`{text}` is not a base {base} integer" }
if digit >= base;
return failure { $"`{text}` does not fit in 64 bits" }
if magnitude > (limit - digit) / base;
magnitude = magnitude * base + digit;
}
return neg
? (0 - magnitude) as T
: magnitude as T;
}
#! A type of real numbers: `f32` or `f64`, or an alias of either.
#!
#! A type parameter bounded by `real` has what numbers have, as `numeric` and
#! `ordered` give, along with a zero value, and `as` to and from the other
#! numbers. It is what the functions of `std::math` ask of what they take, as
#! `math::sqrt<T>(x: T): T where T: real`. The compiler decides what is real, so
#! no other type can implement it.
pub trait real {}
#! Reads the text as a real number such as `42`, `-0.5`, `.25`, or `6.02e23`.
#! @param this The text to read, which may start with `-` or `+`, and may end
#! with an exponent: `e` or `E`, an optional sign, and digits.
#! @returns The 64-bit float nearest the number, halfway between two going to
#! the one whose last bit is zero, or why the text is not one. A number
#! too large for 64 bits is a failure, and one too small is zero.
pub def real::parse<T>(text: strview):
result<T, failure> where T : real
{
var at := 0u;
var neg := false;
if text.length > 0 {
neg = text[0] == '-';
at = (text[0] == '+' || neg) as uint;
}
# The digits, with at most one `.` among them.
val start := at;
var digits := 0u;
var dotted := false;
while at < text.length {
val byte := text[at];
if byte == '.' && !dotted {
dotted = true;
} else {
break if !byte.is_digit;
digits++;
}
at++;
}
return failure { $"`{text}` is not a number" }
if digits == 0;
# The exponent, which is held at a hundred thousand, far past where every number
# is too large or too small, so a long one cannot overflow it.
var exponent := 0;
val written := text.substr(start, at - start);
if at < text.length && (text[at] == 'e' || text[at] == 'E') {
at++;
var down := false;
if at < text.length {
down = text[at] == '-';
at += (text[at] == '+' || down) as uint;
}
val first := at;
while at < text.length && text[at].is_digit {
if exponent < 100000 {
exponent = exponent * 10 + (text[at].digit_value as i64);
}
at++;
}
return failure { $"`{text}` has a malformed exponent" }
if at == first;
if down {
exponent = -exponent;
}
}
return failure { $"`{text}` is not a number" }
if at != text.length;
return failure { $"`{text}` is too large for 64 bits" }
if decimal_digits::nearest(written, exponent)
is not some(result);
return neg
? -result as T
: result as T;
}
#! A value that is an integer underneath: every integer type, and every enum.
#!
#! A type parameter bounded by `ordinal` compares with `==`, orders with `<`,
#! and converts to and from the integer types with `as`, which is what flags and
#! tables indexed by an enum need. An integer becomes an enum only when it is
#! some member's value, and stops the program otherwise.
#!
#! The compiler decides what is ordinal, so no other type can implement it.
pub trait ordinal {}
#! A pointer, whatever it points at, however many pointers deep.
#!
#! A pointer is an address. It is compared, ordered, and hashed as one, starts
#! as `null`, and moves by whole elements, so `p + 1` is the element after `p`,
#! and two pointers subtract to the number of elements between them. Nothing of
#! what it points at is reached through it: `*p`, `p[i]`, and `through(p)` reach
#! that.
#!
#! A type parameter bounded by `pointer` has what pointers have, as `equatable`,
#! `ordered`, and `zeroable` give, along with moving by an integer and
#! subtracting. The compiler decides what is a pointer, so no type can implement
#! it.
#!
#! A pointer names what it points at, `T::target`, and whether what it points at
#! is written through it, `T::mutable`, so `*mut u8` gives `u8` and `true`. A
#! pointer to a pointer gives the pointer it points at, one step at a time.
pub trait pointer {
#! The type it points at.
type target;
#! Whether it writes what it points at, as `*mut T` does.
const mutable: bool;
}
#! A reference, `&T` or `&mut T`.
#!
#! A reference names what it refers to, `T::target`, and whether it writes it,
#! `T::mutable`, so `&mut point` gives `point` and `true`. A type parameter is
#! a reference where it was given one, as `f(&x)` gives `T` the reference. A
#! reference satisfies other traits through what it refers to, but this one only
#! by being one. The compiler decides what is a reference, so no type can
#! implement it.
pub trait reference {
#! The type it refers to.
type target;
#! Whether it writes what it refers to, as `&mut T` does.
const mutable: bool;
}
#! A fixed array, `T[N]`.
#!
#! An array names the type of its elements, `T::element`, and how many it holds,
#! `T::length`, so `u8[16]` gives `u8` and `16`. An array of arrays gives the
#! array it holds, one step at a time. The compiler decides what is an array, so
#! no type can implement it.
pub trait array {
#! The type of its elements.
type element;
#! How many elements it holds.
const length: u64;
}
#! A generic type given its type arguments, as `vector<u8>` or `map<K, V>`.
#!
#! It names the pack of what it was given, `T::args`, in the order they are
#! written, with what a pack parameter was given in its place, so `pair<i64,
#! bool>` gives `(i64, bool)`, and `T is vector`, without arguments, says
#! whether it is an instance of `vector`. An alias is the type it names, so
#! `strview` gives `(u8)` as `span<u8>` does. A type without type parameters, a
#! pointer, a reference, an array, and a function are not generic. The compiler
#! decides what is generic, so no type can implement it.
pub trait generic {
#! The type arguments, as a pack, which only the compiler gives.
type args...;
}
#! A type with a zero value, which a variable left without a value starts at: a
#! number, `bool`, a pointer, an enum with a member of value 0, and an array,
#! struct, or union of what is, where a struct's fields with defaults start at
#! their defaults instead. A reference or a function is not, nor is what holds
#! one.
#!
#! Generic code bounded by it may write `var made: T;`, and code that only may
#! asks `if const T is zeroable` first.
#!
#! The compiler decides what is zeroable, so no type can implement it.
pub trait zeroable {}
+169
View File
@@ -0,0 +1,169 @@
#! @file ownership.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the traits saying what becomes of a value: `owning`, which a type
#! names to own what it holds and close it where its values go away, with the
#! function closing a value where it stands; `closeable`, which the compiler
#! gives every type whose values are closed; `copyable`, with `copy`, which
#! copies a value through it, or byte for byte where nothing it holds closes;
#! and `moveable`, with `move`, which moves a value through it, or byte for
#! byte.
module core;
#! Defines that a type owns what it holds, such as memory or a file, and
#! disposes of it in `close`. A value of a type naming `owning` is closed where
#! its scope ends, as RAII does, so that something like an allocator or
#! collection has released its data by the time it goes away.
#!
#! A type is owning only by naming the trait, so a `close` meant to be called by
#! hand never becomes a destructor by accident. A reference to an owning value
#! owns nothing, so it is never owning, though `close` is called through it.
#!
#! Unlike `copyable` and `moveable`, nothing fails where a type is not owning:
#! generic code asks `if const owns::<T>::value`, or calls `close`, which closes
#! whatever is given as its scope ending would.
pub trait owning {
#! Disposes of what the value owns, as its scope ending does.
#! @param this The value to close, which should be left empty, so closing it
#! again does nothing.
def close(&mut this): void;
}
#! Closes a value where it stands, as its scope ending would: through its own
#! `close` where it is `owning`, then each value it holds that closes, such as
#! a `string` in a field, the last first. A value that closes nothing is left
#! alone.
#! @tparam T The type of the value.
#! @param value The value to close, which is left empty.
#! @remarks Containers close their elements with it, so that an element holding
#! something that closes is closed as a local holding it would be.
pub def close<T>(value: &mut T): void {
if const T is closeable {
close_where_it_is(value);
memset(value as *mut u8, 0, size_of::<T>());
}
}
# Closes a value where it is, as the compiler closes a local whose scope ends:
# its own `close` where it is `owning`, then each field that closes, the last
# first, or the field a union holds, or each element of a fixed array.
@intrinsic
def close_where_it_is<T>(value: &mut T): void;
#! A type whose values are closed where they go away: one that is `owning`, or
#! one holding a value that is, in a field or an element.
#!
#! Generic code asks `if const T is closeable` where what it does only matters
#! for values that close, such as emptying the memory a value was moved out of
#! so that it is not closed twice, which plain data has no need of.
#!
#! The compiler decides what is closeable, so no type can implement it.
pub trait closeable {}
#! A type whose values can be copied, by a static function building a copy of
#! another value.
#!
#! The function is static, and gives the copy back rather than filling a
#! destination that already exists, so that returning it writes straight into
#! whatever takes it and nothing throwaway is built on the way.
#!
#! A type that must not be copied simply does not implement this trait, which is
#! why the function gives the copy rather than an error: the type system says
#! what cannot be copied, and running out of memory stops the program, as
#! `acquire` does.
pub trait copyable {
#! Builds a copy of a value, which owns copies of whatever the value owns.
#! @param other The value to copy.
#! @returns The copy.
def copy_of(other: &self): self;
}
#! Shortcut function for copying a value, giving the copy back.
#! @tparam T The type of the value.
#! @param src The source object to copy.
#! @returns The copy, which whatever takes it owns. A type that is `copyable` is
#! copied by its `copy_of`, and one that closes nothing byte for byte.
#! @remarks The copy is given back rather than written into a destination that
#! already exists, so that returning it writes straight into whatever
#! takes it. A type that closes, or holds what does, and is not
#! `copyable` is an error where it is copied, since its bytes would
#! share what it closes, and both copies would close it.
pub def copy<T>(src: &T): T {
if const T is copyable {
return T::copy_of(src);
}
if const T is closeable {
compile_error("`copy` copies a value that closes, or holds one that does, only through `copyable`, which this type does not implement.");
}
return src;
}
#! Defines that a type or generic must conform to being moveable, where the data
#! of one object is handed to a new one and the source left empty.
#!
#! The function is static, and gives the moved value back rather than filling a
#! destination that already exists, so that returning it writes straight into
#! whatever takes it and nothing throwaway is built on the way.
#!
#! The source is `&mut` because a move empties it, which is the whole difference
#! between this and `copyable`. What it leaves is valid but empty rather than
#! dead, so closing it afterwards is harmless.
pub trait moveable {
#! Builds a value from what another holds, leaving the other empty.
#! @param other The value to move from, which is left empty but valid.
#! @returns The new value, holding what the other held.
def move_of(other: &mut self): self;
}
#! Moves a value out of where it stands, leaving it empty.
#! @tparam T The type of the value.
#! @param src The value to move from, which holds nothing after.
#! @returns The moved value, which whatever takes it owns. A type that is
#! `moveable` is moved by its `move_of`, and any other byte for byte.
#! @remarks The source is left valid but empty rather than dead, so closing it
#! afterwards is harmless: one that closes, or holds what does, is
#! zeroed. Plain data, which nothing closes, is left as it was.
pub def move<T>(src: &mut T): T {
if const T is moveable {
return T::move_of(src);
}
# Plain data, which nothing closes, is copied as it is.
if const !(T is closeable) {
return src;
}
# Fallback: read the value out byte for byte, then leave the source zeroed, so it
# is not closed twice: by a store of each word where it is one to four words, as
# most that close are, and by `memset` otherwise.
val made := bits_of(src as *T);
val words := src as *mut u64;
if const size_of::<T>() == 8 {
words[0] = 0;
} else if const size_of::<T>() == 16 {
words[0] = 0;
words[1] = 0;
} else if const size_of::<T>() == 24 {
words[0] = 0;
words[1] = 0;
words[2] = 0;
} else if const size_of::<T>() == 32 {
words[0] = 0;
words[1] = 0;
words[2] = 0;
words[3] = 0;
} else {
memset(src as *mut u8, 0, size_of::<T>());
}
return made;
}
# The value a pointer points at, byte for byte. A `return` hands over what a pointer
# points at without emptying it, so the caller decides what is left there.
def bits_of<T>(from: *T): T {
return from[0];
}