Initial Commit
This commit is contained in:
706 files changed
+135430
No files matched your search
@@ -0,0 +1,9 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = true
|
||||
insert_final_newline = true
|
||||
@@ -0,0 +1 @@
|
||||
.blossom
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
# Changelog
|
||||
|
||||
Each version's changes, newest first. Versions follow [semantic
|
||||
versioning](https://semver.org).
|
||||
|
||||
## Unreleased
|
||||
|
||||
- Checking holds less and does less: of the compiler's own sources, the
|
||||
analyzer's tables take 28 MB where they took 49, and checking them runs
|
||||
1,440 million instructions where it ran 1,900, with a fifth fewer cycles.
|
||||
- A token keeps its kind, where it begins, and its name. How many bytes it
|
||||
covers is its kind's, or its name's, and only a literal's is kept. A node
|
||||
keeps where it ends in a byte, as how many tokens past its own.
|
||||
- The token and node vectors are trimmed to fit once a file is read.
|
||||
- A node's result flags take two bytes. The type it converts to and the
|
||||
constant it is, which few nodes have, are kept by row in maps rather than
|
||||
in columns mostly of zeros, and each constant is kept once.
|
||||
- The checker's maps hold a key and a value, twelve bytes a slot, where a
|
||||
`dict` took forty, and types, constants, and known values are found by
|
||||
their hash in an index of IDs, eight bytes a slot.
|
||||
- The resolver looks each path up by the IDs of its names, once for the
|
||||
program, where it made the path's text again in each file, a tenth of
|
||||
checking.
|
||||
- The lifetime warnings walk each body on one stack, noting where its locals
|
||||
are in a column by node, where they made a vector for each node and two
|
||||
maps for each function, an eighth of checking.
|
||||
- A frame zeroes a cell whose address a call is given, or an edge, only where
|
||||
a word of it may not be written yet, and the copy of a function inlined
|
||||
clears only the cells its own frame would zero, where it cleared every one:
|
||||
the checker's `expr` cleared 1.9 KB on each call. Checking the compiler runs
|
||||
5% fewer instructions.
|
||||
- `values_of` in a default argument evaluates the locals of the call where it
|
||||
was written, rather than a parameter of the function whose default it is
|
||||
with the same node in another file, which gave a wrong value, or none, as
|
||||
`std::testing`'s `expects` did of a loop's variable, stopping the virtual
|
||||
machine.
|
||||
- `sakura::analyzer`'s interface changed:
|
||||
- `source::open` takes the path alone, and `names::new` and `syntax::new`
|
||||
take no allocator.
|
||||
- `parser::new`, `syntax::reparse`, `syntax::print`, and `syntax::token`
|
||||
take the names the tokens were lexed with, and `syntax::token_length`
|
||||
gives a token's length, for `token_lengths`.
|
||||
- `syntax::node_end` and `syntax::set_node_end` read and write where a node
|
||||
ends, for `node_ends`.
|
||||
- A `note` holds its `detail`, `instance`, and `related` as `string`s, so it
|
||||
is moved rather than copied: `note_sink::give` and what hears notes take
|
||||
`&mut note`, `checker::keep` is gone, and `report_text` and `warn_text`
|
||||
take `&string`.
|
||||
- The kinds of type are `ty`, for `tkind`, and the words the checker knows
|
||||
are `word`'s members, constants, for `checker.words`.
|
||||
- `resolver::refer` is given the program's one table of names for each file.
|
||||
- `id_index` takes the place of `chains`, and `core`'s `trailing_zeros` of
|
||||
`lowest_bit`.
|
||||
|
||||
- Executables work `f32` arithmetic in single precision, `addss` and the rest,
|
||||
where every reader rounds it to an `f32` anyway, which gives the same bits, and
|
||||
hold `f32`s as `f32`s where every reader takes one, rather than converting
|
||||
each way around every operation.
|
||||
- The register allocator keeps a value a loop reads in every arm in one register
|
||||
through the loop: one living across a call takes a register a call keeps from
|
||||
a value read later, and none takes a register from a value read more often.
|
||||
The virtual machine's loop does about half the work it did for each operation.
|
||||
- A function calling one whose x86-64-v3 version is small enough to be inlined
|
||||
gets a version too, so `simd`'s `fma` in a loop is one instruction there.
|
||||
- `simd`'s `fma` is `vfmadd231ps` or `vfmadd231pd` alone. It also took the
|
||||
product where it was NaN, five instructions more, to give the NaN std's `fma`
|
||||
gave without FMA3, which gives the instruction's now.
|
||||
- Splatting `f32`, `f64`, and 32-bit lanes shuffles within the register, and an
|
||||
`f32` only splats read is held as an `f32` too, rather than converted to an
|
||||
`f64` and back.
|
||||
- A function returning memory copies it 16 bytes at a time, as callers read it
|
||||
back, so the processor forwards the stores.
|
||||
- Each function begins at a multiple of 16 bytes.
|
||||
- The virtual machine works an `f32` arithmetic and its rounding as one
|
||||
operation, and each arithmetic of reals as a case of its own.
|
||||
- The virtual machine's loop keeps why it stops in a register: each check of
|
||||
its steps gives the reason, rather than writing it where the loop read it
|
||||
back every operation.
|
||||
- A loop whose head jumps through a table, as the virtual machine's loop over
|
||||
its operations does, begins that head at a multiple of 64 bytes, so it never
|
||||
lies across two lines of the cache. The machine's loop ran 16% slower where
|
||||
it did, as code before it grew or shrank.
|
||||
- `@inline` copies a function, method, or property wherever it's called, at
|
||||
every level, `-O0` too, whatever its size, and `core`'s word and byte tests
|
||||
are `@inline`, so `-O0` searches of text no longer call a function for each
|
||||
word.
|
||||
- Debugging information keeps a variable whose value is a constant the
|
||||
optimizer made where it's read, so gdb shows a parameter given a constant, as
|
||||
`scale (by=2)`, at `-O2` too.
|
||||
- A `compile_error` in a branch of `if const` that only running the condition
|
||||
decides, as `if const size_of::<A>() != size_of::<B>()`, is reported once the
|
||||
condition chooses that branch, by `check`, `run`, and `build` alike, rather
|
||||
than stopping the program as it runs; one in a branch not chosen never is.
|
||||
- `compile_error` says text it is given that isn't written, a constant's or text
|
||||
worked out while compiling, as `$"{f.name} is not read"`, rather than "The
|
||||
program reports an error here."
|
||||
- The accessors of a generic type's property are checked for each instance a
|
||||
value reaches, as a method called is, so a `compile_error` in one is reported
|
||||
while checking, rather than stopping lowering without the note.
|
||||
- `simd`'s `bits` refuses a vector of another size while compiling, rather than
|
||||
stopping the program as it runs.
|
||||
- `lanes_have` and `lanes_apply` take one real alone, worked with the
|
||||
instruction of one number: `roundss` and `roundsd`, `sqrtss` and `sqrtsd`, and
|
||||
`vfmadd231ss` and `vfmadd231sd`.
|
||||
- Counting a word's ones, leading zeros, and trailing zeros is `popcnt`,
|
||||
`lzcnt`, and `tzcnt` in a function's x86-64-v3 version, which asks for them.
|
||||
`SAKURA_CPU` names `popcnt`, `lzcnt`, `bmi1`, `avx512`, and `x86-64-v4` too.
|
||||
- `simd`'s lanes are worked with instructions where they were a lane at a time:
|
||||
`*` of every width of integer, the least and greatest of 64-bit lanes, `abs`
|
||||
and `>>` of `i64`, shifts of bytes, `round`, `sum`, the `product` of reals,
|
||||
the `smallest` and `largest` of integers, `shuffle`, by `pshufb` and across 32
|
||||
bytes `vpermd`, `convert`, and gathering. A constant vector, as a splat of a
|
||||
constant, is read from constants written after the function.
|
||||
- `simd` has `low` and `high`, the halves of 32 bytes, `join`, of two of 16,
|
||||
`widened` and `widened_high`, each lane twice as wide, `narrowed`, half as
|
||||
wide and saturated, `gather`, and `scatter`.
|
||||
- Vectors of 64 bytes, of 16 bits a lane or more: `f32x16`, `f64x8`, `i16x32`,
|
||||
`u16x32`, `i32x16`, `u32x16`, `i64x8`, and `u64x8`. Executables work them with
|
||||
AVX-512 where the processor has it, which an x86-64-v3 version still asks,
|
||||
and a half or a quarter at a time where it doesn't.
|
||||
- The stores filling 16 bytes of a struct, four `f32`s or two words, are merged
|
||||
into one store of a vector, so a struct returned in memory is copied out
|
||||
without waiting on each field: `linear`'s `cross` takes 12 cycles where it
|
||||
took 30, and `quat * quat` 18 where it took 35.
|
||||
- A narrow integer held as a value is wrapped once, where it was wrapped again
|
||||
as each field read and through each loop's parameter, so a loop of
|
||||
`vec3<i32>` arithmetic takes 11 ms where it took 17.
|
||||
- The register allocator weighs values by how often they're read only where they
|
||||
live in a loop. Elsewhere it spills the value read furthest ahead, rather than
|
||||
each value as it's made, which it read straight back, as `linear`'s
|
||||
`mat4::inverse` did with nearly every product.
|
||||
|
||||
## 1.0.0 - Unreleased
|
||||
|
||||
- The first version of `sakurac`, the Sakura compiler, written in Sakura and
|
||||
built by itself. It holds:
|
||||
- the command line: `check`; `run`, on the virtual machine; `build`, of
|
||||
standalone x86-64 executables for Linux and Windows, with no assembler,
|
||||
linker, or C library; and `lsp`, the language server;
|
||||
- the language as the README describes it;
|
||||
- `core`, `system`, and the runtime, in `runtime`, found beside the compiler, and
|
||||
the standard library;
|
||||
- checked programs, with `run --checks` checking memory too, and contracts,
|
||||
which `--contracts off` leaves out;
|
||||
- debugging information, as DWARF, and for Windows as a PDB file too;
|
||||
- the tests, run with `blossom test`.
|
||||
- Its parts are libraries of this repository, each in the folder of its name
|
||||
with its tests in `tests/`, and exported for other projects to read:
|
||||
- `sakura::analyzer`: the lexer and parser, with reparsing after an edit; the
|
||||
checker, with checking again after an edit and the evaluation of constants;
|
||||
the resolver finding a program's library files; and the queries the language
|
||||
server answers with;
|
||||
- `sakura::compiler`: lowering a checked program to intermediate code,
|
||||
verifying and optimizing it, and assembling each function into the
|
||||
machine's code, on threads, with the same result however many there are;
|
||||
- `sakura::machine`: the virtual machine `run` runs programs on, with its
|
||||
heap, its threads, and its calls to the system and to C; the memory checks
|
||||
`run --checks` asks for; and the evaluation of constants while compiling;
|
||||
- `sakura::native`: x86-64 executables for Linux as ELF and for Windows as PE;
|
||||
the selection of instructions, with SSE and AVX for a `simd`'s lanes; the
|
||||
register allocator, and the checker replaying what it chose; calls to C and
|
||||
from it; and the debugging information, as DWARF and as a PDB file;
|
||||
- `sakura::server`: the language server `lsp` serves, with diagnostics,
|
||||
hovering, completion, signature help, colouring, going to a declaration,
|
||||
finding references, and renaming, each job in a process of its own; and
|
||||
`toolchain_folder`, which finds `core`, `system`, and `runtime`.
|
||||
- Each was a package of its own, at version 1.0.0, from 2026-10-25 or 2026-10-26
|
||||
until it came back on 2026-10-26.
|
||||
- The standard library is a repository of its own, `sakura/std`, each module
|
||||
a library of its own, which it requires, naming the modules each of its
|
||||
libraries reads. Its tests went with it, but for those of `core` and
|
||||
`system`, which ship with the compiler, as `tests/core`.
|
||||
- `core` holds only what the compiler names, or what that, `system`, and the
|
||||
runtime are built from:
|
||||
- `dict`, `hashset`, `rc`, `arc`, and `arena` are std's, as are the streams'
|
||||
traits, `readable`, `writable`, and `flushable`, with `string`'s `write`
|
||||
and `strview`'s `read`, so the built-in `string` names no `writable`;
|
||||
- `io_error` is `system`'s;
|
||||
- `core::intrinsics` holds `square_root`, `lanes_have`, and `lanes_apply`,
|
||||
which `std::math` declared, and `system` holds `start`, which
|
||||
`std::thread` did, so std declares no intrinsic.
|
||||
- The standard library is the folder `--lib std=DIR` names, else a `std`
|
||||
folder beside the compiler or above it, else its libraries in the
|
||||
`share/sakura` folder above it, where `blossom install` puts them. `--std`
|
||||
and `SAKURA_STD` are gone, and `sakurac lsp` finds it the same way.
|
||||
- `install` puts `system` beside `core` and `runtime`.
|
||||
- It requires packages for the standard library, `std::args` and `std::json`
|
||||
among it, and for the back end's libraries, in `binary`.
|
||||
- Fixed, from what building `hearth` met:
|
||||
- `close(x)`, which a `box` and the containers close what they hold with,
|
||||
closed a value's own `close` but not its fields after, as a scope ending
|
||||
does, so what the fields held leaked; and generic code closing a type of
|
||||
another module whose `close` isn't `pub` was refused. It's the compiler's
|
||||
own closing now, `close_where_it_is`.
|
||||
- `f(...xs)` copied a pack's values that close to the function given them,
|
||||
so both closed them; it moves them.
|
||||
- An anonymous function whose parameters' types are written gives its type
|
||||
to a type parameter where overloads are chosen between, and to the type
|
||||
parameters a function type leaves unknown, as `T` of `def(&T): bool`,
|
||||
where before neither was given and the call was refused.
|
||||
- `? :` names what its condition's `is` tests give, as `if` does.
|
||||
- `for` walks a literal of text, as the `strview` it settles as.
|
||||
- A pack of types has a `length`, as `Ts.length`.
|
||||
- A folder holding a module's file and the one file of a module within it,
|
||||
as `nest/nest.sakura` and `nest/deeper.sakura`, was taken for the deeper
|
||||
module's alone, by its first file, which hid the folder's own module.
|
||||
- A file beginning with UTF-8's byte order mark is read past it.
|
||||
- `decl_of` of a type no declaration makes, as a reference, is refused where
|
||||
it's checked, rather than failing as it's lowered.
|
||||
- The checker's columns are given back as a checker closes, which the
|
||||
language server leaked a checker's worth of with each check.
|
||||
- Notes: a property called, as `m.is_none()`, says it's a property; and a
|
||||
copy an `is` test names, written, says `&mut` names the reference.
|
||||
- `is some(_)`, `is not some(_)`, and an arm's `some(_)` took a field that
|
||||
closes out of the union and closed it, through a reference too, so the
|
||||
union's owner lost it; `_` names nothing, and takes nothing.
|
||||
- The condition of an `if const` within a pass of `for const` over
|
||||
reflection, where only evaluating decides it, as `d.name == "x"`, couldn't
|
||||
read the pass's description, which evaluating's function never declared.
|
||||
- `path_of::<T>()` spells a type with the module of each type it names, as
|
||||
`&mut game::position`, which no two types share, as `name_of` doesn't.
|
||||
- `sakura::machine` is embeddable, as `hearth::scripting` runs scripts:
|
||||
- `begin` gives a program's globals their values without calling `main`, and
|
||||
`call` and `call_value` call a function, or a function value, given the
|
||||
words of its parameters, `result` giving the words it returned;
|
||||
- `provide` gives a foreign declaration's name a function of the host's, as
|
||||
a `cfn`, found before any library's, which may call back into the program,
|
||||
a fault there stopping the calls under way as the host returns to them;
|
||||
- `interpreting::steps` stops a call taking more steps than that, with the
|
||||
new `halt::step_limit`;
|
||||
- `interpreting::capture`, `stack`, and `steps` are `pub`, and `take_output`
|
||||
gives what was kept; on Windows it keeps what `WriteFile` and
|
||||
`WriteConsoleW` write to the output and error, as it kept Linux's `write`
|
||||
alone before;
|
||||
- a fault in a function C called back keeps the trace of where each function
|
||||
was, which the program's call of C ending forgot.
|
||||
@@ -0,0 +1,18 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Malunal Studios, LLC.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
||||
associated documentation files (the "Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
|
||||
following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial
|
||||
portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
|
||||
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
|
||||
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
|
||||
USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,143 @@
|
||||
# sakura::analyzer
|
||||
|
||||
`sakura::analyzer` is the front end of the compiler and of its language server.
|
||||
It holds the lexer, the parser, and the checker, which keep what they work out
|
||||
in tables of numbers, a column for each field, so a pass reads only what it
|
||||
needs and little memory is spent on each token and node. The checker works out what each
|
||||
name refers to and the type of each expression, and notes what is wrong. After
|
||||
an edit, it checks again only what the edit touched. It also answers what an
|
||||
editor asks of a checked program. `sakura::compiler` lowers what it checks to
|
||||
code.
|
||||
|
||||
## Using it
|
||||
|
||||
Require this repository, which exports each of the compiler's libraries, and name this
|
||||
one among a target's `deps`:
|
||||
|
||||
```yaml
|
||||
requires:
|
||||
- https://git.malunal.studio/sakura/std@v1.0.0
|
||||
- https://git.malunal.studio/sakura/sakurac@v1.0.0
|
||||
|
||||
targets:
|
||||
- name: app
|
||||
type: program
|
||||
deps: [sakura.analyzer, std.io]
|
||||
```
|
||||
|
||||
Every program is checked with two things: `core`, the folder beside the
|
||||
`sakura` executable, read whole; and the types the syntax makes, which the
|
||||
analyzer holds as `builtin_text`:
|
||||
|
||||
```sakura
|
||||
import std::io;
|
||||
import sakura::analyzer;
|
||||
|
||||
# Checks a file importing nothing, with `core`, whose folder is given, and
|
||||
# prints each note as `sakura check` does. Gives how many there were.
|
||||
def check(path: strview, core: strview): u64 {
|
||||
var paths := vector::<string>::new();
|
||||
paths.append(string::from(path, nothing {}));
|
||||
paths.append(string::from(builtin_path, nothing {})); # The types the syntax makes.
|
||||
every_file(core, &mut paths);
|
||||
|
||||
var names := names::new();
|
||||
var notes := vector::<note>::new();
|
||||
var sources := vector::<source>::new();
|
||||
var syntaxes := vector::<syntax>::new();
|
||||
var roots := vector::<u32>::new();
|
||||
# The checker refers to each source and syntax, so none moves once made.
|
||||
sources.reserve(paths.length);
|
||||
syntaxes.reserve(paths.length);
|
||||
for i in 0..paths.length {
|
||||
val at := paths[i].view();
|
||||
sources.append(at == builtin_path ? source::from(at, builtin_text) : source::open(at));
|
||||
syntaxes.append(syntax::new());
|
||||
var lexing := lexer::new(sources.at(i), &mut names, &mut notes, i as u32);
|
||||
lexing.tokenize_all(syntaxes.at(i));
|
||||
var parsing := parser::new(syntaxes.at(i), &names, &mut notes, i as u32);
|
||||
roots.append(parsing.parse());
|
||||
}
|
||||
|
||||
var checker := checker::new(&mut names, &mut notes);
|
||||
for i in 0..paths.length {
|
||||
checker.add(sources.at(i), syntaxes.at(i), roots.at(i));
|
||||
}
|
||||
checker.check();
|
||||
for &each in notes {
|
||||
val held := &sources.at(each.file);
|
||||
val at := held.lines.place_of(each.offset);
|
||||
println($"{held.path}:{at.line}:{at.column}: {each.code}: {each.message(held)}");
|
||||
}
|
||||
return notes.length;
|
||||
}
|
||||
```
|
||||
|
||||
Given a file whose `main` holds `val x: i32 = true;` and `val y: u8 = 300;`, it
|
||||
prints:
|
||||
|
||||
```
|
||||
wrong.sakura:2:16: mismatch: Expected `i32`, but the value is `bool`.
|
||||
wrong.sakura:3:15: overflow: The constant is outside the range of `u8`.
|
||||
```
|
||||
|
||||
A program that imports modules is read a round at a time by a `resolver`. It
|
||||
is given the libraries: `whole` for `core`, and `add_library` for `system`,
|
||||
`std` and the rest. After each round, `refer` adds the files of the modules
|
||||
that round's files refer to, until a round refers to nothing new.
|
||||
`sakura::machine`'s README does that. Every file it is given is read with the
|
||||
program's one table of names, which it looks each path up by.
|
||||
|
||||
## What it holds
|
||||
|
||||
- **Sources**:
|
||||
- `source` is a file's text and where its lines begin (`lines`, `place_of`),
|
||||
opened from a path or made from text.
|
||||
- `names` gives each word an ID, the keywords first, then the words the
|
||||
parser and the checker know by ID (`word`), and keeps each word's text in
|
||||
blocks that never move.
|
||||
- **Lexing and parsing**:
|
||||
- `lexer` reads a source into a `syntax`'s tokens, and `parser` builds its
|
||||
tree. Each node has a kind (`nk`), a token, and two slots, whose meaning
|
||||
its `shape` gives, and where it ends, as how many tokens past its own.
|
||||
- A token keeps its kind, where it begins, and its name. How many bytes it
|
||||
covers is its kind's, for a keyword or a punctuator, or its name's, and
|
||||
only a literal's is kept, which `token_length` reads.
|
||||
- `walker` finds the nodes a node holds, and `printer` writes a tree as text.
|
||||
- `syntax::reparse` parses again only the declarations an edit touched.
|
||||
- `read_files` reads files on threads, giving each word the ID it would have
|
||||
if the files were read one after another.
|
||||
- **Checking**: `checker` declares each file's names, then checks every body.
|
||||
- Each part of the language has its own file in `checker/`: lookup, types,
|
||||
conversions, calls and overloads, generics and their instances, traits,
|
||||
operators, patterns, properties, ownership, lifetimes, contracts and
|
||||
checks, attributes, and reflection.
|
||||
- It folds constants. Where a value must be known but folding can't give it,
|
||||
such as an array's length, it runs the code that gives it.
|
||||
- `update` takes a file parsed again and checks again only what changed and
|
||||
what depends on it.
|
||||
- Its tables keep each field in a `column` of its own. What few rows have,
|
||||
as the type a node converts to, is in a `keymap` by row rather than a
|
||||
column mostly of zeros, and what is interned, as types and constants, is
|
||||
found by its hash in an `id_index`.
|
||||
- **Notes**: a `note` says what is wrong and where, with its code (`ec`), its
|
||||
message, and any place it relates to, and holds its text, so it is moved
|
||||
rather than copied. The lexer, parser and checker put notes in a
|
||||
`note_sink`, which keeps them or hands each on as it is made.
|
||||
- **Libraries**: `resolver` finds the files of the modules a program's files
|
||||
refer to, in the libraries it is given. Each library is a folder named by a
|
||||
module, such as `std` or `sakura::analyzer`.
|
||||
- **Queries**: what an editor asks of a checked program, which the language
|
||||
server answers with: `hover`, `complete`, `calls_at` for signature help,
|
||||
`name_at` and `references`, `highlights`, and which program a file belongs to.
|
||||
|
||||
## Testing
|
||||
|
||||
From the repository's root, `blossom test` runs them as `sakura.analyzer.tests`, or:
|
||||
|
||||
```sh
|
||||
sakurac run --lib sakura::analyzer=analyzer tests/main.sakura tests/analyzer/*.sakura
|
||||
```
|
||||
|
||||
The tests are declared within the module, so they can reach its private names.
|
||||
Add `-- --only TEXT` to run only the tests whose name contains the text.
|
||||
@@ -0,0 +1,98 @@
|
||||
#! @file builtin.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the types the syntax makes, which the compiler holds itself rather
|
||||
#! than finding them in a library: `string`, which interpolation makes, the
|
||||
#! views `span`, `slice`, and `strview`, which `a[:]` and literals make, `range`,
|
||||
#! which `a..b` makes, and `maybe`, `result`, and `nothing`, which `else`, `for`,
|
||||
#! and `?` read. They are found where `i64` is, from every file.
|
||||
#!
|
||||
#! Their declarations are text read as the first file of `core`'s root, before
|
||||
#! `core`'s own, so what the compiler relies on of them is written here, beside
|
||||
#! the code relying on it: `string`'s fields in their order, `maybe`'s `none`
|
||||
#! first, `span`'s two words, and `range`'s three fields. They name `core`'s
|
||||
#! traits and `allocator`, so they are read only with `core`. Their methods are
|
||||
#! `core`'s, declared through them as `u8`'s are.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! The path the text is read as, which notes and traces into it name.
|
||||
pub const builtin_path: strview = "<built-in>";
|
||||
|
||||
#! The declarations of the types the syntax makes, as `core`'s root.
|
||||
pub const builtin_text: strview = """
|
||||
#! The types the syntax makes, which the compiler holds. Their methods are
|
||||
#! `core`'s.
|
||||
module core;
|
||||
|
||||
#! What a `maybe` holds where its value is missing, which `nothing {}` makes
|
||||
#! the empty one of any `maybe`. It is apart from `void`, the value of what
|
||||
#! gives nothing.
|
||||
pub struct nothing {}
|
||||
|
||||
#! A value that may be missing: either a `T`, as `some`, or `nothing`, as
|
||||
#! `none`, which comes first, so a `maybe` left without a value holds nothing.
|
||||
#! A value converts to a `maybe` of its type wherever one is wanted.
|
||||
#! @tparam T The type of the value it may hold.
|
||||
pub union maybe<T> {
|
||||
pub var none: nothing; #! Holds nothing: the value is missing.
|
||||
pub var some: T; #! Holds the value.
|
||||
}
|
||||
|
||||
#! The outcome of something that may fail: either the value it gave, as
|
||||
#! `value`, or the error that stopped it, as `error`, which must be handled
|
||||
#! where it is made.
|
||||
#! @tparam T The type of the value it gives where it succeeds.
|
||||
#! @tparam E The type of the error it gives where it fails.
|
||||
@nodiscard
|
||||
pub union result<T, E> {
|
||||
pub var value: T; #! The value, where it succeeded.
|
||||
pub var error: E; #! The error, where it failed.
|
||||
}
|
||||
|
||||
#! A view over a run of elements that something else holds: where they begin,
|
||||
#! and how many there are. It owns nothing, and writes nothing.
|
||||
#! @tparam T The type of the elements it views.
|
||||
pub struct span<T> : hashable, equatable, indexable<u64, T>, viewable<T>, iterable<T> {
|
||||
var _dat: *T;
|
||||
var _len: u64;
|
||||
}
|
||||
|
||||
#! A writable view over a run of elements that something else holds, which
|
||||
#! converts to a `span<T>` wherever a reader is wanted.
|
||||
#! @tparam T The type of the elements it views.
|
||||
pub struct slice<T> : hashable, equatable, indexable<u64, T>, viewable<T>, sliceable<T>, iterable<T> {
|
||||
var _dat: *mut T;
|
||||
var _len: u64;
|
||||
}
|
||||
|
||||
#! Text that is only read, as a literal is: a view of bytes.
|
||||
pub type strview = span<u8>;
|
||||
|
||||
#! Text that owns the memory its bytes are written in, which interpolation
|
||||
#! makes. Its memory is its allocator's, or `raw_allocate`'s where it has
|
||||
#! none, and goes back where its scope ends.
|
||||
pub struct string
|
||||
: owning, hashable, indexable<u64, u8>, viewable<u8>, sliceable<u8>, iterable<u8>,
|
||||
extendable<strview>, equatable, ordered, copyable, moveable
|
||||
{
|
||||
var _alc: maybe<&mut allocator>;
|
||||
var _dat: *mut u8;
|
||||
var _len: u64;
|
||||
var _cap: u64;
|
||||
}
|
||||
|
||||
#! The integers from `start` up to, but not including, `end`, as `a..b`
|
||||
#! makes, or through `end`, as `a..=b` makes, or the members of an enum
|
||||
#! between them, in the order of their values. The compiler makes one from
|
||||
#! its fields in the order they are declared.
|
||||
#! @tparam T The type of the integers, or the enum.
|
||||
pub struct range<T> : sized_iterator<T>, backward_iterator<T> where T: ordinal {
|
||||
pub var start: T; #! The first value it gives, while it gives any.
|
||||
pub var end: T; #! Where it ends: just past its last, or its last where it was made by `..=`.
|
||||
var _last: bool; #! Whether `end` is still to be given, as `a..=b` gives it.
|
||||
}
|
||||
""";
|
||||
@@ -0,0 +1,464 @@
|
||||
#! @file checker.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the checker, which works out what the parsed files of a program
|
||||
#! mean: what each name refers to, the type of each expression, and whether
|
||||
#! the program is valid, and `check`, where it begins. What it checks is split
|
||||
#! across the files of the `checker` directory, one for each part of the
|
||||
#! language, as the parser's are.
|
||||
#!
|
||||
#! The checker never changes a syntax. What it works out is kept in tables of
|
||||
#! its own: the types and declarations of the type table and declaration
|
||||
#! table, and the results of each node, which a result table holds for the
|
||||
#! node's file, or for the instance of a generic the node is checked in. An
|
||||
#! instance is checked over its template's nodes with a result table of its
|
||||
#! own, so nothing of the template is ever copied.
|
||||
|
||||
import std::containers;
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! A file the checker is given: its source, its syntax, and what the checker
|
||||
#! keeps of it.
|
||||
pub struct unit {
|
||||
pub var source: &source; #! The file's source, which its notes are placed in.
|
||||
pub val syntax: &syntax; #! What the file parsed into.
|
||||
var root: u32; #! The `document` node.
|
||||
var imports: u32; #! The run of the modules it imports, in the lists of the declarations.
|
||||
pub var table: u32; #! The result table of its nodes.
|
||||
var parses: u32; #! How many times its syntax had been parsed whole again when it was last checked.
|
||||
}
|
||||
|
||||
#! The results of a run of nodes of a file: those of the whole file, or of the
|
||||
#! nodes of a template, checked for one of its instances. A node's results are
|
||||
#! at `offset + node - base` of the result vectors.
|
||||
pub struct rtable {
|
||||
pub var file: u32; #! The file whose nodes it holds the results of.
|
||||
pub var base: u32; #! The first node it holds.
|
||||
pub var count: u32; #! How many nodes it holds.
|
||||
var offset: u32; #! Where its results begin in the result vectors.
|
||||
var instance: u32; #! One more than the instance it is of, or 0 for a file's.
|
||||
pub var parent: u32; #! One more than the table it was made within, which holds the nodes it does not, or 0.
|
||||
}
|
||||
|
||||
#! A value known while compiling: an integer, as its magnitude and sign, a
|
||||
#! float, or a `bool`, as a magnitude of 0 or 1. An integer's magnitude and a
|
||||
#! float's bits share one word, which `magnitude` and `real` read as the kind
|
||||
#! of constant says, so it takes sixteen bytes rather than thirty-two.
|
||||
pub struct constant {
|
||||
var word: u64; #! An integer's magnitude, a `bool` as 0 or 1, or a float's bits.
|
||||
pub var negative: bool; #! Whether an integer is below zero.
|
||||
pub var floating: bool; #! Whether it is a float, whose bits `word` holds.
|
||||
}
|
||||
|
||||
#! An instance of a generic function: its template, given type arguments, whose
|
||||
#! body is checked with a result table of its own once something uses it.
|
||||
pub struct instance {
|
||||
var decl: u32; #! The template.
|
||||
pub var args: u32; #! The pack of its type arguments, its owner's first.
|
||||
pub var table: u32; #! One more than its result table, once its body is checked.
|
||||
pub var kind: u32; #! Its function type.
|
||||
}
|
||||
|
||||
#! Where checking is: what a name resolves within, and what a body's
|
||||
#! statements are checked against. It is saved and put back as a whole where
|
||||
#! checking moves to another declaration, so nothing of one leaks into another.
|
||||
pub struct checker::frame {
|
||||
pub var file: u32; #! The file being checked.
|
||||
pub var table: u32; #! The result table being written.
|
||||
var base: u32; #! Of that table, kept here so reaching a node's results is quick.
|
||||
var offset: u32; #! Of that table, where its results begin.
|
||||
var count: u32; #! Of that table, how many nodes it holds.
|
||||
var decl: u32; #! The declaration whose signature or body is checked.
|
||||
var scope: u32; #! The type whose own names are named without it there, or 0.
|
||||
var home: u32; #! The module names resolve in.
|
||||
var result: u32; #! What `return` gives, in a function's body.
|
||||
var loops: u32; #! How many loops are around what is checked.
|
||||
var block: u32; #! The block whose statements are checked.
|
||||
var opened: u32; #! Where the bindings of that block begin, past which a local of the same name is declared twice.
|
||||
var body: u32; #! The block of the function whose body is checked, which every `return` leaves, so its `ensures` may name what it returns.
|
||||
pub var instance: u32; #! One more than the instance being checked, which notes name.
|
||||
var marks: u32; #! Where the bindings of the body begin.
|
||||
|
||||
# The fields of the nodes and tokens of the file being checked, which never
|
||||
# change while it is checked, so each is read where it is without a call.
|
||||
var kinds: *nk; #! The kind of each node.
|
||||
var tokens: *u32; #! The token each node says what it is by.
|
||||
var lefts: *u32; #! The first slot of each node.
|
||||
var rights: *u32; #! The second slot of each node.
|
||||
var extras: *u32; #! The records and runs the slots begin at.
|
||||
var names: *u32; #! The name of each token that is a word, or 0.
|
||||
var tkinds: *tk; #! The kind of each token.
|
||||
}
|
||||
|
||||
#! The target a program is checked for, which `when` decides by, each value
|
||||
#! the ID of its name.
|
||||
pub struct target {
|
||||
pub var os: u32; #! The operating system's name, as `linux`.
|
||||
pub var arch: u32; #! The processor's name, as `x86_64`.
|
||||
pub var backend: u32; #! How the program runs, as `vm`.
|
||||
}
|
||||
|
||||
#! A type parameter standing for a type a bound asks of another, as `C::cursor`
|
||||
#! where `C: walk`, which becomes the type the type given for `C` gives.
|
||||
pub struct checker::stand_in {
|
||||
var base: u32; #! The type parameter's type it is asked of.
|
||||
var asked: u32; #! The declaration of the type the bound asks for.
|
||||
var param: u32; #! The declaration of the parameter standing for it.
|
||||
var bound: u32; #! The bound asking for it.
|
||||
}
|
||||
|
||||
#! A branch of an `if const` whose condition only evaluating decides, around
|
||||
#! what is checked.
|
||||
pub struct checker::branch {
|
||||
pub var table: u32; #! The result table the `if const` was checked in.
|
||||
pub var node: u32; #! The `if_const` node.
|
||||
pub var holds: bool; #! Whether it is the branch taken where the condition holds.
|
||||
}
|
||||
|
||||
#! A `compile_error` checking leaves to evaluating: one within branches of
|
||||
#! `if const` only evaluating decides, reported where each is the one taken, or
|
||||
#! one given text that is not written, which evaluating works out.
|
||||
pub struct checker::held_error {
|
||||
pub var table: u32; #! The result table it was checked in.
|
||||
pub var node: u32; #! The `call` node.
|
||||
var file: u32; #! The file it is reported in.
|
||||
var place: u32; #! The node it is reported at: the call, or the declaration whose `at` it was given.
|
||||
var decl: u32; #! The declaration whose body it is in.
|
||||
var instance: u32; #! One more than the instance it was checked in, which its note names, or 0.
|
||||
var detail: string; #! What it says, where checking knew it.
|
||||
pub var first: u32; #! The first of the branches around it, in `held_branches`.
|
||||
pub var count: u32; #! How many branches are around it.
|
||||
pub var computed: bool; #! Whether evaluating works out what it says.
|
||||
}
|
||||
|
||||
#! The checker.
|
||||
pub struct checker {
|
||||
pub var names: &mut names; #! The names the files were lexed with, which the checker interns more into.
|
||||
pub var sink: note_sink; #! Where what the checker finds is noted, kept or heard as it is made, which `max_notes` bounds.
|
||||
pub var units: vector<unit>; #! The files it is given, by their index.
|
||||
pub var types: type_table; #! Every type, by its ID.
|
||||
pub var decls: decl_table; #! Every declaration, by its ID.
|
||||
pub var modules: module_table; #! Every module, by its ID.
|
||||
pub var target: target; #! The target the program is checked for.
|
||||
pub var contracts_off: bool; #! Whether contracts are left out, conditions and all, as `--contracts off` asks.
|
||||
pub var checks_off: bool; #! Whether the checks a checked build makes are left out, as a build without `--checks` and `run --fast` ask.
|
||||
pub var at: checker::frame; #! Where checking is.
|
||||
|
||||
# Results: a table for each file and each instance, whose nodes' types,
|
||||
# what they refer to, and flags are runs of these columns, a row for each
|
||||
# node. The few nodes that convert, or whose values are known, are found by
|
||||
# their rows in maps of their own, rather than in columns mostly of zeros.
|
||||
pub var tables: column<rtable>; #! The result tables, of each file and each instance.
|
||||
var r_types: column<u32>; #! The type of each node, by table.
|
||||
var r_refs: column<u32>; #! What each node refers to, by table.
|
||||
var r_flags: column<u16>; #! The flags of each node, by table.
|
||||
var r_converts: keymap; #! The type each node converts to, where it is not its own, by its row.
|
||||
var r_values: keymap; #! The constant each node is, by index in `constants`, by its row, where it is known.
|
||||
var converts: keymap; #! The type a node no table holds converts to: `table << 32 | node`.
|
||||
var values: keymap; #! The constant a node no table holds is, by index in `constants`: `table << 32 | node`.
|
||||
var constants: column<constant>; #! The constants nodes and declarations are, each once, the first a zero constant standing for none.
|
||||
var constant_index: id_index; #! The constants of each hash, which interning finds them by.
|
||||
|
||||
# Bindings: the locals, parameters, and type parameters names refer to, a
|
||||
# stack cut back where each scope ends. `innermost` holds one more than the
|
||||
# binding of each name nearest the top.
|
||||
var bind_names: vector<u32>; #! The name of each binding, from the bottom of the stack.
|
||||
var bind_values: vector<u32>; #! What each binding refers to.
|
||||
var bind_prev: vector<u32>; #! The binding of the same name each hides, plus one, or 0.
|
||||
var innermost: vector<u32>; #! One more than the binding of each name nearest the top, by its name.
|
||||
|
||||
# Declarations: those every program has, those declared through a type that
|
||||
# wait for their type to resolve, and those of std the checker gives meaning.
|
||||
var builtins: dict<u32, u32>; #! The declaration of each built-in type, by its name.
|
||||
pub var shelves: vector<library>; #! The libraries the program's modules are found in, which completion lists the modules of by their folders.
|
||||
var builtin_of: vector<u32>; #! The declaration of each built-in type, by its type.
|
||||
var pending: vector<u32>; #! Declarations through a type, waiting for it to resolve.
|
||||
var pending_imports: vector<u64>; #! Each import, as `file << 32 | node`, resolved once every module is declared.
|
||||
pub var libraries: vector<u64>; #! Each `extern import` the target takes, as `file << 32 | node`, which names the library of its file's C functions.
|
||||
var external: bool; #! Whether what is being declared is in an `extern module`, where functions without a body, structs, and unions are C's.
|
||||
var cores_own: u32; #! How deeply what a trait of `core`'s asks for is being met, where `core`'s types meet it by `core`'s own members.
|
||||
var known: dict<u32, u32>; #! The declarations of std the checker knows, by name.
|
||||
var selves: dict<u32, u32>; #! The declaration `self` is within each trait.
|
||||
var decl_values: column<u32>; #! One more than the constant each constant and enum member holds, by index in `constants`, or 0, by its declaration.
|
||||
|
||||
# Generics.
|
||||
pub var instances: vector<instance>; #! The instances of generic functions.
|
||||
var instanced: keymap; #! One more than the instance of each template and arguments: `decl << 32 | args`.
|
||||
var wants: vector<u32>; #! Instances used whose bodies are not yet checked.
|
||||
var wants_checked: u64; #! How many of `wants` have been checked, which checking goes on from.
|
||||
var satisfied: keymap; #! Whether a type satisfies a trait: `type << 32 | trait`.
|
||||
var composed: column<u32>; #! One more than the run of the traits a struct, union, or trait names, once worked out, or 0, by its declaration.
|
||||
var decl_bases: column<u32>; #! The first node of each generic declaration, whose nodes an instance's table holds, once worked out, or 0, by its declaration.
|
||||
pub var called: keymap; #! One more than the instance a call uses: `table << 32 | node`.
|
||||
var mirrors: column<u32>; #! The type's parameter each parameter a receiver names stands for, or 0, by the parameter.
|
||||
var shapes: dict<u32, u32>; #! The written shape of each declaration with a pattern among its type parameters, as `record_shape` makes it.
|
||||
var only_bounds: dict<u32, bool>; #! Whether each trait is only a bound, once worked out.
|
||||
var outers: dict<u32, u32>; #! The bounds each trait's method puts on the trait's type parameters and `self`, once worked out.
|
||||
var locks: vector<u32>; #! What the loops around what is checked iterate.
|
||||
var undecided: u32; #! How many `if const` and `for const` around what is checked are not decided.
|
||||
pub var to_evaluate: vector<u64>; #! What only evaluating can work out, once checking is done: local constants, conditions of `if const`, and the text of `compile_error`, each as its table and node.
|
||||
var branches: vector<checker::branch>; #! The branches of `if const` only evaluating decides around what is checked, the outermost first.
|
||||
pub var held_errors: vector<checker::held_error>; #! The `compile_error`s left to evaluating, in the order checking reached them.
|
||||
pub var held_branches: vector<checker::branch>; #! The branches around each held `compile_error`, a run of each.
|
||||
|
||||
# Reflection: the descriptions of declarations, and what each expression of
|
||||
# reflection gives, as `kind, descriptions...` runs of `reflected`.
|
||||
pub var descs: vector<desc>; #! The descriptions of declarations reflection gives.
|
||||
var desc_ids: keymap; #! Each description by `decl << 32 | param`.
|
||||
var reflected: runs<u32>; #! What expressions of reflection give, as runs of `kind, descriptions...`.
|
||||
var reflections: keymap; #! The run of `reflected` each node gives: `table << 32 | node`.
|
||||
var lengths: keymap; #! How many values a view of reflection holds: `table << 32 | node`.
|
||||
var consent: u32; #! A declaration reflection reaches, which its attribute consents to.
|
||||
var attr_decls: keymap; #! The declaration each attribute is as `attributes_of` gives it: `file << 32 | node`.
|
||||
|
||||
# Dependencies, recorded as declarations are checked, for checking again
|
||||
# only what an edit affects: from each top-level declaration to what it
|
||||
# resolved, or to a name with `named_dependency` set.
|
||||
pub var tracks: bool; #! Whether dependencies are recorded, which a program checked only once has no use for.
|
||||
var dep_from: vector<u32>; #! Of each dependency, the declaration that resolved something.
|
||||
var dep_to: vector<u32>; #! Of each dependency, what it resolved.
|
||||
var dep_seen: keymap; #! Which dependencies are recorded, each as 1: `from << 32 | to`.
|
||||
var depended: vector<bool>; #! Whether any declaration resolved each declaration, whether or not dependencies are recorded.
|
||||
|
||||
# What walks each function's body to warn of what it keeps past what it
|
||||
# refers to, made once and walking each in turn.
|
||||
var lifetimes: lifetime_walk; #! The walk.
|
||||
|
||||
# The evaluator: the frames of the calls it runs, each the values of its
|
||||
# locals by the node declaring them, the elements of the arrays it holds,
|
||||
# and the arrays constants hold.
|
||||
var ev_frames: vector<dict<u32, ev>>; #! The locals of each call being evaluated, by the node declaring them.
|
||||
var ev_heap: vector<constant>; #! The elements of the arrays being evaluated.
|
||||
var ev_arrays: dict<u32, ev>; #! The arrays constants hold, by the node declaring them.
|
||||
var ev_result: ev; #! What the call being evaluated gives.
|
||||
var ev_steps: u64; #! How many steps evaluation has taken, which a limit stops.
|
||||
var ev_depth: u32; #! How deeply evaluation's calls nest.
|
||||
var ev_site: u32; #! The node evaluation was asked at, which its failure is noted at.
|
||||
var ev_file: u32; #! The file of that node.
|
||||
var ev_failed: bool; #! Whether evaluation failed.
|
||||
var projections: keymap; #! The parameter standing for a type a bound asks for: `param << 32 | asked`.
|
||||
var stand_ins: vector<checker::stand_in>; #! Each parameter standing for a type a bound asks for, which substituting its type parameter resolves.
|
||||
|
||||
# Constants: the values constant type arguments are, each interned once.
|
||||
var knowns: column<known>; #! The values worked out while checking, by ID, the first standing for none.
|
||||
var known_parts: runs<u32>; #! The parts of each, a run each.
|
||||
var known_texts: vector<string>; #! The bytes text values hold.
|
||||
var known_index: id_index; #! The values of each hash, which interning finds them by.
|
||||
|
||||
# Bounds an `if const` proved of type parameters, for the branch it guards.
|
||||
var proved_params: vector<u32>; #! The type parameters an `if const` proved bounds of.
|
||||
var proved_bounds: vector<u32>; #! The bound proved of each.
|
||||
|
||||
# Notes.
|
||||
var failed: bool; #! Whether the program is not valid.
|
||||
var errors: u64; #! How many errors were reported, which a function's body must add none of to be warned of.
|
||||
pub var skipped: u32; #! What was met that the checker does not check yet, and let through.
|
||||
# Notes dropped while an argument is tried quietly, and how many of them were
|
||||
# type arguments nothing gave, which tells one that needs another argument's
|
||||
# type first from one that is wrong.
|
||||
var mute: u32; #! Whether notes are dropped, where more than 0.
|
||||
var dropped: u32; #! How many notes were dropped.
|
||||
var uninferred: u32; #! How many of those were type arguments nothing gave.
|
||||
var free_result: bool; #! Whether the next lambda takes its result from its body, or the next generic function named as a value from its parameters, whatever the type expected says.
|
||||
var generic_names: vector<bool>; #! Whether a generic function is declared of each name, by its ID.
|
||||
var owned_names: bool; #! Whether types declared through others are described with them, as `token::kind`, as an editor shows them.
|
||||
var qualified_names: bool; #! Whether types are described with the modules they're declared in, as `path_of` spells them.
|
||||
}
|
||||
|
||||
#! The most notes the checker makes.
|
||||
pub const checker::max_notes: u32 = 200;
|
||||
|
||||
#! How many notes the checker has made, whether kept in its notes or heard as
|
||||
#! they were made.
|
||||
#! @param this The checker.
|
||||
#! @returns How many, at most `max_notes`.
|
||||
pub val checker::notes_made: u32 { get => this.sink.count; }
|
||||
|
||||
#! How deeply type arguments may nest, which a generic instantiating itself
|
||||
#! with ever larger types soon passes.
|
||||
pub const checker::max_nesting: u32 = 32;
|
||||
|
||||
#! The most instances the checker makes.
|
||||
pub const checker::max_instances: u32 = 65536;
|
||||
|
||||
#! Makes a checker of the names the files were lexed with, which notes what it
|
||||
#! finds in `notes`.
|
||||
#! @param names The names the files were lexed with.
|
||||
#! @param notes Where what the checker finds is noted.
|
||||
#! @returns The checker, which knows the built-in types and the names it looks
|
||||
#! for.
|
||||
pub def checker::new(names: &mut names, notes: &mut vector<note>): checker {
|
||||
var made := checker {
|
||||
names = names,
|
||||
sink = note_sink::new(notes, checker::max_notes),
|
||||
units = vector::<unit>::new(),
|
||||
types = type_table::new(),
|
||||
decls = decl_table::new(),
|
||||
modules = module_table::new(),
|
||||
tables = column::<rtable>::new(),
|
||||
r_types = column::<u32>::new(),
|
||||
r_refs = column::<u32>::new(),
|
||||
r_flags = column::<u16>::new(),
|
||||
r_converts = keymap::new(),
|
||||
r_values = keymap::new(),
|
||||
converts = keymap::new(),
|
||||
values = keymap::new(),
|
||||
constants = column::<constant>::new(),
|
||||
constant_index = id_index::new(),
|
||||
bind_names = vector::<u32>::new(),
|
||||
bind_values = vector::<u32>::new(),
|
||||
bind_prev = vector::<u32>::new(),
|
||||
innermost = vector::<u32>::new(),
|
||||
builtins = dict::<u32, u32>::new(),
|
||||
shelves = vector::<library>::new(),
|
||||
builtin_of = vector::<u32>::new(),
|
||||
pending = vector::<u32>::new(),
|
||||
pending_imports = vector::<u64>::new(),
|
||||
libraries = vector::<u64>::new(),
|
||||
known = dict::<u32, u32>::new(),
|
||||
selves = dict::<u32, u32>::new(),
|
||||
decl_values = column::<u32>::new(),
|
||||
instances = vector::<instance>::new(),
|
||||
instanced = keymap::new(),
|
||||
wants = vector::<u32>::new(),
|
||||
satisfied = keymap::new(),
|
||||
composed = column::<u32>::new(),
|
||||
decl_bases = column::<u32>::new(),
|
||||
called = keymap::new(),
|
||||
mirrors = column::<u32>::new(),
|
||||
shapes = dict::<u32, u32>::new(),
|
||||
only_bounds = dict::<u32, bool>::new(),
|
||||
outers = dict::<u32, u32>::new(),
|
||||
locks = vector::<u32>::new(),
|
||||
descs = vector::<desc>::new(),
|
||||
desc_ids = keymap::new(),
|
||||
reflected = runs::<u32>::new(),
|
||||
reflections = keymap::new(),
|
||||
lengths = keymap::new(),
|
||||
attr_decls = keymap::new(),
|
||||
tracks = true,
|
||||
dep_from = vector::<u32>::new(),
|
||||
dep_to = vector::<u32>::new(),
|
||||
dep_seen = keymap::new(),
|
||||
lifetimes = lifetime_walk::new(),
|
||||
depended = vector::<bool>::new(),
|
||||
ev_frames = vector::<dict<u32, ev>>::new(),
|
||||
ev_heap = vector::<constant>::new(),
|
||||
ev_arrays = dict::<u32, ev>::new(),
|
||||
projections = keymap::new(),
|
||||
stand_ins = vector::<checker::stand_in>::new(),
|
||||
knowns = column::<known>::new(),
|
||||
known_parts = runs::<u32>::new(),
|
||||
known_texts = vector::<string>::new(),
|
||||
known_index = id_index::new(),
|
||||
generic_names = vector::<bool>::new(),
|
||||
proved_params = vector::<u32>::new(),
|
||||
proved_bounds = vector::<u32>::new(),
|
||||
to_evaluate = vector::<u64>::new(),
|
||||
branches = vector::<checker::branch>::new(),
|
||||
held_errors = vector::<checker::held_error>::new(),
|
||||
held_branches = vector::<checker::branch>::new()
|
||||
};
|
||||
|
||||
# Constant 0 stands for none, and is the integer 0 too.
|
||||
_ = made.intern_constant(constant {});
|
||||
made.declare_builtins();
|
||||
made.target = target {
|
||||
os = made.names.intern(&"linux"),
|
||||
arch = made.names.intern(&"x86_64"),
|
||||
backend = made.names.intern(&"vm")
|
||||
};
|
||||
# Known value 0 stands for none.
|
||||
made.knowns.append(known {});
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Gives the checker a file to check, lexed with its names and parsed.
|
||||
#! @param this The checker.
|
||||
#! @param source The file's source.
|
||||
#! @param syntax What it parsed into.
|
||||
#! @param root Its `document` node.
|
||||
#! @returns The index of the file, which its notes give.
|
||||
pub def checker::add(&mut this, source: &source, syntax: &syntax, root: u32): u32 {
|
||||
val file := this.units.length as u32;
|
||||
val table := this.add_table(file, 0, syntax.node_count as u32, 0);
|
||||
this.units.append(unit {
|
||||
source = source,
|
||||
syntax = syntax,
|
||||
root = root,
|
||||
table = table,
|
||||
parses = syntax.parses
|
||||
});
|
||||
return file;
|
||||
}
|
||||
|
||||
#! Checks the files given: declares what each declares, resolves what each
|
||||
#! declaration is, then checks the bodies of functions and the values of
|
||||
#! variables, and then the bodies of the instances of generics they use.
|
||||
#! @param this The checker.
|
||||
#! @returns Whether the program is valid.
|
||||
pub def checker::check(&mut this): bool {
|
||||
for file in 0..this.units.length {
|
||||
this.declare_unit(file as u32);
|
||||
}
|
||||
|
||||
this.link();
|
||||
this.name_types();
|
||||
for id in 1..this.decls.count {
|
||||
this.resolve(id as u32);
|
||||
}
|
||||
|
||||
for id in 1..this.decls.count {
|
||||
this.check_decl(id as u32);
|
||||
}
|
||||
|
||||
this.check_wanted();
|
||||
return !this.failed;
|
||||
}
|
||||
|
||||
#! A built-in type and the names it goes by.
|
||||
struct checker::builtin_name {
|
||||
val text: strview;
|
||||
val kind: bt;
|
||||
}
|
||||
|
||||
const _builtin_names: checker::builtin_name[15] = [
|
||||
checker::builtin_name { text = "void", kind = bt::void_type },
|
||||
checker::builtin_name { text = "bool", kind = bt::boolean },
|
||||
checker::builtin_name { text = "i8", kind = bt::int8 },
|
||||
checker::builtin_name { text = "i16", kind = bt::int16 },
|
||||
checker::builtin_name { text = "i32", kind = bt::int32 },
|
||||
checker::builtin_name { text = "i64", kind = bt::int64 },
|
||||
checker::builtin_name { text = "u8", kind = bt::uint8 },
|
||||
checker::builtin_name { text = "u16", kind = bt::uint16 },
|
||||
checker::builtin_name { text = "u32", kind = bt::uint32 },
|
||||
checker::builtin_name { text = "u64", kind = bt::uint64 },
|
||||
checker::builtin_name { text = "f32", kind = bt::float32 },
|
||||
checker::builtin_name { text = "f64", kind = bt::float64 },
|
||||
checker::builtin_name { text = "int", kind = bt::int64 },
|
||||
checker::builtin_name { text = "uint", kind = bt::uint64 },
|
||||
checker::builtin_name { text = "float", kind = bt::float64 },
|
||||
];
|
||||
|
||||
#! Declares the built-in types, one declaration for each type, which every
|
||||
#! name it goes by finds, so `int::f` and `i64::f` are methods of one type.
|
||||
#! @param this The checker.
|
||||
def checker::declare_builtins(&mut this): void {
|
||||
this.builtin_of.resize(bt::count as u64);
|
||||
|
||||
for &each in _builtin_names {
|
||||
val name := this.names.intern(&each.text);
|
||||
var decl: u32 = this.builtin_of[each.kind as u64];
|
||||
if decl == 0 {
|
||||
decl = this.decls.add(dk::builtin, name, 0, 0, 0);
|
||||
this.decls.types.p[decl as u32] = each.kind;
|
||||
this.decls.states.p[decl as u32] = ds::resolved;
|
||||
this.decls.mark(decl, df::exported);
|
||||
this.builtin_of[each.kind as u64] = decl;
|
||||
}
|
||||
this.builtins.set(name, decl);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,918 @@
|
||||
#! @file access.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the checking of what reaches into a value: its members, as a field
|
||||
#! or a property, and its elements, by an index or a slice. Each reaches
|
||||
#! through references and pointers, so `p.field` and `r[i]` work where `p` and
|
||||
#! `r` point at what has them.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! What a value of the type is once read through its references, however many
|
||||
#! there are. A pointer is an address, so nothing is reached through it.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns What it reaches, or the type itself where it is no reference.
|
||||
pub def checker::reached(&mut this, kind: u32): u32 {
|
||||
var at := kind;
|
||||
var steps := 0;
|
||||
while this.types.kind_of(this.unalias(at)) == ty::reference && steps < 8 {
|
||||
at = this.types.first_of(this.unalias(at));
|
||||
steps++;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
#! Whether what a value of the type reaches through can be written: a `&mut`
|
||||
#! reference or a `*mut` pointer, where it reaches through one.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param object The node of the value, which says whether it can be written
|
||||
#! where it is no reference.
|
||||
#! @returns Whether it can be.
|
||||
def checker::reaches_writable(&mut this, kind: u32, object: u32): bool {
|
||||
var at := this.unalias(kind);
|
||||
var steps := 0;
|
||||
while this.types.kind_of(at) == ty::reference && steps < 8 {
|
||||
val inner := this.unalias(this.types.first_of(at));
|
||||
if this.types.kind_of(inner) != ty::reference {
|
||||
return this.types.second_of(at) != 0;
|
||||
}
|
||||
at = inner;
|
||||
steps++;
|
||||
}
|
||||
return this.types.second_of(at) != 0 if this.types.kind_of(at) == ty::pointer;
|
||||
return this.is_writable(object);
|
||||
}
|
||||
|
||||
#! What a member of a type is: the declaration, and the struct a spread field
|
||||
#! is reached through.
|
||||
pub struct checker::found {
|
||||
pub var decl: u32; #! The member, or 0.
|
||||
var owner: u32; #! The type it is a member of, given its arguments.
|
||||
}
|
||||
|
||||
#! The member of the name of a value of the type: a field, a property, or a
|
||||
#! method, found on an alias before what it stands for, on a struct's spread
|
||||
#! fields after its own, and on a type parameter among its bounds.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param name The ID of the name.
|
||||
#! @returns The member and the type it is of, or no member.
|
||||
pub def checker::find_member(&mut this, kind: u32, name: u32): checker::found {
|
||||
return this.find_member_of(kind, name, false);
|
||||
}
|
||||
|
||||
#! The member of the name of the type `::` reaches, as `token::kind`: a type
|
||||
#! declared through it before a field of the same name, which only a value
|
||||
#! reaches, and otherwise as `find_member` finds it.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param name The ID of the name.
|
||||
#! @returns The member and the type it is of, or no member.
|
||||
pub def checker::find_path_member(&mut this, kind: u32, name: u32): checker::found {
|
||||
return this.find_member_of(kind, name, true);
|
||||
}
|
||||
|
||||
#! The member of the name of the type, with a type declared through it before a
|
||||
#! field of the same name where `types` says.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param name The ID of the name.
|
||||
#! @param types Whether a type declared through it comes first.
|
||||
#! @returns The member and the type it is of, or no member.
|
||||
def checker::find_member_of(&mut this, kind: u32, name: u32, types: bool): checker::found {
|
||||
this.depend(this.type_decl(this.unalias(kind)));
|
||||
var at := kind;
|
||||
var steps := 0;
|
||||
while steps < 16 {
|
||||
steps++;
|
||||
val decl := this.type_decl(at);
|
||||
if decl != 0 {
|
||||
val member := this.member_here(decl, name, types);
|
||||
return checker::found { decl = member, owner = at } if member != 0;
|
||||
}
|
||||
|
||||
match this.types.kind_of(at) {
|
||||
ty::named => {
|
||||
val kind_of: dk = this.decls.kinds.p[this.types.first_of(at)];
|
||||
if kind_of == dk::alias_type {
|
||||
at = this.alias_target(at);
|
||||
continue;
|
||||
}
|
||||
if kind_of == dk::struct_type {
|
||||
val spread := this.find_spread(at, name);
|
||||
return spread if spread.decl != 0;
|
||||
}
|
||||
if kind_of == dk::struct_type || kind_of == dk::union_type {
|
||||
return this.find_default(this.types.first_of(at), name, 0);
|
||||
}
|
||||
# A trait has the members of the traits it composes.
|
||||
if kind_of == dk::trait_type {
|
||||
val member := this.trait_member(this.types.first_of(at), name);
|
||||
return checker::found { decl = member, owner = this.declaring_bound(at, member) } if member != 0;
|
||||
}
|
||||
return checker::found {};
|
||||
}
|
||||
ty::param => return this.find_in_bounds(at, name);
|
||||
else => return checker::found {};
|
||||
}
|
||||
}
|
||||
return checker::found {};
|
||||
}
|
||||
|
||||
#! The default of the name a trait a struct or union names gives it, or one of
|
||||
#! those a trait composes gives that trait: a method the trait writes a body
|
||||
#! for, which the type has as its own where it does not write one itself.
|
||||
#! @param this The checker.
|
||||
#! @param decl The struct's, union's, or trait's declaration.
|
||||
#! @param name The ID of the name.
|
||||
#! @param depth How deeply composition has been followed.
|
||||
#! @returns The default and the trait it is of, or no member.
|
||||
def checker::find_default(&mut this, decl: u32, name: u32, depth: u32): checker::found {
|
||||
return checker::found {} if depth > 16;
|
||||
|
||||
val run := this.composed_of(decl);
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val trait_kind := this.decls.list_at(run, i as u32);
|
||||
val holder := this.types.first_of(trait_kind);
|
||||
val member := this.decls.member(holder, name);
|
||||
if member != 0 && this.decls.kinds.p[member] == dk::function && this.has_body(member)
|
||||
&& this.trait_asks(member) {
|
||||
return checker::found { decl = member, owner = trait_kind };
|
||||
}
|
||||
val inner := this.find_default(holder, name, depth + 1);
|
||||
return inner if inner.decl != 0;
|
||||
}
|
||||
return checker::found {};
|
||||
}
|
||||
|
||||
#! The field of the name among the fields a struct's spread fields bring in.
|
||||
#! @param this The checker.
|
||||
#! @param kind The struct's type.
|
||||
#! @param name The ID of the name.
|
||||
#! @returns The field and the struct it is of, or no member.
|
||||
def checker::find_spread(&mut this, kind: u32, name: u32): checker::found {
|
||||
val decl := this.types.first_of(kind);
|
||||
val run: u32 = this.decls.children.p[decl];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val field := this.decls.list_at(run, i as u32);
|
||||
continue if this.decls.kinds.p[field] != dk::field || !this.is_spread(field);
|
||||
|
||||
this.resolve(field);
|
||||
val spread := this.instantiated(this.decls.types.p[field], decl, kind);
|
||||
val inner := this.renamed(field, name);
|
||||
val found := this.find_member(spread, inner);
|
||||
if found.decl != 0 && this.decls.kinds.p[found.decl] == dk::field {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
return checker::found {};
|
||||
}
|
||||
|
||||
#! Whether a member is seen where checking is. One a module declares on a type
|
||||
#! of another module, or on a built-in type, is seen within that module and
|
||||
#! where a file imports it, as `std::math`'s `sqrt` of a `simd` is, and `core`'s
|
||||
#! everywhere; so what a file means never hangs on what another file of the
|
||||
#! program imports. A type's own members are seen wherever it is.
|
||||
#! @param this The checker.
|
||||
#! @param id The member.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::member_seen(&this, id: u32): bool {
|
||||
var at := id;
|
||||
var owner: u32 = this.decls.owners.p[id];
|
||||
# An accessor is seen as its property is.
|
||||
if owner != 0 && this.decls.kinds.p[owner] == dk::property {
|
||||
at = owner;
|
||||
owner = this.decls.owners.p[owner];
|
||||
}
|
||||
return true if owner == 0;
|
||||
val home: u32 = this.decls.modules.p[at];
|
||||
return true if this.decls.kinds.p[owner] != dk::builtin && this.decls.modules.p[owner] == home;
|
||||
return true if this.modules.within(this.at.home, home) || this.in_core(home);
|
||||
val imports: u32 = this.units[this.at.file].imports;
|
||||
for &imported in this.decls.list_view(imports) {
|
||||
return true if imported == home;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Whether a module is `core` or one within it.
|
||||
#! @param this The checker.
|
||||
#! @param id The module.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::in_core(&this, id: u32): bool {
|
||||
var at := id;
|
||||
var steps := 0;
|
||||
while at != 0 && this.modules.parents[at] != 0 && steps < 64 {
|
||||
at = this.modules.parents[at];
|
||||
steps++;
|
||||
}
|
||||
return at != 0 && this.modules.names[at] == word::core;
|
||||
}
|
||||
|
||||
#! The first of a member's overloads seen where checking is, or 0.
|
||||
#! @param this The checker.
|
||||
#! @param first The first of them, or 0.
|
||||
#! @returns The overload, or 0.
|
||||
pub def checker::first_seen(&this, first: u32): u32 {
|
||||
return first if first == 0 || this.member_seen(first);
|
||||
var walk := this.decls.walk_overloads(first);
|
||||
while true {
|
||||
val at := walk.next();
|
||||
return 0 if at == 0;
|
||||
return at if this.member_seen(at);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! The first of the type's members of the name seen where checking is, with a
|
||||
#! type declared through it before a field of the same name where `types` says,
|
||||
#! or 0. One declared outside `core` on `core`'s type is chosen over `core`'s
|
||||
#! member or type of its name, where it is seen, and never within `core` or for
|
||||
#! a trait of `core`'s.
|
||||
#! @param this The checker.
|
||||
#! @param decl The type's declaration.
|
||||
#! @param name The ID of the name.
|
||||
#! @param types Whether a type declared through it comes first.
|
||||
#! @returns The member, whose overloads follow it, or 0.
|
||||
pub def checker::member_here(&this, decl: u32, name: u32, types: bool): u32 {
|
||||
if !this.in_core(this.at.home) && this.cores_own == 0 {
|
||||
val added := this.first_seen(this.decls.added_member(decl, name));
|
||||
return added if added != 0;
|
||||
}
|
||||
return this.first_seen(types ? this.decls.path_member(decl, name) : this.decls.member(decl, name));
|
||||
}
|
||||
|
||||
#! The overloads a call chooses from: those beginning with `first`, or `core`'s
|
||||
#! of their name where they were declared outside `core` on `core`'s type and
|
||||
#! none of them takes the arguments, so a program's overload of `core`'s
|
||||
#! method is chosen where it fits, and `core`'s elsewhere.
|
||||
#! @param this The checker.
|
||||
#! @param first The first of the overloads `member_here` gave.
|
||||
#! @param object The value a method is called on, or 0.
|
||||
#! @param owner The type the method is of, given its arguments.
|
||||
#! @param through The type it is reached through.
|
||||
#! @param args The arguments' nodes.
|
||||
#! @returns The first of the overloads chosen from.
|
||||
pub def checker::overloads_for(&mut this, first: u32, object: u32, owner: u32, through: u32, args: span<u32>): u32 {
|
||||
val behind := this.core_behind(first);
|
||||
return first if behind == 0 || this.fits_overload(first, object, owner, through, args);
|
||||
return behind;
|
||||
}
|
||||
|
||||
#! The first of the overloads a member of a type is among: those declared
|
||||
#! outside `core` on `core`'s type are kept apart from `core`'s of their name.
|
||||
#! @param this The checker.
|
||||
#! @param id The member.
|
||||
#! @returns The first of them, or 0 where it is no type's member.
|
||||
pub def checker::first_member(&this, id: u32): u32 {
|
||||
val owner: u32 = this.decls.owners.p[id];
|
||||
return 0 if owner == 0;
|
||||
val name: u32 = this.decls.names.p[id];
|
||||
val added := this.decls.added_member(owner, name);
|
||||
return added if added != 0 && !this.in_core(this.decls.modules.p[id]);
|
||||
return this.decls.member(owner, name);
|
||||
}
|
||||
|
||||
#! `core`'s members of the name seen where checking is, behind those a module
|
||||
#! outside `core` declared on `core`'s type, or 0 where these are not those.
|
||||
#! @param this The checker.
|
||||
#! @param first The first of the members `member_here` gave.
|
||||
#! @returns The first of `core`'s, or 0.
|
||||
pub def checker::core_behind(&this, first: u32): u32 {
|
||||
val holder: u32 = this.decls.owners.p[first];
|
||||
return 0 if first == 0 || holder == 0 || this.in_core(this.decls.modules.p[first]);
|
||||
val name: u32 = this.decls.names.p[first];
|
||||
return 0 if this.decls.added_member(holder, name) == 0;
|
||||
return this.first_seen(this.decls.member_in(holder, name, false));
|
||||
}
|
||||
|
||||
#! Reports a member named where it is not visible. A field a spread brings in
|
||||
#! is as visible as the spread field and its own.
|
||||
#! @param this The checker.
|
||||
#! @param node The node naming it.
|
||||
#! @param kind The type it is a member of.
|
||||
#! @param member The member.
|
||||
pub def checker::check_reaches(&mut this, node: u32, kind: u32, member: u32): void {
|
||||
if !this.visible(member) {
|
||||
this.report_hidden(node, member);
|
||||
return;
|
||||
}
|
||||
return if this.decls.kinds.p[member] != dk::field;
|
||||
val spread := this.spread_of(kind, this.decls.names.p[member]);
|
||||
if spread != 0 && !this.visible(spread) {
|
||||
this.report_hidden(node, spread);
|
||||
}
|
||||
}
|
||||
|
||||
#! The spread field of a struct a field of the name is brought in by, or 0
|
||||
#! where the struct declares it itself or has none of the name.
|
||||
#! @param this The checker.
|
||||
#! @param kind The struct's type.
|
||||
#! @param name The ID of the name.
|
||||
#! @returns The spread field, or 0.
|
||||
def checker::spread_of(&mut this, kind: u32, name: u32): u32 {
|
||||
val plain := this.unalias(kind);
|
||||
return 0 if this.named_kind(plain) != dk::struct_type;
|
||||
val decl := this.types.first_of(plain);
|
||||
return 0 if this.decls.member(decl, name) != 0;
|
||||
|
||||
val run: u32 = this.decls.children.p[decl];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val field := this.decls.list_at(run, i as u32);
|
||||
continue if this.decls.kinds.p[field] != dk::field || !this.is_spread(field);
|
||||
this.resolve(field);
|
||||
val spread := this.instantiated(this.decls.types.p[field], decl, plain);
|
||||
val found := this.find_member(spread, this.renamed(field, name));
|
||||
return field if found.decl != 0 && this.decls.kinds.p[found.decl] == dk::field;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! Whether a field spreads another struct's fields into its own.
|
||||
#! @param this The checker.
|
||||
#! @param field The field's declaration.
|
||||
#! @returns Whether it does.
|
||||
pub def checker::is_spread(&this, field: u32): bool {
|
||||
val syntax := &this.units[this.decls.files.p[field]].syntax;
|
||||
val record := syntax.node_lefts[this.decls.nodes.p[field]];
|
||||
val written := syntax.extras[record as u64 + variable_slot::type_expr as u64];
|
||||
return written != 0 && syntax.node_kinds[written] == nk::spread;
|
||||
}
|
||||
|
||||
#! The name a spread field's struct gives the field a rename calls `name`, as
|
||||
#! `x` where `x as left` renames it `left`, or `name` itself.
|
||||
#! @param this The checker.
|
||||
#! @param field The spread field's declaration.
|
||||
#! @param name The ID of the name it is reached by.
|
||||
#! @returns The ID of the name its struct gives it.
|
||||
def checker::renamed(&this, field: u32, name: u32): u32 {
|
||||
val syntax := &this.units[this.decls.files.p[field]].syntax;
|
||||
val record := syntax.node_lefts[this.decls.nodes.p[field]];
|
||||
val written := syntax.extras[record as u64 + variable_slot::type_expr as u64];
|
||||
for &rename in syntax.run_view(syntax.node_rights[written]) {
|
||||
val target := syntax.node_lefts[rename];
|
||||
if syntax.token_names[syntax.node_tokens[target]] == name {
|
||||
return syntax.token_names[syntax.node_tokens[rename]];
|
||||
}
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
#! The member of the name a type parameter has through the traits bounding it.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type parameter's type.
|
||||
#! @param name The ID of the name.
|
||||
#! @returns The member and the trait it is of, or no member.
|
||||
def checker::find_in_bounds(&mut this, kind: u32, name: u32): checker::found {
|
||||
val param := this.types.first_of(kind);
|
||||
this.resolve(param);
|
||||
val run: u32 = this.decls.children.p[param];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val bound := this.decls.list_at(run, i as u32);
|
||||
val member := this.trait_member(this.types.first_of(bound), name);
|
||||
return checker::found { decl = member, owner = this.declaring_bound(bound, member) } if member != 0;
|
||||
}
|
||||
|
||||
# What an `if const` proved of it, in the branch it guards.
|
||||
for i in 0..this.proved_params.length {
|
||||
continue if this.proved_params[i] != param;
|
||||
val bound: u32 = this.proved_bounds[i];
|
||||
val member := this.trait_member(this.types.first_of(bound), name);
|
||||
return checker::found { decl = member, owner = this.declaring_bound(bound, member) } if member != 0;
|
||||
}
|
||||
|
||||
# Within a trait, `self` has the trait's members.
|
||||
if this.decls.names.p[param] == names::self_id && this.decls.owners.p[param] != 0 {
|
||||
val holder: u32 = this.decls.owners.p[param];
|
||||
val member := this.trait_member(holder, name);
|
||||
return checker::found { decl = member, owner = this.declaring_bound(this.decls.types.p[holder], member) } if member != 0;
|
||||
}
|
||||
return checker::found {};
|
||||
}
|
||||
|
||||
#! The trait, given its arguments, that declares a member a bound has: the
|
||||
#! bound itself, or a trait it composes, in terms of the bound's arguments, as
|
||||
#! `into<T>` of `pair<T>: into<T>`.
|
||||
#! @param this The checker.
|
||||
#! @param bound The bound's type.
|
||||
#! @param member The member.
|
||||
#! @returns The trait's type.
|
||||
def checker::declaring_bound(&mut this, bound: u32, member: u32): u32 {
|
||||
val declarer := this.enclosing_trait(member);
|
||||
return bound if declarer == 0 || this.types.kind_of(this.unalias(bound)) != ty::named;
|
||||
return this.bound_for(this.unalias(bound), declarer);
|
||||
}
|
||||
|
||||
#! The member of the name a trait has, its own or a trait's it composes.
|
||||
#! @param this The checker.
|
||||
#! @param trait_decl The trait's declaration.
|
||||
#! @param name The ID of the name.
|
||||
#! @returns The member, or 0.
|
||||
pub def checker::trait_member(&mut this, trait_decl: u32, name: u32): u32 {
|
||||
val own := this.decls.member(trait_decl, name);
|
||||
return own if own != 0 && this.trait_asks(own);
|
||||
|
||||
this.resolve_composed(trait_decl);
|
||||
val held := this.composed.at_or_zero(trait_decl);
|
||||
val run: u32 = held != 0 ? held - 1 : 0;
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val inner := this.decls.list_at(run, i as u32);
|
||||
val found := this.trait_member(this.types.first_of(inner), name);
|
||||
return found if found != 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! Whether a value of the type has a method of the name: its own, through a
|
||||
#! bound, or one the compiler gives a built-in type.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param name The ID of the name.
|
||||
#! @returns Whether it has.
|
||||
pub def checker::has_method(&mut this, kind: u32, name: u32): bool {
|
||||
val found := this.find_member(kind, name);
|
||||
if found.decl != 0 {
|
||||
return this.decls.kinds.p[found.decl] == dk::function;
|
||||
}
|
||||
return this.builtin_method(kind, name) != 0;
|
||||
}
|
||||
|
||||
#! The type of the method the compiler gives a built-in type, as `equals` of a
|
||||
#! number, or 0: every number has `equals`, `hash`, `compare`, and the methods
|
||||
#! of `numeric`, and `bool`, enums, and pointers have `equals` and `hash`, and
|
||||
#! enums and pointers `compare`. A fixed array has `equals` and `hash` where
|
||||
#! its elements do.
|
||||
#! @param this The checker.
|
||||
#! @param kind The built-in type.
|
||||
#! @param name The ID of the method's name.
|
||||
#! @returns The method's type, or 0.
|
||||
pub def checker::builtin_method(&mut this, kind: u32, name: u32): u32 {
|
||||
val plain := this.unalias(kind);
|
||||
# A function, and the address of a C function, are called by an `invoke`
|
||||
# taking what they take, which makes each `invokable` of its own type.
|
||||
if name == word::invoke {
|
||||
val function := this.signature_function(plain);
|
||||
return 0 if function == 0;
|
||||
var taken := vector::<u32>::new();
|
||||
taken.append(this.types.reference(kind, false));
|
||||
taken.extend(this.types.parts_view(function));
|
||||
return this.types.function(taken.view(), this.types.first_of(function), this.types.second_of(function) != 0);
|
||||
}
|
||||
# A fixed array has `equals` and `hash` where its elements do.
|
||||
if this.types.kind_of(plain) == ty::fixed {
|
||||
return 0 if this.types.part_count(plain) != 0 || (name != word::equals && name != word::hash);
|
||||
return 0 if !this.has_method(this.types.first_of(plain), name);
|
||||
var taken := vector::<u32>::new();
|
||||
taken.append(this.types.reference(kind, false));
|
||||
if name == word::equals {
|
||||
taken.append(this.types.reference(kind, false));
|
||||
return this.types.function(taken.view(), bt::boolean, false);
|
||||
}
|
||||
return this.types.function(taken.view(), bt::uint64, false);
|
||||
}
|
||||
val number := this.types.is_numeric(plain) && !this.types.is_untyped(plain);
|
||||
val ordered := number || this.named_kind(plain) == dk::enum_type || this.types.kind_of(plain) == ty::pointer;
|
||||
val equal := ordered || this.types.kind_of(plain) == ty::boolean;
|
||||
val this_ref := this.types.reference(kind, false);
|
||||
|
||||
var params := vector::<u32>::new();
|
||||
params.append(this_ref);
|
||||
if name == word::equals && equal {
|
||||
params.append(this_ref);
|
||||
return this.types.function(params.view(), bt::boolean, false);
|
||||
}
|
||||
if name == word::hash && equal {
|
||||
return this.types.function(params.view(), bt::uint64, false);
|
||||
}
|
||||
if name == word::compare && ordered {
|
||||
params.append(this_ref);
|
||||
return this.types.function(params.view(), bt::int64, false);
|
||||
}
|
||||
if number && (name == word::add || name == word::sub || name == word::mul
|
||||
|| name == word::div || name == word::rem) {
|
||||
params.append(this_ref);
|
||||
return this.types.function(params.view(), kind, false);
|
||||
}
|
||||
if number && name == word::negate {
|
||||
return this.types.function(params.view(), kind, false);
|
||||
}
|
||||
# Integers give their bitwise operators and shifts as methods too, a shift
|
||||
# taking how far as a `u32`.
|
||||
val integer := number && this.types.is_integer(plain);
|
||||
if integer && (name == word::bit_and || name == word::bit_or || name == word::bit_xor) {
|
||||
params.append(this_ref);
|
||||
return this.types.function(params.view(), kind, false);
|
||||
}
|
||||
if integer && (name == word::shift_left || name == word::shift_right) {
|
||||
params.append(this.types.reference(bt::uint32, false));
|
||||
return this.types.function(params.view(), kind, false);
|
||||
}
|
||||
if integer && name == word::bit_not {
|
||||
return this.types.function(params.view(), kind, false);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! `x.name`: a field, a property, or the length of a fixed array.
|
||||
#! @param this The checker.
|
||||
#! @param node The `member` node.
|
||||
#! @returns The member's type, or the error type where the value has none of the
|
||||
#! name.
|
||||
def checker::member(&mut this, node: u32): u32 {
|
||||
val object := this.left_of(node);
|
||||
val name := this.name_of(node);
|
||||
# A pack of types has a length as a pack of values does, as `Ts.length` of
|
||||
# `def f<Ts...>()`, known in each instance.
|
||||
if name == word::length && this.kind_of(object) == nk::name {
|
||||
val named := this.tested_type(object);
|
||||
if named != 0 && named != bt::error && this.types.kind_of(this.unalias(named)) == ty::pack {
|
||||
if !this.types.is_open_pack(this.unalias(named)) {
|
||||
this.set_value(node, constant::integer(this.types.part_count(this.unalias(named)) as u64, false));
|
||||
}
|
||||
return bt::uint64;
|
||||
}
|
||||
}
|
||||
# A constant settles as it would alone, so `"text".length` is a `strview`'s.
|
||||
var kind := this.infer_expr(object);
|
||||
return bt::error if kind == bt::error;
|
||||
if this.types.is_untyped(kind) {
|
||||
kind = this.settle_expr(object);
|
||||
}
|
||||
|
||||
val through := this.reached(kind);
|
||||
val plain := this.unalias(through);
|
||||
# Within a template, a length only each instance knows is no constant there.
|
||||
if this.types.kind_of(plain) == ty::fixed && name == word::length {
|
||||
if this.types.part_count(plain) == 0 {
|
||||
this.set_value(node, constant::integer(this.types.second_of(plain) as u64, false));
|
||||
}
|
||||
return bt::uint64;
|
||||
}
|
||||
|
||||
# A pack's length is how many types it has, known in each instance.
|
||||
if this.types.kind_of(plain) == ty::pack {
|
||||
if name != word::length {
|
||||
this.report(node, ec::member, "A pack has only `length`; each of its values is reached with `for const` or `args[i]`.");
|
||||
return bt::error;
|
||||
}
|
||||
if !this.types.is_open_pack(plain) {
|
||||
this.set_value(node, constant::integer(this.types.part_count(plain) as u64, false));
|
||||
}
|
||||
return bt::uint64;
|
||||
}
|
||||
|
||||
val found := this.find_member(through, name);
|
||||
if found.decl == 0 {
|
||||
this.report_no_member(node, through, name);
|
||||
return bt::error;
|
||||
}
|
||||
this.check_reaches(node, through, found.decl);
|
||||
|
||||
# What reflection gives says some of itself while checking.
|
||||
val one := this.reflected_one(object);
|
||||
if one != checker::no_reflection {
|
||||
this.reflected_field(node, one, name);
|
||||
}
|
||||
if name == word::length {
|
||||
val key := this.result_key(object);
|
||||
if this.lengths.get(&key) is some(got) {
|
||||
this.set_value(node, constant::integer(got as u64, false));
|
||||
} else {
|
||||
val list := this.reflected_at(object);
|
||||
if list != checker::no_reflection && this.reflected_kind(list) == rk::list as u32 {
|
||||
this.set_value(node, constant::integer(this.reflected_count(list) as u64, false));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.set_ref(node, found.decl);
|
||||
match this.decls.kinds.p[found.decl] {
|
||||
dk::field => {
|
||||
this.resolve(found.decl);
|
||||
val owner := this.types.first_of(found.owner);
|
||||
val held := this.instantiated(this.decls.types.p[found.decl], owner, found.owner);
|
||||
val writes := this.reaches_writable(kind, object) && this.decls.has(found.decl, df::mutable);
|
||||
this.mark_place(node, writes || (this.named_kind(found.owner) == dk::union_type && this.reaches_writable(kind, object)));
|
||||
if this.types.kind_of(this.unalias(kind)) != ty::reference && this.types.kind_of(this.unalias(kind)) != ty::pointer
|
||||
&& !this.is_place(object) {
|
||||
this.clear_flag(node, rf::place);
|
||||
this.clear_flag(node, rf::writable);
|
||||
}
|
||||
return held;
|
||||
}
|
||||
dk::property => {
|
||||
# A property's type names the parameters its receiver did.
|
||||
this.resolve(found.decl);
|
||||
val property: u32 = this.decls.types.p[found.decl];
|
||||
val named := this.types.kind_of(found.owner) == ty::named;
|
||||
val held := named ? this.instantiated(property, found.decl, found.owner) : property;
|
||||
if this.property_setter(found.decl) != 0 && this.reaches_writable(kind, object) {
|
||||
this.set_flag(node, rf::writable);
|
||||
}
|
||||
this.want_accessor(this.property_getter(found.decl), found.owner, node);
|
||||
return held;
|
||||
}
|
||||
dk::function => {
|
||||
this.report(node, ec::not_value, "A method is called, as `x.name()`; take it through its type, as `T::name`, for its value.");
|
||||
return bt::error;
|
||||
}
|
||||
else => {
|
||||
this.report(node, ec::member, "Only fields, properties, and methods are reached with `.`; reach this through its type with `::`.");
|
||||
return bt::error;
|
||||
}
|
||||
}
|
||||
return bt::error;
|
||||
}
|
||||
|
||||
#! The getter of a property, or 0 where it has none.
|
||||
#! @param this The checker.
|
||||
#! @param property The property's declaration.
|
||||
#! @returns The getter's declaration, or 0.
|
||||
pub def checker::property_getter(&this, property: u32): u32 {
|
||||
val run: u32 = this.decls.children.p[property];
|
||||
for &accessor in this.decls.list_view(run) {
|
||||
return accessor if !this.decls.has(accessor, df::setter);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! The setter of a property, or 0 where it has none.
|
||||
#! @param this The checker.
|
||||
#! @param property The property's declaration.
|
||||
#! @returns The setter's declaration, or 0.
|
||||
pub def checker::property_setter(&this, property: u32): u32 {
|
||||
val run: u32 = this.decls.children.p[property];
|
||||
for &accessor in this.decls.list_view(run) {
|
||||
return accessor if this.decls.has(accessor, df::setter);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! Asks for the instance of a generic type's property accessor that a value of
|
||||
#! the type given its arguments reaches, so its body is checked, as a method's
|
||||
#! called is, rather than only once lowering asks for it.
|
||||
#! @param this The checker.
|
||||
#! @param accessor The accessor's declaration, or 0.
|
||||
#! @param owner The type the property was found on.
|
||||
#! @param node The node a note is placed at, where too many instances
|
||||
#! are made.
|
||||
pub def checker::want_accessor(&mut this, accessor: u32, owner: u32, node: u32): void {
|
||||
return if accessor == 0;
|
||||
this.resolve(accessor);
|
||||
val plain := this.unalias(owner);
|
||||
return if !this.decls.has(accessor, df::generic) || this.trait_asks(accessor) || this.types.kind_of(plain) != ty::named;
|
||||
val args := this.types.parts_of(plain);
|
||||
this.instance_of(accessor, args.view(), node);
|
||||
}
|
||||
|
||||
#! Reports a member a type does not have.
|
||||
#! @param this The checker.
|
||||
#! @param node The `member` node.
|
||||
#! @param kind The type.
|
||||
#! @param name The ID of the name.
|
||||
def checker::report_no_member(&mut this, node: u32, kind: u32, name: u32): void {
|
||||
if this.types.kind_of(this.unalias(kind)) == ty::pointer {
|
||||
var said := string::from("A pointer is an address, whose only members are `equals`, `compare`, and `hash`. Reach what it points at with `(*p).", nothing {});
|
||||
val member := this.names.text(name);
|
||||
said.append(member);
|
||||
said.append("`, `p[0].");
|
||||
said.append(member);
|
||||
said.append("`, or `through(p).");
|
||||
said.append(member);
|
||||
said.append("`.");
|
||||
this.report_text(node, ec::member, &said);
|
||||
return;
|
||||
}
|
||||
var text := string::from("`", nothing {});
|
||||
val named := this.describe(kind);
|
||||
text.append(named.view());
|
||||
# A module may declare one on the type that this file does not see.
|
||||
val decl := this.type_decl(this.unalias(kind));
|
||||
val unseen := decl == 0 ? 0 : this.decls.member(decl, name);
|
||||
if unseen != 0 && !this.member_seen(unseen) {
|
||||
var holder := string::new(nothing {});
|
||||
this.module_text(this.decls.modules.p[unseen], &mut holder);
|
||||
text.append("` has `");
|
||||
text.append(this.names.text(name));
|
||||
text.append("` where `");
|
||||
text.append(holder.view());
|
||||
text.append("` is imported, as `import ");
|
||||
text.append(holder.view());
|
||||
text.append(";`, since that module declares it.");
|
||||
this.report_text(node, ec::member, &text);
|
||||
return;
|
||||
}
|
||||
text.append("` has no field, property, or method `");
|
||||
text.append(this.names.text(name));
|
||||
text.append("`.");
|
||||
this.report_text(node, ec::member, &text);
|
||||
}
|
||||
|
||||
#! `x[i]`: an element of a fixed array, of what a pointer points at, or of what
|
||||
#! implements `indexable` through its `at`, which is the reference `at` gives.
|
||||
#! @param this The checker.
|
||||
#! @param node The `index` node.
|
||||
#! @returns The element's type, the reference to it `at` gives, or the error
|
||||
#! type where the value cannot be indexed.
|
||||
def checker::index(&mut this, node: u32): u32 {
|
||||
val object := this.left_of(node);
|
||||
val at := this.right_of(node);
|
||||
# A constant settles as it would alone, so `"text"[0]` is a `strview`'s.
|
||||
var kind := this.infer_expr(object);
|
||||
if kind == bt::error {
|
||||
this.infer_expr(at);
|
||||
return bt::error;
|
||||
}
|
||||
if this.types.is_untyped(kind) {
|
||||
kind = this.settle_expr(object);
|
||||
}
|
||||
|
||||
# A reference is indexed through, but a pointer is indexed itself.
|
||||
val through := this.reached_value(kind);
|
||||
val plain := this.unalias(through);
|
||||
match this.types.kind_of(plain) {
|
||||
ty::fixed => {
|
||||
this.check_index(at);
|
||||
# Within a template, a length only each instance knows is theirs to check.
|
||||
if this.is_known(at) && this.types.part_count(plain) == 0
|
||||
&& this.value_at(at).magnitude >= this.types.second_of(plain) as u64 {
|
||||
this.report(at, ec::overflow, "The index is past the end of the array.");
|
||||
}
|
||||
this.mark_place(node, this.reaches_writable(kind, object));
|
||||
|
||||
# An element of a constant array, at an index known, is known.
|
||||
val held := this.ref_at(object);
|
||||
if held != 0 && (held & (ref_local | ref_type)) == 0 && this.ev_arrays.contains(&held) && this.is_known(at) {
|
||||
val array: ev = this.ev_arrays[held];
|
||||
val index := this.value_at(at).magnitude;
|
||||
if index < array.count as u64 {
|
||||
this.set_value(node, this.ev_heap[array.start as u64 + index]);
|
||||
}
|
||||
}
|
||||
return this.types.first_of(plain);
|
||||
}
|
||||
ty::pointer => {
|
||||
this.check_index(at);
|
||||
this.mark_place(node, this.types.second_of(plain) != 0);
|
||||
return this.types.first_of(plain);
|
||||
}
|
||||
ty::pack => {
|
||||
# `args[i]` is one of a pack's values, at an index known while compiling,
|
||||
# of a type known in each instance.
|
||||
this.check_index(at);
|
||||
this.mark_place(node, this.reaches_writable(kind, object));
|
||||
if this.types.is_open_pack(plain) {
|
||||
return this.types.param(this.types.first_of(plain));
|
||||
}
|
||||
if !this.is_known(at) {
|
||||
this.report(at, ec::constant, "A pack's values are reached at an index known while compiling.");
|
||||
return bt::error;
|
||||
}
|
||||
val index := this.value_at(at).magnitude;
|
||||
if index >= this.types.part_count(plain) as u64 {
|
||||
this.report(at, ec::overflow, "The index is past the last of the pack's values.");
|
||||
return bt::error;
|
||||
}
|
||||
return this.pack_value_type(plain, index as u32);
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
|
||||
# What implements `indexable` gives the place its `at` refers to, and the one
|
||||
# taking `&mut this` where the value can be written. A slice writes what it
|
||||
# views however it is held, as a `*mut` pointer does.
|
||||
val writes := this.reaches_writable(kind, object) || this.is_std(this.unalias(through), word::slice);
|
||||
val method := this.pick_at(through, writes);
|
||||
if method == 0 {
|
||||
var text := string::from("`", nothing {});
|
||||
val named := this.describe(kind);
|
||||
text.append(named.view());
|
||||
text.append("` is not indexed: a type is by implementing `indexable`.");
|
||||
this.report_text(node, ec::member, &text);
|
||||
this.infer_expr(at);
|
||||
return bt::error;
|
||||
}
|
||||
|
||||
val signature := this.method_type(method, through);
|
||||
if this.types.part_count(signature) >= 2 {
|
||||
this.check_expr(at, this.types.part_at(signature, 1));
|
||||
}
|
||||
this.set_ref(node, method);
|
||||
|
||||
# An element of a list of reflection, at an index known, describes one.
|
||||
val list := this.reflected_at(object);
|
||||
if list != checker::no_reflection && this.reflected_kind(list) == rk::list as u32 && this.is_known(at) {
|
||||
val index := this.value_at(at).magnitude;
|
||||
if index < this.reflected_count(list) as u64 {
|
||||
var items := vector::<u32>::new();
|
||||
items.append(this.reflected_item(list, index as u32));
|
||||
this.set_reflected(node, rk::one, items.view());
|
||||
}
|
||||
}
|
||||
|
||||
# `x[k]` is `x.at(k)`: the reference it gives, `&V` or `&mut V`, which is
|
||||
# read, written, and bound as any reference is, so it copies nothing.
|
||||
return this.types.first_of(signature);
|
||||
}
|
||||
|
||||
#! Checks an index of an array or a pointer, which is an integer.
|
||||
#! @param this The checker.
|
||||
#! @param node The index's node.
|
||||
def checker::check_index(&mut this, node: u32): void {
|
||||
val kind := this.infer_expr(node);
|
||||
return if kind == bt::error;
|
||||
if this.types.is_untyped(kind) {
|
||||
this.check_expr(node, bt::uint64);
|
||||
} else if !this.types.is_integer(this.read_type(kind)) {
|
||||
this.report_operand(node, kind, "An index is an integer.");
|
||||
}
|
||||
}
|
||||
|
||||
#! The `at` of a type indexing it: the one taking `&mut this` where `writes`
|
||||
#! says and there is one, or else the one taking `&this`, or 0.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param writes Whether the element is written.
|
||||
#! @returns The method's declaration, or 0.
|
||||
pub def checker::pick_at(&mut this, kind: u32, writes: bool): u32 {
|
||||
val found := this.find_member(kind, word::at);
|
||||
return 0 if found.decl == 0 || this.decls.kinds.p[found.decl] != dk::function;
|
||||
|
||||
# Through a type parameter's bound, the accessor that writes is `@optional`, and
|
||||
# no bound promises it.
|
||||
val bounded := this.types.kind_of(this.unalias(kind)) == ty::param;
|
||||
var reads: u32 = 0;
|
||||
var walk := this.decls.walk_overloads(found.decl);
|
||||
while true {
|
||||
val at := walk.next();
|
||||
break if at == 0;
|
||||
if this.decls.has(at, df::method) && !(bounded && this.decls.has(at, df::optional)) && this.member_seen(at) {
|
||||
if this.decls.has(at, df::mut_this) {
|
||||
return at if writes;
|
||||
} else if reads == 0 {
|
||||
reads = at;
|
||||
}
|
||||
}
|
||||
}
|
||||
return reads != 0 ? reads : (writes ? 0 : found.decl);
|
||||
}
|
||||
|
||||
#! The type of a method of a value of the type, given the type's arguments.
|
||||
#! @param this The checker.
|
||||
#! @param method The method's declaration.
|
||||
#! @param kind The type of the value.
|
||||
#! @returns The method's type.
|
||||
pub def checker::method_type(&mut this, method: u32, kind: u32): u32 {
|
||||
this.resolve(method);
|
||||
if this.trait_asks(method) {
|
||||
return this.trait_method_type(method, kind);
|
||||
}
|
||||
val plain := this.unalias(kind);
|
||||
return this.member_function_type(method, this.types.kind_of(plain) == ty::named ? plain : kind);
|
||||
}
|
||||
|
||||
#! `x[start:count]`: a view of the elements of a fixed array, of what a pointer
|
||||
#! points at, or of another view, which writes where they can be written.
|
||||
#! @param this The checker.
|
||||
#! @param node The `slice` node.
|
||||
#! @returns The view's type, or the error type where the value cannot be sliced.
|
||||
def checker::slice(&mut this, node: u32): u32 {
|
||||
val object := this.left_of(node);
|
||||
val kind := this.infer_expr(object);
|
||||
val start := this.record(node, slice_slot::start);
|
||||
val count := this.record(node, slice_slot::count);
|
||||
if start != 0 { this.check_index(start); }
|
||||
if count != 0 { this.check_index(count); }
|
||||
return bt::error if kind == bt::error;
|
||||
|
||||
val through := this.reached_value(kind);
|
||||
val plain := this.unalias(through);
|
||||
var element: u32 = bt::error;
|
||||
var writes := false;
|
||||
match this.types.kind_of(plain) {
|
||||
ty::fixed => {
|
||||
element = this.types.first_of(plain);
|
||||
writes = this.reaches_writable(kind, object);
|
||||
}
|
||||
ty::pointer => {
|
||||
element = this.types.first_of(plain);
|
||||
writes = this.types.second_of(plain) != 0;
|
||||
}
|
||||
else => {
|
||||
if this.is_std(plain, word::span) || this.is_std(plain, word::slice) {
|
||||
return plain;
|
||||
}
|
||||
this.report_operand(node, kind, "A slice is taken of a fixed array, a pointer, or a view.");
|
||||
return bt::error;
|
||||
}
|
||||
}
|
||||
|
||||
var args := vector::<u32>::new();
|
||||
args.append(element);
|
||||
return this.std_type(writes ? word::slice : word::span, args.view());
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
#! @file attributes.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the checking of attributes. An attribute is a struct literal of a
|
||||
#! struct declaring `attribute`, written before a declaration with `@`, whose
|
||||
#! fields are checked as any literal's are. A struct's `@usage` says what kinds
|
||||
#! of declaration its attributes may describe, and whether one may have more
|
||||
#! than one of them.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! What a struct's `@usage` allows of its attributes.
|
||||
pub struct checker::usage {
|
||||
var on: u64; #! The bits of `core::target` it may be written on.
|
||||
var many: bool; #! Whether a declaration may have more than one.
|
||||
}
|
||||
|
||||
#! Checks the attributes written before the declaration.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
pub def checker::check_attributes(&mut this, id: u32): void {
|
||||
val node: u32 = this.decls.nodes.p[id];
|
||||
val attrs := this.attributes_of(node);
|
||||
return if this.run_length(attrs) == 0;
|
||||
|
||||
val attribute := this.std_decl(word::attribute);
|
||||
var seen := vector::<u32>::new();
|
||||
for &attr in this.run_view(attrs) {
|
||||
continue if this.kind_of(attr) != nk::attribute;
|
||||
|
||||
# What C gives was written with attributes before `extern` sections were.
|
||||
val named := this.left_of(attr);
|
||||
val name := this.segment_name(named, this.segment_count(named) - 1);
|
||||
if (name == word::foreign || name == word::link) && this.segment_count(named) == 1
|
||||
&& this.lookup_named(name, attr, true).decl == 0 {
|
||||
this.report(attr, ec::invalid,
|
||||
"`@foreign` and `@link` are gone: C's functions, structs, and unions are declared in an `extern module`, and `extern import` names their library.");
|
||||
continue;
|
||||
}
|
||||
|
||||
val kind := this.resolve_type(this.left_of(attr));
|
||||
continue if kind == bt::error;
|
||||
if this.named_kind(kind) != dk::struct_type || (attribute != 0 && !this.names_trait(kind, attribute)) {
|
||||
var text := string::from("`", nothing {});
|
||||
val named := this.describe(kind);
|
||||
text.append(named.view());
|
||||
text.append("` is not an attribute: an attribute's type is a struct declaring `attribute`.");
|
||||
this.report_text(attr, ec::invalid, &text);
|
||||
continue;
|
||||
}
|
||||
|
||||
this.construct_struct(attr, kind, this.right_of(attr));
|
||||
val decl := this.types.first_of(kind);
|
||||
val usage := this.usage_of(decl);
|
||||
val bit := this.target_bit(id);
|
||||
if bit != 0 && (usage.on & bit) == 0 {
|
||||
var text := string::from("`", nothing {});
|
||||
text.append(this.decl_text(decl));
|
||||
text.append("` is not written on ");
|
||||
text.append(this.target_word(id));
|
||||
text.append(", as its `@usage` says.");
|
||||
this.report_text(attr, ec::invalid, &text);
|
||||
}
|
||||
|
||||
# What is copied where it is called has a body to copy.
|
||||
val written := this.decls.kinds.p[id];
|
||||
if name == word::inline && (written == dk::function || written == dk::property)
|
||||
&& (this.decls.has(id, df::intrinsic) || this.decls.has(id, df::foreign)) {
|
||||
this.report(attr, ec::invalid,
|
||||
"`@inline` copies a function's body where it is called, and a function C or the compiler gives has none.");
|
||||
}
|
||||
|
||||
if seen.view().contains(&decl) && !usage.many {
|
||||
var text := string::from("`", nothing {});
|
||||
text.append(this.decl_text(decl));
|
||||
text.append("` is written once on a declaration, unless its `@usage` says `many = true`.");
|
||||
this.report_text(attr, ec::duplicate, &text);
|
||||
}
|
||||
seen.append(decl);
|
||||
}
|
||||
}
|
||||
|
||||
#! What a struct's `@usage` allows of its attributes, or anything, once each,
|
||||
#! where it has none.
|
||||
#! @param this The checker.
|
||||
#! @param decl The attribute struct's declaration.
|
||||
#! @returns What it may be written on, and whether more than once.
|
||||
pub def checker::usage_of(&mut this, decl: u32): checker::usage {
|
||||
var made := checker::usage { on = 0xFFFF, many = false };
|
||||
val usage := this.std_decl(word::usage);
|
||||
return made if usage == 0;
|
||||
|
||||
val saved := this.at;
|
||||
this.enter_decl(decl, 0);
|
||||
val attrs := this.attributes_of(this.decls.nodes.p[decl]);
|
||||
for &attr in this.run_view(attrs) {
|
||||
continue if this.kind_of(attr) != nk::attribute;
|
||||
val named := this.left_of(attr);
|
||||
continue if this.segment_name(named, this.segment_count(named) - 1) != word::usage;
|
||||
|
||||
val inits := this.right_of(attr);
|
||||
for &init in this.run_view(inits) {
|
||||
val value := this.left_of(init);
|
||||
this.infer_expr(value);
|
||||
continue if !this.is_known(value);
|
||||
val name := this.name_of(init);
|
||||
if name == this.names.intern(&"on") {
|
||||
made.on = this.value_at(value).magnitude;
|
||||
} else if name == this.names.intern(&"many") {
|
||||
made.many = this.value_at(value).magnitude != 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
this.leave(saved);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The bit of `core::target` the kind of declaration is, or 0 where std has none.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns The bit, or 0.
|
||||
pub def checker::target_bit(&mut this, id: u32): u64 {
|
||||
val holder := this.std_decl(this.names.intern(&"target"));
|
||||
return 0 if holder == 0;
|
||||
|
||||
val member := this.decls.member(holder, this.names.intern(&this.target_name(id)));
|
||||
var value := constant {};
|
||||
this.resolve(holder);
|
||||
return 0 if member == 0 || !this.decl_value(member, &mut value);
|
||||
return value.magnitude;
|
||||
}
|
||||
|
||||
#! The name of the member of `core::target` the kind of declaration is.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns The name, as `functions`.
|
||||
def checker::target_name(&mut this, id: u32): strview {
|
||||
val owner: u32 = this.decls.owners.p[id];
|
||||
val in_trait := owner != 0 && this.decls.kinds.p[owner] == dk::trait_type && !this.receiver_declared(id);
|
||||
return "requirements" if in_trait;
|
||||
return match this.decls.kinds.p[id] {
|
||||
dk::function => owner != 0 ? "methods" : "functions",
|
||||
dk::variable => this.decls.has(id, df::constant) ? "constants" : "variables",
|
||||
dk::field => "fields",
|
||||
dk::struct_type => "structs",
|
||||
dk::union_type => "unions",
|
||||
dk::enum_type => "enums",
|
||||
dk::enum_member => "members",
|
||||
dk::trait_type => "traits",
|
||||
dk::alias_type => "aliases",
|
||||
dk::property => "properties",
|
||||
dk::attribute => "constants",
|
||||
else => "all"
|
||||
};
|
||||
}
|
||||
|
||||
#! The kind of declaration, as a note says it.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns The words, as `a function`.
|
||||
def checker::target_word(&mut this, id: u32): strview {
|
||||
val owner: u32 = this.decls.owners.p[id];
|
||||
val in_trait := owner != 0 && this.decls.kinds.p[owner] == dk::trait_type && !this.receiver_declared(id);
|
||||
return "what a trait declares" if in_trait;
|
||||
return match this.decls.kinds.p[id] {
|
||||
dk::function => owner != 0 ? "methods" : "functions",
|
||||
dk::variable => this.decls.has(id, df::constant) ? "constants" : "variables",
|
||||
dk::field => "fields",
|
||||
dk::struct_type => "structs",
|
||||
dk::union_type => "unions",
|
||||
dk::enum_type => "enums",
|
||||
dk::enum_member => "enum members",
|
||||
dk::trait_type => "traits",
|
||||
dk::alias_type => "aliases",
|
||||
dk::property => "properties",
|
||||
else => "this"
|
||||
};
|
||||
}
|
||||
|
||||
#! Checks a function given by C: never generic, overloaded, or a method, and of
|
||||
#! parameters and a result whose types C lays out the same way.
|
||||
#! @param this The checker.
|
||||
#! @param id The function's declaration.
|
||||
pub def checker::check_foreign(&mut this, id: u32): void {
|
||||
val node: u32 = this.decls.nodes.p[id];
|
||||
if this.decls.has(id, df::generic) || this.decls.has(id, df::method) || this.decls.overloads.p[id] != 0 {
|
||||
this.report(node, ec::invalid, "A C function is never generic, overloaded, or a method.");
|
||||
return;
|
||||
}
|
||||
|
||||
val kind: u32 = this.decls.types.p[id];
|
||||
for i in 0..this.types.part_count(kind) {
|
||||
val param := this.types.part_at(kind, i as u32);
|
||||
if !this.crosses(param, true, 0) {
|
||||
this.report_crossing(node, param);
|
||||
}
|
||||
}
|
||||
val result := this.types.first_of(kind);
|
||||
if result != bt::void_type && !this.crosses(result, false, 0) {
|
||||
this.report_crossing(node, result);
|
||||
}
|
||||
}
|
||||
|
||||
def checker::report_crossing(&mut this, node: u32, kind: u32): void {
|
||||
var text := string::from("`", nothing {});
|
||||
val named := this.describe(kind);
|
||||
text.append(named.view());
|
||||
text.append("` does not cross to C, which lays out only numbers, `bool`, enums, pointers, function pointers, and structs and C's unions of them.");
|
||||
this.report_text(node, ec::invalid, &text);
|
||||
}
|
||||
|
||||
#! Checks a function given where C's address of one is expected, which C calls
|
||||
#! back: never generic or a method, and of parameters and a result that cross.
|
||||
#! @param this The checker.
|
||||
#! @param node The node naming it.
|
||||
#! @param id The function's declaration.
|
||||
pub def checker::check_callback(&mut this, node: u32, id: u32): void {
|
||||
if this.decls.has(id, df::generic) || this.decls.has(id, df::method) || this.decls.has(id, df::intrinsic) {
|
||||
this.report(node, ec::invalid, "C calls back a function of the program that is neither generic, a method, nor `@intrinsic`.");
|
||||
return;
|
||||
}
|
||||
|
||||
val kind: u32 = this.decls.types.p[id];
|
||||
for i in 0..this.types.part_count(kind) {
|
||||
val param := this.types.part_at(kind, i as u32);
|
||||
if !this.crosses(param, true, 0) {
|
||||
this.report_crossing(node, param);
|
||||
}
|
||||
}
|
||||
val result := this.types.first_of(kind);
|
||||
if result != bt::void_type && !this.crosses(result, false, 0) {
|
||||
this.report_crossing(node, result);
|
||||
}
|
||||
}
|
||||
|
||||
#! Checks a struct or union of an `extern module`, which C lays out: never
|
||||
#! generic, and of fields whose types cross.
|
||||
#! @param this The checker.
|
||||
#! @param id The type's declaration.
|
||||
def checker::check_c_type(&mut this, id: u32): void {
|
||||
val node: u32 = this.decls.nodes.p[id];
|
||||
if this.decls.has(id, df::generic) {
|
||||
this.report(node, ec::invalid, "A struct or union of an `extern module` is laid out as C's, so it is never generic.");
|
||||
return;
|
||||
}
|
||||
|
||||
val run: u32 = this.decls.children.p[id];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val field := this.decls.list_at(run, i as u32);
|
||||
continue if this.decls.kinds.p[field] != dk::field;
|
||||
this.resolve(field);
|
||||
val kind: u32 = this.decls.types.p[field];
|
||||
if !this.crosses(kind, false, 1) {
|
||||
this.report_crossing(this.decls.nodes.p[field], kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether C lays out a value of the type as Sakura does: a number, `bool`, an
|
||||
#! enum, a pointer, a function pointer, a reference where it is a parameter,
|
||||
#! and a struct, or a C union, of what crosses, with arrays within.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param parameter Whether it is a parameter's, where a reference crosses as
|
||||
#! a pointer.
|
||||
#! @param depth How deeply the search has gone, which stops a type nesting
|
||||
#! without end.
|
||||
#! @returns Whether it does.
|
||||
def checker::crosses(&mut this, kind: u32, parameter: bool, depth: u32): bool {
|
||||
return true if depth > 8 || kind == bt::error;
|
||||
val plain := this.unalias(kind);
|
||||
match this.types.kind_of(plain) {
|
||||
ty::boolean, ty::signed, ty::unsigned, ty::floating, ty::pointer => return true;
|
||||
ty::reference => return parameter;
|
||||
ty::fixed => return depth > 0 && this.crosses(this.types.first_of(plain), false, depth + 1);
|
||||
ty::named => {
|
||||
val named := this.named_kind(plain);
|
||||
return true if named == dk::enum_type || this.is_std(plain, word::cfn);
|
||||
return false if named != dk::struct_type && !(named == dk::union_type && this.decls.has(this.types.first_of(plain), df::foreign));
|
||||
val fields := this.field_types(plain);
|
||||
for &each in fields {
|
||||
return false if !this.crosses(each, false, depth + 1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
else => return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
#! @file bodies.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the checking of what each declaration holds beyond its signature:
|
||||
#! the body of a function, checked once against the bounds of its type
|
||||
#! parameters where it is generic, the values of variables and fields, and
|
||||
#! that a struct or union implements the traits it names.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! Checks what the declaration holds.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
pub def checker::check_decl(&mut this, id: u32): void {
|
||||
return if this.decls.has(id, df::checked) || this.decls.has(id, df::failed);
|
||||
this.decls.mark(id, df::checked);
|
||||
|
||||
# The attributes written before it, in its own file and scope.
|
||||
if this.decls.kinds.p[id] != dk::type_param && this.decls.kinds.p[id] != dk::builtin
|
||||
&& !this.decls.has(id, df::accessor) && this.decls.nodes.p[id] != 0 {
|
||||
val saved := this.at;
|
||||
this.enter_decl(id, 0);
|
||||
this.check_attributes(id);
|
||||
this.leave(saved);
|
||||
}
|
||||
|
||||
match this.decls.kinds.p[id] {
|
||||
dk::function => {
|
||||
this.resolve(id);
|
||||
this.check_overloads(id);
|
||||
this.check_main(id);
|
||||
if this.decls.has(id, df::foreign) {
|
||||
val saved := this.at;
|
||||
this.use_table(this.units[this.decls.files.p[id]].table);
|
||||
this.check_foreign(id);
|
||||
this.at = saved;
|
||||
}
|
||||
return if this.decls.has(id, df::intrinsic) || this.decls.has(id, df::foreign) && !this.has_body(id);
|
||||
val saved := this.at;
|
||||
this.enter_decl(id, 0);
|
||||
this.check_asked(id);
|
||||
# Its lifetimes are warned of only where its body checks.
|
||||
val errors := this.errors;
|
||||
this.check_function_body(id, this.decls.types.p[id]);
|
||||
if this.errors == errors {
|
||||
this.check_lifetimes(id);
|
||||
}
|
||||
this.leave(saved);
|
||||
}
|
||||
dk::variable, dk::field => this.check_value(id);
|
||||
dk::struct_type, dk::union_type => {
|
||||
this.check_implements(id);
|
||||
this.check_contains(id);
|
||||
if this.decls.has(id, df::foreign) {
|
||||
val saved := this.at;
|
||||
this.use_table(this.units[this.decls.files.p[id]].table);
|
||||
this.check_c_type(id);
|
||||
this.at = saved;
|
||||
}
|
||||
}
|
||||
dk::trait_type => {
|
||||
this.resolve_composed(id);
|
||||
}
|
||||
else => this.resolve(id);
|
||||
}
|
||||
}
|
||||
|
||||
#! Checks a function a trait asks for, which each type implementing the trait
|
||||
#! gives: one with type parameters of its own gives a default, which each type
|
||||
#! takes as its own, since no table holds a generic, and one taking no `this`
|
||||
#! has no default, since nothing within the trait names the type implementing
|
||||
#! it.
|
||||
#! @param this The checker.
|
||||
#! @param id The function's declaration, whose file is the one checked.
|
||||
def checker::check_asked(&mut this, id: u32): void {
|
||||
return if !this.trait_asks(id) || this.decls.has(id, df::accessor);
|
||||
|
||||
val node: u32 = this.decls.nodes.p[id];
|
||||
val params := this.record(node, function_slot::type_params);
|
||||
if this.run_length(params) != 0 && !this.has_body(id) {
|
||||
this.report(this.run_at(params, 0), ec::generic,
|
||||
"A trait's generic method gives a default, which each type implementing the trait takes as its own, since no table holds a generic.");
|
||||
}
|
||||
if !this.decls.has(id, df::method) && this.has_body(id) {
|
||||
this.report(node, ec::invalid,
|
||||
"Static methods of a trait have no default, since nothing within the trait names the type implementing them.");
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether a function has a body, rather than ending at its signature.
|
||||
#! @param this The checker.
|
||||
#! @param id The function's declaration.
|
||||
#! @returns Whether it has.
|
||||
pub def checker::has_body(&this, id: u32): bool {
|
||||
val syntax := &this.units[this.decls.files.p[id]].syntax;
|
||||
val node := this.decls.nodes.p[id];
|
||||
if this.decls.has(id, df::accessor) {
|
||||
return syntax.extras[syntax.node_rights[node]] != 0;
|
||||
}
|
||||
return syntax.extras[syntax.node_lefts[node] as u64 + function_slot::body as u64] != 0;
|
||||
}
|
||||
|
||||
#! Checks a function's body against its type: its parameters are locals of
|
||||
#! their types, its default values are checked where its parameters are, and
|
||||
#! it returns a value on every path where its result is not `void`.
|
||||
#! @param this The checker.
|
||||
#! @param id The function's declaration.
|
||||
#! @param kind Its function type, given the type arguments it is checked with.
|
||||
pub def checker::check_function_body(&mut this, id: u32, kind: u32): void {
|
||||
val node: u32 = this.decls.nodes.p[id];
|
||||
val accessor := this.decls.has(id, df::accessor);
|
||||
val body := accessor ? this.record(node, accessor_slot::body) : this.record(node, function_slot::body);
|
||||
val params := accessor ? this.left_of(node) : this.record(node, function_slot::params);
|
||||
if body == 0 {
|
||||
if !this.decls.has(id, df::intrinsic) && !this.decls.has(id, df::foreign)
|
||||
&& this.enclosing_trait(id) == 0 {
|
||||
this.report(node, ec::invalid, "A function has a body, unless it is `@intrinsic`, given by the compiler, or C's: a function with no body is C's only in an `extern module`.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
this.at.result = this.types.first_of(kind);
|
||||
val count := this.types.part_count(kind);
|
||||
# A trait's method's own body has the bounds it puts on the trait's parameters
|
||||
# and `self`, which an instance's arguments meet.
|
||||
val proved := this.proved_params.length;
|
||||
if this.at.instance == 0 {
|
||||
this.prove_outer(id);
|
||||
}
|
||||
|
||||
# A pack parameter is a local holding the pack: in the generic's own body,
|
||||
# a pack of types not known, and in an instance, the types the parameters
|
||||
# from it on were given.
|
||||
val written: u32 = this.decls.types.p[id];
|
||||
val wcount := this.types.part_count(written);
|
||||
val packed := this.decls.has(id, df::variadic) && wcount != 0
|
||||
&& this.types.is_open_pack(this.types.part_at(written, wcount - 1));
|
||||
for i in 0..this.run_length(params) {
|
||||
val param := this.run_at(params, i as u32);
|
||||
var held: u32 = i < count ? this.types.part_at(kind, i as u32) : bt::error;
|
||||
if packed && i as u32 + 1 == wcount {
|
||||
var rest := vector::<u32>::new();
|
||||
for j in i..count {
|
||||
rest.append(this.types.part_at(kind, j as u32));
|
||||
}
|
||||
# Given a variadic function's parameters, as a pattern's pack may be, the
|
||||
# pack ends in a view of the rest, which its type says as a variadic pack.
|
||||
val open := i < count && this.types.is_open_pack(this.types.part_at(kind, i as u32));
|
||||
held = open ? this.types.part_at(kind, i as u32)
|
||||
: this.types.second_of(kind) != 0 && rest.length != 0 ? this.types.variadic_pack(rest.view())
|
||||
: this.types.pack(rest.view(), 0);
|
||||
} else if this.types.second_of(kind) != 0 && i as u32 + 1 == count {
|
||||
held = this.variadic_type(held);
|
||||
}
|
||||
|
||||
# A default value is checked where its parameter is, with the parameters
|
||||
# before it named, and runs at each call that leaves it out.
|
||||
val value := accessor ? 0 : this.record(param, parameter_slot::value);
|
||||
if value != 0 {
|
||||
this.check_expr(value, held);
|
||||
}
|
||||
this.declare_local(param, this.param_name(param), held);
|
||||
this.set_flag(param, rf::mutable);
|
||||
}
|
||||
|
||||
this.at.body = body;
|
||||
val how := this.check_block(body);
|
||||
this.unprove_to(proved);
|
||||
val result := this.at.result;
|
||||
if how == flow::goes_on && result != bt::void_type && result != bt::error {
|
||||
this.report(node, ec::control, "The function can end without returning a value.");
|
||||
}
|
||||
}
|
||||
|
||||
#! The type a variadic parameter is within its function: a view of its
|
||||
#! arguments, or with a pack, the pack itself.
|
||||
#! @param this The checker.
|
||||
#! @param element The type of the parameter as written: of each argument.
|
||||
#! @returns The type.
|
||||
def checker::variadic_type(&mut this, element: u32) : u32 {
|
||||
return element if this.types.kind_of(element) == ty::pack;
|
||||
return this.span_of(element);
|
||||
}
|
||||
|
||||
#! Checks the value a variable or field is declared with, against the type
|
||||
#! written for it.
|
||||
#! @param this The checker.
|
||||
#! @param id The variable's or field's declaration.
|
||||
def checker::check_value(&mut this, id: u32): void {
|
||||
this.resolve(id);
|
||||
val node: u32 = this.decls.nodes.p[id];
|
||||
val saved := this.at;
|
||||
this.enter_decl(id, 0);
|
||||
val value := this.record(node, variable_slot::value);
|
||||
if value != 0 && !this.has_flag(value, rf::checked) {
|
||||
this.check_expr(value, this.decls.types.p[id]);
|
||||
} else if value == 0 && this.decls.kinds.p[id] == dk::variable && !this.has_zero(this.decls.types.p[id], 0) {
|
||||
var text := string::from("`", nothing {});
|
||||
val named := this.describe(this.decls.types.p[id]);
|
||||
text.append(named.view());
|
||||
text.append("` has no zero value, so the variable is given a value where it is declared.");
|
||||
this.report_text(node, ec::zero_value, &text);
|
||||
}
|
||||
this.leave(saved);
|
||||
}
|
||||
|
||||
#! Checks that a struct or union implements each trait it names.
|
||||
#! @param this The checker.
|
||||
#! @param id The struct's or union's declaration.
|
||||
def checker::check_implements(&mut this, id: u32): void {
|
||||
val run := this.composed_of(id);
|
||||
val kind: u32 = this.decls.types.p[id];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val wanted := this.decls.list_at(run, i as u32);
|
||||
continue if this.satisfies(kind, wanted);
|
||||
|
||||
var text := string::from("`", nothing {});
|
||||
text.append(this.decl_text(id));
|
||||
text.append("` names `");
|
||||
val named := this.describe(wanted);
|
||||
text.append(named.view());
|
||||
text.append("` but does not implement all of it");
|
||||
val missing := this.missing_requirement(kind, wanted);
|
||||
if missing != 0 {
|
||||
text.append(": it has no `");
|
||||
text.append(this.decl_text(missing));
|
||||
text.append("` of the signature the trait asks for");
|
||||
}
|
||||
text.append(".");
|
||||
this.report_decl(id, ec::bound, text.view());
|
||||
}
|
||||
}
|
||||
|
||||
#! The first thing a trait asks for that the type does not have, or 0.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param trait_kind The trait's type, given its arguments.
|
||||
#! @returns The declaration of what it asks for, or 0.
|
||||
def checker::missing_requirement(&mut this, kind: u32, trait_kind: u32): u32 {
|
||||
val holder := this.types.first_of(trait_kind);
|
||||
val run := this.decls.children.p[holder];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val wanted := this.decls.list_at(run, i as u32);
|
||||
continue if this.decls.has(wanted, df::optional);
|
||||
return wanted if !this.meets(kind, trait_kind, wanted);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! Reports an overload taking the same parameters as one declared before it,
|
||||
#! which no call could choose between.
|
||||
#! @param this The checker.
|
||||
#! @param id The function's declaration.
|
||||
def checker::check_overloads(&mut this, id: u32): void {
|
||||
val owner := this.decls.owners.p[id];
|
||||
val first: u32 = owner != 0 && this.decls.kinds.p[owner] != dk::property
|
||||
? this.first_member(id)
|
||||
: this.modules.decl(this.decls.modules.p[id], this.decls.names.p[id]);
|
||||
return if first == 0 || first == id || this.decls.has(id, df::accessor);
|
||||
|
||||
var walk := this.decls.walk_overloads(first);
|
||||
while true {
|
||||
val at := walk.next();
|
||||
break if at == 0 || at == id;
|
||||
this.resolve(at);
|
||||
if this.decls.kinds.p[at] == dk::function && this.same_params(at, id) {
|
||||
this.report_decl_related(id, ec::duplicate,
|
||||
"Another overload of this name takes the same parameters, so no call could choose between them.",
|
||||
at, "The other overload.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether two functions take the same parameters: of the same types, an alias
|
||||
#! being a type of its own, both static or both taking `this` alike.
|
||||
#! @param this The checker.
|
||||
#! @param a One function's declaration.
|
||||
#! @param b The other's.
|
||||
#! @returns Whether they do.
|
||||
def checker::same_params(&mut this, a: u32, b: u32): bool {
|
||||
return false if this.decls.has(a, df::method) != this.decls.has(b, df::method);
|
||||
return false if this.decls.has(a, df::mut_this) != this.decls.has(b, df::mut_this);
|
||||
return false if this.decls.has(a, df::generic) || this.decls.has(b, df::generic);
|
||||
|
||||
val ka := this.decls.types.p[a];
|
||||
val kb := this.decls.types.p[b];
|
||||
return false if this.types.part_count(ka) != this.types.part_count(kb);
|
||||
return false if (this.types.second_of(ka) != 0) != (this.types.second_of(kb) != 0);
|
||||
for i in 0..this.types.part_count(ka) {
|
||||
return false if this.types.part_at(ka, i as u32) != this.types.part_at(kb, i as u32);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Checks `main`, of the program itself, which takes nothing or the arguments
|
||||
#! as views of text, and returns nothing.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration of `main`.
|
||||
def checker::check_main(&mut this, id: u32): void {
|
||||
return if this.decls.names.p[id] != word::main || this.decls.modules.p[id] != 0 || this.decls.owners.p[id] != 0;
|
||||
|
||||
val kind: u32 = this.decls.types.p[id];
|
||||
var valid := this.types.first_of(kind) == bt::void_type && this.types.part_count(kind) <= 1;
|
||||
if valid && this.types.part_count(kind) == 1 {
|
||||
val texts := this.span_of(this.span_of(bt::uint8));
|
||||
valid = texts == bt::error || this.strip(this.types.part_at(kind, 0), 0) == this.strip(texts, 0);
|
||||
}
|
||||
if this.decls.overloads.p[id] != 0 || this.modules.decl(0, word::main) != id {
|
||||
valid = false;
|
||||
}
|
||||
return if valid;
|
||||
|
||||
this.report_decl(id, ec::invalid,
|
||||
"`main` is `def main(): void` or `def main(args: span<strview>): void`, and is not overloaded.");
|
||||
}
|
||||
|
||||
#! Reports a struct or union holding itself, other than through a pointer or a
|
||||
#! reference, which no amount of memory could hold.
|
||||
#! @param this The checker.
|
||||
#! @param id The struct's or union's declaration.
|
||||
def checker::check_contains(&mut this, id: u32): void {
|
||||
var seen := vector::<u32>::new();
|
||||
if this.holds(this.decls.types.p[id], id, &mut seen, 0) {
|
||||
var text := string::from("`", nothing {});
|
||||
text.append(this.decl_text(id));
|
||||
text.append("` holds itself, which only a pointer or a reference to it can.");
|
||||
this.report_decl(id, ec::recursive, text.view());
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether a value of the type holds a value of the declaration's type, in its
|
||||
#! fields or elements, rather than through a pointer or reference.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param target The declaration looked for.
|
||||
#! @param seen The types already looked within, which are not looked within
|
||||
#! again.
|
||||
#! @param depth How deeply the search has gone.
|
||||
#! @returns Whether it does.
|
||||
def checker::holds(&mut this, kind: u32, target: u32, seen: &mut vector<u32>, depth: u32): bool {
|
||||
return false if depth > 32;
|
||||
val plain := this.unalias(kind);
|
||||
if this.types.kind_of(plain) == ty::fixed {
|
||||
return this.holds(this.types.first_of(plain), target, seen, depth + 1);
|
||||
}
|
||||
val named := this.named_kind(plain);
|
||||
return false if named != dk::struct_type && named != dk::union_type;
|
||||
|
||||
val decl := this.types.first_of(plain);
|
||||
return true if decl == target && depth > 0;
|
||||
return false if seen.view().contains(&plain);
|
||||
seen.append(plain);
|
||||
|
||||
val fields := this.field_types(plain);
|
||||
for &field in fields {
|
||||
return true if this.holds(field, target, seen, depth + 1);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,587 @@
|
||||
#! @file composite.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the checking of values built from others: struct and union
|
||||
#! literals, array literals, and anonymous functions, which may take their
|
||||
#! types from the type expected of them.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! A struct or union literal, as `vec2{1, 2}`, `vec2{ y = 8 }`, or
|
||||
#! `res::<i64>{ error = 5 }`. A generic struct written without its type
|
||||
#! arguments takes them from the type expected, or from its fields' values.
|
||||
#! @param this The checker.
|
||||
#! @param node The `construct` node.
|
||||
#! @param expected The type expected, or the error type where none is.
|
||||
#! @returns The literal's type, or the error type where it is not valid.
|
||||
def checker::construct(&mut this, node: u32, expected: u32): u32 {
|
||||
val named := this.left_of(node);
|
||||
val inits := this.right_of(node);
|
||||
val decl := this.type_name_decl(named);
|
||||
if decl == 0 {
|
||||
this.check_inits(inits);
|
||||
return bt::error;
|
||||
}
|
||||
|
||||
var kind: u32 = bt::error;
|
||||
val wanted := this.unalias(expected);
|
||||
val written_args := this.segment_args(named, this.segment_count(named) - 1);
|
||||
if this.decls.has(decl, df::generic) && written_args == 0 && this.segment_count(named) == 1
|
||||
&& !this.scope_gives_args(this.segment_name(named, 0), decl) {
|
||||
if this.types.kind_of(wanted) == ty::named && this.types.first_of(wanted) == decl {
|
||||
kind = wanted;
|
||||
} else {
|
||||
kind = this.infer_struct(decl, inits, named);
|
||||
}
|
||||
} else {
|
||||
kind = this.resolve_type(named);
|
||||
}
|
||||
if kind == bt::error {
|
||||
this.check_inits(inits);
|
||||
return bt::error;
|
||||
}
|
||||
|
||||
# `void {}` is the one value of `void`, which holds nothing.
|
||||
val plain := this.unalias(kind);
|
||||
if plain == bt::void_type {
|
||||
if this.run_length(inits) != 0 {
|
||||
this.report(this.run_at(inits, 0), ec::invalid, "`void` holds nothing, so `void {}` is given no fields.");
|
||||
this.check_inits(inits);
|
||||
}
|
||||
return kind;
|
||||
}
|
||||
match this.named_kind(plain) {
|
||||
dk::struct_type => this.construct_struct(node, plain, inits);
|
||||
dk::union_type => this.construct_union(node, plain, inits);
|
||||
else => {
|
||||
this.report(named, ec::not_type, "Only a struct or a union is made with `{}`.");
|
||||
this.check_inits(inits);
|
||||
return bt::error;
|
||||
}
|
||||
}
|
||||
return kind;
|
||||
}
|
||||
|
||||
#! The declaration a type name names, without looking at its type arguments,
|
||||
#! or 0 where it names none.
|
||||
#! @param this The checker.
|
||||
#! @param node The `type_name` node.
|
||||
#! @returns The declaration, or 0.
|
||||
def checker::type_name_decl(&mut this, node: u32): u32 {
|
||||
if this.segment_count(node) == 1 {
|
||||
val name := this.segment_name(node, 0);
|
||||
val bound := this.bound(name);
|
||||
if (bound & ref_type) != 0 {
|
||||
this.set_ref(node, bound);
|
||||
return this.type_decl(bound & ref_mask);
|
||||
}
|
||||
|
||||
val decl := this.lookup_type(name, node);
|
||||
if decl == 0 || !this.is_type_decl(decl) {
|
||||
var text := string::from("No struct or union `", nothing {});
|
||||
text.append(this.names.text(name));
|
||||
text.append("` is declared where it is written.");
|
||||
this.report_text(node, ec::undefined, &text);
|
||||
return 0;
|
||||
}
|
||||
this.set_ref(node, decl);
|
||||
return decl;
|
||||
}
|
||||
|
||||
val kind := this.resolve_type(node);
|
||||
return kind == bt::error ? 0 : this.type_decl(this.unalias(kind));
|
||||
}
|
||||
|
||||
#! Whether a type around a name gives the arguments of the generic type it
|
||||
#! names, as `list<T>` gives `node` its `T` within it, which then takes no more.
|
||||
#! @param this The checker.
|
||||
#! @param name The ID of the name.
|
||||
#! @param decl The type's declaration.
|
||||
#! @returns Whether it does.
|
||||
def checker::scope_gives_args(&mut this, name: u32, decl: u32): bool {
|
||||
return false if this.bound(name) != 0 || this.own_param_count(decl) != 0;
|
||||
val found := this.in_scope(name, true);
|
||||
return found.decl == decl && this.types.kind_of(found.owner) == ty::named && this.types.part_count(found.owner) != 0;
|
||||
}
|
||||
|
||||
#! Checks the values of a literal whose type went wrong, so what is wrong
|
||||
#! within them is still reported.
|
||||
#! @param this The checker.
|
||||
#! @param run The run of `field_init` nodes.
|
||||
def checker::check_inits(&mut this, run: u32): void {
|
||||
for &each in this.run_view(run) {
|
||||
this.infer_expr(this.left_of(each));
|
||||
}
|
||||
}
|
||||
|
||||
#! The type of a generic struct whose type arguments its fields' values give.
|
||||
#! @param this The checker.
|
||||
#! @param decl The struct's declaration.
|
||||
#! @param inits The run of `field_init` nodes.
|
||||
#! @param node The node notes are placed at.
|
||||
#! @returns The struct's type, or the error type where its fields do not give
|
||||
#! its arguments.
|
||||
def checker::infer_struct(&mut this, decl: u32, inits: u32, node: u32): u32 {
|
||||
var inferred := this.begin_inference(decl, bt::error, span::<u32>::empty());
|
||||
val fields: u32 = this.decls.children.p[decl];
|
||||
for i in 0..this.run_length(inits) {
|
||||
val init := this.run_at(inits, i as u32);
|
||||
val field := this.init_field(decl, init, i as u32);
|
||||
continue if field == 0;
|
||||
|
||||
this.resolve(field);
|
||||
val value := this.left_of(init);
|
||||
if !this.deferred(value) {
|
||||
this.unify(this.decls.types.p[field], this.infer_expr(value), &mut inferred, 0);
|
||||
}
|
||||
}
|
||||
|
||||
val missing := this.unbound(&inferred);
|
||||
if missing != 0 {
|
||||
var text := string::from("Nothing gives the type of `", nothing {});
|
||||
text.append(this.decl_text(missing));
|
||||
text.append("`, so give the type arguments, as `");
|
||||
text.append(this.decl_text(decl));
|
||||
text.append("::<...>{...}`.");
|
||||
this.report_text(node, ec::generic, &text);
|
||||
return bt::error;
|
||||
}
|
||||
return this.named_of(decl, inferred.binds.view(), node, true);
|
||||
}
|
||||
|
||||
#! The field a value of a literal is given for: the one it names, or the one at
|
||||
#! its place, or 0.
|
||||
#! @param this The checker.
|
||||
#! @param decl The struct's or union's declaration.
|
||||
#! @param init The `field_init` node.
|
||||
#! @param index Its position in the literal.
|
||||
#! @returns The field's declaration, or 0.
|
||||
def checker::init_field(&mut this, decl: u32, init: u32, index: u32): u32 {
|
||||
if this.node_has(init, nf::named) {
|
||||
val found := this.find_member(this.decls.types.p[decl], this.name_of(init));
|
||||
return found.decl != 0 && this.decls.kinds.p[found.decl] == dk::field ? found.decl : 0;
|
||||
}
|
||||
|
||||
val run: u32 = this.decls.children.p[decl];
|
||||
var at: u32 = 0;
|
||||
for &field in this.decls.list_view(run) {
|
||||
continue if this.decls.kinds.p[field] != dk::field;
|
||||
return field if at == index;
|
||||
at++;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! The fields of a struct literal: each value given converts to its field,
|
||||
#! and each field left out takes its default, or its zero value.
|
||||
#! @param this The checker.
|
||||
#! @param node The `construct` node.
|
||||
#! @param kind The struct's type.
|
||||
#! @param inits The run of `field_init` nodes.
|
||||
def checker::construct_struct(&mut this, node: u32, kind: u32, inits: u32): void {
|
||||
val decl := this.types.first_of(kind);
|
||||
var given := vector::<u32>::new();
|
||||
for i in 0..this.run_length(inits) {
|
||||
val init := this.run_at(inits, i as u32);
|
||||
val value := this.left_of(init);
|
||||
val field := this.init_field(decl, init, i as u32);
|
||||
if field == 0 {
|
||||
if this.node_has(init, nf::named) {
|
||||
this.report_no_member(init, kind, this.name_of(init));
|
||||
} else {
|
||||
this.report(init, ec::arguments, "The literal gives more values than the struct has fields.");
|
||||
}
|
||||
this.infer_expr(value);
|
||||
continue;
|
||||
}
|
||||
|
||||
var twice := false;
|
||||
for &each in given {
|
||||
twice = twice || each == field;
|
||||
}
|
||||
if twice {
|
||||
this.report(init, ec::duplicate, "The field is given a value twice.");
|
||||
}
|
||||
given.append(field);
|
||||
this.check_reaches(init, kind, field);
|
||||
|
||||
this.resolve(field);
|
||||
val owner: u32 = this.decls.owners.p[field];
|
||||
val held := owner == decl
|
||||
? this.instantiated(this.decls.types.p[field], decl, kind)
|
||||
: this.decls.types.p[field];
|
||||
this.check_expr(value, held);
|
||||
this.check_owned(value, held);
|
||||
this.set_ref(init, field);
|
||||
}
|
||||
|
||||
# A field left out takes its default, or its zero value, which a reference
|
||||
# or a function does not have.
|
||||
val run: u32 = this.decls.children.p[decl];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val field := this.decls.list_at(run, i as u32);
|
||||
continue if this.decls.kinds.p[field] != dk::field;
|
||||
|
||||
var was_given := false;
|
||||
for &each in given {
|
||||
was_given = was_given || each == field;
|
||||
}
|
||||
continue if was_given || this.field_default(field) != 0;
|
||||
|
||||
this.resolve(field);
|
||||
val held := this.instantiated(this.decls.types.p[field], decl, kind);
|
||||
if !this.has_zero(held, 0) {
|
||||
var text := string::from("`", nothing {});
|
||||
text.append(this.decl_text(field));
|
||||
text.append("` has no zero value, so the literal gives it a value.");
|
||||
this.report_text(node, ec::zero_value, &text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! The default value a field is declared with, or 0.
|
||||
#! @param this The checker.
|
||||
#! @param field The field's declaration.
|
||||
#! @returns The default's node, or 0.
|
||||
pub def checker::field_default(&this, field: u32): u32 {
|
||||
return this.record_in(field, variable_slot::value);
|
||||
}
|
||||
|
||||
#! A union literal, which names the one field it holds, or none for its zero
|
||||
#! value.
|
||||
#! @param this The checker.
|
||||
#! @param node The `construct` node.
|
||||
#! @param kind The union's type.
|
||||
#! @param inits The run of `field_init` nodes.
|
||||
def checker::construct_union(&mut this, node: u32, kind: u32, inits: u32): void {
|
||||
# Naming none, it is the union's zero value.
|
||||
return if this.run_length(inits) == 0;
|
||||
if this.run_length(inits) != 1 {
|
||||
this.report(node, ec::arguments, "A union literal names the one field it holds, as `res{ error = 5 }`.");
|
||||
this.check_inits(inits);
|
||||
return;
|
||||
}
|
||||
|
||||
val decl := this.types.first_of(kind);
|
||||
val init := this.run_at(inits, 0);
|
||||
val field := this.init_field(decl, init, 0);
|
||||
if field == 0 || !this.node_has(init, nf::named) {
|
||||
this.report(init, ec::member, "A union literal names the field it holds, as `res{ error = 5 }`.");
|
||||
this.infer_expr(this.left_of(init));
|
||||
return;
|
||||
}
|
||||
|
||||
this.check_reaches(init, kind, field);
|
||||
this.resolve(field);
|
||||
this.check_expr(this.left_of(init), this.instantiated(this.decls.types.p[field], decl, kind));
|
||||
this.set_ref(init, field);
|
||||
}
|
||||
|
||||
#! Whether a type has a zero value, which a variable without a value starts at:
|
||||
#! numbers, `bool`, pointers, and enums with a member of value 0 do, and so do
|
||||
#! arrays, structs, and unions of what does, but references and functions do
|
||||
#! not, and a type parameter only where its bounds say so.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param depth How deeply the search has gone, which stops a type nesting
|
||||
#! without end.
|
||||
#! @returns Whether it has.
|
||||
pub def checker::has_zero(&mut this, kind: u32, depth: u32): bool {
|
||||
return true if depth > 8 || kind == bt::error;
|
||||
|
||||
val plain := this.unalias(kind);
|
||||
match this.types.kind_of(plain) {
|
||||
ty::reference, ty::function => return false;
|
||||
ty::param, ty::pack => return this.param_zeroable(plain);
|
||||
ty::fixed => return this.has_zero(this.types.first_of(plain), depth + 1);
|
||||
ty::named => {
|
||||
val decl := this.types.first_of(plain);
|
||||
match this.decls.kinds.p[decl] {
|
||||
dk::enum_type => {
|
||||
this.resolve(decl);
|
||||
val run: u32 = this.decls.children.p[decl];
|
||||
for &member in this.decls.list_view(run) {
|
||||
var value := constant {};
|
||||
if this.decl_value(member, &mut value) && value.magnitude == 0 {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
dk::struct_type => {
|
||||
val run: u32 = this.decls.children.p[decl];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val field := this.decls.list_at(run, i as u32);
|
||||
continue if this.decls.kinds.p[field] != dk::field || this.field_default(field) != 0;
|
||||
this.resolve(field);
|
||||
return false if !this.has_zero(this.instantiated(this.decls.types.p[field], decl, plain), depth + 1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
dk::union_type => {
|
||||
val fields := this.field_types(plain);
|
||||
return fields.length == 0 || this.has_zero(fields[0], depth + 1);
|
||||
}
|
||||
else => return true;
|
||||
}
|
||||
}
|
||||
else => return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Whether a type parameter's bounds give it a zero value: `zeroable` does, and
|
||||
#! so do `integer`, `real`, and `pointer`, since every number and pointer has one.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type parameter's type.
|
||||
#! @returns Whether they do.
|
||||
def checker::param_zeroable(&mut this, kind: u32): bool {
|
||||
val zeroable := this.std_decl(word::zeroable);
|
||||
val integer := this.std_decl(word::integer);
|
||||
val real := this.std_decl(word::real);
|
||||
val pointer := this.std_decl(word::pointer);
|
||||
return (zeroable != 0 && this.param_bounded(kind, zeroable)) || (integer != 0 && this.param_bounded(kind, integer))
|
||||
|| (real != 0 && this.param_bounded(kind, real)) || (pointer != 0 && this.param_bounded(kind, pointer));
|
||||
}
|
||||
|
||||
#! Says why a type has no zero value, for a report that it is not `zeroable`:
|
||||
#! the type itself, or the field within it that has none, followed through
|
||||
#! fields and the elements of arrays as `has_zero` follows them, as "its field
|
||||
#! `inner.r` holds `&i64`, which has no zero value".
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns Why, as a note's detail.
|
||||
pub def checker::zero_lacking(&mut this, kind: u32): string {
|
||||
var fields := string::new(nothing {});
|
||||
var at := this.unalias(kind);
|
||||
for _ in 0..8 {
|
||||
if this.types.kind_of(at) == ty::fixed {
|
||||
at = this.unalias(this.types.first_of(at));
|
||||
continue;
|
||||
}
|
||||
val is_union := this.named_kind(at) == dk::union_type;
|
||||
break if this.named_kind(at) != dk::struct_type && !is_union;
|
||||
|
||||
# A union is zeroed as its first field, and a struct as each without a
|
||||
# default.
|
||||
val decl := this.types.first_of(at);
|
||||
val run: u32 = this.decls.children.p[decl];
|
||||
var lacking: u32 = 0;
|
||||
var held: u32 = 0;
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val field := this.decls.list_at(run, i as u32);
|
||||
continue if this.decls.kinds.p[field] != dk::field;
|
||||
this.resolve(field);
|
||||
val inner := this.instantiated(this.decls.types.p[field], decl, at);
|
||||
if (is_union || this.field_default(field) == 0) && !this.has_zero(inner, 0) {
|
||||
lacking = field;
|
||||
held = inner;
|
||||
}
|
||||
break if lacking != 0 || is_union;
|
||||
}
|
||||
break if lacking == 0;
|
||||
|
||||
if fields.length > 0 {
|
||||
fields.append(".");
|
||||
}
|
||||
fields.append(this.decl_text(lacking));
|
||||
at = this.unalias(held);
|
||||
}
|
||||
|
||||
val described := this.describe(at);
|
||||
val is_enum := this.named_kind(at) == dk::enum_type;
|
||||
val is_param := this.types.kind_of(at) == ty::param;
|
||||
var text := string::new(nothing {});
|
||||
if fields.length > 0 {
|
||||
text.append("its field `");
|
||||
text.append(fields.view());
|
||||
text.append("` holds `");
|
||||
text.append(described.view());
|
||||
text.append(is_enum ? "`, no member of which has the value 0"
|
||||
: is_param ? "`, which has a zero value only where its bounds say it is `zeroable`"
|
||||
: "`, which has no zero value");
|
||||
return text;
|
||||
}
|
||||
if is_enum {
|
||||
text.append("no member of `");
|
||||
text.append(described.view());
|
||||
text.append("` has the value 0");
|
||||
return text;
|
||||
}
|
||||
if is_param {
|
||||
text.append("a type parameter has a zero value only where its bounds say it is `zeroable`");
|
||||
return text;
|
||||
}
|
||||
if this.types.kind_of(at) == ty::reference || this.types.kind_of(at) == ty::function {
|
||||
text.append(this.types.kind_of(at) == ty::reference ? "a reference has no zero value" : "a function has no zero value");
|
||||
return text;
|
||||
}
|
||||
text.append("`");
|
||||
text.append(described.view());
|
||||
text.append("` has no zero value");
|
||||
return text;
|
||||
}
|
||||
|
||||
#! An array literal: a fixed array of the type its elements share, or of the
|
||||
#! type expected, or where a `span<T>` is expected, a view of itself.
|
||||
#! @param this The checker.
|
||||
#! @param node The `array` node.
|
||||
#! @param expected The type expected, or the error type where none is.
|
||||
#! @returns The array's type, or the error type where its elements share none.
|
||||
def checker::array(&mut this, node: u32, expected: u32): u32 {
|
||||
val run := this.left_of(node);
|
||||
val count := this.run_length(run);
|
||||
val wanted := this.unalias(expected);
|
||||
if this.types.kind_of(wanted) == ty::fixed {
|
||||
val element := this.types.first_of(wanted);
|
||||
for i in 0..count {
|
||||
this.check_expr(this.run_at(run, i as u32), element);
|
||||
}
|
||||
# Within a template, a length only each instance knows is theirs to check.
|
||||
if count != this.types.second_of(wanted) && this.types.part_count(wanted) == 0 {
|
||||
val words := $"The array holds {this.types.second_of(wanted)} elements, but {count} are written.";
|
||||
var text := string::from(words.view(), nothing {});
|
||||
this.report_text(node, ec::mismatch, &text);
|
||||
}
|
||||
return expected;
|
||||
}
|
||||
|
||||
if this.is_std(wanted, word::span) {
|
||||
val element := this.types.part_at(wanted, 0);
|
||||
for i in 0..count {
|
||||
this.check_expr(this.run_at(run, i as u32), element);
|
||||
}
|
||||
return expected;
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
this.report(node, ec::mismatch, "An empty array takes its type from where it is written, and nothing gives it here.");
|
||||
return bt::error;
|
||||
}
|
||||
|
||||
var shared: u32 = 0;
|
||||
for i in 0..count {
|
||||
val kind := this.infer_expr(this.run_at(run, i as u32));
|
||||
if kind == bt::error {
|
||||
shared = bt::error;
|
||||
continue;
|
||||
}
|
||||
if shared == 0 {
|
||||
shared = kind;
|
||||
continue;
|
||||
}
|
||||
if shared != bt::error {
|
||||
val joined := this.common(shared, kind);
|
||||
if joined == bt::error {
|
||||
this.report_operands(this.run_at(run, i as u32), shared, kind, "are elements of one array, which share no type");
|
||||
}
|
||||
shared = joined;
|
||||
}
|
||||
}
|
||||
return bt::error if shared == bt::error;
|
||||
|
||||
val element := this.settle(shared);
|
||||
for i in 0..count {
|
||||
this.convert(this.run_at(run, i as u32), element);
|
||||
}
|
||||
return this.types.fixed(element, count);
|
||||
}
|
||||
|
||||
#! An anonymous function, whose parameter types and result may be left out
|
||||
#! where the function type expected gives them. It shares the locals of the
|
||||
#! function around it, so it is checked within that function's bindings.
|
||||
#! @param this The checker.
|
||||
#! @param node The `lambda` node.
|
||||
#! @param expected The function type expected, or the error type where none
|
||||
#! is.
|
||||
#! @returns The function type.
|
||||
def checker::lambda(&mut this, node: u32, expected: u32): u32 {
|
||||
# C calls back what it is given with nothing more, so it can't reach what a
|
||||
# lambda refers to.
|
||||
val c_wanted := this.unalias(expected);
|
||||
if this.is_std(c_wanted, word::cfn) && this.types.part_count(c_wanted) == 1 {
|
||||
this.report(node, ec::invalid, "C calls back a function of the program named where its address is expected, not a lambda, whose locals C gives it no way to reach.");
|
||||
this.lambda(node, this.types.part_at(c_wanted, 0));
|
||||
return bt::error;
|
||||
}
|
||||
|
||||
val params := this.left_of(node);
|
||||
val result := this.record(node, lambda_slot::result);
|
||||
val body := this.record(node, lambda_slot::body);
|
||||
val wanted := this.unalias(expected);
|
||||
val gives := this.types.kind_of(wanted) == ty::function;
|
||||
|
||||
var kinds := vector::<u32>::new();
|
||||
for i in 0..this.run_length(params) {
|
||||
val param := this.run_at(params, i as u32);
|
||||
val written := this.left_of(param);
|
||||
if written != 0 {
|
||||
kinds.append(this.resolve_type(written));
|
||||
} else if gives && i < this.types.part_count(wanted) {
|
||||
kinds.append(this.types.part_at(wanted, i as u32));
|
||||
} else {
|
||||
this.report(param, ec::mismatch, gives
|
||||
? "The function type expected here has fewer parameters, so give this one a type."
|
||||
: "No function type is expected here, so give the parameter a type.");
|
||||
kinds.append(bt::error);
|
||||
}
|
||||
}
|
||||
|
||||
# A lambda whose result infers a type argument takes it from its body.
|
||||
val free := this.free_result;
|
||||
this.free_result = false;
|
||||
var returns: u32 = 0;
|
||||
if result != 0 {
|
||||
returns = this.resolve_type(result);
|
||||
} else if gives && !free {
|
||||
returns = this.types.first_of(wanted);
|
||||
}
|
||||
|
||||
val saved := this.at;
|
||||
this.at.result = returns != 0 ? returns : bt::void_type;
|
||||
this.at.loops = 0;
|
||||
this.at.body = body;
|
||||
val mark := this.scope_mark();
|
||||
for i in 0..this.run_length(params) {
|
||||
val param := this.run_at(params, i as u32);
|
||||
this.set_type(param, kinds[i]);
|
||||
this.set_flag(param, rf::local);
|
||||
this.set_flag(param, rf::mutable);
|
||||
this.bind(this.name_of(param), ref_local | param);
|
||||
}
|
||||
|
||||
if this.kind_of(body) == nk::block {
|
||||
val leaves := this.check_block(body) != flow::goes_on;
|
||||
if returns == 0 {
|
||||
returns = bt::void_type;
|
||||
} else if returns != bt::void_type && !leaves {
|
||||
this.report(node, ec::control, "The function can end without returning a value.");
|
||||
}
|
||||
} else if returns == 0 {
|
||||
# What the body gives is taken as a binding takes it: what a reference
|
||||
# reaches, unless `&` is written.
|
||||
returns = this.settle_expr(body);
|
||||
if this.takes_value(body, returns) {
|
||||
returns = this.types.first_of(this.unalias(returns));
|
||||
this.convert(body, returns);
|
||||
this.check_owned(body, returns);
|
||||
}
|
||||
} else if returns == bt::void_type {
|
||||
this.settle_expr(body);
|
||||
} else {
|
||||
this.check_expr(body, returns);
|
||||
}
|
||||
|
||||
this.unbind_to(mark);
|
||||
this.at.result = saved.result;
|
||||
this.at.loops = saved.loops;
|
||||
this.at.body = saved.body;
|
||||
# One whose parameter has no type was reported, and is nothing a call can take.
|
||||
for &kind in kinds.view() {
|
||||
return bt::error if kind == bt::error;
|
||||
}
|
||||
return this.types.function(kinds.view(), returns, false);
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
#! @file constants.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the constants the checker works out while checking: the values of
|
||||
#! literals, and of operators applied to constants, which the length of a
|
||||
#! fixed array, the value of an enum member, and whether a constant fits its
|
||||
#! type need. An integer is kept as its magnitude and sign, so every value of
|
||||
#! both `i64` and `u64` is one.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! A constant integer of the magnitude and sign, where zero is never negative.
|
||||
#! @param magnitude Its magnitude.
|
||||
#! @param negative Whether it is below zero.
|
||||
#! @returns The constant.
|
||||
pub def constant::integer(magnitude: u64, negative: bool): constant {
|
||||
return constant { word = magnitude, negative = negative && magnitude != 0 };
|
||||
}
|
||||
|
||||
#! A constant float.
|
||||
#! @param real Its value.
|
||||
#! @returns The constant.
|
||||
pub def constant::real_of(real: f64): constant {
|
||||
var held := real;
|
||||
return constant { word = ((&mut held) as *mut u64)[0], floating = true };
|
||||
}
|
||||
|
||||
#! A constant `bool`, as a magnitude of 0 or 1.
|
||||
#! @param value Its value.
|
||||
#! @returns The constant.
|
||||
pub def constant::truth(value: bool): constant {
|
||||
return constant { word = value ? 1 : 0 };
|
||||
}
|
||||
|
||||
#! An integer's magnitude, or a `bool` as 0 or 1, or 0 for a float.
|
||||
#! @param this The constant.
|
||||
#! @returns The magnitude.
|
||||
pub val constant::magnitude: u64 { get => this.floating ? 0 : this.word; }
|
||||
|
||||
#! A float's value, or 0 for an integer.
|
||||
#! @param this The constant.
|
||||
#! @returns The value.
|
||||
pub val constant::real: f64 {
|
||||
get {
|
||||
return 0.0 if !this.floating;
|
||||
var held := this.word;
|
||||
return ((&mut held) as *mut f64)[0];
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether two constants are the same value, a float's bits and all, as
|
||||
#! interning them asks.
|
||||
#! @param this The one constant.
|
||||
#! @param other The other.
|
||||
#! @returns Whether they are.
|
||||
pub def constant::same(&this, other: &constant): bool {
|
||||
return this.word == other.word && this.negative == other.negative && this.floating == other.floating;
|
||||
}
|
||||
|
||||
#! The constant as a float.
|
||||
#! @param this The constant.
|
||||
#! @returns The float, which an integer converts to.
|
||||
pub def constant::as_real(&this): f64 {
|
||||
return this.real if this.floating;
|
||||
val magnitude := this.magnitude as f64;
|
||||
return this.negative ? -magnitude : magnitude;
|
||||
}
|
||||
|
||||
#! The constant's 64 bits, as two's complement where it is negative.
|
||||
#! @param this The constant.
|
||||
#! @returns The bits.
|
||||
pub def constant::bits(&this): u64 {
|
||||
return this.negative ? ~this.magnitude + 1 : this.magnitude;
|
||||
}
|
||||
|
||||
#! The constant of the 64 bits, read as signed where `signed` says.
|
||||
#! @param bits The bits.
|
||||
#! @param signed Whether they are two's complement.
|
||||
#! @returns The constant.
|
||||
pub def constant::from_bits(bits: u64, signed: bool): constant {
|
||||
if signed && (bits >> 63) != 0 {
|
||||
return constant::integer(~bits + 1, true);
|
||||
}
|
||||
return constant::integer(bits, false);
|
||||
}
|
||||
|
||||
#! The integer an integer literal writes, in decimal or with `0x`, `0o`, or
|
||||
#! `0b`, without its `u`, or false where it is past 64 bits.
|
||||
#! @param this The checker.
|
||||
#! @param text The literal as written.
|
||||
#! @param out Where the integer is written.
|
||||
#! @returns Whether it fits in 64 bits.
|
||||
pub def checker::read_integer(&this, text: strview, out: &mut constant): bool {
|
||||
var at := 0u;
|
||||
var base := 10u;
|
||||
var limit := text.length;
|
||||
if limit > 0 && text[limit - 1] == 'u' {
|
||||
limit--;
|
||||
}
|
||||
if limit > 2 && text[0] == '0' {
|
||||
val prefix := text[1];
|
||||
if prefix == 'x' { base = 16; at = 2; }
|
||||
if prefix == 'o' { base = 8; at = 2; }
|
||||
if prefix == 'b' { base = 2; at = 2; }
|
||||
}
|
||||
|
||||
var magnitude := 0u;
|
||||
while at < limit {
|
||||
val c := text[at];
|
||||
var digit := 0u;
|
||||
if c >= '0' && c <= '9' {
|
||||
digit = (c - '0') as u64;
|
||||
} else if c >= 'a' && c <= 'f' {
|
||||
digit = (c - 'a') as u64 + 10;
|
||||
} else if c >= 'A' && c <= 'F' {
|
||||
digit = (c - 'A') as u64 + 10;
|
||||
} else {
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if magnitude > (0xFFFFFFFFFFFFFFFFu - digit) / base {
|
||||
return false;
|
||||
}
|
||||
magnitude = magnitude * base + digit;
|
||||
at++;
|
||||
}
|
||||
|
||||
out.word = magnitude;
|
||||
out.negative = false;
|
||||
out.floating = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
#! The float a float literal writes, without its `f`.
|
||||
#! @param this The checker.
|
||||
#! @param text The literal as written.
|
||||
#! @returns The float.
|
||||
pub def checker::read_real(&this, text: strview): f64 {
|
||||
var limit := text.length;
|
||||
if limit > 0 && text[limit - 1] == 'f' {
|
||||
limit--;
|
||||
}
|
||||
|
||||
return match real::parse::<f64>(text.substr(0, limit)) {
|
||||
value(read) => read,
|
||||
else => 0.0
|
||||
};
|
||||
}
|
||||
|
||||
#! The code point a character literal writes, from its escape where it is one.
|
||||
#! @param this The checker.
|
||||
#! @param text The literal as written, with its quotes.
|
||||
#! @returns The code point.
|
||||
pub def checker::read_character(&this, text: strview): u64 {
|
||||
return 0 if text.length < 3;
|
||||
|
||||
val inner := text.substr(1, text.length - 2);
|
||||
if inner[0] == '\\' && inner.length >= 2 {
|
||||
return match inner[1] {
|
||||
'n' => 10,
|
||||
't' => 9,
|
||||
'r' => 13,
|
||||
'0' => 0,
|
||||
'x' => this.read_hex(inner.substr(2, 2)),
|
||||
else => inner[1] as u64
|
||||
};
|
||||
}
|
||||
|
||||
# UTF-8: the lead byte's bits, then six of each byte continuing it.
|
||||
val lead := inner[0];
|
||||
return lead as u64 if lead < 0x80;
|
||||
|
||||
val count: u64 = lead >= 0xF0 ? 3 : lead >= 0xE0 ? 2 : 1;
|
||||
var code: u64 = (lead & (0x3F >> count as u8)) as u64;
|
||||
for i in 1..(count + 1) {
|
||||
break if i >= inner.length;
|
||||
code = (code << 6) | (inner[i] & 0x3F) as u64;
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
def checker::read_hex(&this, text: strview): u64 {
|
||||
var value := 0u;
|
||||
for &c in text {
|
||||
var digit := 0u;
|
||||
if c >= '0' && c <= '9' { digit = (c - '0') as u64; }
|
||||
else if c >= 'a' && c <= 'f' { digit = (c - 'a') as u64 + 10; }
|
||||
else if c >= 'A' && c <= 'F' { digit = (c - 'A') as u64 + 10; }
|
||||
value = value * 16 + digit;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
#! Whether the constant is within the range of the type, as a signed or
|
||||
#! unsigned integer of its bits, a float, or a constant of no type.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param value The constant.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::in_range(&this, kind: u32, value: &constant): bool {
|
||||
val bits := this.types.first_of(kind);
|
||||
match this.types.kind_of(kind) {
|
||||
ty::signed => {
|
||||
return true if value.floating;
|
||||
val top: u64 = 1u << (bits - 1) as u64;
|
||||
return value.negative ? value.magnitude <= top : value.magnitude < top;
|
||||
}
|
||||
ty::unsigned => {
|
||||
return true if value.floating;
|
||||
return false if value.negative;
|
||||
return bits == 64 || value.magnitude < (1u << bits as u64);
|
||||
}
|
||||
ty::untyped_uint => return !value.negative;
|
||||
else => return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! The constant an operator gives of two constants, where it gives one: false
|
||||
#! where it overflows 64 bits, divides by zero, or is no operator on constants.
|
||||
#! @param this The checker.
|
||||
#! @param operator The operator.
|
||||
#! @param a The left constant.
|
||||
#! @param b The right constant.
|
||||
#! @param signed Whether they are signed, which division, remainder,
|
||||
#! comparisons, and shifts care about.
|
||||
#! @param out Where the constant given is written.
|
||||
#! @returns Whether it gives one.
|
||||
pub def checker::fold_binary(&this, operator: tk, a: &constant, b: &constant, signed: bool, out: &mut constant): bool {
|
||||
if a.floating || b.floating {
|
||||
val x := a.as_real();
|
||||
val y := b.as_real();
|
||||
match operator {
|
||||
tk::plus => { out = constant::real_of(x + y); return true; }
|
||||
tk::minus => { out = constant::real_of(x - y); return true; }
|
||||
tk::star => { out = constant::real_of(x * y); return true; }
|
||||
tk::slash => { out = constant::real_of(x / y); return true; }
|
||||
tk::modulo => { out = constant::real_of(x % y); return true; }
|
||||
tk::equals => { out = constant::truth(x == y); return true; }
|
||||
tk::noteq => { out = constant::truth(x != y); return true; }
|
||||
tk::less => { out = constant::truth(x < y); return true; }
|
||||
tk::lesseq => { out = constant::truth(x <= y); return true; }
|
||||
tk::more => { out = constant::truth(x > y); return true; }
|
||||
tk::moreeq => { out = constant::truth(x >= y); return true; }
|
||||
else => return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
match operator {
|
||||
tk::plus => return this.fold_add(a, b.magnitude, b.negative, out);
|
||||
tk::minus => return this.fold_add(a, b.magnitude, !b.negative, out);
|
||||
tk::star => {
|
||||
if a.magnitude != 0 && b.magnitude > 0xFFFFFFFFFFFFFFFFu / a.magnitude {
|
||||
return false;
|
||||
}
|
||||
out = constant::integer(a.magnitude * b.magnitude, a.negative != b.negative);
|
||||
return true;
|
||||
}
|
||||
tk::slash => {
|
||||
return false if b.magnitude == 0;
|
||||
out = constant::integer(a.magnitude / b.magnitude, a.negative != b.negative);
|
||||
return true;
|
||||
}
|
||||
tk::modulo => {
|
||||
return false if b.magnitude == 0;
|
||||
out = constant::integer(a.magnitude % b.magnitude, a.negative);
|
||||
return true;
|
||||
}
|
||||
tk::bitand => { out = constant::from_bits(a.bits() & b.bits(), a.negative || b.negative); return true; }
|
||||
tk::bitor => { out = constant::from_bits(a.bits() | b.bits(), a.negative || b.negative); return true; }
|
||||
tk::bitxor => { out = constant::from_bits(a.bits() ^ b.bits(), a.negative != b.negative); return true; }
|
||||
tk::lshift => {
|
||||
return false if b.negative || b.magnitude >= 64;
|
||||
val shifted := a.magnitude << b.magnitude;
|
||||
return false if (shifted >> b.magnitude) != a.magnitude;
|
||||
out = constant::integer(shifted, a.negative);
|
||||
return true;
|
||||
}
|
||||
tk::rshift => {
|
||||
return false if b.negative;
|
||||
if b.magnitude >= 64 {
|
||||
out = constant::integer(a.negative ? 1 : 0, a.negative);
|
||||
return true;
|
||||
}
|
||||
out = a.negative
|
||||
? constant::from_bits(((a.bits() as i64) >> b.magnitude as i64) as u64, true)
|
||||
: constant::integer(a.magnitude >> b.magnitude, false);
|
||||
return true;
|
||||
}
|
||||
tk::equals => { out = constant::truth(this.compare_constants(a, b) == 0); return true; }
|
||||
tk::noteq => { out = constant::truth(this.compare_constants(a, b) != 0); return true; }
|
||||
tk::less => { out = constant::truth(this.compare_constants(a, b) < 0); return true; }
|
||||
tk::lesseq => { out = constant::truth(this.compare_constants(a, b) <= 0); return true; }
|
||||
tk::more => { out = constant::truth(this.compare_constants(a, b) > 0); return true; }
|
||||
tk::moreeq => { out = constant::truth(this.compare_constants(a, b) >= 0); return true; }
|
||||
tk::logand => { out = constant::truth(a.magnitude != 0 && b.magnitude != 0); return true; }
|
||||
tk::logor => { out = constant::truth(a.magnitude != 0 || b.magnitude != 0); return true; }
|
||||
else => return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
def checker::fold_add(&this, a: &constant, magnitude: u64, negative: bool, out: &mut constant): bool {
|
||||
if a.negative == negative {
|
||||
return false if a.magnitude > 0xFFFFFFFFFFFFFFFFu - magnitude;
|
||||
out = constant::integer(a.magnitude + magnitude, negative);
|
||||
return true;
|
||||
}
|
||||
|
||||
out = a.magnitude >= magnitude
|
||||
? constant::integer(a.magnitude - magnitude, a.negative)
|
||||
: constant::integer(magnitude - a.magnitude, negative);
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Below zero where `a` is less than `b`, zero where they are equal, and above
|
||||
#! zero where `a` is more.
|
||||
#! @param this The checker.
|
||||
#! @param a One constant.
|
||||
#! @param b The other.
|
||||
#! @returns Their order.
|
||||
pub def checker::compare_constants(&this, a: &constant, b: &constant): i32 {
|
||||
if a.floating || b.floating {
|
||||
val x := a.as_real();
|
||||
val y := b.as_real();
|
||||
return x < y ? -1 : x > y ? 1 : 0;
|
||||
}
|
||||
|
||||
return -1 if a.negative && !b.negative;
|
||||
return 1 if !a.negative && b.negative;
|
||||
if a.magnitude == b.magnitude {
|
||||
return 0;
|
||||
}
|
||||
val less := a.magnitude < b.magnitude;
|
||||
return (less != a.negative) ? -1 : 1;
|
||||
}
|
||||
@@ -0,0 +1,829 @@
|
||||
#! @file convert.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains when a value of one type is taken where another is expected, and
|
||||
#! how well it fits there, which overloads are chosen by: a type exactly, then
|
||||
#! a constant taking the type expected, then any other conversion, then
|
||||
#! becoming a union. Also contains the type two values share, as both sides of
|
||||
#! an operator or both branches of a ternary must.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! How a value fits where a type is expected, best first.
|
||||
pub enum fit : u8 {
|
||||
exact, #! It is the type.
|
||||
read, #! It is a reference, read through to what it refers to, which is the type.
|
||||
constant, #! It is a constant, which takes the type.
|
||||
convert, #! It converts: widening, an alias, a view lent, or reading through a reference.
|
||||
unite, #! It becomes a union holding it.
|
||||
none, #! It does not fit.
|
||||
overflow, #! It is a constant outside the range of the type.
|
||||
}
|
||||
|
||||
#! The declaration of `core`'s root of the name, which the language relies on,
|
||||
#! or 0 where it declares none.
|
||||
#! @param this The checker.
|
||||
#! @param word The ID of the name.
|
||||
#! @returns The declaration, or 0.
|
||||
pub def checker::std_decl(&mut this, word: u32): u32 {
|
||||
if this.known.get(&word) is some(got) {
|
||||
return got;
|
||||
}
|
||||
|
||||
val core := this.modules.find(0, word::core);
|
||||
val found := core == 0 ? 0 : this.modules.decl(core, word);
|
||||
this.known.set(word, found);
|
||||
return found;
|
||||
}
|
||||
|
||||
#! The type of `core`'s root of the name given the arguments, or the error type
|
||||
#! where it declares none.
|
||||
#! @param this The checker.
|
||||
#! @param word The ID of the name.
|
||||
#! @param args The type arguments, or none.
|
||||
#! @returns The type, or the error type.
|
||||
pub def checker::std_type(&mut this, word: u32, args: span<u32>): u32 {
|
||||
val decl := this.std_decl(word);
|
||||
return bt::error if decl == 0;
|
||||
|
||||
this.resolve(decl);
|
||||
return this.types.named(decl, args) if args.length != 0;
|
||||
return this.decls.types.p[decl];
|
||||
}
|
||||
|
||||
#! A `span<T>` of the element.
|
||||
#! @param this The checker.
|
||||
#! @param element The element's type.
|
||||
#! @returns The span's type, or the error type where `core` declares no `span`.
|
||||
pub def checker::span_of(&mut this, element: u32): u32 {
|
||||
var args := vector::<u32>::new();
|
||||
args.append(element);
|
||||
return this.std_type(word::span, args.view());
|
||||
}
|
||||
|
||||
#! The declaration a type is of: a named type's, a built-in type's, or a type
|
||||
#! parameter's, or 0.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns The declaration, or 0.
|
||||
pub def checker::type_decl(&this, kind: u32): u32 {
|
||||
return match this.types.kind_of(kind) {
|
||||
ty::named, ty::param => this.types.first_of(kind),
|
||||
else => kind < bt::count as u32 ? this.builtin_of[kind] : 0
|
||||
};
|
||||
}
|
||||
|
||||
#! Whether the type is the named type of `core`'s root of the name, of any
|
||||
#! arguments.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param word The ID of the name.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::is_std(&mut this, kind: u32, word: u32): bool {
|
||||
return this.types.kind_of(kind) == ty::named && this.types.first_of(kind) == this.std_decl(word)
|
||||
&& this.std_decl(word) != 0;
|
||||
}
|
||||
|
||||
#! Whether a type is `core`'s vector or mask, `simd<L[N]>` or `mask<L[N]>`, which an
|
||||
#! executable holds in vector registers.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::is_lanes_type(&mut this, kind: u32): bool {
|
||||
val plain := this.unalias(kind);
|
||||
return this.is_std(plain, word::simd) || this.is_std(plain, word::mask);
|
||||
}
|
||||
|
||||
#! The type an alias stands for, given its arguments.
|
||||
#! @param this The checker.
|
||||
#! @param kind The alias's type.
|
||||
#! @returns The type it stands for.
|
||||
pub def checker::alias_target(&mut this, kind: u32): u32 {
|
||||
val decl := this.types.first_of(kind);
|
||||
this.resolve(decl);
|
||||
return this.instantiated(this.decls.targets.p[decl], decl, kind);
|
||||
}
|
||||
|
||||
#! The type with the type parameters of the declaration replaced by the type
|
||||
#! arguments of `kind`, a named type of it.
|
||||
#! @param this The checker.
|
||||
#! @param inner The type written within the declaration, as a field's.
|
||||
#! @param decl The generic declaration.
|
||||
#! @param kind The named type of it, whose arguments replace its parameters.
|
||||
#! @returns The type with them replaced.
|
||||
pub def checker::instantiated(&mut this, inner: u32, decl: u32, kind: u32): u32 {
|
||||
val params: u32 = this.decls.params.p[decl];
|
||||
return inner if params == 0 || !this.types.is_open(inner);
|
||||
|
||||
val from := this.decls.list_of(params);
|
||||
val args := this.types.parts_of(kind);
|
||||
return this.substitute(inner, from.view(), args.view());
|
||||
}
|
||||
|
||||
#! Whether the type is an alias.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::is_alias(&this, kind: u32): bool {
|
||||
return this.types.kind_of(kind) == ty::named
|
||||
&& this.decls.kinds.p[this.types.first_of(kind)] == dk::alias_type;
|
||||
}
|
||||
|
||||
#! The type with every alias it is followed to what it stands for.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns The type at the end of its aliases, or the type itself where it is
|
||||
#! none.
|
||||
pub def checker::unalias(&mut this, kind: u32): u32 {
|
||||
# Nearly every type given is no alias, which its flags say once asked, so
|
||||
# that is told first, and the rest are followed apart.
|
||||
return kind if (this.types.flags.p[kind] & (tf::asked as u8 | tf::alias as u8)) == tf::asked as u8;
|
||||
return this.follow_aliases(kind);
|
||||
}
|
||||
|
||||
# The type at the end of the aliases a type is followed through, as `unalias`
|
||||
# gives it, for a type not yet asked of or that is an alias.
|
||||
def checker::follow_aliases(&mut this, kind: u32): u32 {
|
||||
var at := kind;
|
||||
var steps := 0;
|
||||
while this.aliases(at) && steps < 32 {
|
||||
at = this.alias_target(at);
|
||||
steps++;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
#! Whether the type is an alias, as `is_alias` says, worked out once and kept in
|
||||
#! its flags, as nearly every type `unalias` is given is none.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns Whether it is.
|
||||
def checker::aliases(&mut this, kind: u32): bool {
|
||||
val flags := this.types.flags.p[kind];
|
||||
return (flags & tf::alias as u8) != 0 if (flags & tf::asked as u8) != 0;
|
||||
val alias := this.is_alias(kind);
|
||||
this.types.flags.p[kind] = flags | tf::asked as u8 | (alias ? tf::alias as u8 : 0);
|
||||
return alias;
|
||||
}
|
||||
|
||||
#! The kind of declaration a named type is of, or `none`.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns The kind of its declaration, or `none` where it is not named.
|
||||
pub def checker::named_kind(&this, kind: u32): dk {
|
||||
return this.types.kind_of(kind) == ty::named
|
||||
? this.decls.kinds.p[this.types.first_of(kind)]
|
||||
: dk::none;
|
||||
}
|
||||
|
||||
#! The integer type an enum is held as.
|
||||
#! @param this The checker.
|
||||
#! @param kind The enum's type.
|
||||
#! @returns The integer type.
|
||||
pub def checker::enum_integer(&mut this, kind: u32): u32 {
|
||||
# An enum's members may name earlier ones while it resolves, and its integer
|
||||
# type is known before them.
|
||||
val decl := this.types.first_of(kind);
|
||||
if this.decls.states.p[decl] != ds::resolving {
|
||||
this.resolve(decl);
|
||||
}
|
||||
val integer: u32 = this.decls.targets.p[decl];
|
||||
return integer == 0 ? bt::int32 : integer;
|
||||
}
|
||||
|
||||
#! What the values of an enum's members are flipped by to be ordered as words
|
||||
#! without a sign: the sign bit where the enum is held signed, and nothing
|
||||
#! otherwise.
|
||||
#! @param this The checker.
|
||||
#! @param kind The enum's type.
|
||||
#! @returns The bits to flip.
|
||||
pub def checker::member_flip(&mut this, kind: u32): u64 {
|
||||
return this.types.is_signed(this.unalias(this.enum_integer(this.unalias(kind)))) ? 0x8000000000000000u : 0;
|
||||
}
|
||||
|
||||
#! The values of an enum's members, each once, from the least, as a range of
|
||||
#! its members counts through them: each a word flipped by `member_flip`, so
|
||||
#! the words order as the values do when compared without a sign.
|
||||
#! @param this The checker.
|
||||
#! @param kind The enum's type.
|
||||
#! @returns The words.
|
||||
pub def checker::member_order(&mut this, kind: u32): vector<u64> {
|
||||
val plain := this.unalias(kind);
|
||||
val flip := this.member_flip(plain);
|
||||
val run: u32 = this.decls.children.p[this.types.first_of(plain)];
|
||||
var values := vector::<u64>::new();
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val member := this.decls.list_at(run, i as u32);
|
||||
var held := constant {};
|
||||
continue if this.decls.kinds.p[member] != dk::enum_member || !this.decl_value(member, &mut held);
|
||||
values.append(held.bits() ^ flip);
|
||||
}
|
||||
values.sort();
|
||||
|
||||
# A member given an earlier one's value is another name for it.
|
||||
var made := vector::<u64>::new();
|
||||
for each in values {
|
||||
if made.length == 0 || made[made.length - 1] != each {
|
||||
made.append(each);
|
||||
}
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The types of the fields of a struct or union type, given its arguments.
|
||||
#! @param this The checker.
|
||||
#! @param kind The struct or union type.
|
||||
#! @returns The type of each field, in order.
|
||||
pub def checker::field_types(&mut this, kind: u32): vector<u32> {
|
||||
var made := vector::<u32>::new();
|
||||
val decl := this.types.first_of(kind);
|
||||
val run: u32 = this.decls.children.p[decl];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val field := this.decls.list_at(run, i as u32);
|
||||
continue if this.decls.kinds.p[field] != dk::field;
|
||||
this.resolve(field);
|
||||
made.append(this.instantiated(this.decls.types.p[field], decl, kind));
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! How the value of the node fits where the type is expected.
|
||||
#! @param this The checker.
|
||||
#! @param node The value's node.
|
||||
#! @param to The type expected.
|
||||
#! @returns How it fits.
|
||||
pub def checker::fits_node(&mut this, node: u32, to: u32): fit {
|
||||
val value := this.value_at(node);
|
||||
return this.fits(this.type_at(node), to, &value, this.is_known(node), 0);
|
||||
}
|
||||
|
||||
#! How a value of the type fits where `to` is expected, where `value` is its
|
||||
#! value when `known`.
|
||||
#! @param this The checker.
|
||||
#! @param from The value's type.
|
||||
#! @param to The type expected.
|
||||
#! @param value The value, where it is known while compiling.
|
||||
#! @param known Whether it is.
|
||||
#! @param depth How deeply the search has gone, which stops a type nesting
|
||||
#! without end.
|
||||
#! @returns How it fits.
|
||||
pub def checker::fits(&mut this, from: u32, to: u32, value: &constant, known: bool, depth: u32): fit {
|
||||
return fit::exact if from == to || from == bt::error || to == bt::error;
|
||||
return fit::none if depth > 8;
|
||||
|
||||
val target := this.unalias(to);
|
||||
val source := this.unalias(from);
|
||||
val goal := this.types.kind_of(target);
|
||||
match this.types.kind_of(source) {
|
||||
ty::untyped_int, ty::untyped_char => {
|
||||
if goal == ty::signed || goal == ty::unsigned {
|
||||
return known && !this.in_range(target, value) ? fit::overflow : fit::constant;
|
||||
}
|
||||
if goal == ty::untyped_uint {
|
||||
return known && value.negative ? fit::overflow : fit::constant;
|
||||
}
|
||||
return fit::constant if goal == ty::floating || goal == ty::untyped_int
|
||||
|| goal == ty::untyped_float || this.numeric_param(target);
|
||||
return this.unites(source, target, value, known, depth);
|
||||
}
|
||||
ty::untyped_uint => {
|
||||
if goal == ty::unsigned {
|
||||
return known && !this.in_range(target, value) ? fit::overflow : fit::constant;
|
||||
}
|
||||
return fit::constant if this.numeric_param(target);
|
||||
return this.unites(source, target, value, known, depth);
|
||||
}
|
||||
ty::untyped_float, ty::untyped_float32 => {
|
||||
return fit::constant if goal == ty::floating || this.numeric_param(target);
|
||||
return this.unites(source, target, value, known, depth);
|
||||
}
|
||||
ty::untyped_bool => return goal == ty::boolean ? fit::constant : this.unites(source, target, value, known, depth);
|
||||
ty::untyped_text => {
|
||||
return fit::constant if this.is_std(target, word::string) || this.is_text_view(target);
|
||||
return this.unites(source, target, value, known, depth);
|
||||
}
|
||||
ty::null_type => {
|
||||
return fit::constant if goal == ty::pointer || this.is_std(target, word::cfn);
|
||||
return this.unites(source, target, value, known, depth);
|
||||
}
|
||||
ty::empty => return fit::constant;
|
||||
else => {}
|
||||
}
|
||||
|
||||
# What only differs by aliases converts, anywhere within the types.
|
||||
return fit::convert if source == target || this.strip(source, 0) == this.strip(target, 0);
|
||||
|
||||
val skind := this.types.kind_of(source);
|
||||
if this.types.is_numeric(source) && this.types.is_numeric(target) {
|
||||
val sbits := this.types.first_of(source);
|
||||
val tbits := this.types.first_of(target);
|
||||
return fit::convert if skind == goal && tbits > sbits;
|
||||
return fit::convert if skind == ty::unsigned && goal == ty::signed && tbits > sbits;
|
||||
return fit::none;
|
||||
}
|
||||
|
||||
# An enum is its integer type wherever one is expected.
|
||||
if this.named_kind(source) == dk::enum_type && this.types.is_integer(target) {
|
||||
val integer := this.enum_integer(source);
|
||||
return integer == target || this.fits(integer, target, value, false, depth + 1) == fit::convert
|
||||
? fit::convert
|
||||
: fit::none;
|
||||
}
|
||||
|
||||
if (skind == ty::reference || skind == ty::pointer) && skind == goal {
|
||||
val inner_from := this.types.first_of(source);
|
||||
val inner_to := this.types.first_of(target);
|
||||
val writes := this.types.second_of(source) != 0;
|
||||
val wants := this.types.second_of(target) != 0;
|
||||
if !wants || writes {
|
||||
return fit::convert if this.unalias(inner_from) == this.unalias(inner_to);
|
||||
|
||||
# A reference to a constant, as `&200`, refers to a copy of it of the type
|
||||
# referred to.
|
||||
if this.types.is_untyped(inner_from) {
|
||||
val how := this.fits(inner_from, inner_to, value, false, depth + 1);
|
||||
return how == fit::none || how == fit::overflow ? how : fit::constant;
|
||||
}
|
||||
|
||||
# A reference to a value converts to a reference to a trait it satisfies.
|
||||
if skind == ty::reference && this.named_kind(inner_to) == dk::trait_type
|
||||
&& this.satisfies(inner_from, inner_to) {
|
||||
return fit::convert;
|
||||
}
|
||||
}
|
||||
|
||||
# A reference to a reference is otherwise read through to the one it holds,
|
||||
# where that converts, as a generic given a reference for `T` reads a `T`
|
||||
# through a `&mut T`.
|
||||
if skind == ty::reference && this.types.kind_of(this.unalias(inner_from)) == ty::reference {
|
||||
val read := this.fits(inner_from, target, value, false, depth + 1);
|
||||
return read == fit::none || read == fit::overflow ? read : fit::convert;
|
||||
}
|
||||
return fit::none;
|
||||
}
|
||||
|
||||
# A union holds a reference as it holds anything else, before it is read.
|
||||
if this.named_kind(target) == dk::union_type {
|
||||
val united := this.unites(source, target, value, known, depth);
|
||||
return united if united != fit::none;
|
||||
}
|
||||
|
||||
# A plain reference is read through where its value is expected.
|
||||
if skind == ty::reference && goal != ty::reference {
|
||||
val read := this.fits(this.types.first_of(source), target, value, false, depth + 1);
|
||||
return read == fit::none || read == fit::overflow ? read : fit::convert;
|
||||
}
|
||||
|
||||
# A view lends a read-only one, and a string lends a view of its text.
|
||||
if this.is_std(target, word::span) {
|
||||
if this.is_std(source, word::slice) && this.types.part_at(source, 0) == this.types.part_at(target, 0) {
|
||||
return fit::convert;
|
||||
}
|
||||
if this.is_std(source, word::string) && this.is_text_view(target) {
|
||||
return fit::convert;
|
||||
}
|
||||
}
|
||||
|
||||
# Bytes become a string by being copied into memory the string owns, so it
|
||||
# outlives whatever they were read from.
|
||||
if this.is_std(target, word::string) && this.is_byte_view(source) {
|
||||
return fit::convert;
|
||||
}
|
||||
|
||||
if skind == ty::function && goal == ty::function {
|
||||
return this.same_function(source, target) ? fit::convert : fit::none;
|
||||
}
|
||||
|
||||
return this.unites(source, target, value, known, depth);
|
||||
}
|
||||
|
||||
#! Whether the type is a view of bytes, read-only or writable.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::is_byte_view(&mut this, kind: u32): bool {
|
||||
val plain := this.unalias(kind);
|
||||
return (this.is_std(plain, word::span) || this.is_std(plain, word::slice))
|
||||
&& this.unalias(this.types.part_at(plain, 0)) == bt::uint8;
|
||||
}
|
||||
|
||||
#! The type with every alias within it followed to what it stands for, so
|
||||
#! types differing only by aliases are the same once stripped.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param depth How deeply the search has gone, which stops a type nesting
|
||||
#! without end.
|
||||
#! @returns The type stripped.
|
||||
pub def checker::strip(&mut this, kind: u32, depth: u32): u32 {
|
||||
return kind if depth > 16 || this.types.is_untyped(kind);
|
||||
val plain := this.unalias(kind);
|
||||
match this.types.kind_of(plain) {
|
||||
ty::reference, ty::pointer, ty::fixed => {
|
||||
val inner := this.strip(this.types.first_of(plain), depth + 1);
|
||||
if this.types.part_count(plain) == 0 {
|
||||
return this.types.intern(this.types.kind_of(plain), inner, this.types.second_of(plain), span::<u32>::empty());
|
||||
}
|
||||
val length := this.types.parts_of(plain);
|
||||
return this.types.intern(this.types.kind_of(plain), inner, this.types.second_of(plain), length.view());
|
||||
}
|
||||
ty::named, ty::function => {
|
||||
return plain if this.types.part_count(plain) == 0 && this.types.kind_of(plain) == ty::named;
|
||||
var parts := vector::<u32>::new();
|
||||
for i in 0..this.types.part_count(plain) {
|
||||
parts.append(this.strip(this.types.part_at(plain, i as u32), depth + 1));
|
||||
}
|
||||
val first := this.types.kind_of(plain) == ty::function
|
||||
? this.strip(this.types.first_of(plain), depth + 1)
|
||||
: this.types.first_of(plain);
|
||||
return this.types.intern(this.types.kind_of(plain), first, this.types.second_of(plain), parts.view());
|
||||
}
|
||||
else => return plain;
|
||||
}
|
||||
return plain;
|
||||
}
|
||||
|
||||
#! Whether the type is a view of bytes, which text read in place is: a
|
||||
#! `span<u8>`, or a `strview`.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::is_text_view(&mut this, kind: u32): bool {
|
||||
val target := this.unalias(kind);
|
||||
return this.is_std(target, word::span) && this.unalias(this.types.part_at(target, 0)) == bt::uint8;
|
||||
}
|
||||
|
||||
#! Whether the type is a type parameter that numbers may stand in for.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns Whether it is one.
|
||||
def checker::numeric_param(&mut this, kind: u32): bool {
|
||||
return this.types.kind_of(kind) == ty::param && this.param_has_numeric(this.types.first_of(kind));
|
||||
}
|
||||
|
||||
#! Whether function types only differ by aliases.
|
||||
#! @param this The checker.
|
||||
#! @param a One function type.
|
||||
#! @param b The other.
|
||||
#! @returns Whether they do.
|
||||
def checker::same_function(&mut this, a: u32, b: u32): bool {
|
||||
return false if this.types.part_count(a) != this.types.part_count(b);
|
||||
return false if this.strip(this.types.first_of(a), 0) != this.strip(this.types.first_of(b), 0);
|
||||
for i in 0..this.types.part_count(a) {
|
||||
# Aliases are looked through wherever they are, so `&strview` is `&span<u8>`,
|
||||
# and a variadic parameter is the view it takes, so `def(i64...)` is
|
||||
# `def(span<i64>)`.
|
||||
val x := this.strip(this.param_taken(a, i as u32), 0);
|
||||
val y := this.strip(this.param_taken(b, i as u32), 0);
|
||||
return false if x != y;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! The type a function takes a parameter as: its own, or of a variadic one, a
|
||||
#! view of what it gathers.
|
||||
#! @param this The checker.
|
||||
#! @param kind The function type.
|
||||
#! @param index The parameter's position.
|
||||
#! @returns The type.
|
||||
def checker::param_taken(&mut this, kind: u32, index: u32): u32 {
|
||||
val part := this.types.part_at(kind, index);
|
||||
return part if this.types.second_of(kind) == 0 || index + 1 != this.types.part_count(kind);
|
||||
return this.span_of(part);
|
||||
}
|
||||
|
||||
#! How a value fits a union: as the field of its own type, or else the one
|
||||
#! field it converts to.
|
||||
#! @param this The checker.
|
||||
#! @param from The value's type.
|
||||
#! @param to The union's type.
|
||||
#! @param value The value, where it is known while compiling.
|
||||
#! @param known Whether it is.
|
||||
#! @param depth How deeply the search has gone.
|
||||
#! @returns How it fits: `unite`, or `none`.
|
||||
def checker::unites(&mut this, from: u32, to: u32, value: &constant, known: bool, depth: u32): fit {
|
||||
return fit::none if this.named_kind(to) != dk::union_type;
|
||||
|
||||
# A constant goes to the field of the type it would be where nothing else is
|
||||
# expected, before any other it fits.
|
||||
val fields := this.field_types(to);
|
||||
val settled := this.types.is_untyped(from) ? this.settle(from) : from;
|
||||
var exact := 0;
|
||||
var fitting := 0;
|
||||
for &each in fields {
|
||||
if each == from || each == settled {
|
||||
exact++;
|
||||
continue;
|
||||
}
|
||||
val how := this.fits(from, each, value, known, depth + 1);
|
||||
if how != fit::none && how != fit::overflow && how != fit::unite {
|
||||
fitting++;
|
||||
}
|
||||
}
|
||||
return fit::unite if exact == 1 || (exact == 0 && fitting == 1);
|
||||
return fit::none;
|
||||
}
|
||||
|
||||
#! The field of a union a value of the type becomes, or 0.
|
||||
#! @param this The checker.
|
||||
#! @param from The value's type.
|
||||
#! @param to The union's type.
|
||||
#! @returns The field's declaration, or 0.
|
||||
pub def checker::united_field(&mut this, from: u32, to: u32): u32 {
|
||||
val decl := this.types.first_of(to);
|
||||
val run: u32 = this.decls.children.p[decl];
|
||||
val settled := this.types.is_untyped(from) ? this.settle(from) : from;
|
||||
var found: u32 = 0;
|
||||
var none_value := constant {};
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val field := this.decls.list_at(run, i as u32);
|
||||
continue if this.decls.kinds.p[field] != dk::field;
|
||||
this.resolve(field);
|
||||
val kind := this.instantiated(this.decls.types.p[field], decl, to);
|
||||
return field if kind == from || kind == settled;
|
||||
val how := this.fits(from, kind, &none_value, false, 1);
|
||||
if how != fit::none && how != fit::overflow && how != fit::unite && found == 0 {
|
||||
found = field;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
#! Converts the node's value to the type, reporting where it does not fit.
|
||||
#! @param this The checker.
|
||||
#! @param node The value's node.
|
||||
#! @param to The type expected.
|
||||
#! @returns Whether it fits.
|
||||
pub def checker::convert(&mut this, node: u32, to: u32): bool {
|
||||
return true if to == bt::error;
|
||||
|
||||
val from := this.type_at(node);
|
||||
val how := this.fits_node(node, to);
|
||||
match how {
|
||||
fit::exact => return true;
|
||||
fit::none => {
|
||||
# A reference written as one is a pointer at what it refers to where one
|
||||
# is expected, which keeps nothing alive.
|
||||
if this.lends_pointer(node, from, to) {
|
||||
this.refuse_lent_temporary(node);
|
||||
this.set_convert(node, to);
|
||||
return true;
|
||||
}
|
||||
# A function named where another function type is expected is called as
|
||||
# that type asks, by a function made for it.
|
||||
if this.adapts(node, from, to) {
|
||||
this.set_convert(node, to);
|
||||
this.set_flag(node, rf::adapted);
|
||||
return true;
|
||||
}
|
||||
this.report_mismatch(node, from, to);
|
||||
return false;
|
||||
}
|
||||
fit::overflow => {
|
||||
var text := string::from("The constant is outside the range of `", nothing {});
|
||||
val named := this.describe(to);
|
||||
text.append(named.view());
|
||||
text.append("`.");
|
||||
this.report_text(node, ec::overflow, &text);
|
||||
return false;
|
||||
}
|
||||
else => {
|
||||
this.set_convert(node, to);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Whether a function named as a value, of the type `from`, is called as the
|
||||
#! function type `to` asks, as a function of `to`'s type made for it calls it:
|
||||
#! each of `to`'s parameters given as a call gives an argument, those after them
|
||||
#! given their defaults, and what it gives converted to what `to` gives. A
|
||||
#! function type matching it exactly takes it as it is.
|
||||
#! @param this The checker.
|
||||
#! @param node The node naming it.
|
||||
#! @param from Its type.
|
||||
#! @param to The function type expected.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::adapts(&mut this, node: u32, from: u32, to: u32): bool {
|
||||
return false if this.kind_of(node) != nk::name && this.kind_of(node) != nk::path;
|
||||
val source := this.unalias(from);
|
||||
val target := this.unalias(to);
|
||||
return false if this.types.kind_of(source) != ty::function || this.types.kind_of(target) != ty::function;
|
||||
return false if this.types.second_of(source) != 0 || this.types.second_of(target) != 0;
|
||||
return false if source == target || this.strip(source, 0) == this.strip(target, 0);
|
||||
|
||||
val ref := this.ref_at(node);
|
||||
return false if ref == 0 || (ref & (ref_local | ref_type)) != 0;
|
||||
return this.adapt_cost(ref, source, target) >= 0;
|
||||
}
|
||||
|
||||
#! How far a function of the type `from` is from being called as the function
|
||||
#! type `to` asks, as `adapts` says it is: 0 for each parameter given as it is,
|
||||
#! 1 for one lent or read through, and 2 for one converted, or -1 where it is not
|
||||
#! called so. A call chooses between overloads by it.
|
||||
#! @param this The checker.
|
||||
#! @param decl The function's declaration, whose defaults it is given.
|
||||
#! @param from Its type.
|
||||
#! @param to The function type expected.
|
||||
#! @returns How far, or -1.
|
||||
pub def checker::adapt_cost(&mut this, decl: u32, from: u32, to: u32): i32 {
|
||||
val source := this.unalias(from);
|
||||
val target := this.unalias(to);
|
||||
return -1 if this.types.kind_of(source) != ty::function || this.types.kind_of(target) != ty::function;
|
||||
return -1 if this.types.second_of(source) != 0 || this.types.second_of(target) != 0;
|
||||
|
||||
# Only a function of the program is called so, with the defaults it declares.
|
||||
val kind_of: dk = this.decls.kinds.p[decl];
|
||||
return -1 if kind_of != dk::function && kind_of != dk::property;
|
||||
return -1 if kind_of == dk::function && (this.decls.has(decl, df::foreign) || this.decls.has(decl, df::intrinsic)
|
||||
|| this.decls.has(decl, df::variadic));
|
||||
|
||||
val given := this.types.part_count(target);
|
||||
val takes := this.types.part_count(source);
|
||||
val required: u32 = kind_of == dk::function ? this.required_params(decl) : takes;
|
||||
return -1 if given > takes || given < required;
|
||||
var cost: i32 = 0;
|
||||
for i in 0..given {
|
||||
val wanted := this.types.part_at(target, i as u32);
|
||||
val param := this.types.part_at(source, i as u32);
|
||||
return -1 if !this.passes(wanted, param);
|
||||
if this.unalias(wanted) != this.unalias(param) {
|
||||
cost += this.unalias(this.reached(wanted)) == this.unalias(this.reached(param)) ? 1 : 2;
|
||||
}
|
||||
}
|
||||
|
||||
# What a call around it still infers from what it gives, as `U` of `map`,
|
||||
# takes whatever it gives.
|
||||
return cost if this.free_result;
|
||||
val none := constant {};
|
||||
val gives := this.types.first_of(source);
|
||||
val wants := this.types.first_of(target);
|
||||
if this.types.kind_of(this.unalias(gives)) == ty::reference && this.types.kind_of(this.unalias(wants)) != ty::reference
|
||||
&& this.closes(this.reached(gives)) {
|
||||
return -1;
|
||||
}
|
||||
val how := this.fits(gives, wants, &none, false, 0);
|
||||
return -1 if how == fit::none || how == fit::overflow;
|
||||
return cost + (how == fit::exact ? 0 : 1);
|
||||
}
|
||||
|
||||
#! Whether a value of the type `given` is given for a parameter of the type
|
||||
#! `param` as a call gives it: a value lent where the parameter is a reference,
|
||||
#! a reference read through to one of the type asked, and what a reference
|
||||
#! reaches copied where the parameter takes a value, where that closes nothing.
|
||||
#! @param this The checker.
|
||||
#! @param given The type given.
|
||||
#! @param param The parameter's type.
|
||||
#! @returns Whether it is.
|
||||
def checker::passes(&mut this, given: u32, param: u32): bool {
|
||||
val none := constant {};
|
||||
val wanted := this.unalias(param);
|
||||
val held := this.unalias(given);
|
||||
if this.types.kind_of(wanted) == ty::reference && this.types.kind_of(held) != ty::reference {
|
||||
val how := this.fits(held, this.types.first_of(wanted), &none, false, 0);
|
||||
return how == fit::exact || how == fit::convert;
|
||||
}
|
||||
if this.types.kind_of(wanted) != ty::reference && this.types.kind_of(held) == ty::reference
|
||||
&& this.closes(this.reached(held)) {
|
||||
return false;
|
||||
}
|
||||
val how := this.fits(held, wanted, &none, false, 0);
|
||||
return how == fit::exact || how == fit::convert;
|
||||
}
|
||||
|
||||
#! Whether a value is a reference written as one, `&x` or `&mut x`, given where
|
||||
#! a pointer at what it refers to is expected, which it becomes: `&T` a `*T`, and
|
||||
#! `&mut T` a `*mut T` or a `*T`. Nothing else becomes a pointer without `as`,
|
||||
#! so taking an address is always written.
|
||||
#! @param this The checker.
|
||||
#! @param node The value's node.
|
||||
#! @param from Its type.
|
||||
#! @param to The type expected.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::lends_pointer(&mut this, node: u32, from: u32, to: u32): bool {
|
||||
return false if !this.lent(node);
|
||||
val source := this.unalias(from);
|
||||
val target := this.unalias(to);
|
||||
return false if this.types.kind_of(source) != ty::reference || this.types.kind_of(target) != ty::pointer;
|
||||
return false if this.types.second_of(target) != 0 && this.types.second_of(source) == 0;
|
||||
val inner_from := this.types.first_of(source);
|
||||
val inner_to := this.types.first_of(target);
|
||||
# A reference to a constant, as `&10`, refers to a copy of it of the type
|
||||
# pointed at.
|
||||
if this.types.is_untyped(inner_from) {
|
||||
val none := constant {};
|
||||
val how := this.fits(inner_from, inner_to, &none, false, 0);
|
||||
return how != fit::none && how != fit::overflow;
|
||||
}
|
||||
return this.unalias(inner_from) == this.unalias(inner_to);
|
||||
}
|
||||
|
||||
#! Whether a reference written as one refers to a value that is no place, as
|
||||
#! `&10` or `&make()`, which lives to the end of its statement, or as long as a
|
||||
#! name a reference binds.
|
||||
#! @param this The checker.
|
||||
#! @param node The value's node.
|
||||
#! @returns Whether it does.
|
||||
pub def checker::lends_temporary(&mut this, node: u32): bool {
|
||||
if this.kind_of(node) == nk::ternary {
|
||||
return this.lends_temporary(this.record(node, if_slot::then)) || this.lends_temporary(this.record(node, if_slot::other));
|
||||
}
|
||||
return false if this.kind_of(node) != nk::reference;
|
||||
val operand := this.left_of(node);
|
||||
return !this.is_place(operand) && this.types.kind_of(this.unalias(this.type_at(operand))) != ty::reference;
|
||||
}
|
||||
|
||||
#! Reports a pointer kept past its statement at a value that ends with it: a
|
||||
#! pointer keeps nothing alive, as a reference bound to a name does.
|
||||
#! @param this The checker.
|
||||
#! @param node The value's node: a reference written as one, or one cast to a
|
||||
#! pointer.
|
||||
pub def checker::refuse_lent_temporary(&mut this, node: u32): void {
|
||||
val lent := this.kind_of(node) == nk::cast ? this.left_of(node) : node;
|
||||
return if !this.lends_temporary(lent);
|
||||
this.report(node, ec::invalid,
|
||||
"A pointer keeps nothing alive, and this one points at a value that ends with its statement: keep the value in a variable first, or refer to it, as a reference bound to a name keeps it.");
|
||||
}
|
||||
|
||||
#! Reports a value of one type where another is expected.
|
||||
#! @param this The checker.
|
||||
#! @param node The value's node.
|
||||
#! @param from Its type.
|
||||
#! @param to The type expected.
|
||||
pub def checker::report_mismatch(&mut this, node: u32, from: u32, to: u32): void {
|
||||
var text := string::from("Expected `", nothing {});
|
||||
val want := this.describe(to);
|
||||
val given := this.describe(from);
|
||||
text.append(want.view());
|
||||
text.append("`, but the value is `");
|
||||
text.append(given.view());
|
||||
text.append("`.");
|
||||
this.report_text(node, ec::mismatch, &text);
|
||||
}
|
||||
|
||||
#! The type a value of the type becomes where nothing is expected of it: a
|
||||
#! number constant its default type, and text a `strview`, or a `string` where
|
||||
#! std declares no `strview`.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns The type it settles as.
|
||||
pub def checker::settle(&mut this, kind: u32): u32 {
|
||||
if this.types.kind_of(kind) == ty::reference && this.types.is_untyped(this.types.first_of(kind)) {
|
||||
return this.types.reference(this.settle(this.types.first_of(kind)), this.types.second_of(kind) != 0);
|
||||
}
|
||||
# A literal is a view of the bytes the program was written with, or a `string`
|
||||
# where std declares no `strview`.
|
||||
if this.types.kind_of(kind) == ty::untyped_text {
|
||||
val view := this.std_type(word::strview, span::<u32>::empty());
|
||||
return view != bt::error ? view : this.std_type(word::string, span::<u32>::empty());
|
||||
}
|
||||
if this.types.kind_of(kind) == ty::null_type || this.types.kind_of(kind) == ty::empty {
|
||||
return kind;
|
||||
}
|
||||
return this.types.settled(kind);
|
||||
}
|
||||
|
||||
#! The type two values share, as the operands of an operator or the branches
|
||||
#! of a ternary, or the error type where they share none.
|
||||
#! @param this The checker.
|
||||
#! @param a One value's type.
|
||||
#! @param b The other's.
|
||||
#! @returns The type they share, or the error type.
|
||||
pub def checker::common(&mut this, a: u32, b: u32): u32 {
|
||||
return a if a == b;
|
||||
return b if a == bt::error;
|
||||
return a if b == bt::error;
|
||||
|
||||
val none := constant {};
|
||||
val a_untyped := this.types.is_untyped(a);
|
||||
val b_untyped := this.types.is_untyped(b);
|
||||
if a_untyped && b_untyped {
|
||||
val a_float := this.types.is_float(a);
|
||||
val b_float := this.types.is_float(b);
|
||||
return a if a_float && !b_float;
|
||||
return b if b_float && !a_float;
|
||||
return a if this.types.kind_of(a) == ty::untyped_uint;
|
||||
return b if this.types.kind_of(b) == ty::untyped_uint;
|
||||
return a if this.types.is_integer(a) && this.types.is_integer(b);
|
||||
return bt::error;
|
||||
}
|
||||
|
||||
if a_untyped {
|
||||
val how := this.fits(a, b, &none, false, 0);
|
||||
return how == fit::none ? bt::error : b;
|
||||
}
|
||||
if b_untyped {
|
||||
val how := this.fits(b, a, &none, false, 0);
|
||||
return how == fit::none ? bt::error : a;
|
||||
}
|
||||
|
||||
val forward := this.fits(a, b, &none, false, 0);
|
||||
val backward := this.fits(b, a, &none, false, 0);
|
||||
return b if forward == fit::convert && backward == fit::none;
|
||||
return a if backward == fit::convert && forward == fit::none;
|
||||
return a if forward != fit::none && backward != fit::none;
|
||||
return bt::error;
|
||||
}
|
||||
@@ -0,0 +1,627 @@
|
||||
#! @file declare.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the declaring of what each file declares: its modules, its
|
||||
#! imports, and every declaration outside a function, with the members of
|
||||
#! types and the type parameters of generics. A declaration made through a
|
||||
#! type, as `vec2::length`, waits until every file is declared, since its type
|
||||
#! may be declared in any of them.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! Declares what the file declares.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
pub def checker::declare_unit(&mut this, file: u32): void {
|
||||
this.use_table(this.units[file].table);
|
||||
this.at.home = 0;
|
||||
this.at.scope = 0;
|
||||
|
||||
val decls := this.left_of(this.units[file].root);
|
||||
var active := true;
|
||||
var begun := false;
|
||||
var sections := false;
|
||||
var first_library: u32 = 0;
|
||||
this.external = false;
|
||||
for &node in this.run_view(decls) {
|
||||
match this.kind_of(node) {
|
||||
nk::import_decl, nk::extern_import => {
|
||||
if begun {
|
||||
this.report(node, ec::invalid, "Imports come before every other declaration.");
|
||||
}
|
||||
if this.kind_of(node) == nk::import_decl {
|
||||
this.pending_imports.append(pair_key(file, node));
|
||||
} else if this.right_of(node) == 0 || this.target_holds(this.right_of(node)) {
|
||||
first_library = first_library == 0 ? node : first_library;
|
||||
this.add_library(file, node);
|
||||
}
|
||||
}
|
||||
nk::module_decl, nk::extern_module => {
|
||||
begun = true;
|
||||
this.at.home = this.module_path(this.left_of(node), true);
|
||||
this.modules.named[this.at.home] = true;
|
||||
active = this.right_of(node) == 0 || this.target_holds(this.right_of(node));
|
||||
this.external = this.kind_of(node) == nk::extern_module;
|
||||
if this.external {
|
||||
sections = true;
|
||||
this.check_section(node);
|
||||
}
|
||||
}
|
||||
else => {
|
||||
begun = true;
|
||||
if active {
|
||||
this.declare_top(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
this.external = false;
|
||||
|
||||
if first_library != 0 && !sections {
|
||||
this.warn(first_library, ec::invalid,
|
||||
"Nothing in this file is C's, so nothing uses the libraries it imports: C's functions are declared in an `extern module`.");
|
||||
}
|
||||
}
|
||||
|
||||
#! Checks that an `extern module` says which systems it is for, since a library
|
||||
#! is one system's and C's calling convention is the system's too.
|
||||
#! @param this The checker.
|
||||
#! @param node The `extern_module` node.
|
||||
def checker::check_section(&mut this, node: u32): void {
|
||||
val condition := this.right_of(node);
|
||||
if condition == 0 || !this.names_system(condition) {
|
||||
this.report(node, ec::invalid, "An `extern module` says which systems it's for: `when os == ...`, `arch == ...`, or both.");
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether a condition on the target names `os` or `arch` anywhere.
|
||||
#! @param this The checker.
|
||||
#! @param node The condition's node.
|
||||
#! @returns Whether it does.
|
||||
def checker::names_system(&this, node: u32): bool {
|
||||
return match this.kind_of(node) {
|
||||
nk::unary => this.names_system(this.left_of(node)),
|
||||
nk::binary => this.token_kind(node) == tk::logand || this.token_kind(node) == tk::logor
|
||||
? this.names_system(this.left_of(node)) || this.names_system(this.right_of(node))
|
||||
: this.name_of(this.left_of(node)) == word::os || this.name_of(this.left_of(node)) == word::arch,
|
||||
else => false
|
||||
};
|
||||
}
|
||||
|
||||
#! Notes a library a file's C functions come from. On Windows each function is
|
||||
#! listed under its library, so a file names one there.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param node The `extern_import` node.
|
||||
def checker::add_library(&mut this, file: u32, node: u32): void {
|
||||
if this.names.text(this.target.os) == "windows" {
|
||||
for i in 0..this.libraries.length {
|
||||
if (this.libraries[i] >> 32) as u32 == file {
|
||||
this.report(node, ec::invalid,
|
||||
"A file names one library on Windows, which lists each C function under its library: declare the functions of another in a file of their own.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
this.libraries.append(pair_key(file, node));
|
||||
}
|
||||
|
||||
#! Marks what an `extern module` declares as C's: a function without a body, a
|
||||
#! struct, or a union. Whatever else it declares is ordinary Sakura.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @param kind Its kind.
|
||||
#! @param node Its node.
|
||||
def checker::mark_external(&mut this, id: u32, kind: dk, node: u32): void {
|
||||
if kind == dk::struct_type || kind == dk::union_type
|
||||
|| kind == dk::function && this.record(node, function_slot::body) == 0 {
|
||||
this.decls.mark(id, df::foreign);
|
||||
}
|
||||
}
|
||||
|
||||
#! The module a path names, made where `make` says and it is new, or 0 where
|
||||
#! it names none.
|
||||
#! @param this The checker.
|
||||
#! @param path The `path` node.
|
||||
#! @param make Whether a module it names is made where it is new.
|
||||
#! @returns The module, or 0.
|
||||
pub def checker::module_path(&mut this, path: u32, make: bool): u32 {
|
||||
var at: u32 = 0;
|
||||
for i in 0..this.segment_count(path) {
|
||||
val name := this.segment_name(path, i as u32);
|
||||
if make {
|
||||
at = this.modules.child(at, name);
|
||||
continue;
|
||||
}
|
||||
|
||||
at = this.modules.find(at, name);
|
||||
return 0 if at == 0;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
#! Declares a declaration at the top level, or those of the branch of a `when`
|
||||
#! the target takes.
|
||||
#! @param this The checker.
|
||||
#! @param node The top-level node.
|
||||
def checker::declare_top(&mut this, node: u32): void {
|
||||
match this.kind_of(node) {
|
||||
nk::when_block => {
|
||||
val chosen := this.when_branch(node);
|
||||
return if chosen == 0;
|
||||
|
||||
val decls := this.left_of(chosen);
|
||||
for &node in this.run_view(decls) {
|
||||
this.declare_top(node);
|
||||
}
|
||||
}
|
||||
nk::error => {}
|
||||
else => {
|
||||
this.decls.top = node;
|
||||
this.declare_decl(node, 0);
|
||||
this.decls.top = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! The block of a `when` the target takes, following `else when`, or 0.
|
||||
#! @param this The checker.
|
||||
#! @param node The `when_block` node.
|
||||
#! @returns The block, or 0.
|
||||
pub def checker::when_branch(&mut this, node: u32): u32 {
|
||||
var at := node;
|
||||
while at != 0 && this.kind_of(at) == nk::when_block {
|
||||
return this.record(at, if_slot::then) if this.target_holds(this.left_of(at));
|
||||
at = this.record(at, if_slot::other);
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
#! Whether the target meets the condition of a `when`, reporting a key or a
|
||||
#! value it does not know.
|
||||
#! @param this The checker.
|
||||
#! @param node The condition's node.
|
||||
#! @returns Whether it does.
|
||||
pub def checker::target_holds(&mut this, node: u32): bool {
|
||||
match this.kind_of(node) {
|
||||
nk::unary => return !this.target_holds(this.left_of(node));
|
||||
nk::binary => {
|
||||
val operator := this.token_kind(node);
|
||||
if operator == tk::logand {
|
||||
val left := this.target_holds(this.left_of(node));
|
||||
return this.target_holds(this.right_of(node)) && left;
|
||||
}
|
||||
if operator == tk::logor {
|
||||
val left := this.target_holds(this.left_of(node));
|
||||
return this.target_holds(this.right_of(node)) || left;
|
||||
}
|
||||
|
||||
val key := this.name_of(this.left_of(node));
|
||||
val value := this.name_of(this.right_of(node));
|
||||
val held := this.target_value(this.left_of(node), key, this.right_of(node), value);
|
||||
return operator == tk::equals ? held : !held;
|
||||
}
|
||||
else => return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Whether the target's value of the key is the value, reporting a key or a
|
||||
#! value no target has.
|
||||
#! @param this The checker.
|
||||
#! @param key_node The node of the key, which a note is placed at.
|
||||
#! @param key The ID of the key, as `os`.
|
||||
#! @param value_node The node of the value.
|
||||
#! @param value The ID of the value, as `linux`.
|
||||
#! @returns Whether it is.
|
||||
def checker::target_value(&mut this, key_node: u32, key: u32, value_node: u32, value: u32): bool {
|
||||
val text := this.names.text(value);
|
||||
if key == word::os {
|
||||
if text != "linux" && text != "macos" && text != "windows" && text != "freebsd" {
|
||||
this.report(value_node, ec::invalid, "`os` is `linux`, `macos`, `windows`, or `freebsd`.");
|
||||
}
|
||||
return value == this.target.os;
|
||||
}
|
||||
|
||||
if key == word::arch {
|
||||
if text != "x86_64" && text != "aarch64" {
|
||||
this.report(value_node, ec::invalid, "`arch` is `x86_64` or `aarch64`.");
|
||||
}
|
||||
return value == this.target.arch;
|
||||
}
|
||||
|
||||
if key == word::backend {
|
||||
if text != "vm" && text != "native" {
|
||||
this.report(value_node, ec::invalid, "`backend` is `vm` or `native`.");
|
||||
}
|
||||
return value == this.target.backend;
|
||||
}
|
||||
|
||||
this.report(key_node, ec::invalid, "The target keys are `os`, `arch`, and `backend`.");
|
||||
return false;
|
||||
}
|
||||
|
||||
#! The kind of declaration a node declares.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns The kind.
|
||||
def checker::decl_kind(&this, node: u32): dk {
|
||||
return match this.kind_of(node) {
|
||||
nk::function => dk::function,
|
||||
nk::variable => dk::variable,
|
||||
nk::field => dk::field,
|
||||
nk::property => dk::property,
|
||||
nk::struct_decl => dk::struct_type,
|
||||
nk::union_decl => dk::union_type,
|
||||
nk::trait_decl => dk::trait_type,
|
||||
nk::enumeration => dk::enum_type,
|
||||
nk::alias => dk::alias_type,
|
||||
nk::assoc_type => dk::assoc_type,
|
||||
nk::enumerator => dk::enum_member,
|
||||
else => dk::none
|
||||
};
|
||||
}
|
||||
|
||||
#! The receiver a declaration is made through, as `vec2` of `vec2::length`, or
|
||||
#! 0.
|
||||
#! @param this The checker.
|
||||
#! @param node The declaration's node.
|
||||
#! @returns The receiver's `type_name`, or 0.
|
||||
def checker::receiver_of(&this, node: u32): u32 {
|
||||
return match this.kind_of(node) {
|
||||
nk::function, nk::variable, nk::property, nk::struct_decl, nk::union_decl,
|
||||
nk::trait_decl, nk::enumeration, nk::alias => this.record(node, decl_slot::receiver),
|
||||
else => 0
|
||||
};
|
||||
}
|
||||
|
||||
#! The run of a declaration's own type parameters, or 0.
|
||||
#! @param this The checker.
|
||||
#! @param node The declaration's node.
|
||||
#! @returns The run, or 0.
|
||||
def checker::own_params_of(&this, node: u32): u32 {
|
||||
return match this.kind_of(node) {
|
||||
nk::function, nk::struct_decl, nk::union_decl, nk::trait_decl, nk::alias => this.record(node, decl_slot::type_params),
|
||||
else => 0
|
||||
};
|
||||
}
|
||||
|
||||
#! The run of a declaration's attributes, or 0.
|
||||
#! @param this The checker.
|
||||
#! @param node The declaration's node.
|
||||
#! @returns The run, or 0.
|
||||
pub def checker::attributes_of(&this, node: u32): u32 {
|
||||
return match this.kind_of(node) {
|
||||
nk::function, nk::variable, nk::field, nk::property, nk::struct_decl, nk::union_decl,
|
||||
nk::trait_decl, nk::enumeration, nk::alias, nk::assoc_type => this.record(node, decl_slot::attributes),
|
||||
nk::enumerator => this.left_of(node),
|
||||
else => 0
|
||||
};
|
||||
}
|
||||
|
||||
#! Declares the declaration, as a member of `owner` where it is given, or
|
||||
#! else in the module, or waiting for its receiver.
|
||||
#! @param this The checker.
|
||||
#! @param node The declaration's node.
|
||||
#! @param owner The type it is a member of, or 0.
|
||||
#! @returns Its ID, or 0 where it declares nothing.
|
||||
pub def checker::declare_decl(&mut this, node: u32, owner: u32): u32 {
|
||||
val kind := this.decl_kind(node);
|
||||
return 0 if kind == dk::none;
|
||||
|
||||
val id := this.decls.add(kind, this.name_of(node), this.at.file, node, this.at.home);
|
||||
val flags := this.node_flags(node);
|
||||
if (flags & nf::exported as u32) != 0 { this.decls.mark(id, df::exported); }
|
||||
if (flags & nf::mutable as u32) != 0 { this.decls.mark(id, df::mutable); }
|
||||
if (flags & nf::constant as u32) != 0 { this.decls.mark(id, df::constant); }
|
||||
if kind == dk::assoc_type && (flags & nf::packed as u32) != 0 { this.decls.mark(id, df::packed); }
|
||||
this.mark_attributes(id, node);
|
||||
if this.external && owner == 0 {
|
||||
this.mark_external(id, kind, node);
|
||||
}
|
||||
|
||||
if kind == dk::function {
|
||||
this.mark_signature(id, node);
|
||||
}
|
||||
|
||||
# A trait's members and the fields of a struct belong to it as they are
|
||||
# declared. Anything else declared through a type waits for its type.
|
||||
if owner != 0 {
|
||||
this.add_member(owner, id);
|
||||
} else if this.receiver_of(node) != 0 {
|
||||
this.pending.append(id);
|
||||
} else {
|
||||
this.add_global(id);
|
||||
}
|
||||
|
||||
val own := this.declare_params(this.own_params_of(node), id);
|
||||
this.record_shape(id, this.own_params_of(node));
|
||||
# A function's type parameters are inferred from its arguments, and an alias is
|
||||
# the type it is written as, so only a struct, union, or trait takes a pattern.
|
||||
if kind == dk::function || kind == dk::alias_type {
|
||||
val run := this.own_params_of(node);
|
||||
for ¶m in this.run_view(run) {
|
||||
val written := this.kind_of(param);
|
||||
if written == nk::type_pattern || written == nk::array_pattern {
|
||||
this.report(param, ec::generic, "Only a struct, union, or trait takes a pattern parameter, as `def(Ts...): R` or `L[N]`.");
|
||||
}
|
||||
}
|
||||
}
|
||||
# The names of generic functions, which an argument naming one waits by.
|
||||
if kind == dk::function && own.length != 0 {
|
||||
val name := this.name_of(node);
|
||||
if this.generic_names.length <= name as u64 {
|
||||
this.generic_names.resize(name as u64 + 1, false);
|
||||
}
|
||||
this.generic_names[name] = true;
|
||||
}
|
||||
if this.receiver_of(node) == 0 {
|
||||
this.set_params(id, own.view());
|
||||
} else {
|
||||
this.decls.params.p[id] = this.decls.make_list(own.view());
|
||||
}
|
||||
|
||||
this.declare_members(id, node);
|
||||
return id;
|
||||
}
|
||||
|
||||
#! Gives the declaration its own type parameters, which make it generic.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @param own Its own type parameters' declarations.
|
||||
def checker::set_params(&mut this, id: u32, own: span<u32>): void {
|
||||
this.decls.params.p[id] = this.decls.make_list(own);
|
||||
if own.length != 0 {
|
||||
this.decls.mark(id, df::generic);
|
||||
}
|
||||
}
|
||||
|
||||
#! Declares the type parameters of the run, each owned by the declaration.
|
||||
#! @param this The checker.
|
||||
#! @param run The run of `type_param` nodes.
|
||||
#! @param owner The declaration they belong to.
|
||||
#! @returns Their declarations.
|
||||
def checker::declare_params(&mut this, run: u32, owner: u32): vector<u32> {
|
||||
var made := vector::<u32>::new();
|
||||
for &node in this.run_view(run) {
|
||||
# A pattern, `def(Ts...): R`, declares the type parameters it names, those of
|
||||
# its parameters and then its result's.
|
||||
if this.kind_of(node) == nk::type_pattern {
|
||||
val named := this.declare_params(this.left_of(node), owner);
|
||||
made.extend(named.view());
|
||||
if this.right_of(node) != 0 {
|
||||
val result := this.decls.add(dk::type_param, this.name_of(this.right_of(node)), this.at.file, this.right_of(node), this.at.home);
|
||||
this.decls.own(result, owner);
|
||||
made.append(result);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
# A pattern, `L[N]`, declares its element's type parameter, and its length's
|
||||
# constant one.
|
||||
if this.kind_of(node) == nk::array_pattern {
|
||||
val element := this.decls.add(dk::type_param, this.name_of(this.left_of(node)), this.at.file, this.left_of(node), this.at.home);
|
||||
this.decls.own(element, owner);
|
||||
made.append(element);
|
||||
if this.right_of(node) != 0 {
|
||||
val length := this.decls.add(dk::type_param, this.name_of(this.right_of(node)), this.at.file, this.right_of(node), this.at.home);
|
||||
this.decls.own(length, owner);
|
||||
this.decls.mark(length, df::valued);
|
||||
made.append(length);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
val id := this.decls.add(dk::type_param, this.name_of(node), this.at.file, node, this.at.home);
|
||||
this.decls.own(id, owner);
|
||||
# A constant parameter stands for a value, whose type it resolves with its bounds.
|
||||
if this.kind_of(node) == nk::const_param {
|
||||
this.decls.mark(id, df::valued);
|
||||
} else if this.node_has(node, nf::packed) {
|
||||
this.decls.mark(id, df::packed);
|
||||
# A function's variadic parameter takes a pack, and a struct, union, or
|
||||
# trait takes one for what it holds or asks for to pass on.
|
||||
val kind: dk = this.decls.kinds.p[owner];
|
||||
if kind != dk::function && kind != dk::struct_type && kind != dk::union_type && kind != dk::trait_type {
|
||||
this.report(node, ec::generic, "Only a function, struct, union, or trait takes a pack.");
|
||||
}
|
||||
}
|
||||
made.append(id);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Declares the fields of a struct or union, the members of a trait, the
|
||||
#! members of an enum, and the accessors of a property.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @param node Its node.
|
||||
def checker::declare_members(&mut this, id: u32, node: u32): void {
|
||||
val kind := this.kind_of(node);
|
||||
if kind != nk::struct_decl && kind != nk::union_decl && kind != nk::trait_decl
|
||||
&& kind != nk::enumeration && kind != nk::property {
|
||||
return;
|
||||
}
|
||||
|
||||
var children := vector::<u32>::new();
|
||||
val members := this.right_of(node);
|
||||
for &member in this.run_view(members) {
|
||||
if kind == nk::property {
|
||||
children.append(this.declare_accessor(id, member));
|
||||
continue;
|
||||
}
|
||||
|
||||
val made := this.declare_decl(member, id);
|
||||
if made != 0 {
|
||||
children.append(made);
|
||||
}
|
||||
}
|
||||
this.decls.children.p[id] = this.decls.make_list(children.view());
|
||||
}
|
||||
|
||||
#! Declares an accessor of a property, a function of the property's name taking
|
||||
#! `this`, which is no member of its own: reading or writing the property
|
||||
#! calls it.
|
||||
#! @param this The checker.
|
||||
#! @param property The property's declaration.
|
||||
#! @param node The `accessor` node.
|
||||
#! @returns The accessor's declaration.
|
||||
def checker::declare_accessor(&mut this, property: u32, node: u32): u32 {
|
||||
val id := this.decls.add(dk::function, this.decls.names.p[property], this.at.file, node, this.at.home);
|
||||
this.decls.own(id, property);
|
||||
this.decls.mark(id, df::accessor);
|
||||
this.decls.mark(id, df::method);
|
||||
if this.name_of(node) == this.names.intern(&"set") {
|
||||
this.decls.mark(id, df::setter);
|
||||
}
|
||||
if this.decls.has(property, df::exported) || this.node_has(node, nf::exported) {
|
||||
this.decls.mark(id, df::exported);
|
||||
}
|
||||
if this.decls.has(property, df::inline) {
|
||||
this.decls.mark(id, df::inline);
|
||||
}
|
||||
|
||||
val params := this.left_of(node);
|
||||
if this.run_length(params) != 0 && this.node_has(this.run_at(params, 0), nf::mutable) {
|
||||
this.decls.mark(id, df::mut_this);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
#! Marks what the attributes the compiler reads say of the declaration.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @param node Its node.
|
||||
def checker::mark_attributes(&mut this, id: u32, node: u32): void {
|
||||
val attrs := this.attributes_of(node);
|
||||
for &attr in this.run_view(attrs) {
|
||||
continue if this.kind_of(attr) != nk::attribute;
|
||||
|
||||
val named := this.left_of(attr);
|
||||
val name := this.segment_name(named, this.segment_count(named) - 1);
|
||||
if name == word::intrinsic {
|
||||
this.decls.mark(id, df::intrinsic);
|
||||
} else if name == word::optional {
|
||||
this.decls.mark(id, df::optional);
|
||||
} else if name == word::nodiscard {
|
||||
this.decls.mark(id, df::nodiscard);
|
||||
} else if name == word::allow {
|
||||
this.decls.mark(id, df::allows);
|
||||
} else if name == word::inline {
|
||||
this.decls.mark(id, df::inline);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Marks what a function's parameters say of it: whether it takes `this`, and
|
||||
#! `&mut this`, and whether its last parameter is variadic.
|
||||
#! @param this The checker.
|
||||
#! @param id The function's declaration.
|
||||
#! @param node Its node.
|
||||
def checker::mark_signature(&mut this, id: u32, node: u32): void {
|
||||
val params := this.record(node, function_slot::params);
|
||||
val count := this.run_length(params);
|
||||
return if count == 0;
|
||||
|
||||
# `&this` takes the value a method is called on, as does `this` written with
|
||||
# a reference to the method's type, `this: &mut T`.
|
||||
val first := this.run_at(params, 0);
|
||||
if this.name_of(first) == names::this_id {
|
||||
val written := this.left_of(first);
|
||||
if written == 0 {
|
||||
this.decls.mark(id, df::method);
|
||||
if this.node_has(first, nf::mutable) {
|
||||
this.decls.mark(id, df::mut_this);
|
||||
}
|
||||
} else if this.kind_of(written) == nk::type_ref {
|
||||
this.decls.mark(id, df::method);
|
||||
if this.node_has(written, nf::mutable) {
|
||||
this.decls.mark(id, df::mut_this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if this.node_has(this.run_at(params, count - 1), nf::variadic) {
|
||||
this.decls.mark(id, df::variadic);
|
||||
}
|
||||
}
|
||||
|
||||
#! Declares the declaration in its module, as an overload of the functions of
|
||||
#! its name there, or reporting a name already taken.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
def checker::add_global(&mut this, id: u32): void {
|
||||
val home: u32 = this.decls.modules.p[id];
|
||||
val name: u32 = this.decls.names.p[id];
|
||||
val first := this.modules.decl(home, name);
|
||||
if first == 0 {
|
||||
this.modules.set_decl(home, name, id);
|
||||
return;
|
||||
}
|
||||
|
||||
if this.decls.kinds.p[first] == dk::function && this.decls.kinds.p[id] == dk::function {
|
||||
this.decls.chain(first, id);
|
||||
return;
|
||||
}
|
||||
|
||||
this.report_duplicate(id, first);
|
||||
}
|
||||
|
||||
#! Makes the declaration a member of the type, as an overload of the functions
|
||||
#! of its name, or reporting a name already taken. A field is reached through a
|
||||
#! value, and a type declared through the type through the type, so those two
|
||||
#! may share a name, as `kind` and `token::kind`. One declared outside `core` on
|
||||
#! `core`'s type, of a name `core` gives it a member or type of too, is kept
|
||||
#! apart from `core`'s.
|
||||
#! @param this The checker.
|
||||
#! @param owner The type's declaration.
|
||||
#! @param id The member's declaration.
|
||||
def checker::add_member(&mut this, owner: u32, id: u32): void {
|
||||
val name: u32 = this.decls.names.p[id];
|
||||
val types := this.decls.nests(id);
|
||||
val same := this.decls.member_in(owner, name, types);
|
||||
val other := this.decls.member_in(owner, name, !types);
|
||||
|
||||
# A member or type of `core`'s type declared outside `core`, of a name `core`
|
||||
# gives it too, is kept apart and chosen over `core`'s where it is seen, so
|
||||
# `core` adding one later never refuses a program or takes its calls.
|
||||
val core_id := this.in_core(this.decls.modules.p[id]);
|
||||
if !core_id && ((same != 0 && this.in_core(this.decls.modules.p[same]))
|
||||
|| (other != 0 && this.in_core(this.decls.modules.p[other]))) {
|
||||
val first := this.decls.added_member(owner, name);
|
||||
if first == 0 || (this.decls.kinds.p[first] == dk::function && this.decls.kinds.p[id] == dk::function) {
|
||||
this.decls.add_added(owner, id);
|
||||
return;
|
||||
}
|
||||
this.decls.own(id, owner);
|
||||
this.report_duplicate(id, first);
|
||||
return;
|
||||
}
|
||||
# `core`'s, declared after them, takes their place.
|
||||
if core_id && this.decls.added_member(owner, name) == 0 {
|
||||
if same != 0 && !this.in_core(this.decls.modules.p[same]) {
|
||||
this.decls.set_aside(owner, name, types);
|
||||
this.add_member(owner, id);
|
||||
return;
|
||||
}
|
||||
if other != 0 && !this.in_core(this.decls.modules.p[other]) {
|
||||
this.decls.set_aside(owner, name, !types);
|
||||
this.add_member(owner, id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
val shares := other == 0 || this.decls.kinds.p[types ? other : id] == dk::field;
|
||||
if shares && (same == 0 || (this.decls.kinds.p[same] == dk::function && this.decls.kinds.p[id] == dk::function)) {
|
||||
this.decls.add_member(owner, id);
|
||||
return;
|
||||
}
|
||||
|
||||
this.decls.own(id, owner);
|
||||
this.report_duplicate(id, same != 0 ? same : other);
|
||||
}
|
||||
|
||||
def checker::report_duplicate(&mut this, id: u32, first: u32): void {
|
||||
this.report_decl_related(id, ec::duplicate, "The name is already declared here.", first, "First declared here.");
|
||||
this.decls.mark(id, df::failed);
|
||||
}
|
||||
@@ -0,0 +1,579 @@
|
||||
#! @file decls.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the declaration table, which gives every declaration outside a
|
||||
#! function an ID of its own, with each of its fields in a column of its own
|
||||
#! and the declarations of each file, owner, and module listed, and the modules
|
||||
#! declarations are made in. Locals and parameters are no declarations here:
|
||||
#! each is known by the node declaring it, whose type the results of the body
|
||||
#! it is in hold.
|
||||
|
||||
import std::containers;
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! The kinds of declaration.
|
||||
pub enum dk : u8 {
|
||||
none, #! Declaration 0, which stands for "no declaration".
|
||||
builtin, #! A type every program has, as `i64`, which methods may be declared through.
|
||||
function, #! A function or method, whose type is its function type.
|
||||
variable, #! A global variable or constant, or one declared through a type.
|
||||
field, #! A field of a struct or union.
|
||||
struct_type, #! A struct.
|
||||
union_type, #! A union.
|
||||
enum_type, #! An enum.
|
||||
enum_member, #! A member of an enum, a constant of it.
|
||||
trait_type, #! A trait.
|
||||
alias_type, #! A type alias.
|
||||
type_param, #! A type parameter of a generic declaration.
|
||||
assoc_type, #! A type a trait asks for.
|
||||
property, #! A property, whose accessors are functions declared through its type.
|
||||
attribute, #! An attribute written on a declaration, as `attributes_of` gives it: a constant of its type, whose value it writes.
|
||||
}
|
||||
|
||||
#! What a declaration's `flags` hold.
|
||||
pub enum df : u32 {
|
||||
exported = 0x0001, #! `pub`.
|
||||
mutable = 0x0002, #! `var`.
|
||||
constant = 0x0004, #! `const`, or `const def`.
|
||||
method = 0x0008, #! A function taking `this`.
|
||||
mut_this = 0x0010, #! A method taking `&mut this`.
|
||||
variadic = 0x0020, #! A function whose last parameter is variadic.
|
||||
generic = 0x0040, #! A declaration with type parameters of its own or of its owner.
|
||||
intrinsic = 0x0080, #! Given by the compiler, `@intrinsic`.
|
||||
foreign = 0x0100, #! C's: a function without a body, a struct, or a union of an `extern module`.
|
||||
failed = 0x0200, #! Its signature is wrong, so what uses it reports nothing more.
|
||||
optional = 0x0400, #! A trait's member written `@optional`.
|
||||
packed = 0x0800, #! A type parameter that is a pack, `Ts...`.
|
||||
accessor = 0x1000, #! A function that is a property's accessor.
|
||||
setter = 0x2000, #! The `set` of a property.
|
||||
checked = 0x4000, #! Its body has been checked.
|
||||
nodiscard = 0x8000, #! What it gives, or a value of it, must be handled where it is made: `@nodiscard`.
|
||||
valued = 0x10000, #! A type parameter that is a constant parameter, `const N: u64`, whose value's type is its target.
|
||||
bounding = 0x20000, #! A method whose `where` bounds its type's parameters further, so only the types meeting them have it.
|
||||
allows = 0x40000, #! A function whose warnings are quieted: `@allow`.
|
||||
callback = 0x80000, #! A function given where a `cfn` is expected, which C calls back through an entry of its own.
|
||||
inline = 0x100000, #! A function each call of which is copied, at every level: `@inline`, or an accessor of a property written so.
|
||||
}
|
||||
|
||||
#! How far a declaration's signature is resolved, which says where one depends
|
||||
#! on itself.
|
||||
pub enum ds : u8 {
|
||||
unresolved, #! Not yet resolved.
|
||||
resolving, #! Being resolved, so meeting it again means it depends on itself.
|
||||
resolved, #! Resolved.
|
||||
}
|
||||
|
||||
#! Every declaration, by its ID, a field in a column of its own.
|
||||
pub struct decl_table {
|
||||
# The columns the compiler reads too, through each one's `p`, without a call.
|
||||
pub var kinds: column<dk>; #! The kind of each declaration.
|
||||
pub var names: column<u32>; #! The name of each, by its ID.
|
||||
pub var files: column<u32>; #! The file each is declared in.
|
||||
pub var nodes: column<u32>; #! The node declaring each.
|
||||
pub var modules: column<u32>; #! The module each belongs to.
|
||||
pub var owners: column<u32>; #! The type a member belongs to, or the declaration a type parameter belongs to.
|
||||
pub var types: column<u32>; #! What a variable holds, a function's type, or the type a type declares.
|
||||
pub var overloads: column<u32>; #! The next declaration of the same name and place.
|
||||
pub var children: column<u32>; #! The run of a type's fields, enum members, or trait members in `lists`, or a type parameter's bounds.
|
||||
|
||||
var flags: column<u32>; #! The flags of each, as `df` says.
|
||||
var states: column<ds>; #! How far each is resolved.
|
||||
var params: column<u32>; #! The run of a declaration's type parameters in `lists`, its owner's first.
|
||||
var targets: column<u32>; #! What an alias stands for, an enum's integer type, or the default of a type a trait asks for.
|
||||
var tops: column<u32>; #! The node of the top-level declaration each was declared with, or 0 for what the checker made.
|
||||
var top: u32; #! The node of the top-level declaration being declared, which `add` gives what it adds.
|
||||
var lists: runs<u32>; #! The runs `params` and `children` name.
|
||||
var members: keymap; #! The first member of each name of a type: `owner << 32 | name`.
|
||||
var nested: keymap; #! The type of each name declared through a type, as `token::kind`: `owner << 32 | name`.
|
||||
var added: keymap; #! The first member, or the type, of each name a module outside `core` declares through a type `core` gives a member or type of that name too: `owner << 32 | name`.
|
||||
|
||||
# The declarations of each file, owner, and module, for what walks only those
|
||||
# rather than every declaration.
|
||||
var by_file: decl_index; #! The declarations of each file.
|
||||
var by_owner: decl_index; #! The declarations each declaration has owned: a type's members, or a declaration's type parameters.
|
||||
var by_module: decl_index; #! The declarations each module has held.
|
||||
}
|
||||
|
||||
#! Makes a declaration table holding declaration 0, which stands for no
|
||||
#! declaration.
|
||||
#! @returns The table.
|
||||
pub def decl_table::new(): decl_table {
|
||||
var made := decl_table {
|
||||
kinds = column::<dk>::new(),
|
||||
names = column::<u32>::new(),
|
||||
files = column::<u32>::new(),
|
||||
nodes = column::<u32>::new(),
|
||||
modules = column::<u32>::new(),
|
||||
owners = column::<u32>::new(),
|
||||
types = column::<u32>::new(),
|
||||
flags = column::<u32>::new(),
|
||||
states = column::<ds>::new(),
|
||||
overloads = column::<u32>::new(),
|
||||
params = column::<u32>::new(),
|
||||
children = column::<u32>::new(),
|
||||
targets = column::<u32>::new(),
|
||||
tops = column::<u32>::new(),
|
||||
lists = runs::<u32>::new(),
|
||||
members = keymap::new(),
|
||||
nested = keymap::new(),
|
||||
added = keymap::new(),
|
||||
by_file = decl_index::new(),
|
||||
by_owner = decl_index::new(),
|
||||
by_module = decl_index::new()
|
||||
};
|
||||
|
||||
made.add(dk::none, 0, 0, 0, 0);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! How many declarations there are.
|
||||
#! @param this The declaration table.
|
||||
#! @returns The number, which is one more than the newest's ID.
|
||||
pub val decl_table::count: u64 { get => this.kinds.length; }
|
||||
|
||||
#! Appends a declaration.
|
||||
#! @param this The declaration table.
|
||||
#! @param kind Its kind.
|
||||
#! @param name Its name's ID.
|
||||
#! @param file The file it is declared in.
|
||||
#! @param node The node declaring it.
|
||||
#! @param home The module it belongs to.
|
||||
#! @returns Its ID.
|
||||
pub def decl_table::add(&mut this, kind: dk, name: u32, file: u32, node: u32, home: u32): u32 {
|
||||
val id := this.kinds.length as u32;
|
||||
this.kinds.append(kind);
|
||||
this.names.append(name);
|
||||
this.files.append(file);
|
||||
this.nodes.append(node);
|
||||
this.modules.append(home);
|
||||
this.owners.append(0);
|
||||
this.types.append(0);
|
||||
this.flags.append(0);
|
||||
this.states.append(ds::unresolved);
|
||||
this.overloads.append(0);
|
||||
this.params.append(0);
|
||||
this.children.append(0);
|
||||
this.targets.append(0);
|
||||
this.tops.append(this.top);
|
||||
if id != 0 {
|
||||
this.by_file.add(file, id);
|
||||
this.by_module.add(home, id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
#! Makes a declaration belong to an owner: a member to its type, or a type
|
||||
#! parameter to the declaration it is of.
|
||||
#! @param this The declaration table.
|
||||
#! @param id The declaration.
|
||||
#! @param owner Its owner.
|
||||
pub def decl_table::own(&mut this, id: u32, owner: u32): void {
|
||||
this.owners.p[id] = owner;
|
||||
if owner != 0 {
|
||||
this.by_owner.add(owner, id);
|
||||
}
|
||||
}
|
||||
|
||||
#! Makes a top-level declaration anew at its new node, as declaring it again
|
||||
#! does: it keeps its ID, kind, name, file, and type, and is otherwise as `add`
|
||||
#! made it, with no owner, overloads, flags, or runs.
|
||||
#! @param this The declaration table.
|
||||
#! @param id The declaration.
|
||||
#! @param node Its new node, which is its top-level declaration's too.
|
||||
#! @param home The module it belongs to now.
|
||||
pub def decl_table::renew(&mut this, id: u32, node: u32, home: u32): void {
|
||||
this.nodes.p[id] = node;
|
||||
this.tops.p[id] = node;
|
||||
this.modules.p[id] = home;
|
||||
this.owners.p[id] = 0;
|
||||
this.overloads.p[id] = 0;
|
||||
this.flags.p[id] = 0;
|
||||
this.states.p[id] = ds::unresolved;
|
||||
this.params.p[id] = 0;
|
||||
this.children.p[id] = 0;
|
||||
this.targets.p[id] = 0;
|
||||
this.by_module.add(home, id);
|
||||
}
|
||||
|
||||
#! Whether a declaration has a flag.
|
||||
#! @param this The declaration table.
|
||||
#! @param id The declaration.
|
||||
#! @param flag The flag.
|
||||
#! @returns Whether it has it.
|
||||
pub def decl_table::has(&this, id: u32, flag: df): bool {
|
||||
return (this.flags.p[id] & flag as u32) != 0;
|
||||
}
|
||||
|
||||
#! Gives a declaration a flag.
|
||||
#! @param this The declaration table.
|
||||
#! @param id The declaration.
|
||||
#! @param flag The flag.
|
||||
pub def decl_table::mark(&mut this, id: u32, flag: df): void {
|
||||
this.flags.p[id] |= flag as u32;
|
||||
}
|
||||
|
||||
#! Adds a run of the items to `lists`.
|
||||
#! @param this The declaration table.
|
||||
#! @param items The items, which are no view of `lists`.
|
||||
#! @returns The run's ID, or 0 for none.
|
||||
pub def decl_table::make_list(&mut this, items: span<u32>): u32 {
|
||||
return this.lists.add(items);
|
||||
}
|
||||
|
||||
#! How many items a run of `lists` holds.
|
||||
#! @param this The declaration table.
|
||||
#! @param run The run's ID.
|
||||
#! @returns How many items it holds.
|
||||
pub def decl_table::list_length(&this, run: u32): u32 {
|
||||
return this.lists.length(run) as u32;
|
||||
}
|
||||
|
||||
#! The items of a run of `lists`, copied.
|
||||
#! @param this The declaration table.
|
||||
#! @param run The run's ID, or 0 for none.
|
||||
#! @returns The items.
|
||||
pub def decl_table::list_of(&this, run: u32): vector<u32> {
|
||||
var made := vector::<u32>::new();
|
||||
made.extend(this.lists.view(run));
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The items of a run of `lists`, where they are.
|
||||
#! @param this The declaration table.
|
||||
#! @param run The run's ID, or 0 for none.
|
||||
#! @returns The items, a view only good until a run is added, so a loop that
|
||||
#! may add one, as by resolving a declaration, walks them by
|
||||
#! `list_at`, or copies them by `list_of`.
|
||||
pub def decl_table::list_view(&this, run: u32): span<u32> {
|
||||
return this.lists.view(run);
|
||||
}
|
||||
|
||||
#! An item of a run of `lists`, by its position.
|
||||
#! @param this The declaration table.
|
||||
#! @param run The run's ID.
|
||||
#! @param index The position, below its length.
|
||||
#! @returns The item.
|
||||
pub def decl_table::list_at(&this, run: u32, index: u32): u32 {
|
||||
return this.lists.at(run, index as u64);
|
||||
}
|
||||
|
||||
#! The first member of the type of the name, or 0. A field and a type declared
|
||||
#! through the type may share a name, and this is the field.
|
||||
#! @param this The declaration table.
|
||||
#! @param owner The type's declaration.
|
||||
#! @param name The name's ID.
|
||||
#! @returns The member, whose overloads follow it, or 0 where the type has none
|
||||
#! of the name.
|
||||
pub def decl_table::member(&this, owner: u32, name: u32): u32 {
|
||||
val found := this.member_in(owner, name, false);
|
||||
return found != 0 ? found : this.member_in(owner, name, true);
|
||||
}
|
||||
|
||||
#! The member of the type of the name `::` reaches: a type declared through it,
|
||||
#! as `token::kind`, before a field of the same name, which only a value reaches.
|
||||
#! @param this The declaration table.
|
||||
#! @param owner The type's declaration.
|
||||
#! @param name The name's ID.
|
||||
#! @returns The member, whose overloads follow it, or 0 where the type has none
|
||||
#! of the name.
|
||||
pub def decl_table::path_member(&this, owner: u32, name: u32): u32 {
|
||||
val found := this.member_in(owner, name, true);
|
||||
return found != 0 ? found : this.member_in(owner, name, false);
|
||||
}
|
||||
|
||||
#! The first member of the type of the name among its types, or among the
|
||||
#! rest of its members.
|
||||
#! @param this The declaration table.
|
||||
#! @param owner The type's declaration.
|
||||
#! @param name The name's ID.
|
||||
#! @param types Whether it is a type declared through the type.
|
||||
#! @returns The member, or 0.
|
||||
pub def decl_table::member_in(&this, owner: u32, name: u32, types: bool): u32 {
|
||||
val key := pair_key(owner, name);
|
||||
return types ? this.nested.get_or(&key, 0) : this.members.get_or(&key, 0);
|
||||
}
|
||||
|
||||
#! The first member of the name a module outside `core` declares on the type,
|
||||
#! where `core` declares one of that name on it too, or 0. Where it is seen, it
|
||||
#! is chosen over `core`'s, so `core` adding a member never takes a program's
|
||||
#! place.
|
||||
#! @param this The declaration table.
|
||||
#! @param owner The type's declaration.
|
||||
#! @param name The name's ID.
|
||||
#! @returns The member, whose overloads follow it, or 0.
|
||||
pub def decl_table::added_member(&this, owner: u32, name: u32): u32 {
|
||||
val key := pair_key(owner, name);
|
||||
return this.added.get_or(&key, 0);
|
||||
}
|
||||
|
||||
#! Makes a member declared outside `core` one of those `added_member` gives,
|
||||
#! after the others of its name, or the first.
|
||||
#! @param this The declaration table.
|
||||
#! @param owner The type's declaration.
|
||||
#! @param id The member's declaration.
|
||||
pub def decl_table::add_added(&mut this, owner: u32, id: u32): void {
|
||||
this.own(id, owner);
|
||||
val key := pair_key(owner, this.names.p[id]);
|
||||
val first := this.added.get_or(&key, 0);
|
||||
if first == 0 {
|
||||
this.added.set(key, id);
|
||||
} else {
|
||||
this.chain(first, id);
|
||||
}
|
||||
}
|
||||
|
||||
#! Makes the members or the type of a name declared outside `core` what
|
||||
#! `added_member` gives, once `core` declares a member or type of that name too.
|
||||
#! @param this The declaration table.
|
||||
#! @param owner The type's declaration.
|
||||
#! @param name The name's ID.
|
||||
#! @param types Whether it is a type declared through the type.
|
||||
pub def decl_table::set_aside(&mut this, owner: u32, name: u32, types: bool): void {
|
||||
val key := pair_key(owner, name);
|
||||
val first := this.member_in(owner, name, types);
|
||||
return if first == 0;
|
||||
this.added.set(key, first);
|
||||
if types {
|
||||
this.nested.remove(&key);
|
||||
} else {
|
||||
this.members.remove(&key);
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether a member is a type declared through its type, which is kept apart
|
||||
#! from the type's other members.
|
||||
#! @param this The declaration table.
|
||||
#! @param id The member's declaration.
|
||||
#! @returns Whether it is.
|
||||
pub def decl_table::nests(&this, id: u32): bool {
|
||||
return match this.kinds.p[id] {
|
||||
dk::struct_type, dk::union_type, dk::enum_type, dk::trait_type, dk::alias_type => true,
|
||||
else => false
|
||||
};
|
||||
}
|
||||
|
||||
#! Makes the declaration a member of its type, after the members of its name
|
||||
#! already there.
|
||||
#! @param this The declaration table.
|
||||
#! @param owner The type's declaration.
|
||||
#! @param id The member's declaration.
|
||||
#! @returns The first member of the name.
|
||||
pub def decl_table::add_member(&mut this, owner: u32, id: u32): u32 {
|
||||
this.own(id, owner);
|
||||
val key := pair_key(owner, this.names.p[id]);
|
||||
val types := this.nests(id);
|
||||
val first := this.member_in(owner, this.names.p[id], types);
|
||||
if first == 0 {
|
||||
if types {
|
||||
this.nested.set(key, id);
|
||||
} else {
|
||||
this.members.set(key, id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
this.chain(first, id);
|
||||
return first;
|
||||
}
|
||||
|
||||
#! Puts the declaration last among the overloads beginning with `first`.
|
||||
#! @param this The declaration table.
|
||||
#! @param first The first of the overloads.
|
||||
#! @param id The declaration to put last.
|
||||
pub def decl_table::chain(&mut this, first: u32, id: u32): void {
|
||||
var last := first;
|
||||
var walk := this.walk_overloads(first);
|
||||
while true {
|
||||
val at := walk.next();
|
||||
break if at == 0;
|
||||
last = at;
|
||||
}
|
||||
this.overloads.p[last] = id;
|
||||
}
|
||||
|
||||
#! A walk along a chain of overloads from its first, in the order they were
|
||||
#! chained: `next` gives each in turn, then 0 from then on.
|
||||
#!
|
||||
#! Each step reads the overload after the one given last as `next` is called,
|
||||
#! so what is chained after it while the walk is on it is met, and the table's
|
||||
#! columns may move as declarations are made.
|
||||
pub struct overload_walk {
|
||||
var decls: &decl_table; #! The table holding the chain.
|
||||
var at: u32; #! The overload given last, or 0 before the first.
|
||||
var first: u32; #! The first overload, until it is given.
|
||||
var left: u32; #! How many more overloads it gives at most.
|
||||
}
|
||||
|
||||
#! The most overloads a walk gives where it is not limited, more than any chain
|
||||
#! holds.
|
||||
pub const overload_walk::unlimited: u32 = 0xFFFFFFFF;
|
||||
|
||||
#! A walk along the overloads beginning with `first`.
|
||||
#! @param this The declaration table.
|
||||
#! @param first The first of the overloads, or 0 for none.
|
||||
#! @param limit The most overloads it gives, past which it ends.
|
||||
#! @returns The walk.
|
||||
pub def decl_table::walk_overloads(&this, first: u32, limit: u32 = overload_walk::unlimited): overload_walk {
|
||||
return overload_walk { decls = this, first = first, left = limit };
|
||||
}
|
||||
|
||||
#! The next overload of the walk.
|
||||
#! @param this The walk.
|
||||
#! @returns The overload, or 0 where there are no more, or the walk gave as
|
||||
#! many as it was limited to.
|
||||
pub def overload_walk::next(&mut this): u32 {
|
||||
return 0 if this.left == 0;
|
||||
this.left--;
|
||||
|
||||
# Held in a local, so it is not read back after it is stored, which keeps the
|
||||
# walk short enough to be inlined where it is used.
|
||||
val at := this.at == 0 ? this.first : this.decls.overloads.p[this.at];
|
||||
this.at = at;
|
||||
this.first = 0;
|
||||
return at;
|
||||
}
|
||||
|
||||
#! Lists of declarations by a key, as the declarations of each file, each in
|
||||
#! increasing ID order, so walking one meets them in the order walking every
|
||||
#! declaration would.
|
||||
#!
|
||||
#! A declaration is listed under a key once given it, and stays listed once it
|
||||
#! no longer has it, as where it is forgotten or declared again elsewhere, so
|
||||
#! what walks a list asks each declaration for the key, and its kind, as it
|
||||
#! would walking every declaration.
|
||||
pub struct decl_index {
|
||||
var lists: vector<vector<u32>>; #! The declarations of each key, in increasing ID order.
|
||||
}
|
||||
|
||||
#! Makes an index listing no declaration.
|
||||
#! @returns The index.
|
||||
pub def decl_index::new(): decl_index {
|
||||
return decl_index { lists = vector::<vector<u32>>::new() };
|
||||
}
|
||||
|
||||
#! Lists a declaration under a key, where it is not listed already.
|
||||
#! @param this The index.
|
||||
#! @param key The key, as a file, a module, or a declaration, which are
|
||||
#! counted from 0, so each has a list of its own.
|
||||
#! @param id The declaration.
|
||||
pub def decl_index::add(&mut this, key: u32, id: u32): void {
|
||||
if key as u64 >= this.lists.length {
|
||||
this.lists.resize(key as u64 + 1, vector::<u32>::new());
|
||||
}
|
||||
val list := &mut this.lists[key];
|
||||
|
||||
# A declaration just made is the newest, which goes last.
|
||||
if list.length == 0 || list.last() < id {
|
||||
list.append(id);
|
||||
return;
|
||||
}
|
||||
val at := list.view().lower_bound(&id);
|
||||
if list[at] != id {
|
||||
list.insert_at(at, id);
|
||||
}
|
||||
}
|
||||
|
||||
#! The declarations listed under a key.
|
||||
#! @param this The index.
|
||||
#! @param key The key.
|
||||
#! @returns The declarations, in increasing ID order, a view only good until
|
||||
#! one is listed under the key, so a loop that may add a declaration
|
||||
#! of it, as by resolving one, copies them first.
|
||||
pub def decl_index::of(&this, key: u32): span<u32> {
|
||||
return (key as u64) < this.lists.length ? this.lists[key].view() : span::<u32>::empty();
|
||||
}
|
||||
|
||||
#! The modules of a program. Module 0 is the program itself, which files
|
||||
#! declaring no module are part of.
|
||||
pub struct module_table {
|
||||
pub var names: vector<u32>; #! The name of each module, by its ID.
|
||||
pub var parents: vector<u32>; #! The module each is within.
|
||||
pub var named: vector<bool>; #! Whether a file's `module` line names each, rather than only one within it.
|
||||
var children: keymap; #! Each module by its parent and name: `parent << 32 | name`.
|
||||
var decls: keymap; #! The first declaration of each name a module makes: `module << 32 | name`.
|
||||
}
|
||||
|
||||
#! Makes a module table holding module 0, the program itself.
|
||||
#! @returns The table.
|
||||
pub def module_table::new(): module_table {
|
||||
var made := module_table {
|
||||
names = vector::<u32>::new(),
|
||||
parents = vector::<u32>::new(),
|
||||
named = vector::<bool>::new(),
|
||||
children = keymap::new(),
|
||||
decls = keymap::new()
|
||||
};
|
||||
|
||||
made.names.append(0);
|
||||
made.parents.append(0);
|
||||
made.named.append(true);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The module of the name within the parent, made where it is new.
|
||||
#! @param this The module table.
|
||||
#! @param parent The module it is within.
|
||||
#! @param name Its name's ID.
|
||||
#! @returns The module.
|
||||
pub def module_table::child(&mut this, parent: u32, name: u32): u32 {
|
||||
val key := pair_key(parent, name);
|
||||
if this.children.get(&key) is some(got) {
|
||||
return got;
|
||||
}
|
||||
|
||||
val id := this.names.length as u32;
|
||||
this.names.append(name);
|
||||
this.parents.append(parent);
|
||||
this.named.append(false);
|
||||
this.children.set(key, id);
|
||||
return id;
|
||||
}
|
||||
|
||||
#! The module of the name within the parent, or 0 where there is none.
|
||||
#! @param this The module table.
|
||||
#! @param parent The module it is within.
|
||||
#! @param name Its name's ID.
|
||||
#! @returns The module, or 0.
|
||||
pub def module_table::find(&this, parent: u32, name: u32): u32 {
|
||||
val key := pair_key(parent, name);
|
||||
return this.children.get_or(&key, 0);
|
||||
}
|
||||
|
||||
#! The first declaration of the name the module makes, or 0.
|
||||
#! @param this The module table.
|
||||
#! @param home The module.
|
||||
#! @param name The name's ID.
|
||||
#! @returns The declaration, whose overloads follow it, or 0.
|
||||
pub def module_table::decl(&this, home: u32, name: u32): u32 {
|
||||
val key := pair_key(home, name);
|
||||
return this.decls.get_or(&key, 0);
|
||||
}
|
||||
|
||||
#! Records the first declaration of a name a module makes.
|
||||
#! @param this The module table.
|
||||
#! @param home The module.
|
||||
#! @param name The name's ID.
|
||||
#! @param id The declaration.
|
||||
pub def module_table::set_decl(&mut this, home: u32, name: u32, id: u32): void {
|
||||
this.decls.set(pair_key(home, name), id);
|
||||
}
|
||||
|
||||
#! Whether `inner` is `outer`, or within it.
|
||||
#! @param this The module table.
|
||||
#! @param inner The module asked about.
|
||||
#! @param outer The module it may be within.
|
||||
#! @returns Whether it is.
|
||||
pub def module_table::within(&this, inner: u32, outer: u32): bool {
|
||||
var at := inner;
|
||||
var steps := 0;
|
||||
while steps < 64 {
|
||||
return true if at == outer;
|
||||
return false if at == 0;
|
||||
at = this.parents[at];
|
||||
steps++;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
#! @file describe.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains how the checker writes types and declarations as notes spell them,
|
||||
#! as `&mut list<int>` or `def(u8): bool`.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! The type, as notes spell it.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns Its spelling, as `list<i64>`.
|
||||
pub def checker::describe(&this, kind: u32): string {
|
||||
var out := string::new(nothing {});
|
||||
this.describe_into(kind, &mut out, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
def checker::describe_into(&this, kind: u32, out: &mut string, depth: u32): void {
|
||||
if depth > 16 {
|
||||
out.append("...");
|
||||
return;
|
||||
}
|
||||
|
||||
val first := this.types.first_of(kind);
|
||||
match this.types.kind_of(kind) {
|
||||
ty::error => out.append("?");
|
||||
ty::void_type => out.append("void");
|
||||
ty::null_type => out.append("null");
|
||||
ty::boolean => out.append("bool");
|
||||
ty::untyped_bool => out.append("bool");
|
||||
ty::untyped_int => out.append("integer constant");
|
||||
ty::untyped_uint => out.append("unsigned integer constant");
|
||||
ty::untyped_char => out.append("character constant");
|
||||
ty::untyped_float => out.append("float constant");
|
||||
ty::untyped_float32 => out.append("float constant");
|
||||
ty::untyped_text => out.append("text");
|
||||
ty::empty => out.append("empty array element");
|
||||
ty::signed => out.append(first == 64 ? "int" : first == 32 ? "i32" : first == 16 ? "i16" : "i8");
|
||||
ty::unsigned => out.append(first == 64 ? "uint" : first == 32 ? "u32" : first == 16 ? "u16" : "u8");
|
||||
ty::floating => out.append(first == 64 ? "float" : "f32");
|
||||
ty::reference, ty::pointer => {
|
||||
out.append(this.types.kind_of(kind) == ty::reference ? "&" : "*");
|
||||
if this.types.second_of(kind) != 0 {
|
||||
out.append("mut ");
|
||||
}
|
||||
this.describe_into(first, out, depth + 1);
|
||||
}
|
||||
ty::fixed => {
|
||||
this.describe_into(first, out, depth + 1);
|
||||
if this.types.part_count(kind) != 0 {
|
||||
out.append("[");
|
||||
this.describe_into(this.types.part_at(kind, 0), out, depth + 1);
|
||||
out.append("]");
|
||||
} else {
|
||||
val count := $"[{this.types.second_of(kind)}]";
|
||||
out.append(count.view());
|
||||
}
|
||||
}
|
||||
# A constant is written as its value, as `4` of `buffer<u8, 4>`.
|
||||
ty::value => this.describe_known(this.types.second_of(kind), out, depth + 1);
|
||||
ty::function => {
|
||||
# A pack parameter says `...` of itself.
|
||||
out.append("def(");
|
||||
this.describe_parts(kind, out, depth);
|
||||
val count := this.types.part_count(kind);
|
||||
if this.types.second_of(kind) != 0 && (count == 0 || !this.types.is_open_pack(this.types.part_at(kind, count - 1))) {
|
||||
out.append("...");
|
||||
}
|
||||
out.append("): ");
|
||||
this.describe_into(first, out, depth + 1);
|
||||
}
|
||||
# A pack among the type arguments is written as the types it gives, as
|
||||
# `box<i64, bool, u8>` of `box<A, Ts...>`.
|
||||
ty::named => {
|
||||
if this.qualified_names {
|
||||
this.module_names(first, out);
|
||||
}
|
||||
if this.owned_names || this.qualified_names {
|
||||
this.owner_names(first, out, 0);
|
||||
}
|
||||
out.append(this.names.text(this.decls.names.p[first]));
|
||||
if this.types.part_count(kind) != 0 {
|
||||
out.append("<");
|
||||
if this.has_patterns(first) {
|
||||
this.describe_written(kind, out, depth);
|
||||
} else {
|
||||
this.describe_args(this.types.parts_view(kind), out, depth + 1);
|
||||
}
|
||||
out.append(">");
|
||||
}
|
||||
}
|
||||
ty::param => out.append(this.names.text(this.decls.names.p[first]));
|
||||
ty::pack => {
|
||||
if this.types.part_count(kind) == 0 && first != 0 {
|
||||
out.append(this.names.text(this.decls.names.p[first]));
|
||||
out.append("...");
|
||||
} else {
|
||||
# A variadic function's pack of parameters ends in the one taking the rest.
|
||||
out.append("(");
|
||||
this.describe_parts(kind, out, depth);
|
||||
if this.types.second_of(kind) != 0 {
|
||||
out.append("...");
|
||||
}
|
||||
out.append(")");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! The type, with the module of each type it names, as `path_of` spells it:
|
||||
#! `std::containers::dict<core::string, game::item>`, which no two types share.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns Its spelling.
|
||||
pub def checker::describe_path(&mut this, kind: u32): string {
|
||||
val saved := this.qualified_names;
|
||||
this.qualified_names = true;
|
||||
var out := this.describe(kind);
|
||||
this.qualified_names = saved;
|
||||
return out;
|
||||
}
|
||||
|
||||
#! Writes the modules a declaration is in, outermost first, as `std::io::`.
|
||||
#! @param this The checker.
|
||||
#! @param decl The declaration.
|
||||
#! @param out Where they are written.
|
||||
def checker::module_names(&this, decl: u32, out: &mut string): void {
|
||||
var modules := vector::<u32>::new();
|
||||
var at: u32 = this.decls.modules.p[decl];
|
||||
while at != 0 && modules.length < 64 {
|
||||
modules.append(at);
|
||||
at = this.modules.parents[at];
|
||||
}
|
||||
var i := modules.length;
|
||||
while i > 0 {
|
||||
i--;
|
||||
out.append(this.names.text(this.modules.names[modules[i]]));
|
||||
out.append("::");
|
||||
}
|
||||
}
|
||||
|
||||
#! Writes the types a type is declared through, as `token::` of `token::kind`.
|
||||
#! @param this The checker.
|
||||
#! @param decl The type's declaration.
|
||||
#! @param out Where they are written.
|
||||
#! @param depth How many have been written.
|
||||
def checker::owner_names(&this, decl: u32, out: &mut string, depth: u32): void {
|
||||
val owner: u32 = this.decls.owners.p[decl];
|
||||
return if owner == 0 || depth > 8 || !this.decls.nests(decl) || this.decls.kinds.p[owner] == dk::builtin;
|
||||
this.owner_names(owner, out, depth + 1);
|
||||
out.append(this.names.text(this.decls.names.p[owner]));
|
||||
out.append("::");
|
||||
}
|
||||
|
||||
def checker::describe_parts(&this, kind: u32, out: &mut string, depth: u32): void {
|
||||
for i in 0..this.types.part_count(kind) {
|
||||
if i != 0 {
|
||||
out.append(", ");
|
||||
}
|
||||
this.describe_into(this.types.part_at(kind, i as u32), out, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#! The name of the declaration, as notes spell it.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns The name.
|
||||
pub def checker::decl_text(&this, id: u32): strview {
|
||||
return this.names.text(this.decls.names.p[id]);
|
||||
}
|
||||
|
||||
#! What the declaration is, in a word or two, as "function" or "struct".
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns The word.
|
||||
pub def checker::decl_word(&this, id: u32): strview {
|
||||
return match this.decls.kinds.p[id] {
|
||||
dk::builtin => "type",
|
||||
dk::function => "function",
|
||||
dk::variable => this.decls.has(id, df::constant) ? "constant" : "variable",
|
||||
dk::field => "field",
|
||||
dk::struct_type => "struct",
|
||||
dk::union_type => "union",
|
||||
dk::enum_type => "enum",
|
||||
dk::enum_member => "enum member",
|
||||
dk::trait_type => "trait",
|
||||
dk::alias_type => "type alias",
|
||||
dk::type_param => "type parameter",
|
||||
dk::assoc_type => "type",
|
||||
dk::property => "property",
|
||||
dk::attribute => "constant",
|
||||
else => "declaration"
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,594 @@
|
||||
#! @file evaluator.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the evaluator, which runs code while checking where a value must be
|
||||
#! known and folding its operators does not give it: a constant's value that
|
||||
#! calls a function, or the length of a fixed array. It runs over the checked
|
||||
#! results of what it runs, so it needs nothing of its own made first, and
|
||||
#! what goes wrong, as an index past the end or a run that never ends, is
|
||||
#! reported at what asked for the value.
|
||||
#!
|
||||
#! It runs integers, floats, and `bool`, and fixed arrays of them, through
|
||||
#! locals, assignments, branches, loops, and calls of functions that are not
|
||||
#! generic. What it does not run leaves the value unknown, as before.
|
||||
|
||||
import std::containers;
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! A value the evaluator holds: a constant, or a fixed array whose elements
|
||||
#! are `count` constants from `start` of the heap.
|
||||
pub struct ev {
|
||||
var array: bool; #! Whether it is an array, rather than a constant.
|
||||
var scalar: constant; #! The constant, where it is one.
|
||||
var start: u32; #! Where the array's elements begin on the heap.
|
||||
var count: u32; #! How many elements the array holds.
|
||||
}
|
||||
|
||||
#! How evaluating a statement ended.
|
||||
pub enum eflow : u8 {
|
||||
goes_on, #! It went on to its end.
|
||||
returns, #! It returned, with the value in `ev_result`.
|
||||
breaks, #! It broke out of a loop.
|
||||
continues, #! It went on to a loop's next turn.
|
||||
fails, #! It went wrong, which was reported, or it ran into what the evaluator does not run.
|
||||
}
|
||||
|
||||
#! The most steps an evaluation takes, past which it is reported as never
|
||||
#! ending.
|
||||
pub const checker::max_steps: u64 = 10000000;
|
||||
|
||||
#! How deeply evaluated calls nest.
|
||||
pub const checker::max_calls: u32 = 200;
|
||||
|
||||
#! Works out the value of the expression, which checking did not, by running
|
||||
#! it, reporting at `site` what goes wrong.
|
||||
#! @param this The checker.
|
||||
#! @param node The expression.
|
||||
#! @param site The node that asked for the value, which a failure is reported
|
||||
#! at.
|
||||
#! @param out Where the value is written.
|
||||
#! @returns Whether it was worked out, with the value in `out`.
|
||||
pub def checker::evaluate(&mut this, node: u32, site: u32, out: &mut ev): bool {
|
||||
this.ev_steps = 0;
|
||||
this.ev_depth = 0;
|
||||
this.ev_site = site;
|
||||
this.ev_file = this.at.file;
|
||||
this.ev_failed = false;
|
||||
this.ev_frames.append(dict::<u32, ev>::new());
|
||||
val held := this.ev_expr(node, out);
|
||||
this.ev_frames.truncate();
|
||||
return held && !this.ev_failed;
|
||||
}
|
||||
|
||||
#! Reports what went wrong while evaluating, at what asked for the value.
|
||||
#! @param this The checker.
|
||||
#! @param detail What went wrong, finishing the note's sentence.
|
||||
def checker::ev_fault(&mut this, detail: strview): void {
|
||||
return if this.ev_failed;
|
||||
this.ev_failed = true;
|
||||
var text := string::from("The value could not be worked out while compiling: ", nothing {});
|
||||
text.append(detail);
|
||||
this.report_in(this.ev_file, this.ev_site, ec::constant, text.view());
|
||||
}
|
||||
|
||||
#! Takes one step, reporting a run that never ends.
|
||||
#! @param this The checker.
|
||||
#! @returns Whether evaluation may go on, which it may not past `max_steps`.
|
||||
def checker::ev_step(&mut this): bool {
|
||||
this.ev_steps++;
|
||||
if this.ev_steps > checker::max_steps {
|
||||
this.ev_fault("it runs for too long, as one that never ends does.");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
def checker::ev_scalar(&this, value: constant): ev {
|
||||
return ev { scalar = value };
|
||||
}
|
||||
|
||||
#! The local of the frame being run at the node, or false.
|
||||
#! @param this The checker.
|
||||
#! @param node The node declaring the local.
|
||||
#! @param out Where its value is written.
|
||||
#! @returns Whether the frame holds it.
|
||||
def checker::ev_local(&mut this, node: u32, out: &mut ev): bool {
|
||||
val top := this.ev_frames.length - 1;
|
||||
return false if !this.ev_frames[top].contains(&node);
|
||||
val held: ev = this.ev_frames[top][node];
|
||||
out = held;
|
||||
return true;
|
||||
}
|
||||
|
||||
def checker::ev_set_local(&mut this, node: u32, value: ev): void {
|
||||
val top := this.ev_frames.length - 1;
|
||||
this.ev_frames[top].set(node, value);
|
||||
}
|
||||
|
||||
#! A copy of an array, with elements of its own, so assigning one copies it.
|
||||
#! @param this The checker.
|
||||
#! @param value The value, which is given back as it is where it is no array.
|
||||
#! @returns The copy.
|
||||
def checker::ev_copy(&mut this, value: ev): ev {
|
||||
return value if !value.array;
|
||||
val start := this.ev_heap.length as u32;
|
||||
for i in 0..value.count {
|
||||
val element: constant = this.ev_heap[value.start as u64 + i as u64];
|
||||
this.ev_heap.append(element);
|
||||
}
|
||||
return ev { array = true, start = start, count = value.count };
|
||||
}
|
||||
|
||||
#! The constant made to fit an integer type of its bits, wrapping as the
|
||||
#! program running wraps.
|
||||
#! @param this The checker.
|
||||
#! @param value The constant.
|
||||
#! @param kind The integer type.
|
||||
#! @returns The constant wrapped to its bits.
|
||||
def checker::ev_wrap(&mut this, value: constant, kind: u32): constant {
|
||||
val plain := this.unalias(kind);
|
||||
val tkd := this.types.kind_of(plain);
|
||||
return value if value.floating || (tkd != ty::signed && tkd != ty::unsigned);
|
||||
val bits := this.types.first_of(plain);
|
||||
var raw := value.bits();
|
||||
if bits < 64 {
|
||||
raw &= (1u << bits as u64) - 1;
|
||||
if tkd == ty::signed && (raw >> (bits - 1) as u64) != 0 {
|
||||
raw |= ~((1u << bits as u64) - 1);
|
||||
}
|
||||
}
|
||||
return constant::from_bits(raw, tkd == ty::signed);
|
||||
}
|
||||
|
||||
#! Evaluates an expression.
|
||||
#! @param this The checker.
|
||||
#! @param node The expression.
|
||||
#! @param out Where its value is written.
|
||||
#! @returns Whether it was evaluated.
|
||||
def checker::ev_expr(&mut this, node: u32, out: &mut ev): bool {
|
||||
return false if !this.ev_step() || node == 0;
|
||||
|
||||
if this.is_known(node) {
|
||||
out = this.ev_scalar(this.value_at(node));
|
||||
return true;
|
||||
}
|
||||
|
||||
match this.kind_of(node) {
|
||||
nk::name => {
|
||||
val ref := this.ref_at(node);
|
||||
if (ref & ref_local) != 0 {
|
||||
var held := ev {};
|
||||
if !this.ev_local(ref & ref_mask, &mut held) {
|
||||
return false;
|
||||
}
|
||||
out = held;
|
||||
return true;
|
||||
}
|
||||
return this.ev_global(ref, out);
|
||||
}
|
||||
nk::path => return this.ev_global(this.ref_at(node), out);
|
||||
nk::unary => {
|
||||
var operand := ev {};
|
||||
return false if !this.ev_expr(this.left_of(node), &mut operand) || operand.array;
|
||||
val value := operand.scalar;
|
||||
match this.token_kind(node) {
|
||||
tk::minus => out = this.ev_scalar(value.floating ? constant::real_of(-value.real) : constant::integer(value.magnitude, !value.negative));
|
||||
tk::negate => out = this.ev_scalar(constant::truth(value.magnitude == 0));
|
||||
tk::bitnot => out = this.ev_scalar(constant::from_bits(~value.bits(), this.types.is_signed(this.type_at(node))));
|
||||
else => return false;
|
||||
}
|
||||
out.scalar = this.ev_wrap(out.scalar, this.type_at(node));
|
||||
return true;
|
||||
}
|
||||
nk::binary => {
|
||||
val operator := this.token_kind(node);
|
||||
var left := ev {};
|
||||
return false if !this.ev_expr(this.left_of(node), &mut left) || left.array;
|
||||
if operator == tk::logand || operator == tk::logor {
|
||||
val holds := left.scalar.magnitude != 0;
|
||||
if (operator == tk::logand && !holds) || (operator == tk::logor && holds) {
|
||||
out = this.ev_scalar(constant::truth(holds));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
var right := ev {};
|
||||
return false if !this.ev_expr(this.right_of(node), &mut right) || right.array;
|
||||
var made := constant {};
|
||||
if !this.fold_binary(operator, &left.scalar, &right.scalar, this.types.is_signed(this.type_at(this.left_of(node))), &mut made) {
|
||||
this.ev_fault("an operator overflows 64 bits, or divides by zero.");
|
||||
return false;
|
||||
}
|
||||
out = this.ev_scalar(this.ev_wrap(made, this.type_at(node)));
|
||||
return true;
|
||||
}
|
||||
nk::ternary => {
|
||||
var condition := ev {};
|
||||
return false if !this.ev_expr(this.left_of(node), &mut condition);
|
||||
return this.ev_expr(this.record(node, condition.scalar.magnitude != 0 ? if_slot::then : if_slot::other), out);
|
||||
}
|
||||
nk::cast => {
|
||||
var value := ev {};
|
||||
return false if !this.ev_expr(this.left_of(node), &mut value) || value.array;
|
||||
val target := this.unalias(this.type_at(node));
|
||||
var held := value.scalar;
|
||||
if this.types.is_float(target) && !held.floating {
|
||||
held = constant::real_of(held.as_real());
|
||||
} else if this.types.is_integer(target) && held.floating {
|
||||
held = constant::integer((held.real < 0.0 ? -held.real : held.real) as u64, held.real < 0.0);
|
||||
}
|
||||
out = this.ev_scalar(this.ev_wrap(held, target));
|
||||
return true;
|
||||
}
|
||||
nk::array => {
|
||||
val run := this.left_of(node);
|
||||
var items := vector::<constant>::new();
|
||||
for &each in this.run_view(run) {
|
||||
var element := ev {};
|
||||
return false if !this.ev_expr(each, &mut element) || element.array;
|
||||
items.append(element.scalar);
|
||||
}
|
||||
this.ev_heap.extend(items.view());
|
||||
out = ev { array = true, start = this.ev_heap.length as u32 - items.length as u32, count = items.length as u32 };
|
||||
return true;
|
||||
}
|
||||
nk::index => {
|
||||
var object := ev {};
|
||||
var at := ev {};
|
||||
return false if !this.ev_expr(this.left_of(node), &mut object) || !object.array;
|
||||
return false if !this.ev_expr(this.right_of(node), &mut at) || at.array;
|
||||
if at.scalar.negative || at.scalar.magnitude >= object.count as u64 {
|
||||
this.ev_fault("an index is past the end of the array.");
|
||||
return false;
|
||||
}
|
||||
out = this.ev_scalar(this.ev_heap[object.start as u64 + at.scalar.magnitude]);
|
||||
return true;
|
||||
}
|
||||
nk::member => {
|
||||
var object := ev {};
|
||||
return false if !this.ev_expr(this.left_of(node), &mut object);
|
||||
if object.array && this.name_of(node) == word::length {
|
||||
out = this.ev_scalar(constant::integer(object.count as u64, false));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
nk::assign => return this.ev_assign(node, out);
|
||||
nk::postfix => return this.ev_step_place(node, this.left_of(node), true, out);
|
||||
nk::call => return this.ev_call(node, out);
|
||||
else => return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! The value of a global constant or an enum member, evaluated where checking
|
||||
#! did not give it.
|
||||
#! @param this The checker.
|
||||
#! @param ref The declaration.
|
||||
#! @param out Where its value is written.
|
||||
#! @returns Whether it was evaluated.
|
||||
def checker::ev_global(&mut this, ref: u32, out: &mut ev): bool {
|
||||
return false if ref == 0 || (ref & (ref_local | ref_type)) != 0;
|
||||
var value := constant {};
|
||||
if this.decl_value(ref, &mut value) {
|
||||
out = this.ev_scalar(value);
|
||||
return true;
|
||||
}
|
||||
if this.ev_arrays.get(&ref) is some(got) {
|
||||
out = got;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! `x = y`, `x op= y`, and the place each writes: a local, or an element of an
|
||||
#! array a local holds.
|
||||
#! @param this The checker.
|
||||
#! @param node The `assign` node.
|
||||
#! @param out Where the value assigned is written.
|
||||
#! @returns Whether it was evaluated.
|
||||
def checker::ev_assign(&mut this, node: u32, out: &mut ev): bool {
|
||||
val target := this.left_of(node);
|
||||
val value := this.right_of(node);
|
||||
var given := ev {};
|
||||
return false if !this.ev_expr(value, &mut given);
|
||||
|
||||
val operator := this.token_kind(node);
|
||||
if operator != tk::assign {
|
||||
var current := ev {};
|
||||
return false if !this.ev_expr(target, &mut current) || current.array || given.array;
|
||||
var made := constant {};
|
||||
if !this.fold_binary(operator.applied(), ¤t.scalar, &given.scalar,
|
||||
this.types.is_signed(this.type_at(target)), &mut made) {
|
||||
this.ev_fault("an operator overflows 64 bits, or divides by zero.");
|
||||
return false;
|
||||
}
|
||||
given = this.ev_scalar(this.ev_wrap(made, this.type_at(target)));
|
||||
} else {
|
||||
given = this.ev_copy(given);
|
||||
if !given.array {
|
||||
given.scalar = this.ev_wrap(given.scalar, this.type_at(target));
|
||||
}
|
||||
}
|
||||
|
||||
return false if !this.ev_write(target, given);
|
||||
out = given;
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Writes the value to a place: a local, or an element of an array a local
|
||||
#! holds.
|
||||
#! @param this The checker.
|
||||
#! @param target The node of the place.
|
||||
#! @param value The value to write.
|
||||
#! @returns Whether it was written.
|
||||
def checker::ev_write(&mut this, target: u32, value: ev): bool {
|
||||
match this.kind_of(target) {
|
||||
nk::name => {
|
||||
val ref := this.ref_at(target);
|
||||
return false if (ref & ref_local) == 0;
|
||||
this.ev_set_local(ref & ref_mask, value);
|
||||
return true;
|
||||
}
|
||||
nk::index => {
|
||||
var object := ev {};
|
||||
var at := ev {};
|
||||
return false if !this.ev_expr(this.left_of(target), &mut object) || !object.array || value.array;
|
||||
return false if !this.ev_expr(this.right_of(target), &mut at);
|
||||
if at.scalar.negative || at.scalar.magnitude >= object.count as u64 {
|
||||
this.ev_fault("an index is past the end of the array.");
|
||||
return false;
|
||||
}
|
||||
this.ev_heap[object.start as u64 + at.scalar.magnitude] = value.scalar;
|
||||
return true;
|
||||
}
|
||||
else => return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! `x++` and `x--`, which give the value from before.
|
||||
#! @param this The checker.
|
||||
#! @param node The operator's node.
|
||||
#! @param target The node of the number changed.
|
||||
#! @param after Whether the operator follows its operand, as `x++`, giving
|
||||
#! the value from before.
|
||||
#! @param out Where the value it gives is written.
|
||||
#! @returns Whether it was evaluated.
|
||||
def checker::ev_step_place(&mut this, node: u32, target: u32, after: bool, out: &mut ev): bool {
|
||||
var current := ev {};
|
||||
return false if !this.ev_expr(target, &mut current) || current.array;
|
||||
val one := constant::integer(1, false);
|
||||
var made := constant {};
|
||||
val operator := this.token_kind(node) == tk::increment ? tk::plus : tk::minus;
|
||||
return false if !this.fold_binary(operator, ¤t.scalar, &one, true, &mut made);
|
||||
return false if !this.ev_write(target, this.ev_scalar(this.ev_wrap(made, this.type_at(target))));
|
||||
out = current;
|
||||
return true;
|
||||
}
|
||||
|
||||
#! A call of a function that is not generic, with its arguments evaluated, run
|
||||
#! over its checked body in a frame of its own.
|
||||
#! @param this The checker.
|
||||
#! @param node The `call` node.
|
||||
#! @param out Where what it gives is written.
|
||||
#! @returns Whether it was evaluated.
|
||||
def checker::ev_call(&mut this, node: u32, out: &mut ev): bool {
|
||||
val decl := this.ref_at(node);
|
||||
return false if decl == 0 || (decl & (ref_local | ref_type)) != 0;
|
||||
return false if this.decls.kinds.p[decl] != dk::function || this.decls.has(decl, df::generic);
|
||||
return false if this.decls.has(decl, df::intrinsic) || this.decls.has(decl, df::foreign) || this.decls.has(decl, df::method);
|
||||
if this.ev_depth >= checker::max_calls {
|
||||
this.ev_fault("its calls nest too deeply, as one calling itself without end does.");
|
||||
return false;
|
||||
}
|
||||
|
||||
var args := vector::<ev>::new();
|
||||
val run := this.right_of(node);
|
||||
for &arg in this.run_view(run) {
|
||||
var value := ev {};
|
||||
return false if !this.ev_expr(arg, &mut value);
|
||||
args.append(this.ev_copy(value));
|
||||
}
|
||||
|
||||
# The function's body is checked first, so its results are there to run.
|
||||
this.check_decl(decl);
|
||||
val saved := this.at;
|
||||
this.use_table(this.units[this.decls.files.p[decl]].table);
|
||||
val fnode: u32 = this.decls.nodes.p[decl];
|
||||
val params := this.record(fnode, function_slot::params);
|
||||
val body := this.record(fnode, function_slot::body);
|
||||
if body == 0 || this.run_length(params) != args.length as u32 {
|
||||
this.at = saved;
|
||||
return false;
|
||||
}
|
||||
|
||||
var frame := dict::<u32, ev>::new();
|
||||
for i in 0..args.length {
|
||||
frame.set(this.run_at(params, i as u32), args[i]);
|
||||
}
|
||||
this.ev_frames.append(move(&mut frame));
|
||||
this.ev_depth++;
|
||||
this.ev_result = ev {};
|
||||
val how := this.ev_block(body);
|
||||
this.ev_depth--;
|
||||
this.ev_frames.truncate();
|
||||
this.at = saved;
|
||||
|
||||
return false if how == eflow::fails;
|
||||
out = this.ev_result;
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Runs a block or a statement.
|
||||
#! @param this The checker.
|
||||
#! @param node The block or statement.
|
||||
#! @returns How it ended.
|
||||
def checker::ev_block(&mut this, node: u32): eflow {
|
||||
return eflow::goes_on if node == 0;
|
||||
if this.kind_of(node) != nk::block {
|
||||
return this.ev_stmt(node);
|
||||
}
|
||||
val run := this.left_of(node);
|
||||
for &stmt in this.run_view(run) {
|
||||
val how := this.ev_stmt(stmt);
|
||||
return how if how != eflow::goes_on;
|
||||
}
|
||||
return eflow::goes_on;
|
||||
}
|
||||
|
||||
#! Runs a statement.
|
||||
#! @param this The checker.
|
||||
#! @param node The statement.
|
||||
#! @returns How it ended.
|
||||
def checker::ev_stmt(&mut this, node: u32): eflow {
|
||||
return eflow::fails if !this.ev_step();
|
||||
match this.kind_of(node) {
|
||||
nk::block => return this.ev_block(node);
|
||||
nk::variable => {
|
||||
val value := this.record(node, variable_slot::value);
|
||||
var held := ev {};
|
||||
# `undefined` memory holds what it may, which zeroes are.
|
||||
if value != 0 && this.kind_of(value) != nk::undefined {
|
||||
return eflow::fails if !this.ev_expr(value, &mut held);
|
||||
held = this.ev_copy(held);
|
||||
if !held.array {
|
||||
held.scalar = this.ev_wrap(held.scalar, this.type_at(node));
|
||||
}
|
||||
} else {
|
||||
held = this.ev_zero(this.type_at(node));
|
||||
}
|
||||
this.ev_set_local(node, held);
|
||||
return eflow::goes_on;
|
||||
}
|
||||
nk::expr_stmt => {
|
||||
var ignored := ev {};
|
||||
return this.ev_expr(this.left_of(node), &mut ignored) ? eflow::goes_on : eflow::fails;
|
||||
}
|
||||
nk::if_stmt, nk::if_const => {
|
||||
var condition := ev {};
|
||||
return eflow::fails if !this.ev_expr(this.left_of(node), &mut condition);
|
||||
return this.ev_block(this.record(node, condition.scalar.magnitude != 0 ? if_slot::then : if_slot::other));
|
||||
}
|
||||
nk::while_stmt => {
|
||||
while true {
|
||||
var condition := ev {};
|
||||
return eflow::fails if !this.ev_expr(this.left_of(node), &mut condition);
|
||||
break if condition.scalar.magnitude == 0;
|
||||
val how := this.ev_block(this.right_of(node));
|
||||
return how if how == eflow::returns || how == eflow::fails;
|
||||
break if how == eflow::breaks;
|
||||
}
|
||||
return eflow::goes_on;
|
||||
}
|
||||
nk::for_stmt => return this.ev_for(node);
|
||||
nk::return_stmt => {
|
||||
val value := this.left_of(node);
|
||||
this.ev_result = ev {};
|
||||
if value != 0 {
|
||||
var held := ev {};
|
||||
return eflow::fails if !this.ev_expr(value, &mut held);
|
||||
this.ev_result = this.ev_copy(held);
|
||||
}
|
||||
return eflow::returns;
|
||||
}
|
||||
nk::break_stmt => return eflow::breaks;
|
||||
nk::continue_stmt => return eflow::continues;
|
||||
# A contract that fails, and an `ensures`, are left to the machine, which
|
||||
# says what failed.
|
||||
nk::contract => {
|
||||
return eflow::goes_on if this.contracts_off;
|
||||
return eflow::fails if this.clause_of(node) == clause::ensures;
|
||||
var condition := ev {};
|
||||
return eflow::fails if !this.ev_expr(this.left_of(node), &mut condition);
|
||||
return condition.scalar.magnitude != 0 ? eflow::goes_on : eflow::fails;
|
||||
}
|
||||
else => return eflow::fails;
|
||||
}
|
||||
return eflow::fails;
|
||||
}
|
||||
|
||||
#! `for i in a..b` or `a..=b`, over integers or the members of an enum, and
|
||||
#! `for x in a` over an array, by copy.
|
||||
#! @param this The checker.
|
||||
#! @param node The `for_stmt` node.
|
||||
#! @returns How it ended.
|
||||
def checker::ev_for(&mut this, node: u32): eflow {
|
||||
val variable := this.record(node, for_slot::variable);
|
||||
val iterated := this.record(node, for_slot::iterated);
|
||||
val end := this.record(node, for_slot::end);
|
||||
val index := this.record(node, for_slot::index);
|
||||
return eflow::fails if this.node_has(node, nf::reference) || this.node_has(node, nf::constant);
|
||||
|
||||
var first := ev {};
|
||||
return eflow::fails if !this.ev_expr(iterated, &mut first);
|
||||
var count: u64 = 0;
|
||||
var from := constant {};
|
||||
var members := vector::<constant>::new();
|
||||
var enumerated := false;
|
||||
if end != 0 {
|
||||
var last := ev {};
|
||||
return eflow::fails if !this.ev_expr(end, &mut last) || first.array || last.array;
|
||||
from = first.scalar;
|
||||
val inclusive := this.node_has(node, nf::inclusive);
|
||||
val kind := this.unalias(this.type_at(variable != 0 ? variable : iterated));
|
||||
enumerated = this.named_kind(kind) == dk::enum_type;
|
||||
val order := this.compare_constants(&first.scalar, &last.scalar);
|
||||
if enumerated {
|
||||
members = this.members_between(kind, &first.scalar, &last.scalar, inclusive);
|
||||
count = members.length;
|
||||
} else if order < 0 {
|
||||
var span := constant {};
|
||||
this.fold_binary(tk::minus, &last.scalar, &first.scalar, true, &mut span);
|
||||
count = span.magnitude;
|
||||
}
|
||||
# `a..=b` gives `b` too, where it gives any, the count held at the most a
|
||||
# word holds, which the evaluator's steps stop long before.
|
||||
if !enumerated && inclusive && order <= 0 {
|
||||
count = count == 0xFFFFFFFFFFFFFFFFu ? count : count + 1;
|
||||
}
|
||||
} else {
|
||||
return eflow::fails if !first.array;
|
||||
count = first.count as u64;
|
||||
}
|
||||
|
||||
for i in 0..count {
|
||||
if enumerated {
|
||||
this.ev_set_local(variable, this.ev_scalar(members[i]));
|
||||
} else if end != 0 {
|
||||
var at := constant {};
|
||||
val step := constant::integer(i, false);
|
||||
this.fold_binary(tk::plus, &from, &step, true, &mut at);
|
||||
this.ev_set_local(variable, this.ev_scalar(at));
|
||||
} else {
|
||||
this.ev_set_local(variable, this.ev_scalar(this.ev_heap[first.start as u64 + i]));
|
||||
}
|
||||
if index != 0 {
|
||||
this.ev_set_local(index, this.ev_scalar(constant::integer(i, false)));
|
||||
}
|
||||
val how := this.ev_block(this.right_of(node));
|
||||
return how if how == eflow::returns || how == eflow::fails;
|
||||
break if how == eflow::breaks;
|
||||
}
|
||||
return eflow::goes_on;
|
||||
}
|
||||
|
||||
#! The zero value of a type the evaluator holds.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns Its zero value.
|
||||
def checker::ev_zero(&mut this, kind: u32): ev {
|
||||
val plain := this.unalias(kind);
|
||||
if this.types.kind_of(plain) == ty::fixed {
|
||||
val start := this.ev_heap.length as u32;
|
||||
val count := this.types.second_of(plain);
|
||||
val element := this.types.is_float(this.unalias(this.types.first_of(plain)));
|
||||
for _ in 0..count {
|
||||
this.ev_heap.append(element ? constant::real_of(0.0) : constant {});
|
||||
}
|
||||
return ev { array = true, start = start, count = count };
|
||||
}
|
||||
return this.ev_scalar(this.types.is_float(plain) ? constant::real_of(0.0) : constant {});
|
||||
}
|
||||
@@ -0,0 +1,847 @@
|
||||
#! @file expressions.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the checking of expressions. Each is checked once, with the type
|
||||
#! expected of it where one is, which a constant, an array, or an anonymous
|
||||
#! function takes its type from, and is then converted to that type. What an
|
||||
#! expression is checked as is passed down rather than kept on the checker,
|
||||
#! so nothing has to put it back.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! Checks the expression, converting it to the type expected, where one is.
|
||||
#! @param this The checker.
|
||||
#! @param node The expression.
|
||||
#! @param expected The type expected, or the error type where none is.
|
||||
#! @returns The type it is used as: the type expected, or its own where none is.
|
||||
pub def checker::check_expr(&mut this, node: u32, expected: u32): u32 {
|
||||
return bt::error if node == 0;
|
||||
|
||||
val own := this.has_flag(node, rf::checked)
|
||||
? this.type_at(node)
|
||||
: this.expr(node, expected);
|
||||
return own if expected == bt::error;
|
||||
return this.convert(node, expected) ? expected : bt::error;
|
||||
}
|
||||
|
||||
#! Checks the expression where nothing is expected of it.
|
||||
#! @param this The checker.
|
||||
#! @param node The expression.
|
||||
#! @returns Its own type, which may be a constant's.
|
||||
pub def checker::infer_expr(&mut this, node: u32): u32 {
|
||||
return bt::error if node == 0;
|
||||
return this.type_at(node) if this.has_flag(node, rf::checked);
|
||||
return this.expr(node, bt::error);
|
||||
}
|
||||
|
||||
#! Checks the expression with a type in mind, which gives what it leaves open
|
||||
#! but is not what it is converted to, as the right of `+=` is checked before
|
||||
#! what `+` takes there is known.
|
||||
#! @param this The checker.
|
||||
#! @param node The expression.
|
||||
#! @param expected The type in mind.
|
||||
#! @returns Its own type, which may be a constant's.
|
||||
pub def checker::hinted_expr(&mut this, node: u32, expected: u32): u32 {
|
||||
return bt::error if node == 0;
|
||||
return this.type_at(node) if this.has_flag(node, rf::checked);
|
||||
return this.expr(node, expected);
|
||||
}
|
||||
|
||||
#! Checks the expression as a condition, which is a `bool`.
|
||||
#! @param this The checker.
|
||||
#! @param node The expression.
|
||||
pub def checker::check_condition(&mut this, node: u32): void {
|
||||
this.check_expr(node, bt::boolean);
|
||||
}
|
||||
|
||||
#! Checks the expression, recording and giving its own type.
|
||||
#! @param this The checker.
|
||||
#! @param node The expression.
|
||||
#! @param expected The type expected, or the error type where none is.
|
||||
#! @returns Its own type, or the error type where it is not valid.
|
||||
def checker::expr(&mut this, node: u32, expected: u32): u32 {
|
||||
this.set_flag(node, rf::checked);
|
||||
val kind := this.expr_kind(node, expected);
|
||||
this.set_type(node, kind);
|
||||
return kind;
|
||||
}
|
||||
|
||||
def checker::expr_kind(&mut this, node: u32, expected: u32): u32 {
|
||||
match this.kind_of(node) {
|
||||
nk::number => return this.number(node);
|
||||
nk::character => {
|
||||
this.set_value(node, constant::integer(this.read_character(this.text_of(node)), false));
|
||||
return bt::untyped_char;
|
||||
}
|
||||
nk::string => return bt::untyped_text;
|
||||
nk::istring => return this.interpolated(node);
|
||||
nk::boolean => {
|
||||
this.set_value(node, constant::truth(this.token_kind(node) == tk::kw_true));
|
||||
return bt::untyped_bool;
|
||||
}
|
||||
nk::null_lit => return bt::null_type;
|
||||
nk::name => return this.name_value(node, expected);
|
||||
nk::path => return this.path_value(node, expected);
|
||||
nk::unary => return this.unary(node, expected);
|
||||
nk::postfix => return this.step(node, this.left_of(node));
|
||||
nk::reference => return this.reference(node, expected);
|
||||
nk::binary => return this.binary(node, expected);
|
||||
nk::assign => return this.assign(node);
|
||||
nk::ternary => return this.ternary(node, expected);
|
||||
nk::fallback => return this.fallback(node, expected);
|
||||
nk::call => return this.call(node, expected);
|
||||
nk::index => return this.index(node);
|
||||
nk::slice => return this.slice(node);
|
||||
nk::member => return this.member(node);
|
||||
nk::member_of => return this.member_of(node);
|
||||
nk::type_args => return this.type_args_value(node);
|
||||
nk::cast => return this.cast(node);
|
||||
nk::is_test => return this.is_test(node);
|
||||
nk::construct => return this.construct(node, expected);
|
||||
nk::array => return this.array(node, expected);
|
||||
nk::lambda => return this.lambda(node, expected);
|
||||
nk::match_value => return this.match_value(node, expected);
|
||||
nk::range => return this.range_value(node, expected);
|
||||
nk::old_value => return this.old_value(node);
|
||||
nk::undefined => {
|
||||
this.report(node, ec::invalid, "`undefined` is only a local `var`'s value, which leaves its memory as it is.");
|
||||
return bt::error;
|
||||
}
|
||||
nk::error => return bt::error;
|
||||
else => {
|
||||
this.unsupported(node);
|
||||
return bt::error;
|
||||
}
|
||||
}
|
||||
return bt::error;
|
||||
}
|
||||
|
||||
#! Marks the node a place, which can be written where `writable` says.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param writable Whether the place can be written.
|
||||
pub def checker::mark_place(&mut this, node: u32, writable: bool): void {
|
||||
this.set_flag(node, rf::place);
|
||||
if writable {
|
||||
this.set_flag(node, rf::writable);
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether a node is a place: a variable, parameter, field, element, or what a
|
||||
#! reference or pointer reaches.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::is_place(&this, node: u32): bool { return this.has_flag(node, rf::place); }
|
||||
|
||||
#! Whether a node is a place that can be written.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::is_writable(&this, node: u32): bool { return this.has_flag(node, rf::writable); }
|
||||
|
||||
#! A number literal: an integer, an integer written with `u`, or a float.
|
||||
#! @param this The checker.
|
||||
#! @param node The `number` node.
|
||||
#! @returns The constant's type: an untyped integer, unsigned integer, or float.
|
||||
def checker::number(&mut this, node: u32): u32 {
|
||||
val text := this.text_of(node);
|
||||
if this.token_kind(node) == tk::float {
|
||||
this.set_value(node, constant::real_of(this.read_real(text)));
|
||||
return text[text.length - 1] == 'f' ? bt::untyped_float32 : bt::untyped_float;
|
||||
}
|
||||
|
||||
var value := constant {};
|
||||
if !this.read_integer(text, &mut value) {
|
||||
this.report(node, ec::overflow, "Integer constants fit in 64 bits.");
|
||||
return bt::error;
|
||||
}
|
||||
this.set_value(node, value);
|
||||
return this.token_kind(node) == tk::unsigned ? bt::untyped_uint : bt::untyped_int;
|
||||
}
|
||||
|
||||
#! An interpolated string, whose holes may hold anything, which builds a
|
||||
#! `string`.
|
||||
#! @param this The checker.
|
||||
#! @param node The `istring` node.
|
||||
#! @returns The `string` type.
|
||||
def checker::interpolated(&mut this, node: u32): u32 {
|
||||
val run := this.left_of(node);
|
||||
for &piece in this.run_view(run) {
|
||||
continue if this.kind_of(piece) == nk::string;
|
||||
this.settle_expr(piece);
|
||||
}
|
||||
return this.std_type(word::string, span::<u32>::empty());
|
||||
}
|
||||
|
||||
#! Checks the expression where nothing is expected of it, then settles a
|
||||
#! constant to its default type.
|
||||
#! @param this The checker.
|
||||
#! @param node The expression.
|
||||
#! @returns The type it settles as.
|
||||
pub def checker::settle_expr(&mut this, node: u32): u32 {
|
||||
val own := this.infer_expr(node);
|
||||
var settled := this.settle(own);
|
||||
# An integer constant past what an `i64` holds is a `u64`, as `1 << 63` is.
|
||||
if this.types.kind_of(own) == ty::untyped_int && this.is_known(node) {
|
||||
val held := this.value_at(node);
|
||||
if !held.floating && !held.negative && held.magnitude > 0x7FFFFFFFFFFFFFFF {
|
||||
settled = bt::uint64;
|
||||
}
|
||||
}
|
||||
if settled != own && settled != bt::error {
|
||||
this.set_convert(node, settled);
|
||||
}
|
||||
return settled;
|
||||
}
|
||||
|
||||
#! A name written as a value: a local, or a declaration.
|
||||
#! @param this The checker.
|
||||
#! @param node The `name` node.
|
||||
#! @param expected The type expected, or the error type where none is.
|
||||
#! @returns Its type, or the error type where it names nothing.
|
||||
def checker::name_value(&mut this, node: u32, expected: u32): u32 {
|
||||
val name := this.name_of(node);
|
||||
val bound := this.bound(name);
|
||||
val found := bound != 0 ? checker::found { decl = bound } : this.lookup_named(name, node, false);
|
||||
if found.decl == 0 {
|
||||
this.report_undeclared(node, name);
|
||||
return bt::error;
|
||||
}
|
||||
return this.scoped_value(node, found, expected) if found.owner != 0;
|
||||
return this.ref_value(node, found.decl, expected);
|
||||
}
|
||||
|
||||
#! The value of what a type around a name gives it, as though it were named
|
||||
#! through the type, as `zero` within `vec2` is `vec2::zero`.
|
||||
#! @param this The checker.
|
||||
#! @param node The `name` node.
|
||||
#! @param found The member and the type giving it.
|
||||
#! @param expected The type expected, or the error type where none is.
|
||||
#! @returns Its type.
|
||||
def checker::scoped_value(&mut this, node: u32, found: checker::found, expected: u32): u32 {
|
||||
val made := this.decl_value_of(node, found.decl, expected);
|
||||
# A member of a generic enum is of the enum given its arguments.
|
||||
val owner := found.owner;
|
||||
if this.decls.kinds.p[found.decl] == dk::enum_member && made != bt::error
|
||||
&& this.types.kind_of(owner) == ty::named && this.types.part_count(owner) != 0
|
||||
&& this.types.first_of(owner) == this.decls.owners.p[found.decl] {
|
||||
return owner;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The value of what a name refers to.
|
||||
#! @param this The checker.
|
||||
#! @param node The node naming it.
|
||||
#! @param ref What it refers to: a local, with `ref_local`, or a
|
||||
#! declaration.
|
||||
#! @param expected The type expected, or the error type where none is.
|
||||
#! @returns Its type.
|
||||
def checker::ref_value(&mut this, node: u32, ref: u32, expected: u32): u32 {
|
||||
this.set_ref(node, ref);
|
||||
if (ref & ref_local) != 0 {
|
||||
val local := ref & ref_mask;
|
||||
this.mark_place(node, this.has_flag(local, rf::mutable));
|
||||
if this.is_known(local) {
|
||||
this.set_value(node, this.value_at(local));
|
||||
}
|
||||
val described := this.reflected_at(local);
|
||||
if described != checker::no_reflection {
|
||||
this.reflections.set(this.result_key(node), described);
|
||||
this.set_flag(node, rf::reflected);
|
||||
}
|
||||
return this.type_at(local);
|
||||
}
|
||||
|
||||
if (ref & ref_type) != 0 {
|
||||
val kind := ref & ref_mask;
|
||||
return this.constant_ref(node, kind) if this.is_constant_arg(kind);
|
||||
this.report(node, ec::not_value, "A type is not a value.");
|
||||
return bt::error;
|
||||
}
|
||||
return this.decl_value_of(node, ref, expected);
|
||||
}
|
||||
|
||||
#! The value of a declaration named as one: a function, a variable, an enum
|
||||
#! member, or a property, whose value is its `get`.
|
||||
#! @param this The checker.
|
||||
#! @param node The node naming it.
|
||||
#! @param decl The declaration.
|
||||
#! @param expected The type expected, or the error type where none is.
|
||||
#! @returns Its type, or the error type where it is no value.
|
||||
pub def checker::decl_value_of(&mut this, node: u32, decl: u32, expected: u32): u32 {
|
||||
# A property named as a value is its `get`, a function of `&this`, as
|
||||
# `rect::area` is a `def(&rect): f32`.
|
||||
if this.decls.kinds.p[decl] == dk::property {
|
||||
val getter := this.property_getter(decl);
|
||||
return this.decl_value_of(node, getter, expected) if getter != 0;
|
||||
}
|
||||
if !this.visible(decl) && decl != this.consent {
|
||||
this.report_hidden(node, decl);
|
||||
}
|
||||
|
||||
this.set_ref(node, decl);
|
||||
match this.decls.kinds.p[decl] {
|
||||
dk::function => {
|
||||
# A generic function named as a value is the instance the function type
|
||||
# expected of it gives the type arguments of, as is a method of a generic
|
||||
# type named without them, as `result::is_ok` given for a
|
||||
# `def(&result<i64, failure>): bool`.
|
||||
if this.decls.overloads.p[decl] == 0 && decl != this.consent {
|
||||
this.resolve(decl);
|
||||
if this.decls.has(decl, df::generic) && (this.own_param_count(decl) != 0 || this.decls.owners.p[decl] != 0) {
|
||||
val made := this.function_instance(node, decl, expected, bt::error);
|
||||
return made if made != bt::error;
|
||||
}
|
||||
}
|
||||
# Where C's address of a function is expected, the function is chosen by
|
||||
# the type C calls it with.
|
||||
val plain_expected := this.unalias(expected);
|
||||
val c_expected := this.is_std(plain_expected, word::cfn) && this.types.part_count(plain_expected) == 1
|
||||
? this.types.part_at(plain_expected, 0)
|
||||
: 0;
|
||||
val chosen := this.function_value(node, decl, c_expected != 0 ? c_expected : expected);
|
||||
this.set_ref(node, chosen);
|
||||
return bt::error if chosen == 0;
|
||||
# An overload of a generic type's member is the instance chosen.
|
||||
if chosen != decl || this.decls.overloads.p[decl] != 0 {
|
||||
if this.decls.has(chosen, df::generic) && this.own_param_count(chosen) == 0 && this.decls.owners.p[chosen] != 0 {
|
||||
val made := this.function_instance(node, chosen, expected, bt::error);
|
||||
return made if made != bt::error;
|
||||
}
|
||||
}
|
||||
# A C function is taken as its address, which is what C calls, and a
|
||||
# function of the program given where C's address is expected gets an
|
||||
# entry C calls it back through.
|
||||
val c_given := this.decls.has(chosen, df::foreign);
|
||||
if (c_given || c_expected != 0) && this.std_decl(word::cfn) != 0 {
|
||||
if !c_given {
|
||||
this.check_callback(node, chosen);
|
||||
this.decls.mark(chosen, df::callback);
|
||||
}
|
||||
var parts: u32[1] = [this.decls.types.p[chosen]];
|
||||
return this.types.named(this.std_decl(word::cfn), parts[:]);
|
||||
}
|
||||
return this.decls.types.p[chosen];
|
||||
}
|
||||
dk::variable => {
|
||||
this.resolve(decl);
|
||||
val writes := this.decls.has(decl, df::mutable) && !this.decls.has(decl, df::constant);
|
||||
this.mark_place(node, writes);
|
||||
var value := constant {};
|
||||
if this.decl_value(decl, &mut value) {
|
||||
this.set_value(node, value);
|
||||
}
|
||||
return this.decls.types.p[decl];
|
||||
}
|
||||
dk::enum_member => {
|
||||
this.resolve(decl);
|
||||
var value := constant {};
|
||||
if this.decl_value(decl, &mut value) {
|
||||
this.set_value(node, value);
|
||||
}
|
||||
return this.decls.types.p[decl];
|
||||
}
|
||||
dk::attribute => return this.decls.types.p[decl];
|
||||
else => {
|
||||
var text := string::from("`", nothing {});
|
||||
text.append(this.decl_text(decl));
|
||||
val word := this.decl_word(decl);
|
||||
text.append(word[0] == 'e' ? "` is an " : "` is a ");
|
||||
text.append(word);
|
||||
text.append(", not a value.");
|
||||
this.report_text(node, ec::not_value, &text);
|
||||
return bt::error;
|
||||
}
|
||||
}
|
||||
return bt::error;
|
||||
}
|
||||
|
||||
#! The type of the instance of a generic function the function type expected of
|
||||
#! it gives the type arguments of, as `val f: def(i64): i64 = id;` makes
|
||||
#! `id<i64>`, or the error type where it gives them not all.
|
||||
#! @param this The checker.
|
||||
#! @param node The node naming it.
|
||||
#! @param decl The generic function.
|
||||
#! @param expected The type expected, or the error type where none is.
|
||||
#! @param owner The type it is a member of, given its arguments, which are
|
||||
#! its first, or the error type.
|
||||
#! @returns The instance's function type, or the error type.
|
||||
def checker::function_instance(&mut this, node: u32, decl: u32, expected: u32, owner: u32): u32 {
|
||||
var inferred := this.begin_inference(decl, owner, span::<u32>::empty());
|
||||
val made := this.instance_type(decl, expected, &mut inferred);
|
||||
return bt::error if made == bt::error;
|
||||
val instance := this.instance_of(decl, inferred.binds.view(), node);
|
||||
if instance != 0 {
|
||||
this.called.set(this.result_key(node), instance);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The function type of the instance of a generic function the function type
|
||||
#! expected of it gives the type arguments of, without making the instance, or
|
||||
#! the error type. Its parameters are given those of the type expected, as many
|
||||
#! as it has, so those it leaves to their defaults give nothing.
|
||||
#! @param this The checker.
|
||||
#! @param decl The generic function.
|
||||
#! @param expected The type expected.
|
||||
#! @param inferred What is inferred, which this adds to.
|
||||
#! @returns The instance's function type, or the error type.
|
||||
def checker::instance_type(&mut this, decl: u32, expected: u32, inferred: &mut checker::inferred): u32 {
|
||||
val wanted := this.unalias(expected);
|
||||
return bt::error if this.types.kind_of(wanted) != ty::function;
|
||||
val kind: u32 = this.decls.types.p[decl];
|
||||
val count := this.types.part_count(kind) < this.types.part_count(wanted)
|
||||
? this.types.part_count(kind) : this.types.part_count(wanted);
|
||||
for i in 0..count {
|
||||
this.unify(this.types.part_at(kind, i as u32), this.types.part_at(wanted, i as u32), inferred, 0);
|
||||
}
|
||||
# A result the call around it is still inferring, as `U` of `map`'s, is what
|
||||
# the function gives once its parameters' types give its arguments.
|
||||
if !this.free_result {
|
||||
this.unify(this.types.first_of(kind), this.types.first_of(wanted), inferred, 0);
|
||||
}
|
||||
return bt::error if this.unbound(inferred) != 0;
|
||||
return this.apply(kind, inferred);
|
||||
}
|
||||
|
||||
#! The overload a function named as a value is: the only one, or the one whose
|
||||
#! type is the function type expected.
|
||||
#! @param this The checker.
|
||||
#! @param node The node naming it.
|
||||
#! @param first The first of its overloads.
|
||||
#! @param expected The type expected, or the error type where none is.
|
||||
#! @returns The overload's function type, or the error type where none is
|
||||
#! chosen.
|
||||
def checker::function_value(&mut this, node: u32, first: u32, expected: u32): u32 {
|
||||
if this.decls.overloads.p[first] == 0 {
|
||||
this.resolve(first);
|
||||
if this.decls.has(first, df::generic) && this.own_param_count(first) != 0 {
|
||||
# A generic function is a value once given its type arguments, which
|
||||
# reflection, reaching it as it is, reports in its own words.
|
||||
if first != this.consent {
|
||||
this.report(node, ec::generic, "A generic function is a value once given its type arguments, as `max::<i64>`.");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
return first;
|
||||
}
|
||||
|
||||
var walk := this.decls.walk_overloads(first);
|
||||
while true {
|
||||
val at := walk.next();
|
||||
break if at == 0;
|
||||
this.resolve(at);
|
||||
return at if this.decls.types.p[at] == expected;
|
||||
}
|
||||
|
||||
# Where none is of that type, the one a call with its parameters would choose
|
||||
# is, called as the type asks: a member of a generic type as the instance the
|
||||
# type gives its arguments.
|
||||
if this.types.kind_of(this.unalias(expected)) == ty::function {
|
||||
var best: u32 = 0;
|
||||
var least: i32 = -1;
|
||||
var tied := false;
|
||||
var each := this.decls.walk_overloads(first);
|
||||
while true {
|
||||
val at := each.next();
|
||||
break if at == 0;
|
||||
continue if this.decls.has(at, df::generic) && this.own_param_count(at) != 0;
|
||||
var kind: u32 = this.decls.types.p[at];
|
||||
if this.decls.has(at, df::generic) {
|
||||
var inferred := this.begin_inference(at, bt::error, span::<u32>::empty());
|
||||
kind = this.instance_type(at, expected, &mut inferred);
|
||||
continue if kind == bt::error;
|
||||
if kind == expected {
|
||||
return at;
|
||||
}
|
||||
}
|
||||
val cost := this.adapt_cost(at, kind, expected);
|
||||
continue if cost < 0;
|
||||
if least < 0 || cost < least {
|
||||
best = at;
|
||||
least = cost;
|
||||
tied = false;
|
||||
} else if cost == least {
|
||||
tied = true;
|
||||
}
|
||||
}
|
||||
return best if best != 0 && !tied;
|
||||
}
|
||||
|
||||
this.report(node, ec::ambiguous, "The function is overloaded, so it is a value only where the type of one of them is expected, or one a call as that type asks chooses.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! What a path names: a module, a type, or a declaration, in order of its
|
||||
#! segments.
|
||||
pub struct checker::named {
|
||||
var decl: u32; #! The declaration named, or 0.
|
||||
var kind: u32; #! The type named, where it names one.
|
||||
pub var owner: u32; #! The type a member is of, as `box<i64>` of `box::<i64>::new`.
|
||||
}
|
||||
|
||||
#! What the segments of a path, from the first, name. A local or parameter
|
||||
#! never hides a type or module there.
|
||||
#! @param this The checker.
|
||||
#! @param node The `path` or `type_name` node.
|
||||
#! @returns The declaration or type named, and the type a member is of.
|
||||
pub def checker::path_target(&mut this, node: u32): checker::named {
|
||||
var made := checker::named {};
|
||||
var home: u32 = 0;
|
||||
var in_module := false;
|
||||
# A generic type named without type arguments before a function lets the call
|
||||
# infer them, as `box::new(5)` does.
|
||||
var open := false;
|
||||
val count := this.segment_count(node);
|
||||
for i in 0..count {
|
||||
val name := this.segment_name(node, i as u32);
|
||||
val segment := this.segment_node(node, i as u32);
|
||||
if i == 0 {
|
||||
val bound := this.bound(name);
|
||||
if (bound & ref_type) != 0 {
|
||||
made.kind = bound & ref_mask;
|
||||
made.decl = this.type_decl(made.kind);
|
||||
if segment != node {
|
||||
this.set_ref(segment, bound);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
# A module the first of several segments names comes before a declaration of
|
||||
# the name, as `serial::encode` names the module where `serial` is also the
|
||||
# attribute it declares.
|
||||
if count > 1 {
|
||||
home = this.lookup_module(name);
|
||||
if home != 0 {
|
||||
in_module = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
# What a type around it gives is reached through that type, as `kind::word`
|
||||
# within `token` is `token::kind::word`.
|
||||
val found := this.lookup_named(name, segment, count > 1);
|
||||
made.decl = found.decl;
|
||||
if found.owner != 0 {
|
||||
made.owner = found.owner;
|
||||
}
|
||||
if made.decl == 0 {
|
||||
home = this.lookup_module(name);
|
||||
in_module = home != 0;
|
||||
if !in_module {
|
||||
this.report_undeclared(segment, name);
|
||||
return checker::named {};
|
||||
}
|
||||
continue;
|
||||
}
|
||||
} else if in_module {
|
||||
made.decl = this.modules.decl(home, name);
|
||||
if made.decl == 0 {
|
||||
home = this.modules.find(home, name);
|
||||
if home == 0 {
|
||||
var text := string::from("The module declares no `", nothing {});
|
||||
text.append(this.names.text(name));
|
||||
text.append("`.");
|
||||
this.report_text(segment, ec::undefined, &text);
|
||||
return checker::named {};
|
||||
}
|
||||
continue;
|
||||
}
|
||||
in_module = false;
|
||||
} else {
|
||||
# A type a bound asks of a type parameter given a type, as `F::result` where
|
||||
# `F: signature` is given a function type, is the one the type gives.
|
||||
if i == 1 && made.kind != bt::error {
|
||||
val param := this.param_named(this.segment_name(node, 0));
|
||||
val asked := param != 0 ? this.asked_of_bounds(made.kind, param, name) : bt::error;
|
||||
if asked != bt::error {
|
||||
made.kind = asked;
|
||||
made.decl = this.type_decl(asked);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
val owner := made.decl;
|
||||
if !this.is_type_decl(owner) {
|
||||
this.report(segment, ec::member, "Only a module or a type has members named with `::`.");
|
||||
return checker::named {};
|
||||
}
|
||||
|
||||
made.owner = made.kind != bt::error ? made.kind : this.decls.types.p[owner];
|
||||
val found := this.find_path_member(made.owner, name);
|
||||
# A trait's static methods and constants belong to the types implementing
|
||||
# it, which the trait's own name does not say.
|
||||
if found.decl != 0 && this.trait_asks(found.decl) && this.named_kind(this.unalias(made.owner)) == dk::trait_type {
|
||||
val kind_of: dk = this.decls.kinds.p[found.decl];
|
||||
if kind_of == dk::variable || (kind_of == dk::function && !this.decls.has(found.decl, df::method)) {
|
||||
this.report(segment, ec::invalid, kind_of == dk::variable
|
||||
? "A constant of a trait belongs to the types implementing it, so read it through a type parameter the trait bounds, as `T::name`."
|
||||
: "A static method of a trait belongs to the types implementing it, so call it through a type parameter the trait bounds, as `T::name()`.");
|
||||
return checker::named {};
|
||||
}
|
||||
}
|
||||
made.decl = found.decl;
|
||||
if found.decl != 0 && this.types.kind_of(found.owner) == ty::named
|
||||
&& this.decls.kinds.p[this.types.first_of(found.owner)] != dk::trait_type {
|
||||
made.owner = found.owner;
|
||||
}
|
||||
made.kind = bt::error;
|
||||
if open && made.decl != 0 && (this.decls.kinds.p[made.decl] == dk::function || this.decls.kinds.p[made.decl] == dk::property) {
|
||||
made.owner = bt::error;
|
||||
}
|
||||
if made.decl == 0 {
|
||||
var text := string::from("`", nothing {});
|
||||
val owner_text := this.describe(made.owner);
|
||||
text.append(owner_text.view());
|
||||
text.append("` has no member `");
|
||||
text.append(this.names.text(name));
|
||||
text.append("`.");
|
||||
this.report_text(segment, ec::member, &text);
|
||||
return checker::named {};
|
||||
}
|
||||
}
|
||||
|
||||
if !this.visible(made.decl) {
|
||||
this.report_hidden(segment, made.decl);
|
||||
}
|
||||
# What each segment names is kept for the editor, which shows it and finds
|
||||
# where it is declared.
|
||||
if segment != node {
|
||||
this.set_ref(segment, made.decl);
|
||||
}
|
||||
|
||||
# A type named along the path takes the type arguments its segment gives.
|
||||
if this.is_type_decl(made.decl) && i + 1 < count {
|
||||
var args := vector::<u32>::new();
|
||||
if made.owner != bt::error && this.types.kind_of(made.owner) == ty::named {
|
||||
args.extend(this.types.parts_view(made.owner));
|
||||
}
|
||||
val run := this.segment_args(node, i as u32);
|
||||
for &arg in this.run_view(run) {
|
||||
args.append(this.type_arg_of(arg, made.decl, args.length as u32, args.view()));
|
||||
}
|
||||
open = this.decls.kinds.p[made.decl] != dk::builtin && args.length == 0 && this.decls.params.p[made.decl] != 0
|
||||
&& this.at.decl != made.decl;
|
||||
made.kind = this.decls.kinds.p[made.decl] == dk::builtin || args.length != 0 || this.decls.params.p[made.decl] == 0
|
||||
? this.named_of(made.decl, args.view(), segment)
|
||||
: this.decls.types.p[made.decl];
|
||||
}
|
||||
}
|
||||
|
||||
if in_module {
|
||||
this.report(node, ec::not_value, "A module is not a value.");
|
||||
return checker::named {};
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A path written as a value, as `color::red` or `vec2::zero`.
|
||||
#! @param this The checker.
|
||||
#! @param node The `path` node.
|
||||
#! @param expected The type expected, or the error type where none is.
|
||||
#! @returns Its type, or the error type where it names nothing.
|
||||
def checker::path_value(&mut this, node: u32, expected: u32): u32 {
|
||||
val target := this.path_target(node);
|
||||
return bt::error if target.decl == 0;
|
||||
|
||||
# A generic function given its type arguments, as `max::<f32>`, is the
|
||||
# instance they make.
|
||||
if this.decls.kinds.p[target.decl] == dk::function && this.decls.overloads.p[target.decl] == 0 {
|
||||
this.resolve(target.decl);
|
||||
val written := this.segment_args(node, this.segment_count(node) - 1);
|
||||
if written != 0 && this.decls.has(target.decl, df::generic) && this.own_param_count(target.decl) != 0 {
|
||||
# A method of a generic type takes the type's arguments before its own, as
|
||||
# `pair::<K, V>::make::<U>` does.
|
||||
var args := vector::<u32>::new();
|
||||
if target.owner != bt::error && this.types.kind_of(target.owner) == ty::named {
|
||||
args.extend(this.types.parts_view(target.owner));
|
||||
}
|
||||
args.extend(this.written_args(target.decl, target.owner, written).view());
|
||||
val instance := this.instance_of(target.decl, args.view(), node);
|
||||
if instance != 0 {
|
||||
this.set_ref(node, target.decl);
|
||||
this.called.set(this.result_key(node), instance);
|
||||
return this.instances[instance - 1].kind;
|
||||
}
|
||||
# Within a generic, type arguments naming its own parameters make an
|
||||
# instance only once it is compiled for its own arguments.
|
||||
var from := this.decls.list_of(this.decls.params.p[target.decl]);
|
||||
if this.any_open(args.view()) && args.length == from.length {
|
||||
this.set_ref(node, target.decl);
|
||||
return this.substitute(this.decls.types.p[target.decl], from.view(), args.view());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# A property of a type given its arguments is its `get`, as a method is.
|
||||
var member := target.decl;
|
||||
if this.decls.kinds.p[member] == dk::property && target.owner != bt::error {
|
||||
member = this.property_getter(member);
|
||||
if member != 0 && !this.visible(member) {
|
||||
this.report_hidden(node, member);
|
||||
}
|
||||
}
|
||||
if member != 0 && this.decls.kinds.p[member] == dk::function && target.owner != bt::error {
|
||||
this.set_ref(node, member);
|
||||
this.resolve(member);
|
||||
# A generic function of a type, named without its own type arguments, as
|
||||
# `integer::parse`, is the instance the function type expected gives them.
|
||||
if this.decls.overloads.p[member] == 0 && this.own_param_count(member) != 0 {
|
||||
val made := this.function_instance(node, member, expected, target.owner);
|
||||
return made if made != bt::error;
|
||||
this.report(node, ec::generic,
|
||||
"A generic function is a value once given its type arguments, and the function type expected doesn't give them all: write them, as `max::<i64>`.");
|
||||
return bt::error;
|
||||
}
|
||||
return this.member_function_type(member, target.owner);
|
||||
}
|
||||
val made := this.decl_value_of(node, target.decl, expected);
|
||||
# A member of a generic enum is of the enum given the arguments its path
|
||||
# gives, as `bag::<T>::state::full` is a `bag<T>::state`.
|
||||
if this.decls.kinds.p[target.decl] == dk::enum_member && made != bt::error
|
||||
&& this.types.kind_of(target.owner) == ty::named && this.types.part_count(target.owner) != 0
|
||||
&& this.types.first_of(target.owner) == this.decls.owners.p[target.decl] {
|
||||
return target.owner;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The type of a function declared through a type, given the type's arguments.
|
||||
#! @param this The checker.
|
||||
#! @param decl The function's declaration.
|
||||
#! @param owner The type, given its arguments.
|
||||
#! @returns The function's type.
|
||||
pub def checker::member_function_type(&mut this, decl: u32, owner: u32): u32 {
|
||||
this.resolve(decl);
|
||||
val kind: u32 = this.decls.types.p[decl];
|
||||
return kind if this.types.kind_of(owner) != ty::named || this.types.part_count(owner) == 0;
|
||||
|
||||
var from := vector::<u32>::new();
|
||||
val run: u32 = this.decls.params.p[decl];
|
||||
val count := this.types.part_count(owner);
|
||||
for i in 0..count {
|
||||
break if i >= this.decls.list_length(run);
|
||||
from.append(this.decls.list_at(run, i as u32));
|
||||
}
|
||||
val args := this.types.parts_of(owner);
|
||||
return this.substitute(kind, from.view(), args.view());
|
||||
}
|
||||
|
||||
#! A value given type arguments after it, as `value_of(d)::<i64>`: the instance
|
||||
#! of the generic function a description names that they make.
|
||||
#! @param this The checker.
|
||||
#! @param node The `type_args` node.
|
||||
#! @returns The instance's function type, or the error type.
|
||||
def checker::type_args_value(&mut this, node: u32): u32 {
|
||||
val callee := this.left_of(node);
|
||||
var decl: u32 = 0;
|
||||
if this.kind_of(callee) == nk::call && this.kind_of(this.left_of(callee)) == nk::name {
|
||||
val named := this.lookup(this.name_of(this.left_of(callee)), this.left_of(callee));
|
||||
val run := this.right_of(callee);
|
||||
if named != 0 && (named & (ref_local | ref_type)) == 0 && this.decls.kinds.p[named] == dk::function
|
||||
&& this.is_reflection(named) && this.names.text(this.decls.names.p[named]) == "value_of"
|
||||
&& this.run_length(run) == 1 {
|
||||
val arg := this.run_at(run, 0);
|
||||
this.infer_expr(arg);
|
||||
val one := this.described_arg(arg, "`value_of`");
|
||||
return bt::error if one == checker::no_reflection;
|
||||
val held: desc = this.descs[one];
|
||||
decl = held.param == 0 ? held.decl : 0;
|
||||
}
|
||||
}
|
||||
if decl == 0 || this.decls.kinds.p[decl] != dk::function || this.decls.overloads.p[decl] != 0 {
|
||||
this.report(node, ec::generic, "Type arguments are given after a value only to `value_of` of a generic function, as `value_of(d)::<i64>`.");
|
||||
return bt::error;
|
||||
}
|
||||
|
||||
this.resolve(decl);
|
||||
if !this.decls.has(decl, df::generic) || this.own_param_count(decl) == 0 {
|
||||
this.report(node, ec::generic, "The function takes no type arguments.");
|
||||
return bt::error;
|
||||
}
|
||||
var args := this.written_args(decl, bt::error, this.right_of(node));
|
||||
val instance := this.instance_of(decl, args.view(), node);
|
||||
return bt::error if instance == 0;
|
||||
this.set_ref(node, decl);
|
||||
this.called.set(this.result_key(node), instance);
|
||||
return this.instances[instance - 1].kind;
|
||||
}
|
||||
|
||||
#! `x.(d)`, the member of `x` a description known while compiling describes, as
|
||||
#! though its name were written there: a field, or a property. A method it
|
||||
#! names is called, which the call checks.
|
||||
#! @param this The checker.
|
||||
#! @param node The `member_of` node.
|
||||
#! @returns The member's type, or the error type.
|
||||
def checker::member_of(&mut this, node: u32): u32 {
|
||||
val object := this.left_of(node);
|
||||
val kind := this.infer_expr(object);
|
||||
val found := this.described_member(node, kind);
|
||||
return bt::error if found.decl == 0;
|
||||
|
||||
this.set_ref(node, found.decl);
|
||||
this.resolve(found.decl);
|
||||
match this.decls.kinds.p[found.decl] {
|
||||
dk::field => {
|
||||
this.mark_place(node, this.reaches_writable(kind, object) && this.decls.has(found.decl, df::mutable));
|
||||
return this.instantiated(this.decls.types.p[found.decl], this.types.first_of(found.owner), found.owner);
|
||||
}
|
||||
dk::property => {
|
||||
val property: u32 = this.decls.types.p[found.decl];
|
||||
val held := this.types.kind_of(found.owner) == ty::named
|
||||
? this.instantiated(property, found.decl, found.owner)
|
||||
: property;
|
||||
if this.property_setter(found.decl) != 0 && this.reaches_writable(kind, object) {
|
||||
this.set_flag(node, rf::writable);
|
||||
}
|
||||
this.want_accessor(this.property_getter(found.decl), found.owner, node);
|
||||
return held;
|
||||
}
|
||||
dk::function => {
|
||||
this.report(node, ec::not_value, "A method is called, as `x.(d)()`; take it through its type for its value.");
|
||||
return bt::error;
|
||||
}
|
||||
else => {
|
||||
this.unsupported(node);
|
||||
return bt::error;
|
||||
}
|
||||
}
|
||||
return bt::error;
|
||||
}
|
||||
|
||||
#! The member of a value that `x.(d)` names: the declaration `d` describes,
|
||||
#! where it is a member of the value's type.
|
||||
#! @param this The checker.
|
||||
#! @param node The `member_of` node.
|
||||
#! @param kind The type of the value.
|
||||
#! @returns The member and the type it is of, or no member where it names none.
|
||||
def checker::described_member(&mut this, node: u32, kind: u32): checker::found {
|
||||
val named := this.right_of(node);
|
||||
this.infer_expr(named);
|
||||
return checker::found {} if kind == bt::error || this.type_at(named) == bt::error;
|
||||
val one := this.reflected_one(named);
|
||||
if one == checker::no_reflection {
|
||||
if !this.waits_for_instance() {
|
||||
this.report(named, ec::constant, "A member written `x.(d)` takes a declaration known while compiling, as the variable of `for const d in declarations()` is.");
|
||||
}
|
||||
return checker::found {};
|
||||
}
|
||||
|
||||
# Any overload of the name is the member it names.
|
||||
val held: desc = this.descs[one];
|
||||
val found := held.param != 0 ? checker::found {} : this.find_member(this.reached(kind), this.decls.names.p[held.decl]);
|
||||
var walk := this.decls.walk_overloads(found.decl);
|
||||
var at := walk.next();
|
||||
while at != 0 && at != held.decl {
|
||||
at = this.decls.kinds.p[at] == dk::function ? walk.next() : 0;
|
||||
}
|
||||
if at == 0 {
|
||||
this.report(node, ec::member, "`x.(d)` names a member of `x`, and `d` describes none of it.");
|
||||
return checker::found {};
|
||||
}
|
||||
return checker::found { decl = held.decl, owner = found.owner };
|
||||
}
|
||||
@@ -0,0 +1,738 @@
|
||||
#! @file generics.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains generics: inferring the type arguments of a call from what it is
|
||||
#! given, and the instances of generic functions. A generic's body is checked
|
||||
#! once against its bounds, then again for each instance the program uses,
|
||||
#! over the template's own nodes with a result table of the instance's, so the
|
||||
#! template is never copied. An instance is made where a call gives a generic
|
||||
#! types holding no type parameter, and its body is checked once every
|
||||
#! declaration has been.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! What inferring type arguments works out: the type of each parameter of the
|
||||
#! declaration, its owner's first, and whether each was only suggested by a
|
||||
#! constant, which a typed value given for it overrules.
|
||||
pub struct checker::inferred {
|
||||
var params: vector<u32>; #! The declarations of the type parameters.
|
||||
var binds: vector<u32>; #! The type of each, or `unknown_type` where nothing gave it yet.
|
||||
var soft: vector<bool>; #! Whether each was only suggested by a constant.
|
||||
var outer: vector<u32>; #! The parameters a trait's default names beside its own: the trait's, and `self`.
|
||||
var given: vector<u32>; #! The type each of those is given by the value it is called on.
|
||||
}
|
||||
|
||||
#! Begins inferring the declaration's type arguments, with those of its owner
|
||||
#! and those written given.
|
||||
#! @param this The checker.
|
||||
#! @param decl The generic declaration.
|
||||
#! @param owner The type it is a member of, given its arguments, or the
|
||||
#! error type.
|
||||
#! @param written The type arguments written for its own parameters.
|
||||
#! @returns What is known so far.
|
||||
pub def checker::begin_inference(&mut this, decl: u32, owner: u32, written: span<u32>): checker::inferred {
|
||||
var made := checker::inferred {
|
||||
params = vector::<u32>::new(),
|
||||
binds = vector::<u32>::new(),
|
||||
soft = vector::<bool>::new(),
|
||||
outer = vector::<u32>::new(),
|
||||
given = vector::<u32>::new()
|
||||
};
|
||||
|
||||
val params := this.decls.list_view(this.decls.params.p[decl]);
|
||||
made.params.extend(params);
|
||||
made.binds.resize(params.length, checker::unknown_type);
|
||||
made.soft.resize(params.length, false);
|
||||
|
||||
var at: u64 = 0;
|
||||
if owner != bt::error && this.types.kind_of(owner) == ty::named {
|
||||
for &part in this.types.parts_view(owner) {
|
||||
break if at >= made.binds.length;
|
||||
made.binds[at] = part;
|
||||
at++;
|
||||
}
|
||||
}
|
||||
# Written type arguments fill a pack with whatever the parameters before it
|
||||
# leave, as `show_all::<i64, bool>`.
|
||||
for i in 0..written.length {
|
||||
break if at >= made.binds.length;
|
||||
val param := made.params[at];
|
||||
if this.decls.has(param, df::packed) {
|
||||
made.binds[at] = this.gather_pack(written, i, 0);
|
||||
break;
|
||||
}
|
||||
made.binds[at] = written[i];
|
||||
at++;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Binds a pack parameter to the types of the arguments a call gives it from
|
||||
#! `from` on, each spread pack already its own types.
|
||||
#! @param this The checker.
|
||||
#! @param pack The pack parameter's type.
|
||||
#! @param slots The types of the call's arguments.
|
||||
#! @param from The first argument the pack takes.
|
||||
#! @param into What is inferred, which the pack's types are written to.
|
||||
pub def checker::bind_pack(&mut this, pack: u32, slots: span<u32>, from: u64, into: &mut checker::inferred): void {
|
||||
var types := vector::<u32>::new();
|
||||
for i in from..slots.length {
|
||||
types.append(slots[i] == 0 ? bt::error : this.settle(slots[i]));
|
||||
}
|
||||
|
||||
val decl := this.types.first_of(pack);
|
||||
for i in 0..into.params.length {
|
||||
if into.params[i] == decl && (into.binds[i] == checker::unknown_type || into.soft[i]) {
|
||||
into.binds[i] = this.types.pack(types.view(), 0);
|
||||
into.soft[i] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Infers type parameters a type holds from the type given where it is
|
||||
#! expected, as `T` of `&T` from a `&i64`.
|
||||
#! @param this The checker.
|
||||
#! @param pattern The type written, holding the parameters.
|
||||
#! @param actual The type given.
|
||||
#! @param into What is inferred.
|
||||
#! @param depth How deeply the search has gone, which stops a type nesting
|
||||
#! without end.
|
||||
pub def checker::unify(&mut this, pattern: u32, actual: u32, into: &mut checker::inferred, depth: u32): void {
|
||||
return if depth > 16 || !this.types.is_open(pattern) || actual == bt::error;
|
||||
|
||||
# A reference is read through to what it refers to wherever a type that is no
|
||||
# reference is wanted, so `through(r)` takes the pointer `r` refers to.
|
||||
val shape := this.types.kind_of(pattern);
|
||||
if shape != ty::param && shape != ty::pack && shape != ty::reference {
|
||||
actual = this.reached(actual);
|
||||
}
|
||||
|
||||
match shape {
|
||||
ty::param => {
|
||||
val decl := this.types.first_of(pattern);
|
||||
# A constant parameter is given a constant, and a type parameter a type.
|
||||
val given := this.types.kind_of(actual);
|
||||
val constant := given == ty::value || (given == ty::param && this.decls.has(this.types.first_of(actual), df::valued));
|
||||
return if this.decls.has(decl, df::valued) != constant;
|
||||
for i in 0..into.params.length {
|
||||
continue if into.params[i] != decl;
|
||||
|
||||
if this.types.is_untyped(actual) {
|
||||
if into.binds[i] == checker::unknown_type {
|
||||
into.binds[i] = this.settle(actual);
|
||||
into.soft[i] = true;
|
||||
} else if into.soft[i] && this.types.is_float(actual) && !this.types.is_float(into.binds[i]) {
|
||||
# An integer constant and a float constant share the float.
|
||||
into.binds[i] = this.settle(actual);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if into.binds[i] == checker::unknown_type || into.soft[i] {
|
||||
into.binds[i] = actual;
|
||||
into.soft[i] = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
ty::reference, ty::pointer => {
|
||||
val plain := this.unalias(actual);
|
||||
if this.types.kind_of(plain) == this.types.kind_of(pattern) {
|
||||
this.unify(this.types.first_of(pattern), this.types.first_of(plain), into, depth + 1);
|
||||
} else if this.types.kind_of(pattern) == ty::reference {
|
||||
this.unify(this.types.first_of(pattern), actual, into, depth + 1);
|
||||
}
|
||||
}
|
||||
ty::fixed => {
|
||||
val plain := this.unalias(this.reached_value(actual));
|
||||
if this.types.kind_of(plain) == ty::fixed {
|
||||
this.unify(this.types.first_of(pattern), this.types.first_of(plain), into, depth + 1);
|
||||
# A length that is a constant parameter is given the length of the array.
|
||||
if this.types.part_count(pattern) != 0 {
|
||||
val length := this.types.part_at(pattern, 0);
|
||||
if this.types.part_count(plain) != 0 {
|
||||
this.unify(length, this.types.part_at(plain, 0), into, depth + 1);
|
||||
} else if this.types.kind_of(length) == ty::param && this.decls.has(this.types.first_of(length), df::valued) {
|
||||
val of := this.constant_type(length);
|
||||
val tkd := this.types.kind_of(this.unalias(of));
|
||||
if tkd == ty::signed || tkd == ty::unsigned {
|
||||
val count := this.known_number(constant::integer(this.types.second_of(plain) as u64, false), of);
|
||||
this.unify(length, this.known_type(count), into, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ty::function => {
|
||||
val plain := this.unalias(actual);
|
||||
return if this.types.kind_of(plain) != ty::function;
|
||||
# A pack among the parameters, as `Ts` of `def(Ts...): R`, takes the types of
|
||||
# those after the ones before it, and is variadic where the function is.
|
||||
val count := this.types.part_count(pattern);
|
||||
val given := this.types.part_count(plain);
|
||||
if this.types.second_of(pattern) != 0 && count != 0 && this.types.is_open_pack(this.types.part_at(pattern, count - 1)) {
|
||||
return if given + 1 < count;
|
||||
for i in 0..count - 1 {
|
||||
this.unify(this.types.part_at(pattern, i as u32), this.types.part_at(plain, i as u32), into, depth + 1);
|
||||
}
|
||||
this.bind_param(this.types.first_of(this.types.part_at(pattern, count - 1)), this.types.params_pack(plain, count - 1), into);
|
||||
this.unify(this.types.first_of(pattern), this.types.first_of(plain), into, depth + 1);
|
||||
return;
|
||||
}
|
||||
if given == count {
|
||||
for i in 0..count {
|
||||
this.unify(this.types.part_at(pattern, i as u32), this.types.part_at(plain, i as u32), into, depth + 1);
|
||||
}
|
||||
this.unify(this.types.first_of(pattern), this.types.first_of(plain), into, depth + 1);
|
||||
}
|
||||
}
|
||||
# A pack whose types are not known takes those of the pack given.
|
||||
ty::pack => {
|
||||
if this.types.is_open_pack(pattern) && this.types.kind_of(actual) == ty::pack {
|
||||
this.bind_param(this.types.first_of(pattern), actual, into);
|
||||
} else if !this.types.is_open_pack(pattern) && this.types.kind_of(actual) == ty::pack
|
||||
&& this.types.part_count(actual) == this.types.part_count(pattern) {
|
||||
for i in 0..this.types.part_count(pattern) {
|
||||
this.unify(this.types.part_at(pattern, i as u32), this.types.part_at(actual, i as u32), into, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
ty::named => {
|
||||
var plain := this.reached_value(actual);
|
||||
if this.types.kind_of(plain) == ty::named && this.types.first_of(plain) != this.types.first_of(pattern) {
|
||||
plain = this.unalias(plain);
|
||||
}
|
||||
# A value of a type implementing a generic trait gives its parameters
|
||||
# through what implements the trait's members.
|
||||
val wanted := this.types.first_of(pattern);
|
||||
if this.decls.kinds.p[wanted] == dk::trait_type && this.named_kind(plain) != dk::trait_type
|
||||
&& this.types.kind_of(plain) != ty::param {
|
||||
this.unify_named(pattern, plain, into, depth);
|
||||
this.unify_members(pattern, plain, into, depth);
|
||||
return;
|
||||
}
|
||||
if this.types.kind_of(plain) == ty::named && this.types.first_of(plain) == this.types.first_of(pattern) {
|
||||
for i in 0..this.types.part_count(pattern) {
|
||||
break if i >= this.types.part_count(plain);
|
||||
this.unify(this.types.part_at(pattern, i as u32), this.types.part_at(plain, i as u32), into, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
}
|
||||
|
||||
#! Gives a type parameter, or a pack, the type inferred for it, where nothing
|
||||
#! but a constant has given it one yet.
|
||||
#! @param this The checker.
|
||||
#! @param decl The parameter's declaration.
|
||||
#! @param given The type it is given.
|
||||
#! @param into What is inferred.
|
||||
def checker::bind_param(&mut this, decl: u32, given: u32, into: &mut checker::inferred): void {
|
||||
for i in 0..into.params.length {
|
||||
continue if into.params[i] != decl;
|
||||
if into.binds[i] == checker::unknown_type || into.soft[i] {
|
||||
into.binds[i] = given;
|
||||
into.soft[i] = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
#! Infers type parameters a generic trait holds from a type naming it, as the
|
||||
#! type names it: `x : into<int>` gives the `T` of `into<T>` as `int`. A
|
||||
#! member's types may be what the trait's arguments ask for, as `F::arg`, which
|
||||
#! say nothing of the argument itself, so what the type names is read first.
|
||||
#! @param this The checker.
|
||||
#! @param pattern The trait's type, holding the parameters.
|
||||
#! @param kind The type given.
|
||||
#! @param into What is inferred.
|
||||
#! @param depth How deeply the search has gone.
|
||||
def checker::unify_named(&mut this, pattern: u32, kind: u32, into: &mut checker::inferred, depth: u32): void {
|
||||
return if depth > 16;
|
||||
val holder := this.types.first_of(pattern);
|
||||
val named := this.implemented(this.reached_value(kind), holder);
|
||||
return if named == this.decls.types.p[holder] || this.types.first_of(named) != holder;
|
||||
for i in 0..this.types.part_count(pattern) {
|
||||
break if i >= this.types.part_count(named);
|
||||
this.unify(this.types.part_at(pattern, i as u32), this.types.part_at(named, i as u32), into, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#! Infers type parameters a generic trait holds from a type implementing it,
|
||||
#! through what implements each of the trait's members, as `count::into(&this):
|
||||
#! int` gives the `T` of `into<T>`, and through what implements those of the
|
||||
#! traits it composes.
|
||||
#! @param this The checker.
|
||||
#! @param pattern The trait's type, holding the parameters.
|
||||
#! @param kind The type given.
|
||||
#! @param into What is inferred.
|
||||
#! @param depth How deeply the search has gone.
|
||||
def checker::unify_members(&mut this, pattern: u32, kind: u32, into: &mut checker::inferred, depth: u32): void {
|
||||
return if depth > 16;
|
||||
val holder := this.types.first_of(pattern);
|
||||
val run: u32 = this.decls.children.p[holder];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val wanted := this.decls.list_at(run, i as u32);
|
||||
val kind_of: dk = this.decls.kinds.p[wanted];
|
||||
continue if kind_of != dk::function && kind_of != dk::variable;
|
||||
val found := this.find_member(kind, this.decls.names.p[wanted]);
|
||||
# A method the compiler gives a built-in type, as a function's `invoke`, says
|
||||
# what it takes and gives as a declared one does.
|
||||
if found.decl == 0 && kind_of == dk::function && this.decls.has(wanted, df::method) {
|
||||
val given := this.builtin_method(kind, this.decls.names.p[wanted]);
|
||||
if given != 0 {
|
||||
this.resolve(wanted);
|
||||
val asked := this.trait_in_terms(this.decls.types.p[wanted], holder, pattern, kind);
|
||||
this.unify(this.past_receiver(asked), this.past_receiver(given), into, depth + 1);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
continue if found.decl == 0 || this.enclosing_trait(found.decl) != 0;
|
||||
this.resolve(wanted);
|
||||
val asked := this.trait_in_terms(this.decls.types.p[wanted], holder, pattern, kind);
|
||||
if kind_of == dk::variable {
|
||||
continue if this.decls.kinds.p[found.decl] != dk::variable;
|
||||
this.resolve(found.decl);
|
||||
this.unify(asked, this.instantiated(this.decls.types.p[found.decl], this.type_decl(found.owner), found.owner), into, depth + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
# Of overloads, one of the shape asked for.
|
||||
val count := this.types.part_count(asked);
|
||||
var walk := this.decls.walk_overloads(found.decl);
|
||||
while true {
|
||||
val at := walk.next();
|
||||
break if at == 0;
|
||||
if this.decls.kinds.p[at] == dk::function && this.decls.has(at, df::method) == this.decls.has(wanted, df::method)
|
||||
&& this.member_seen(at) {
|
||||
val given := this.method_type(at, found.owner);
|
||||
if this.types.kind_of(given) == ty::function && this.types.part_count(given) == count {
|
||||
val skip: u64 = this.decls.has(wanted, df::method) ? 1 : 0;
|
||||
for p in skip..count as u64 {
|
||||
this.unify(this.types.part_at(asked, p as u32), this.types.part_at(given, p as u32), into, depth + 1);
|
||||
}
|
||||
this.unify(this.types.first_of(asked), this.types.first_of(given), into, depth + 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val composed := this.composed_of(holder);
|
||||
for i in 0..this.decls.list_length(composed) {
|
||||
val inner := this.trait_in_terms(this.decls.list_at(composed, i as u32), holder, pattern, kind);
|
||||
this.unify_members(inner, kind, into, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#! A method's type without its receiver: the function its other parameters and
|
||||
#! its result make, variadic where the method is.
|
||||
#! @param this The checker.
|
||||
#! @param method The method's type.
|
||||
#! @returns The function's type.
|
||||
def checker::past_receiver(&mut this, method: u32): u32 {
|
||||
var parts := vector::<u32>::new();
|
||||
for i in 1..this.types.part_count(method) {
|
||||
parts.append(this.types.part_at(method, i as u32));
|
||||
}
|
||||
return this.types.function(parts.view(), this.types.first_of(method), this.types.second_of(method) != 0);
|
||||
}
|
||||
|
||||
#! What the type arguments inferred so far give those their bounds name, as `C`,
|
||||
#! where `C: iterable<T>`, gives `T` the type of the elements it lends. A bound
|
||||
#! may name a parameter another bound then gives more of, so the bounds are read
|
||||
#! again until they give nothing new.
|
||||
#! @param this The checker.
|
||||
#! @param into What is inferred.
|
||||
#! @param depth How many times the bounds have been read.
|
||||
pub def checker::unify_bounds(&mut this, into: &mut checker::inferred, depth: u32): void {
|
||||
return if depth > 4 || this.unbound(into) == 0;
|
||||
val before := this.unbound_count(into);
|
||||
for i in 0..into.params.length {
|
||||
val param: u32 = into.params[i];
|
||||
val given: u32 = into.binds[i];
|
||||
continue if given == checker::unknown_type || into.soft[i] || this.decls.has(param, df::valued);
|
||||
this.resolve(param);
|
||||
val bounds: u32 = this.decls.children.p[param];
|
||||
for j in 0..this.decls.list_length(bounds) {
|
||||
val bound := this.outer_terms(this.decls.list_at(bounds, j as u32), into);
|
||||
if this.types.is_open(bound) {
|
||||
this.unify_trait(bound, given, into, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
if this.unbound_count(into) != before {
|
||||
this.unify_bounds(into, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#! A type a trait's default names, with the trait's parameters and `self` given
|
||||
#! the types the value it is called on gives them, leaving its own parameters.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param into What is inferred.
|
||||
#! @returns The type in those terms.
|
||||
pub def checker::outer_terms(&mut this, kind: u32, into: &checker::inferred): u32 {
|
||||
return kind if into.outer.length == 0;
|
||||
return this.substitute(kind, into.outer.view(), into.given.view());
|
||||
}
|
||||
|
||||
#! Gives what is inferred for a trait's default compiled for each type the
|
||||
#! terms its bounds are read in: the trait's parameters, given the trait the
|
||||
#! value it is called on implements, and `self`, given the value's type.
|
||||
#! @param this The checker.
|
||||
#! @param method The default's declaration.
|
||||
#! @param through The type of the value it is called on, read through its
|
||||
#! references.
|
||||
#! @param into What is inferred.
|
||||
pub def checker::give_outer(&mut this, method: u32, through: u32, into: &mut checker::inferred): void {
|
||||
val holder := this.enclosing_trait(method);
|
||||
return if holder == 0;
|
||||
val plain := this.unalias(through);
|
||||
val trait_kind := this.trait_reached(method, plain);
|
||||
val params: u32 = this.decls.params.p[holder];
|
||||
for i in 0..this.decls.list_length(params) {
|
||||
into.outer.append(this.decls.list_at(params, i as u32));
|
||||
into.given.append(i < this.types.part_count(trait_kind) ? this.types.part_at(trait_kind, i as u32) : bt::error);
|
||||
}
|
||||
into.outer.append(this.self_decl(holder));
|
||||
into.given.append(plain);
|
||||
}
|
||||
|
||||
#! How many type parameters nothing has given a type yet.
|
||||
#! @param this The checker.
|
||||
#! @param inferred What was inferred.
|
||||
#! @returns How many.
|
||||
def checker::unbound_count(&this, inferred: &checker::inferred): u32 {
|
||||
var count: u32 = 0;
|
||||
for i in 0..inferred.binds.length {
|
||||
count += inferred.binds[i] == checker::unknown_type ? 1 : 0;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
#! Infers the arguments of a trait a type implements from how it implements it:
|
||||
#! each type the trait asks for is the one the type gives, which the bounds it is
|
||||
#! asked with say more of, and each method's parameters and result are those of
|
||||
#! the type's method.
|
||||
#! @param this The checker.
|
||||
#! @param pattern The trait, as the template writes it.
|
||||
#! @param actual The type implementing it.
|
||||
#! @param into What is inferred.
|
||||
#! @param depth How deeply the search has gone.
|
||||
def checker::unify_trait(&mut this, pattern: u32, actual: u32, into: &mut checker::inferred, depth: u32): void {
|
||||
return if depth > 8 || actual == bt::error;
|
||||
val plain := this.unalias(pattern);
|
||||
return if this.named_kind(plain) != dk::trait_type;
|
||||
val asked := this.types.first_of(plain);
|
||||
this.resolve(asked);
|
||||
this.unify_named(plain, actual, into, depth);
|
||||
|
||||
# The trait's own parameters are the pattern's arguments, and `self` the type.
|
||||
var from := vector::<u32>::new();
|
||||
var to := vector::<u32>::new();
|
||||
val params: u32 = this.decls.params.p[asked];
|
||||
for i in 0..this.decls.list_length(params) {
|
||||
from.append(this.decls.list_at(params, i as u32));
|
||||
to.append(i < this.types.part_count(plain) ? this.types.part_at(plain, i as u32) : bt::error);
|
||||
}
|
||||
from.append(this.self_decl(asked));
|
||||
to.append(actual);
|
||||
|
||||
val members: u32 = this.decls.children.p[asked];
|
||||
for i in 0..this.decls.list_length(members) {
|
||||
val member := this.decls.list_at(members, i as u32);
|
||||
if this.decls.kinds.p[member] == dk::assoc_type {
|
||||
val given := this.member_type(actual, this.decls.names.p[member]);
|
||||
continue if given == bt::error;
|
||||
this.resolve(member);
|
||||
val bounds: u32 = this.decls.children.p[member];
|
||||
for j in 0..this.decls.list_length(bounds) {
|
||||
val bound := this.substitute(this.decls.list_at(bounds, j as u32), from.view(), to.view());
|
||||
this.unify_trait(bound, given, into, depth + 1);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
continue if this.decls.kinds.p[member] != dk::function;
|
||||
val found := this.find_member(this.reached_value(actual), this.decls.names.p[member]);
|
||||
# A method the compiler gives a built-in type, as a function's `invoke`.
|
||||
if found.decl == 0 && this.decls.has(member, df::method) {
|
||||
val given := this.builtin_method(this.reached_value(actual), this.decls.names.p[member]);
|
||||
if given != 0 {
|
||||
this.resolve(member);
|
||||
val want := this.substitute(this.decls.types.p[member], from.view(), to.view());
|
||||
this.unify(this.past_receiver(want), this.past_receiver(given), into, depth + 1);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
continue if found.decl == 0 || this.decls.kinds.p[found.decl] != dk::function;
|
||||
this.resolve(member);
|
||||
val want := this.substitute(this.decls.types.p[member], from.view(), to.view());
|
||||
val have := this.member_function_type(found.decl, found.owner);
|
||||
this.unify(want, have, into, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#! What a value of the type is, read through a reference.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns What it reaches, or the type itself.
|
||||
def checker::reached_value(&mut this, kind: u32): u32 {
|
||||
return this.types.kind_of(kind) == ty::reference ? this.types.first_of(kind) : kind;
|
||||
}
|
||||
|
||||
#! The first type parameter nothing gave a type, or 0 where every one has one.
|
||||
#! @param this The checker.
|
||||
#! @param inferred What was inferred.
|
||||
#! @returns The type parameter's declaration, or 0.
|
||||
pub def checker::unbound(&this, inferred: &checker::inferred): u32 {
|
||||
for i in 0..inferred.params.length {
|
||||
return inferred.params[i] if inferred.binds[i] == checker::unknown_type;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! What a type parameter is inferred as while nothing has given it a type.
|
||||
pub const checker::unknown_type: u32 = 0xFFFFFFFF;
|
||||
|
||||
#! The type with the inferred type parameters replaced by their types.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param inferred What was inferred.
|
||||
#! @returns The type with them replaced.
|
||||
pub def checker::apply(&mut this, kind: u32, inferred: &checker::inferred): u32 {
|
||||
return this.substitute(kind, inferred.params.view(), inferred.binds.view());
|
||||
}
|
||||
|
||||
#! The type with the type parameters inferred so far replaced by their types,
|
||||
#! and those nothing has given a type yet left as they are.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param inferred What was inferred.
|
||||
#! @returns The type with the known ones replaced.
|
||||
pub def checker::apply_known(&mut this, kind: u32, inferred: &checker::inferred): u32 {
|
||||
var from := vector::<u32>::new();
|
||||
var to := vector::<u32>::new();
|
||||
for i in 0..inferred.params.length {
|
||||
continue if inferred.binds[i] == checker::unknown_type;
|
||||
from.append(inferred.params[i]);
|
||||
to.append(inferred.binds[i]);
|
||||
}
|
||||
return this.substitute(kind, from.view(), to.view());
|
||||
}
|
||||
|
||||
#! Whether a type holds a type parameter, so it belongs to a template rather
|
||||
#! than an instance.
|
||||
#! @param this The checker.
|
||||
#! @param kinds The types.
|
||||
#! @returns Whether any does.
|
||||
pub def checker::any_open(&this, kinds: span<u32>): bool {
|
||||
for &each in kinds {
|
||||
return true if this.types.is_open(each);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! How deeply type arguments nest within the type.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param depth How deeply it already nests.
|
||||
#! @returns How deeply its arguments nest.
|
||||
def checker::nesting(&this, kind: u32, depth: u32): u32 {
|
||||
return depth if depth > checker::max_nesting;
|
||||
|
||||
var deepest := depth;
|
||||
match this.types.kind_of(kind) {
|
||||
ty::reference, ty::pointer, ty::fixed => {
|
||||
return this.nesting(this.types.first_of(kind), depth + 1);
|
||||
}
|
||||
ty::function, ty::named, ty::pack => {
|
||||
for &part in this.types.parts_view(kind) {
|
||||
val inner := this.nesting(part, depth + 1);
|
||||
deepest = inner > deepest ? inner : deepest;
|
||||
}
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
return deepest;
|
||||
}
|
||||
|
||||
#! The instance of the generic function given the type arguments, made where it
|
||||
#! is new and waiting for its body to be checked.
|
||||
#! @param this The checker.
|
||||
#! @param decl The generic function.
|
||||
#! @param args Its type arguments, its owner's first.
|
||||
#! @param node The node a note is placed at, where too many instances are
|
||||
#! made.
|
||||
#! @returns One more than its index, or 0 where the arguments hold type
|
||||
#! parameters, or the program has made as many instances as it may.
|
||||
pub def checker::instance_of(&mut this, decl: u32, args: span<u32>, node: u32): u32 {
|
||||
return 0 if this.any_open(args) || args.length == 0;
|
||||
for &each in args {
|
||||
return 0 if each == bt::error;
|
||||
}
|
||||
|
||||
val pack := this.types.pack(args, 0);
|
||||
val key := pair_key(decl, pack);
|
||||
if this.instanced.get(&key) is some(got) {
|
||||
return got;
|
||||
}
|
||||
|
||||
if this.instances.length as u32 >= checker::max_instances {
|
||||
this.report(node, ec::limit, "The program makes more instances of generics than the checker allows.");
|
||||
return 0;
|
||||
}
|
||||
if this.nesting(pack, 0) > checker::max_nesting {
|
||||
this.report(node, ec::limit, "The type arguments nest too deeply, as a generic instantiating itself with ever larger types does.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.resolve(decl);
|
||||
val params: u32 = this.decls.params.p[decl];
|
||||
var from := this.decls.list_of(params);
|
||||
|
||||
val id := this.instances.length as u32;
|
||||
this.instances.append(instance {
|
||||
decl = decl,
|
||||
args = pack,
|
||||
kind = this.substitute(this.decls.types.p[decl], from.view(), args)
|
||||
});
|
||||
this.instanced.set(key, id + 1);
|
||||
this.wants.append(id);
|
||||
return id + 1;
|
||||
}
|
||||
|
||||
#! The instance of a trait's default method a type takes. A default of a trait
|
||||
#! that is only a bound is compiled for each type taking it, with the trait's
|
||||
#! parameters bound to its arguments, `self` to the type, and its own type
|
||||
#! parameters to those the call gives. Any other is compiled for the trait,
|
||||
#! given its arguments, with `self` the trait itself, called through as a
|
||||
#! reference to the trait is, and a default of a trait without parameters is
|
||||
#! then its own template.
|
||||
#! @param this The checker.
|
||||
#! @param method The default's declaration.
|
||||
#! @param trait_kind The trait declaring it, given its arguments.
|
||||
#! @param self_kind The type taking it.
|
||||
#! @param own The method's own type arguments, which a default
|
||||
#! compiled for each type takes after `self`.
|
||||
#! @returns One more than the instance, or 0 where it is its own template or
|
||||
#! its arguments are not known.
|
||||
pub def checker::default_instance(&mut this, method: u32, trait_kind: u32, self_kind: u32, own: span<u32>): u32 {
|
||||
val holder := this.enclosing_trait(method);
|
||||
return 0 if holder == 0 || holder == method || this.types.kind_of(trait_kind) != ty::named;
|
||||
val params: u32 = this.decls.params.p[holder];
|
||||
val typed := this.typed_default(method);
|
||||
return 0 if !typed && this.decls.list_length(params) == 0;
|
||||
var args := this.types.parts_of(trait_kind);
|
||||
if typed {
|
||||
return 0 if own.length != this.decls.list_length(this.decls.params.p[method]);
|
||||
args.append(self_kind);
|
||||
args.extend(own);
|
||||
}
|
||||
return 0 if args.length == 0 || this.any_open(args.view());
|
||||
for &each in args {
|
||||
return 0 if each == bt::error;
|
||||
}
|
||||
|
||||
val pack := this.types.pack(args.view(), 0);
|
||||
val key := pair_key(method, pack);
|
||||
if this.instanced.get(&key) is some(got) {
|
||||
return got;
|
||||
}
|
||||
if this.instances.length as u32 >= checker::max_instances {
|
||||
this.report(this.decls.nodes.p[method], ec::limit, "The program makes more instances of generics than the checker allows.");
|
||||
return 0;
|
||||
}
|
||||
if this.nesting(pack, 0) > checker::max_nesting {
|
||||
this.report(this.decls.nodes.p[method], ec::limit, "The type arguments nest too deeply, as a generic instantiating itself with ever larger types does.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
this.resolve(method);
|
||||
var from := vector::<u32>::new();
|
||||
var to := vector::<u32>::new();
|
||||
val trait_args := this.types.part_count(trait_kind);
|
||||
for i in 0..this.decls.list_length(params) {
|
||||
from.append(this.decls.list_at(params, i as u32));
|
||||
to.append(i < trait_args ? this.types.part_at(trait_kind, i as u32) : bt::error);
|
||||
}
|
||||
from.append(this.self_decl(holder));
|
||||
to.append(typed ? self_kind : trait_kind);
|
||||
if typed {
|
||||
from.extend(this.decls.list_view(this.decls.params.p[method]));
|
||||
to.extend(own);
|
||||
}
|
||||
|
||||
val id := this.instances.length as u32;
|
||||
this.instances.append(instance {
|
||||
decl = method,
|
||||
args = pack,
|
||||
kind = this.substitute(this.decls.types.p[method], from.view(), to.view())
|
||||
});
|
||||
this.instanced.set(key, id + 1);
|
||||
this.wants.append(id);
|
||||
return id + 1;
|
||||
}
|
||||
|
||||
#! The first node of a declaration's nodes, which are one run of indexes, the
|
||||
#! parser having made them as it went, the declaration's own last.
|
||||
#! @param this The checker.
|
||||
#! @param decl The declaration.
|
||||
#! @returns The node.
|
||||
pub def checker::first_node(&mut this, decl: u32): u32 {
|
||||
val held := this.decl_bases.at_or_zero(decl);
|
||||
return held if held != 0;
|
||||
|
||||
val saved := this.at;
|
||||
this.use_table(this.units[this.decls.files.p[decl]].table);
|
||||
val node: u32 = this.decls.nodes.p[decl];
|
||||
var lowest := node;
|
||||
var todo := vector::<u32>::new();
|
||||
todo.append(node);
|
||||
while todo.length != 0 {
|
||||
val at: u32 = todo.last();
|
||||
todo.truncate();
|
||||
lowest = at < lowest ? at : lowest;
|
||||
this.syn().children(at, &mut todo);
|
||||
}
|
||||
this.at = saved;
|
||||
|
||||
this.decl_bases.put(decl, lowest);
|
||||
return lowest;
|
||||
}
|
||||
|
||||
#! Checks the bodies of the instances the program uses, including those the
|
||||
#! bodies checked here use in turn.
|
||||
#! @param this The checker.
|
||||
pub def checker::check_wanted(&mut this): void {
|
||||
while this.wants_checked < this.wants.length {
|
||||
val id: u32 = this.wants[this.wants_checked];
|
||||
this.wants_checked++;
|
||||
this.check_instance(id);
|
||||
}
|
||||
}
|
||||
|
||||
#! Checks an instance's body over its template's nodes, with a result table of
|
||||
#! its own and the type parameters bound to its arguments.
|
||||
#! @param this The checker.
|
||||
#! @param id The instance's index.
|
||||
def checker::check_instance(&mut this, id: u32): void {
|
||||
val held: instance = this.instances[id];
|
||||
val decl := held.decl;
|
||||
return if this.decls.has(decl, df::failed);
|
||||
|
||||
val first := this.first_node(decl);
|
||||
val last: u32 = this.decls.nodes.p[decl];
|
||||
val table := this.add_table(this.decls.files.p[decl], first, last - first + 1, id + 1);
|
||||
this.instances[id].table = table + 1;
|
||||
|
||||
val saved := this.at;
|
||||
this.enter_decl(decl, held.args);
|
||||
this.use_table(table);
|
||||
this.at.instance = id + 1;
|
||||
this.check_function_body(decl, held.kind);
|
||||
this.leave(saved);
|
||||
}
|
||||
@@ -0,0 +1,671 @@
|
||||
#! @file incremental.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains checking again after an edit. While a declaration is checked, what
|
||||
#! it depends on is recorded: each declaration it resolves, and each name it
|
||||
#! looks up outside any scope, found or not. Once a file is parsed again, which
|
||||
#! keeps the nodes of the top-level declarations an edit did not touch, the
|
||||
#! checker keeps what it worked out of those, declares what is new, lets go of
|
||||
#! what is gone, and checks again only what depends on what changed. A changed
|
||||
#! declaration of the same kind, module, and name keeps its ID, so what other
|
||||
#! files worked out of it stays.
|
||||
|
||||
import std::containers;
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! Records that the declaration being checked depends on the declaration.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration depended on.
|
||||
pub def checker::depend(&mut this, id: u32): void {
|
||||
val from := this.top_decl(this.at.decl);
|
||||
return if from == 0 || id == 0 || from == id;
|
||||
if id as u64 >= this.depended.length {
|
||||
this.depended.resize(this.decls.count > id as u64 ? this.decls.count : id as u64 + 1);
|
||||
}
|
||||
this.depended[id] = true;
|
||||
return if !this.tracks;
|
||||
this.add_dependency(from, id);
|
||||
}
|
||||
|
||||
#! Whether any declaration depends on a declaration, as resolving it.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns Whether one does.
|
||||
pub def checker::is_depended(&this, id: u32): bool {
|
||||
return (id as u64) < this.depended.length && this.depended[id];
|
||||
}
|
||||
|
||||
#! Records that the declaration being checked looked up the name outside any
|
||||
#! scope, so a declaration of the name made later may be what it means.
|
||||
#! @param this The checker.
|
||||
#! @param name The ID of the name.
|
||||
pub def checker::depend_name(&mut this, name: u32): void {
|
||||
return if !this.tracks;
|
||||
val from := this.top_decl(this.at.decl);
|
||||
return if from == 0;
|
||||
this.add_dependency(from, name | checker::named_dependency);
|
||||
}
|
||||
|
||||
#! What a dependency on a name, rather than a declaration, has set.
|
||||
pub const checker::named_dependency: u32 = 0x80000000;
|
||||
|
||||
def checker::add_dependency(&mut this, from: u32, to: u32): void {
|
||||
val key := pair_key(from, to);
|
||||
return if !this.dep_seen.insert(key, 1);
|
||||
this.dep_from.append(from);
|
||||
this.dep_to.append(to);
|
||||
}
|
||||
|
||||
#! The top-level declaration a declaration was declared with: itself, or the
|
||||
#! type a field or member is of, or the declaration a type parameter is of.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns The top-level declaration.
|
||||
pub def checker::top_decl(&this, id: u32): u32 {
|
||||
var at := id;
|
||||
var steps := 0;
|
||||
while at != 0 && steps < 8 {
|
||||
val node: u32 = this.decls.nodes.p[at];
|
||||
val top: u32 = this.decls.tops.p[at];
|
||||
return at if top == 0 || node == top;
|
||||
at = this.decls.owners.p[at];
|
||||
steps++;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
#! A top-level declaration of a file, and the module it is declared in.
|
||||
struct checker::placed {
|
||||
var node: u32; #! The declaration's node.
|
||||
var home: u32; #! The module it is declared in.
|
||||
var external: bool; #! Whether it is in an `extern module`.
|
||||
}
|
||||
|
||||
#! The top-level declarations the file declares, in the branches of `when` the
|
||||
#! target takes, each with the module it is declared in, noting the libraries
|
||||
#! its `extern import`s name anew.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @returns Each declaration's node and module, in order.
|
||||
def checker::placements(&mut this, file: u32): vector<checker::placed> {
|
||||
var kept := vector::<u64>::new();
|
||||
for &each in this.libraries {
|
||||
if (each >> 32) as u32 != file {
|
||||
kept.append(each);
|
||||
}
|
||||
}
|
||||
this.libraries = move(&mut kept);
|
||||
|
||||
var made := vector::<checker::placed>::new();
|
||||
val decls := this.left_of(this.units[file].root);
|
||||
var home: u32 = 0;
|
||||
var active := true;
|
||||
var external := false;
|
||||
for &node in this.run_view(decls) {
|
||||
match this.kind_of(node) {
|
||||
nk::import_decl => {}
|
||||
nk::extern_import => {
|
||||
if this.right_of(node) == 0 || this.target_holds(this.right_of(node)) {
|
||||
this.add_library(file, node);
|
||||
}
|
||||
}
|
||||
nk::module_decl, nk::extern_module => {
|
||||
home = this.module_path(this.left_of(node), true);
|
||||
active = this.right_of(node) == 0 || this.target_holds(this.right_of(node));
|
||||
external = this.kind_of(node) == nk::extern_module;
|
||||
if external {
|
||||
this.check_section(node);
|
||||
}
|
||||
}
|
||||
else => {
|
||||
if active {
|
||||
this.place_top(node, home, external, &mut made);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
def checker::place_top(&mut this, node: u32, home: u32, external: bool, into: &mut vector<checker::placed>): void {
|
||||
match this.kind_of(node) {
|
||||
nk::when_block => {
|
||||
val chosen := this.when_branch(node);
|
||||
return if chosen == 0;
|
||||
val decls := this.left_of(chosen);
|
||||
for &node in this.run_view(decls) {
|
||||
this.place_top(node, home, external, into);
|
||||
}
|
||||
}
|
||||
nk::error => {}
|
||||
else => into.append(checker::placed { node = node, home = home, external = external });
|
||||
}
|
||||
}
|
||||
|
||||
#! The key a top-level declaration is matched by across an edit: its kind,
|
||||
#! module, and name, each whole, so no two declarations differing in any share
|
||||
#! one.
|
||||
struct checker::match_key : hashable, equatable {
|
||||
var kind: dk; #! Its kind.
|
||||
var home: u32; #! The module it is declared in.
|
||||
var name: u32; #! The ID of its name.
|
||||
}
|
||||
|
||||
#! Hashes the key, as the dictionary of keys asks.
|
||||
#! @param this The key.
|
||||
#! @returns Its hash code.
|
||||
pub def checker::match_key::hash(&this): u64 {
|
||||
return mix(pair_key(this.home, this.name), this.kind as u64);
|
||||
}
|
||||
|
||||
#! Whether two keys are of the same kind, module, and name.
|
||||
#! @param this The key.
|
||||
#! @param other The other key.
|
||||
#! @returns Whether they are.
|
||||
pub def checker::match_key::equals(&this, other: &checker::match_key): bool {
|
||||
return this.kind == other.kind && this.home == other.home && this.name == other.name;
|
||||
}
|
||||
|
||||
#! Checks the file again once it is parsed again, as `syntax::reparse` does,
|
||||
#! checking again only what the edit affects.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param source The file's text as it was edited, which its tokens are of
|
||||
#! now.
|
||||
#! @param root The file's `document` node, as parsing it again gave it.
|
||||
#! @returns How many top-level declarations were checked again.
|
||||
pub def checker::update(&mut this, file: u32, source: &source, root: u32): u32 {
|
||||
val saved := this.at;
|
||||
this.units[file].source = &source;
|
||||
this.units[file].root = root;
|
||||
val old_table: u32 = this.units[file].table;
|
||||
val count := this.units[file].syntax.node_count as u32;
|
||||
val fresh := this.add_table(file, 0, count, 0);
|
||||
this.units[file].table = fresh;
|
||||
this.use_table(fresh);
|
||||
|
||||
# The top-level declarations the file has now, and those it had.
|
||||
val placed := this.placements(file);
|
||||
var now := dict::<u32, u32>::new(); # Each top-level node now, with its module.
|
||||
for &each in placed {
|
||||
now.set(each.node, each.home);
|
||||
}
|
||||
|
||||
# Parsing the file whole again made every node anew, so none of the old ones
|
||||
# is kept, however their indexes fall.
|
||||
val whole := this.units[file].syntax.parses != this.units[file].parses;
|
||||
this.units[file].parses = this.units[file].syntax.parses;
|
||||
|
||||
var kept := dict::<u32, u32>::new(); # The top-level nodes kept, and their declarations.
|
||||
var gone := vector::<u32>::new(); # The top-level declarations whose nodes are gone.
|
||||
for &decl in this.decls.by_file.of(file) {
|
||||
continue if this.decls.kinds.p[decl] == dk::none || this.decls.kinds.p[decl] == dk::builtin;
|
||||
val top: u32 = this.decls.tops.p[decl];
|
||||
continue if top == 0 || this.decls.nodes.p[decl] != top;
|
||||
if !whole && now.contains(&top) && this.decl_kind(top) == this.decls.kinds.p[decl] {
|
||||
if !kept.contains(&top) {
|
||||
kept.set(top, decl);
|
||||
}
|
||||
} else {
|
||||
gone.append(decl);
|
||||
}
|
||||
}
|
||||
|
||||
# What is kept keeps what was worked out of it.
|
||||
for &each in placed {
|
||||
val decl := kept.get(&each.node) else { continue; };
|
||||
this.move_results(old_table, fresh, each.node, decl);
|
||||
}
|
||||
this.repoint_tables(old_table, fresh);
|
||||
|
||||
# A top-level declaration gone whose kind, module, and name a new one has
|
||||
# keeps its ID, so what other files worked out of it stays.
|
||||
var reusable := dict::<checker::match_key, u32>::new();
|
||||
for &decl in gone {
|
||||
val key := checker::match_key {
|
||||
kind = this.decls.kinds.p[decl as u32],
|
||||
home = this.decls.modules.p[decl as u32],
|
||||
name = this.decls.names.p[decl as u32]
|
||||
};
|
||||
if !reusable.contains(&key) {
|
||||
reusable.set(key, decl);
|
||||
}
|
||||
}
|
||||
|
||||
var changed := vector::<u32>::new();
|
||||
var olds := dict::<u32, u32>::new(); # The type each reused declaration had.
|
||||
for &decl in gone {
|
||||
this.forget_members(decl, file);
|
||||
}
|
||||
|
||||
this.pending.clear();
|
||||
this.at.scope = 0;
|
||||
var made := vector::<u32>::new();
|
||||
for &each in placed {
|
||||
continue if kept.contains(&each.node);
|
||||
this.at.home = each.home;
|
||||
val kind := this.decl_kind(each.node);
|
||||
val name := this.name_of(each.node);
|
||||
val key := checker::match_key { kind = kind, home = each.home, name = name };
|
||||
if reusable.contains(&key) {
|
||||
val decl: u32 = reusable[key];
|
||||
reusable.remove(&key);
|
||||
olds.set(decl, this.decls.types.p[decl]);
|
||||
this.external = each.external;
|
||||
this.redeclare(decl, each.node, each.home);
|
||||
this.external = false;
|
||||
made.append(decl);
|
||||
continue;
|
||||
}
|
||||
|
||||
this.decls.top = each.node;
|
||||
this.external = each.external;
|
||||
val decl := this.declare_decl(each.node, 0);
|
||||
this.external = false;
|
||||
this.decls.top = 0;
|
||||
if decl != 0 {
|
||||
made.append(decl);
|
||||
changed.append(decl);
|
||||
}
|
||||
}
|
||||
|
||||
# What is gone and not reused leaves every scope it was in.
|
||||
for &each in gone {
|
||||
val decl: u32 = each;
|
||||
continue if olds.contains(&decl);
|
||||
this.forget(decl);
|
||||
changed.append(decl);
|
||||
}
|
||||
|
||||
this.relink(file);
|
||||
this.forget_caches();
|
||||
|
||||
# Checking again: what is new or reused, then whatever depends on what
|
||||
# changed, and on what that changes in turn.
|
||||
var checked := hashset::<u32>::new();
|
||||
var queue := vector::<u32>::new();
|
||||
queue.extend(made.view());
|
||||
var at: u64 = 0;
|
||||
var rounds := 0;
|
||||
while rounds < 64 {
|
||||
rounds++;
|
||||
while at < queue.length {
|
||||
val decl: u32 = queue[at];
|
||||
at++;
|
||||
continue if checked.contains(&decl) || this.decls.kinds.p[decl] == dk::none;
|
||||
checked.insert(decl);
|
||||
|
||||
val before := olds.get_or(&decl, this.decls.types.p[decl]);
|
||||
this.check_again(decl);
|
||||
val after: u32 = this.decls.types.p[decl];
|
||||
if !olds.contains(&decl) || before != after || this.is_type_decl(decl) {
|
||||
changed.append(decl);
|
||||
}
|
||||
}
|
||||
|
||||
# Whatever depends on what changed is checked again.
|
||||
val queued := queue.length;
|
||||
var names := hashset::<u32>::new();
|
||||
var ids := hashset::<u32>::new();
|
||||
for &decl in changed {
|
||||
ids.insert(decl);
|
||||
names.insert(this.decls.names.p[decl as u32]);
|
||||
}
|
||||
changed.clear();
|
||||
for i in 0..this.dep_from.length {
|
||||
val to: u32 = this.dep_to[i];
|
||||
val from: u32 = this.dep_from[i];
|
||||
val hit := (to & checker::named_dependency) != 0
|
||||
? names.contains(&(to & ~checker::named_dependency))
|
||||
: ids.contains(&to);
|
||||
if hit && !checked.contains(&from) {
|
||||
queue.append(from);
|
||||
}
|
||||
}
|
||||
break if queue.length == queued;
|
||||
}
|
||||
|
||||
this.check_wanted();
|
||||
this.recount_notes();
|
||||
this.at = saved;
|
||||
return checked.length as u32;
|
||||
}
|
||||
|
||||
#! Copies what was worked out of a top-level declaration's nodes from one
|
||||
#! table of its file to another.
|
||||
#! @param this The checker.
|
||||
#! @param from The table to copy from.
|
||||
#! @param to The table to copy to.
|
||||
#! @param top The top-level declaration's node, whose nodes run from its
|
||||
#! first to it.
|
||||
#! @param decl The declaration.
|
||||
def checker::move_results(&mut this, from: u32, to: u32, top: u32, decl: u32): void {
|
||||
val first := this.first_node(decl);
|
||||
val source: rtable = this.tables.p[from];
|
||||
val target: rtable = this.tables.p[to];
|
||||
for node in first..(top + 1) {
|
||||
val n := node as u32;
|
||||
continue if n >= source.count || n >= target.count;
|
||||
this.copy_results(source.offset as u64 + n as u64, target.offset as u64 + n as u64);
|
||||
this.move_key(from, to, n);
|
||||
}
|
||||
}
|
||||
|
||||
#! Moves what the sparse results hold of the node from one table to another.
|
||||
#! @param this The checker.
|
||||
#! @param from The table to move from.
|
||||
#! @param to The table to move to.
|
||||
#! @param node The node.
|
||||
def checker::move_key(&mut this, from: u32, to: u32, node: u32): void {
|
||||
val old_key := pair_key(from, node);
|
||||
val new_key := pair_key(to, node);
|
||||
if this.reflections.get(&old_key) is some(held) {
|
||||
this.reflections.set(new_key, held);
|
||||
}
|
||||
if this.lengths.get(&old_key) is some(held) {
|
||||
this.lengths.set(new_key, held);
|
||||
}
|
||||
if this.called.get(&old_key) is some(held) {
|
||||
this.called.set(new_key, held);
|
||||
}
|
||||
}
|
||||
|
||||
#! Makes the tables made within the file's old table, for `for const`, be within
|
||||
#! its new one.
|
||||
#! @param this The checker.
|
||||
#! @param from The file's old table.
|
||||
#! @param to Its new table.
|
||||
def checker::repoint_tables(&mut this, from: u32, to: u32): void {
|
||||
for i in 0..this.tables.length {
|
||||
if this.tables.p[i].parent == from + 1 {
|
||||
this.tables.p[i].parent = to + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Lets go of what a top-level declaration declared within it: its members,
|
||||
#! its type parameters, and what the checker made of it, which declaring it
|
||||
#! again makes anew.
|
||||
#! @param this The checker.
|
||||
#! @param decl The top-level declaration.
|
||||
#! @param file The file it is declared in.
|
||||
def checker::forget_members(&mut this, decl: u32, file: u32): void {
|
||||
val top: u32 = this.decls.tops.p[decl];
|
||||
for &each in this.decls.by_file.of(file) {
|
||||
continue if each == decl || this.decls.tops.p[each] != top;
|
||||
this.forget(each);
|
||||
}
|
||||
this.decls.children.p[decl] = 0;
|
||||
}
|
||||
|
||||
#! Lets go of a declaration: it leaves the module or type declaring it, and is
|
||||
#! no longer anything.
|
||||
#! @param this The checker.
|
||||
#! @param decl The declaration.
|
||||
def checker::forget(&mut this, decl: u32): void {
|
||||
val kind: dk = this.decls.kinds.p[decl];
|
||||
return if kind == dk::none;
|
||||
|
||||
val owner: u32 = this.decls.owners.p[decl];
|
||||
val name: u32 = this.decls.names.p[decl];
|
||||
if owner != 0 && (kind != dk::type_param) {
|
||||
this.leave_type(owner, decl);
|
||||
} else if kind != dk::type_param {
|
||||
val home: u32 = this.decls.modules.p[decl];
|
||||
val key := pair_key(home, name);
|
||||
this.unchain(this.modules.decl(home, name), decl, key, chained::modules);
|
||||
}
|
||||
|
||||
this.decls.kinds.p[decl] = dk::none;
|
||||
this.decls.overloads.p[decl] = 0;
|
||||
this.decls.tops.p[decl] = 0;
|
||||
}
|
||||
|
||||
#! Takes a member out of its type's members, or out of the types declared
|
||||
#! through its type.
|
||||
#! @param this The checker.
|
||||
#! @param owner The type's declaration.
|
||||
#! @param decl The member's declaration.
|
||||
def checker::leave_type(&mut this, owner: u32, decl: u32): void {
|
||||
val name: u32 = this.decls.names.p[decl];
|
||||
val key := pair_key(owner, name);
|
||||
val added := this.decls.added_member(owner, name);
|
||||
if added != 0 && !this.in_core(this.decls.modules.p[decl]) {
|
||||
this.unchain(added, decl, key, chained::added);
|
||||
return;
|
||||
}
|
||||
if this.decls.nests(decl) {
|
||||
if this.decls.member_in(owner, name, true) == decl {
|
||||
this.decls.nested.remove(&key);
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.unchain(this.decls.member_in(owner, name, false), decl, key, chained::members);
|
||||
}
|
||||
|
||||
#! Which dictionary holds the first of a chain of overloads by its key.
|
||||
enum chained : u8 {
|
||||
members, #! A type's members, `decls.members`.
|
||||
added, #! Those declared outside `core` on `core`'s type, `decls.added`.
|
||||
modules, #! A module's, `modules.decls`.
|
||||
}
|
||||
|
||||
#! Takes the declaration out of the chain of overloads beginning with `first`,
|
||||
#! which the dictionary holds by the key.
|
||||
#! @param this The checker.
|
||||
#! @param first The first of the overloads, or 0.
|
||||
#! @param decl The declaration to take out.
|
||||
#! @param key The key the dictionary holds the first by.
|
||||
#! @param held Which dictionary that is.
|
||||
def checker::unchain(&mut this, first: u32, decl: u32, key: u64, held: chained): void {
|
||||
return if first == 0;
|
||||
if first == decl {
|
||||
val next: u32 = this.decls.overloads.p[decl];
|
||||
var dict := match held {
|
||||
chained::members => &mut this.decls.members,
|
||||
chained::added => &mut this.decls.added,
|
||||
chained::modules => &mut this.modules.decls
|
||||
};
|
||||
if next == 0 { dict.remove(&key); } else { dict.set(key, next); }
|
||||
return;
|
||||
}
|
||||
|
||||
var walk := this.decls.walk_overloads(first, 4096);
|
||||
while true {
|
||||
val at := walk.next();
|
||||
break if at == 0;
|
||||
if this.decls.overloads.p[at] == decl {
|
||||
val after: u32 = this.decls.overloads.p[decl];
|
||||
this.decls.overloads.p[at] = after;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Declares a top-level declaration again, at its new node, keeping its ID: it
|
||||
#! leaves where it was declared and is declared there again, with its members
|
||||
#! and type parameters made anew.
|
||||
#! @param this The checker.
|
||||
#! @param decl The declaration.
|
||||
#! @param node Its new node.
|
||||
#! @param home The module it is declared in.
|
||||
def checker::redeclare(&mut this, decl: u32, node: u32, home: u32): void {
|
||||
val kind: dk = this.decls.kinds.p[decl];
|
||||
val owner: u32 = this.decls.owners.p[decl];
|
||||
val name: u32 = this.decls.names.p[decl];
|
||||
if owner != 0 {
|
||||
this.leave_type(owner, decl);
|
||||
} else {
|
||||
val key := pair_key(this.decls.modules.p[decl], name);
|
||||
this.unchain(this.modules.decl(this.decls.modules.p[decl], name), decl, key, chained::modules);
|
||||
}
|
||||
|
||||
this.decls.renew(decl, node, home);
|
||||
this.decl_bases.put(decl, 0);
|
||||
this.decl_values.put(decl, 0);
|
||||
|
||||
val flags := this.node_flags(node);
|
||||
if (flags & nf::exported as u32) != 0 { this.decls.mark(decl, df::exported); }
|
||||
if (flags & nf::mutable as u32) != 0 { this.decls.mark(decl, df::mutable); }
|
||||
if (flags & nf::constant as u32) != 0 { this.decls.mark(decl, df::constant); }
|
||||
this.mark_attributes(decl, node);
|
||||
if this.external {
|
||||
this.mark_external(decl, kind, node);
|
||||
}
|
||||
if kind == dk::function {
|
||||
this.mark_signature(decl, node);
|
||||
}
|
||||
|
||||
this.decls.top = node;
|
||||
if this.receiver_of(node) != 0 {
|
||||
this.pending.append(decl);
|
||||
} else {
|
||||
this.add_global(decl);
|
||||
}
|
||||
val own := this.declare_params(this.own_params_of(node), decl);
|
||||
this.record_shape(decl, this.own_params_of(node));
|
||||
if this.receiver_of(node) == 0 {
|
||||
this.set_params(decl, own.view());
|
||||
} else {
|
||||
this.decls.params.p[decl] = this.decls.make_list(own.view());
|
||||
}
|
||||
this.declare_members(decl, node);
|
||||
this.decls.top = 0;
|
||||
}
|
||||
|
||||
#! Links what was declared anew: the file's imports, the declarations made
|
||||
#! through types, and the types of new type declarations.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
def checker::relink(&mut this, file: u32): void {
|
||||
var imports := vector::<u32>::new();
|
||||
val decls := this.left_of(this.units[file].root);
|
||||
for &node in this.run_view(decls) {
|
||||
continue if this.kind_of(node) != nk::import_decl;
|
||||
val found := this.module_path(this.left_of(node), false);
|
||||
if found == 0 {
|
||||
this.report(node, ec::undefined, "No file declares this module.");
|
||||
continue;
|
||||
}
|
||||
imports.append(found);
|
||||
}
|
||||
val run := this.decls.make_list(imports.view());
|
||||
this.units[file].imports = run;
|
||||
|
||||
this.attach_pending();
|
||||
this.pending.clear();
|
||||
this.give_accessors_params();
|
||||
this.name_types();
|
||||
}
|
||||
|
||||
#! Lets go of what was worked out of types and traits, which what changed may
|
||||
#! have changed, to be worked out again as it is needed.
|
||||
#! @param this The checker.
|
||||
def checker::forget_caches(&mut this): void {
|
||||
this.satisfied.clear();
|
||||
this.types.forget();
|
||||
this.only_bounds.clear();
|
||||
this.outers.clear();
|
||||
this.composed.resize(0);
|
||||
this.known.clear();
|
||||
}
|
||||
|
||||
#! Checks a top-level declaration again: its notes are let go of, what it and
|
||||
#! what it declares worked out is let go of, and it is resolved and checked as
|
||||
#! though for the first time, with the instances of it the program uses.
|
||||
#! @param this The checker.
|
||||
#! @param decl The top-level declaration.
|
||||
def checker::check_again(&mut this, decl: u32): void {
|
||||
val top: u32 = this.decls.tops.p[decl];
|
||||
val file: u32 = this.decls.files.p[decl];
|
||||
this.forget_notes(decl);
|
||||
|
||||
var family := vector::<u32>::new();
|
||||
for &each in this.decls.by_file.of(file) {
|
||||
if each == decl || (top != 0 && this.decls.tops.p[each] == top && this.decls.kinds.p[each] != dk::none) {
|
||||
family.append(each);
|
||||
}
|
||||
}
|
||||
|
||||
for &each in family {
|
||||
this.decls.states.p[each as u32] = ds::unresolved;
|
||||
this.decls.flags.p[each as u32] &= ~(df::checked as u32 | df::failed as u32);
|
||||
}
|
||||
this.clear_results(decl);
|
||||
for &each in family {
|
||||
this.resolve(each);
|
||||
}
|
||||
for &each in family {
|
||||
this.check_decl(each);
|
||||
}
|
||||
|
||||
# The instances of what is checked again are checked again with it.
|
||||
for i in 0..this.instances.length {
|
||||
val held: instance = this.instances[i];
|
||||
continue if !family.view().contains(&held.decl);
|
||||
var from := this.decls.list_of(this.decls.params.p[held.decl]);
|
||||
var args := this.types.parts_of(held.args);
|
||||
val kind := this.substitute(this.decls.types.p[held.decl], from.view(), args.view());
|
||||
this.instances[i].kind = kind;
|
||||
this.instances[i].table = 0;
|
||||
this.wants.append(i as u32);
|
||||
}
|
||||
}
|
||||
|
||||
#! Lets go of what was worked out of a declaration's nodes in its file's table.
|
||||
#! @param this The checker.
|
||||
#! @param decl The top-level declaration.
|
||||
def checker::clear_results(&mut this, decl: u32) : void {
|
||||
val file: u32 = this.decls.files.p[decl];
|
||||
val table: u32 = this.units[file].table;
|
||||
val held: rtable = this.tables.p[table];
|
||||
val first := this.first_node(decl);
|
||||
val last: u32 = this.decls.nodes.p[decl];
|
||||
for node in first..(last + 1) {
|
||||
val n := node as u32;
|
||||
continue if n >= held.count;
|
||||
this.drop_results(held.offset as u64 + n as u64);
|
||||
val key := pair_key(table, n);
|
||||
this.reflections.remove(&key);
|
||||
this.lengths.remove(&key);
|
||||
this.called.remove(&key);
|
||||
}
|
||||
}
|
||||
|
||||
#! Lets go of the notes the checker made checking the declaration, or what it
|
||||
#! declares.
|
||||
#! @param this The checker.
|
||||
#! @param decl The top-level declaration.
|
||||
def checker::forget_notes(&mut this, decl: u32): void {
|
||||
# Those kept are moved down over those let go of, which are closed as they
|
||||
# are written over, and those left past the last kept are closed with them.
|
||||
var kept: u64 = 0;
|
||||
for i in 0..this.sink.notes.length {
|
||||
val origin := this.sink.notes[i].origin;
|
||||
continue if origin != 0 && this.top_decl(origin) == decl;
|
||||
if kept != i {
|
||||
this.sink.notes[kept] = move(&mut this.sink.notes[i]);
|
||||
}
|
||||
kept++;
|
||||
}
|
||||
while this.sink.notes.length > kept {
|
||||
this.sink.notes.truncate();
|
||||
}
|
||||
}
|
||||
|
||||
#! Counts the notes the checker made, which the most it makes bounds, and
|
||||
#! whether the program is valid, once some are made again.
|
||||
#! @param this The checker.
|
||||
def checker::recount_notes(&mut this): void {
|
||||
var count: u32 = 0;
|
||||
for i in 0..this.sink.notes.length {
|
||||
if this.sink.notes[i].origin != 0 {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
this.sink.count = count;
|
||||
this.failed = count != 0;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,491 @@
|
||||
#! @file lifetimes.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the lifetime warnings: where a function keeps a reference past what
|
||||
#! it refers to, as the checker is sure of it. A reference, a view, or an
|
||||
#! anonymous function refers to the locals it names, which end where their
|
||||
#! scopes do, and to a value a statement makes, which ends with the statement
|
||||
#! unless a name is bound to it. Nothing keeps what they refer to alive, so one
|
||||
#! that outlives it dangles, which is the program's mistake, as in C++.
|
||||
#!
|
||||
#! The checker is sure of what it sees written: a value refers to a local where
|
||||
#! it is `&` of the local's own storage, a `val` bound to such a value, an
|
||||
#! anonymous function naming the local, or a struct, union, or array literal
|
||||
#! holding one. It is sure the value outlives the local where it is returned
|
||||
#! from the function declaring the local, or written into a global, into what
|
||||
#! a parameter refers or points to, or into a local of a scope around the
|
||||
#! local's. A value a statement makes outlives it where it is returned, written
|
||||
#! anywhere, or held in a literal a name is bound to. What a call does with
|
||||
#! what it is given, the checker does not follow, and says nothing of.
|
||||
#!
|
||||
#! Only functions that are no generic's are walked, so each warning is said
|
||||
#! once, and `@allow` quiets those of a function.
|
||||
|
||||
import std::containers;
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! What a value refers to, as far as the checker is sure.
|
||||
enum lifetime_kind : u8 {
|
||||
none, #! Nothing it is sure of.
|
||||
local, #! A local, as `local` says.
|
||||
temporary, #! A value its statement makes.
|
||||
}
|
||||
|
||||
#! What a value refers to, the local where it is one, and the node of the
|
||||
#! value saying so: the `&`, the slice, the anonymous function, or the `val`
|
||||
#! named, within any literal holding it.
|
||||
struct lifetime_ref {
|
||||
var kind: lifetime_kind; #! What it is.
|
||||
var local: u32; #! The node declaring the local, where it is one.
|
||||
var at: u32; #! The node saying so, which a warning is made at.
|
||||
}
|
||||
|
||||
#! What a walk of a function's body holds. One is kept by the checker and
|
||||
#! walks each function in turn, so what it holds is made once.
|
||||
struct lifetime_walk {
|
||||
var scopes: vector<u32>; #! The scopes it is within, innermost last: the function, then each block, loop, test, arm, and anonymous function.
|
||||
var functions: vector<u32>; #! The function and the anonymous functions within it it is within, innermost last.
|
||||
var nodes: vector<u32>; #! The nodes each node being walked holds, which it walks in turn, those of the nodes around it before them.
|
||||
var notes: column<lifetime_note>; #! What was noted of each node of the file that may declare a local, by the node.
|
||||
var walk: u32; #! Which walk this is, counted from 1, so what earlier walks noted is told apart without being cleared.
|
||||
var depth: u32; #! How deeply the walk is nested, which a body nested past `lifetime_depth` stops.
|
||||
}
|
||||
|
||||
#! Where a node that may declare a local is: its scope, and the function or
|
||||
#! anonymous function it is in, as the walk that noted them found them.
|
||||
struct lifetime_note {
|
||||
var scope: u32; #! The scope it is in.
|
||||
var owner: u32; #! The function or anonymous function it is in.
|
||||
var walk: u32; #! The walk that noted them.
|
||||
}
|
||||
|
||||
#! Makes a walk, which walks nothing until `check_lifetimes` starts it.
|
||||
#! @returns The walk.
|
||||
def lifetime_walk::new(): lifetime_walk {
|
||||
return lifetime_walk {
|
||||
scopes = vector::<u32>::new(),
|
||||
functions = vector::<u32>::new(),
|
||||
nodes = vector::<u32>::new(),
|
||||
notes = column::<lifetime_note>::new()
|
||||
};
|
||||
}
|
||||
|
||||
#! What the walk noted of a node, or nothing noted where it noted nothing.
|
||||
#! @param this The walk.
|
||||
#! @param node The node.
|
||||
#! @returns The note.
|
||||
def lifetime_walk::note_of(&this, node: u32): lifetime_note {
|
||||
if (node as u64) < this.notes.length {
|
||||
val held: lifetime_note = this.notes.p[node];
|
||||
return held if held.walk == this.walk;
|
||||
}
|
||||
return lifetime_note {};
|
||||
}
|
||||
|
||||
#! How deeply a walk goes before it stops, saying nothing of what is deeper.
|
||||
const lifetime_depth: u32 = 400;
|
||||
|
||||
#! Warns of where a function's body keeps a reference past what it refers to,
|
||||
#! unless it is a generic's, which each instance would warn of again, or is
|
||||
#! `@allow`.
|
||||
#! @param this The checker.
|
||||
#! @param id The function's declaration.
|
||||
pub def checker::check_lifetimes(&mut this, id: u32): void {
|
||||
return if this.decls.has(id, df::generic) || this.decls.has(id, df::allows) || this.decls.has(id, df::accessor);
|
||||
val node: u32 = this.decls.nodes.p[id];
|
||||
return if node == 0 || this.kind_of(node) != nk::function;
|
||||
val walk := &mut this.lifetimes;
|
||||
walk.walk++;
|
||||
walk.scopes.clear();
|
||||
walk.functions.clear();
|
||||
walk.nodes.clear();
|
||||
walk.depth = 0;
|
||||
this.lifetime_visit(walk, node);
|
||||
}
|
||||
|
||||
#! Walks a node, noting where what it declares is, then warns of what it keeps
|
||||
#! past what that refers to.
|
||||
#! @param this The checker.
|
||||
#! @param walk The walk.
|
||||
#! @param node The node.
|
||||
def checker::lifetime_visit(&mut this, walk: &mut lifetime_walk, node: u32): void {
|
||||
return if node == 0 || walk.depth >= lifetime_depth;
|
||||
val kind := this.kind_of(node);
|
||||
if kind == nk::variable || kind == nk::param || kind == nk::name || kind == nk::reference {
|
||||
if walk.scopes.length != 0 {
|
||||
walk.notes.put(node, lifetime_note { scope = walk.scopes.last(), owner = walk.functions.last(), walk = walk.walk });
|
||||
}
|
||||
}
|
||||
|
||||
val function := kind == nk::function || kind == nk::lambda;
|
||||
val scope := function || kind == nk::block || kind == nk::for_stmt || kind == nk::if_stmt
|
||||
|| kind == nk::while_stmt || kind == nk::match_arm;
|
||||
if function {
|
||||
walk.functions.append(node);
|
||||
}
|
||||
if scope {
|
||||
walk.scopes.append(node);
|
||||
}
|
||||
|
||||
# Only what was checked is walked: of a `when` or an `if const`, the branch
|
||||
# taken, and of a block, the statements up to one decided to leave it. The
|
||||
# nodes a node holds are put on the walk's, past those of the nodes around
|
||||
# it, walked from there, and taken off again.
|
||||
val mark := walk.nodes.length;
|
||||
match kind {
|
||||
nk::when_block => walk.nodes.append(this.when_branch(node));
|
||||
nk::if_const => {
|
||||
val condition := this.left_of(node);
|
||||
if this.is_known(condition) {
|
||||
walk.nodes.append(this.value_at(condition).magnitude != 0 ? this.record(node, if_slot::then) : this.record(node, if_slot::other));
|
||||
}
|
||||
}
|
||||
nk::block => {
|
||||
val run := this.left_of(node);
|
||||
for i in 0..this.run_length(run) {
|
||||
val each := this.run_at(run, i as u32);
|
||||
walk.nodes.append(each);
|
||||
break if this.lifetime_skips(each);
|
||||
}
|
||||
}
|
||||
else => this.syn().children(node, &mut walk.nodes);
|
||||
}
|
||||
val end := walk.nodes.length;
|
||||
walk.depth++;
|
||||
for i in mark..end {
|
||||
this.lifetime_visit(walk, walk.nodes[i]);
|
||||
}
|
||||
walk.depth--;
|
||||
if end != mark {
|
||||
walk.nodes.resize(mark);
|
||||
}
|
||||
|
||||
match kind {
|
||||
nk::return_stmt => this.lifetime_returned(walk, this.left_of(node));
|
||||
nk::lambda => {
|
||||
# A lambda whose body is a value returns it.
|
||||
val body := this.record(node, lambda_slot::body);
|
||||
if body != 0 && this.kind_of(body) != nk::block {
|
||||
this.lifetime_returned(walk, body);
|
||||
}
|
||||
}
|
||||
nk::assign => {
|
||||
if this.token_kind(node) == tk::assign {
|
||||
this.lifetime_written(walk, this.left_of(node), this.right_of(node));
|
||||
}
|
||||
}
|
||||
nk::variable => {
|
||||
# A name bound to a value its statement makes refers to it as long as
|
||||
# the name lives, but a literal holding a reference to one does not.
|
||||
val value := this.record(node, variable_slot::value);
|
||||
if value != 0 && this.kind_of(value) != nk::reference {
|
||||
val held := this.lifetime_of(walk, value, 0);
|
||||
if held.kind == lifetime_kind::temporary {
|
||||
this.warn(held.at, ec::lifetime,
|
||||
"The value referred to is made in the statement, and ends with it, so the value holding a reference to it outlives it. Bound to a name, as `val p := &point { x = 1 };`, a value lives as long as the name.");
|
||||
}
|
||||
}
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
|
||||
if scope {
|
||||
walk.scopes.truncate();
|
||||
}
|
||||
if function {
|
||||
walk.functions.truncate();
|
||||
}
|
||||
}
|
||||
|
||||
#! Warns where a value returned refers to a local of the function returning it,
|
||||
#! or to a value the `return` makes.
|
||||
#! @param this The checker.
|
||||
#! @param walk The walk.
|
||||
#! @param value The value returned, or 0.
|
||||
def checker::lifetime_returned(&mut this, walk: &mut lifetime_walk, value: u32): void {
|
||||
return if value == 0 || walk.functions.length == 0;
|
||||
val held := this.lifetime_of(walk, value, 0);
|
||||
if held.kind == lifetime_kind::temporary {
|
||||
this.warn(held.at, ec::lifetime, "The value returned refers to a value made in the statement, which ends with it.");
|
||||
return;
|
||||
}
|
||||
return if held.kind != lifetime_kind::local || walk.note_of(held.local).owner != walk.functions.last();
|
||||
var text := string::from("The value returned refers to `", nothing {});
|
||||
text.append(this.names.text(this.local_name(held.local)));
|
||||
text.append("`, which ends as the function returns.");
|
||||
this.warn_text(held.at, ec::lifetime, &text, held.local);
|
||||
}
|
||||
|
||||
#! Warns where a value written to a place refers to a local the place outlives,
|
||||
#! or to a value the statement makes.
|
||||
#! @param this The checker.
|
||||
#! @param walk The walk.
|
||||
#! @param target The place written.
|
||||
#! @param value The value written.
|
||||
def checker::lifetime_written(&mut this, walk: &mut lifetime_walk, target: u32, value: u32): void {
|
||||
return if this.kind_of(target) == nk::name && this.names.text(this.name_of(target)) == "_";
|
||||
val held := this.lifetime_of(walk, value, 0);
|
||||
if held.kind == lifetime_kind::temporary {
|
||||
this.warn(held.at, ec::lifetime,
|
||||
"The value referred to is made in the statement, and ends with it, so the reference written here outlives it. Bound to a name, as `val p := &point { x = 1 };`, a value lives as long as the name.");
|
||||
return;
|
||||
}
|
||||
return if held.kind != lifetime_kind::local;
|
||||
|
||||
# The local or global whose storage the place is within, and whether it is
|
||||
# reached through a reference or pointer.
|
||||
var at := target;
|
||||
var through := false;
|
||||
var steps := 0;
|
||||
while steps < 64 {
|
||||
steps++;
|
||||
val kind := this.kind_of(at);
|
||||
if kind == nk::member || kind == nk::index || kind == nk::slice {
|
||||
val object := this.left_of(at);
|
||||
val held_type := this.types.kind_of(this.unalias(this.type_at(object)));
|
||||
if kind == nk::member {
|
||||
through = through || held_type == ty::reference || held_type == ty::pointer;
|
||||
} else {
|
||||
through = through || held_type != ty::fixed;
|
||||
}
|
||||
at = object;
|
||||
continue;
|
||||
}
|
||||
if kind == nk::unary && this.token_kind(at) == tk::star {
|
||||
through = true;
|
||||
at = this.left_of(at);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return if this.kind_of(at) != nk::name;
|
||||
val ref := this.ref_at(at);
|
||||
return if ref == 0 || (ref & ref_type) != 0;
|
||||
|
||||
var outlives := false;
|
||||
var into := string::new(nothing {});
|
||||
if (ref & ref_local) == 0 {
|
||||
# A global outlives every local.
|
||||
outlives = this.decls.kinds.p[ref & ref_mask] == dk::variable;
|
||||
into.append("a global");
|
||||
} else {
|
||||
val root := ref & ref_mask;
|
||||
if through {
|
||||
# What a parameter refers or points to is the caller's, which outlives
|
||||
# every local of the function.
|
||||
val root_type := this.types.kind_of(this.unalias(this.type_at(root)));
|
||||
outlives = this.kind_of(root) == nk::param && (root_type == ty::reference || root_type == ty::pointer);
|
||||
into.append("what `");
|
||||
into.append(this.names.text(this.local_name(root)));
|
||||
into.append("` refers to");
|
||||
} else {
|
||||
# A local of a scope around the local's outlives it.
|
||||
val outer := this.lifetime_scope(walk, root);
|
||||
val inner := this.lifetime_scope(walk, held.local);
|
||||
outlives = outer >= 0 && inner >= 0 && outer < inner;
|
||||
into.append("`");
|
||||
into.append(this.names.text(this.local_name(root)));
|
||||
into.append("`");
|
||||
}
|
||||
}
|
||||
return if !outlives;
|
||||
var text := string::from("`", nothing {});
|
||||
text.append(this.names.text(this.local_name(held.local)));
|
||||
text.append("` ends where its scope does, so the reference written to ");
|
||||
text.append(into.view());
|
||||
text.append(" outlives it.");
|
||||
this.warn_text(held.at, ec::lifetime, &text, held.local);
|
||||
}
|
||||
|
||||
#! Where among the scopes the walk is within a local is declared.
|
||||
#! @param this The checker.
|
||||
#! @param walk The walk.
|
||||
#! @param local The node declaring the local.
|
||||
#! @returns The index of its scope, or -1 where it is in none of them.
|
||||
def checker::lifetime_scope(&this, walk: &lifetime_walk, local: u32): i64 {
|
||||
val scope := walk.note_of(local).scope;
|
||||
return -1 if scope == 0;
|
||||
for i in 0..walk.scopes.length {
|
||||
return i as i64 if walk.scopes[i] == scope;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
#! What a value refers to, as far as the checker is sure.
|
||||
#! @param this The checker.
|
||||
#! @param walk The walk.
|
||||
#! @param node The value.
|
||||
#! @param depth How many `val`s it was followed through.
|
||||
#! @returns What it refers to.
|
||||
def checker::lifetime_of(&mut this, walk: &lifetime_walk, node: u32, depth: u32): lifetime_ref {
|
||||
val none := lifetime_ref { kind = lifetime_kind::none };
|
||||
return none if node == 0 || depth > 8;
|
||||
match this.kind_of(node) {
|
||||
nk::reference => {
|
||||
val inner := this.left_of(node);
|
||||
if this.is_place(inner) {
|
||||
val root := this.lifetime_root(inner);
|
||||
return root != 0 ? lifetime_ref { kind = lifetime_kind::local, local = root, at = node } : none;
|
||||
}
|
||||
# `&` of a reference refers to what it does, which is not known.
|
||||
val given := this.types.kind_of(this.unalias(this.type_at(inner)));
|
||||
return given == ty::reference ? none : lifetime_ref { kind = lifetime_kind::temporary, at = node };
|
||||
}
|
||||
nk::slice => {
|
||||
val object := this.left_of(node);
|
||||
val held := this.types.kind_of(this.unalias(this.type_at(object)));
|
||||
return none if held != ty::fixed || !this.is_place(object);
|
||||
val root := this.lifetime_root(object);
|
||||
return root != 0 ? lifetime_ref { kind = lifetime_kind::local, local = root, at = node } : none;
|
||||
}
|
||||
nk::name => {
|
||||
# A `val` refers to what its value does, and one bound to a value its
|
||||
# statement makes refers to it as long as the `val` lives.
|
||||
val ref := this.ref_at(node);
|
||||
return none if (ref & ref_local) == 0;
|
||||
val local := ref & ref_mask;
|
||||
return none if this.kind_of(local) != nk::variable || this.node_has(local, nf::mutable);
|
||||
val value := this.record(local, variable_slot::value);
|
||||
return none if value == 0;
|
||||
val held := this.lifetime_of(walk, value, depth + 1);
|
||||
if held.kind == lifetime_kind::temporary {
|
||||
return this.kind_of(value) == nk::reference ? lifetime_ref { kind = lifetime_kind::local, local = local, at = node } : none;
|
||||
}
|
||||
return held.kind == lifetime_kind::none ? none : lifetime_ref { kind = held.kind, local = held.local, at = node };
|
||||
}
|
||||
nk::lambda => {
|
||||
# An anonymous function refers to the locals around it that it names.
|
||||
var held := this.lifetime_captured(walk, node);
|
||||
held.at = node;
|
||||
return held;
|
||||
}
|
||||
nk::construct => {
|
||||
for &each in this.run_view(this.right_of(node)) {
|
||||
val held := this.lifetime_of(walk, this.left_of(each), depth);
|
||||
return held if held.kind != lifetime_kind::none;
|
||||
}
|
||||
return none;
|
||||
}
|
||||
nk::array => {
|
||||
for &each in this.run_view(this.left_of(node)) {
|
||||
val held := this.lifetime_of(walk, each, depth);
|
||||
return held if held.kind != lifetime_kind::none;
|
||||
}
|
||||
return none;
|
||||
}
|
||||
else => return none;
|
||||
}
|
||||
}
|
||||
|
||||
#! The local an anonymous function names that a function around it declares,
|
||||
#! the one declared first where it names several.
|
||||
#! @param this The checker.
|
||||
#! @param walk The walk.
|
||||
#! @param node The `lambda` node.
|
||||
#! @returns The local, or nothing it is sure of.
|
||||
def checker::lifetime_captured(&mut this, walk: &lifetime_walk, node: u32): lifetime_ref {
|
||||
var todo := vector::<u32>::new();
|
||||
this.syn().children(node, &mut todo);
|
||||
var seen := 0;
|
||||
var first: u32 = 0;
|
||||
while todo.length != 0 && seen < 4096 {
|
||||
seen++;
|
||||
val at: u32 = todo.last();
|
||||
todo.truncate();
|
||||
if this.kind_of(at) == nk::name {
|
||||
val ref := this.ref_at(at);
|
||||
if (ref & ref_local) != 0 {
|
||||
val local := ref & ref_mask;
|
||||
val owner := walk.note_of(local).owner;
|
||||
if owner != 0 && walk.functions.view().contains(&owner)
|
||||
&& (first == 0 || this.node_offset_of(local) < this.node_offset_of(first)) {
|
||||
first = local;
|
||||
}
|
||||
}
|
||||
}
|
||||
this.syn().children(at, &mut todo);
|
||||
}
|
||||
return first != 0 ? lifetime_ref { kind = lifetime_kind::local, local = first } : lifetime_ref { kind = lifetime_kind::none };
|
||||
}
|
||||
|
||||
#! The local whose own storage a place is within, past fields and the elements
|
||||
#! of fixed arrays it holds as values. A local that is a reference names what
|
||||
#! it refers to, so a place within it is within no local the checker knows.
|
||||
#! @param this The checker.
|
||||
#! @param node The place.
|
||||
#! @returns The node declaring the local, or 0 where the place is not within one.
|
||||
def checker::lifetime_root(&mut this, node: u32): u32 {
|
||||
var at := node;
|
||||
var steps := 0;
|
||||
while steps < 64 {
|
||||
steps++;
|
||||
val kind := this.kind_of(at);
|
||||
if kind == nk::member || kind == nk::index {
|
||||
val object := this.left_of(at);
|
||||
val held := this.types.kind_of(this.unalias(this.type_at(object)));
|
||||
return 0 if kind == nk::member && (held == ty::reference || held == ty::pointer);
|
||||
return 0 if kind == nk::index && held != ty::fixed;
|
||||
if kind == nk::member {
|
||||
val ref := this.ref_at(at);
|
||||
return 0 if ref == 0 || (ref & (ref_local | ref_type)) != 0 || this.decls.kinds.p[ref] != dk::field;
|
||||
}
|
||||
at = object;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return 0 if this.kind_of(at) != nk::name;
|
||||
val ref := this.ref_at(at);
|
||||
return 0 if (ref & ref_local) == 0;
|
||||
val held := this.types.kind_of(this.unalias(this.type_at(ref & ref_mask)));
|
||||
return held == ty::reference ? 0 : ref & ref_mask;
|
||||
}
|
||||
|
||||
#! Whether a statement leaves where it was decided while checking, so the
|
||||
#! checker checked nothing after it, as the emitter's `skips` says.
|
||||
#! @param this The checker.
|
||||
#! @param node The statement.
|
||||
#! @returns Whether it does.
|
||||
def checker::lifetime_skips(&mut this, node: u32): bool {
|
||||
match this.kind_of(node) {
|
||||
nk::block => {
|
||||
val run := this.left_of(node);
|
||||
for i in 0..this.run_length(run) {
|
||||
return true if this.lifetime_skips(this.run_at(run, i as u32));
|
||||
}
|
||||
}
|
||||
nk::when_block => return this.lifetime_skips(this.when_branch(node));
|
||||
nk::if_const => {
|
||||
val condition := this.left_of(node);
|
||||
return false if !this.is_known(condition);
|
||||
val then := this.record(node, if_slot::then);
|
||||
val other := this.record(node, if_slot::other);
|
||||
if this.value_at(condition).magnitude != 0 {
|
||||
return this.lifetime_skips(then) || (other == 0 && this.has_flag(then, rf::leaves));
|
||||
}
|
||||
return other != 0 && this.lifetime_skips(other);
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Where in the file a node's token begins.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns The token's offset.
|
||||
def checker::node_offset_of(&this, node: u32): u32 {
|
||||
val syntax := &this.syn();
|
||||
return syntax.token_offsets[syntax.node_tokens[node]];
|
||||
}
|
||||
|
||||
#! The name a local is declared with.
|
||||
#! @param this The checker.
|
||||
#! @param local The node declaring it.
|
||||
#! @returns The name's ID.
|
||||
def checker::local_name(&this, local: u32): u32 {
|
||||
return this.name_of(local);
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
#! @file link.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the linking of what every file declared: each file's imports are
|
||||
#! found among the modules declared, and each declaration made through a type,
|
||||
#! as `vec2::length` or `list<T>::iter`, becomes a member of its type, with the
|
||||
#! type parameters its receiver names. A nested type may itself wait for its
|
||||
#! type, so those whose types are not yet members wait for another pass.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! Links the imports and the declarations made through types.
|
||||
#! @param this The checker.
|
||||
pub def checker::link(&mut this): void {
|
||||
var imports := vector::<vector<u32>>::new();
|
||||
for _ in 0..this.units.length {
|
||||
imports.append(vector::<u32>::new());
|
||||
}
|
||||
|
||||
for i in 0..this.pending_imports.length {
|
||||
val each := this.pending_imports[i];
|
||||
val file := pair_high(each);
|
||||
val node := pair_low(each);
|
||||
this.use_table(this.units[file].table);
|
||||
|
||||
val found := this.module_path(this.left_of(node), false);
|
||||
if found == 0 {
|
||||
this.report(node, ec::undefined, "No file declares this module.");
|
||||
continue;
|
||||
}
|
||||
imports[file].append(found);
|
||||
}
|
||||
|
||||
for file in 0..this.units.length {
|
||||
val run := this.decls.make_list(imports[file].view());
|
||||
this.units[file].imports = run;
|
||||
}
|
||||
|
||||
this.attach_pending();
|
||||
this.give_accessors_params();
|
||||
}
|
||||
|
||||
#! Makes each declaration made through a type a member of it. Each pass attaches
|
||||
#! what it can. One whose type is a nested type not yet attached waits for the
|
||||
#! next, and what is left when a pass attaches nothing names no type.
|
||||
#! @param this The checker.
|
||||
def checker::attach_pending(&mut this): void {
|
||||
var waiting := vector::<u32>::new();
|
||||
waiting.extend(this.pending.view());
|
||||
|
||||
var progress := true;
|
||||
while progress && waiting.length != 0 {
|
||||
progress = false;
|
||||
var later := vector::<u32>::new();
|
||||
for &id in waiting {
|
||||
if this.attach(id, false) {
|
||||
progress = true;
|
||||
} else {
|
||||
later.append(id);
|
||||
}
|
||||
}
|
||||
waiting = move(&mut later);
|
||||
}
|
||||
|
||||
for &id in waiting {
|
||||
this.attach(id, true);
|
||||
}
|
||||
}
|
||||
|
||||
#! Gives each accessor its property's type parameters, which its receiver named.
|
||||
#! @param this The checker.
|
||||
def checker::give_accessors_params(&mut this): void {
|
||||
for id in 1..this.decls.count {
|
||||
continue if !this.decls.has(id as u32, df::accessor) || this.decls.kinds.p[id] == dk::none;
|
||||
val params: u32 = this.decls.params.p[this.decls.owners.p[id]];
|
||||
this.decls.params.p[id] = params;
|
||||
if params != 0 {
|
||||
this.decls.mark(id as u32, df::generic);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Makes the declaration a member of the type its receiver names.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @param last Whether this is the last chance, which reports a receiver
|
||||
#! naming no type rather than waiting.
|
||||
#! @returns Whether it was attached, or reported.
|
||||
def checker::attach(&mut this, id: u32, last: bool): bool {
|
||||
val saved := this.at;
|
||||
this.use_table(this.units[this.decls.files.p[id]].table);
|
||||
this.at.home = this.decls.modules.p[id];
|
||||
# A receiver is a path from the module, which no type around it shortens.
|
||||
this.at.scope = 0;
|
||||
|
||||
val node: u32 = this.decls.nodes.p[id];
|
||||
val receiver := this.receiver_of(node);
|
||||
this.decls.top = this.decls.tops.p[id];
|
||||
val owner := this.receiver_decl(receiver, last);
|
||||
if owner == 0 {
|
||||
this.at = saved;
|
||||
this.decls.top = 0;
|
||||
if last {
|
||||
this.decls.mark(id, df::failed);
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
# What a trait asks for is declared within it. Through it, outside it, only
|
||||
# functions of its own are, which take no `this`.
|
||||
if this.decls.kinds.p[owner] == dk::trait_type
|
||||
&& (this.decls.kinds.p[id] != dk::function || this.decls.has(id, df::method)) {
|
||||
this.report(receiver, ec::invalid,
|
||||
"A trait has no methods, associated variables, or nested types declared outside it. What it asks for is declared within it, and outside it only functions of its own, which take no `this`, as `def real::parse<T>(text: strview)`.");
|
||||
this.decls.mark(id, df::failed);
|
||||
this.at = saved;
|
||||
this.decls.top = 0;
|
||||
return true;
|
||||
}
|
||||
# A function of the trait's own takes a name it does not ask for.
|
||||
if this.decls.kinds.p[owner] == dk::trait_type {
|
||||
val asked := this.decls.member(owner, this.decls.names.p[id]);
|
||||
if asked != 0 && this.decls.owners.p[asked] == owner && !this.receiver_declared(asked) {
|
||||
this.report(node, ec::duplicate, "The trait already asks for a member of this name.");
|
||||
this.decls.mark(id, df::failed);
|
||||
this.at = saved;
|
||||
this.decls.top = 0;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
# Each segment of the receiver names the type parameters of the type it
|
||||
# names, as `T` of `box<T>::get`, which the declaration takes first.
|
||||
var params := vector::<u32>::new();
|
||||
var level := owner;
|
||||
for step in 0..this.segment_count(receiver) {
|
||||
val index := this.segment_count(receiver) - 1 - step as u32;
|
||||
val named := this.segment_args(receiver, index);
|
||||
val made := this.declare_params(named, id);
|
||||
# A `where` bounding the type's parameters further makes the method one only
|
||||
# the types meeting it have.
|
||||
for &written in this.run_view(named) {
|
||||
if this.kind_of(written) == nk::type_param && this.left_of(written) != 0 {
|
||||
this.decls.mark(id, df::bounding);
|
||||
}
|
||||
}
|
||||
for k in 0..made.length {
|
||||
params.insert_at(k, made[k]);
|
||||
}
|
||||
|
||||
# Each stands for a parameter of the type, whose bounds it takes.
|
||||
val wanted := this.own_param_count(level);
|
||||
val owned: u32 = this.decls.params.p[level];
|
||||
val total := this.decls.list_length(owned);
|
||||
for k in 0..made.length {
|
||||
if k < wanted as u64 && total >= wanted {
|
||||
val source := this.decls.list_at(owned, total - wanted + k as u32);
|
||||
val param: u32 = made[k];
|
||||
this.mirrors.put(param, source);
|
||||
# A constant parameter of the type is named a constant here too.
|
||||
if this.decls.has(source, df::valued) {
|
||||
this.decls.mark(param, df::valued);
|
||||
} else if this.kind_of(this.decls.nodes.p[param]) == nk::const_param {
|
||||
this.report(this.decls.nodes.p[param], ec::generic,
|
||||
"A type parameter of the type is named here without `const`.");
|
||||
}
|
||||
}
|
||||
}
|
||||
if made.length as u32 != wanted && level != 0 {
|
||||
var text := string::from("`", nothing {});
|
||||
text.append(this.decl_text(level));
|
||||
val words := $"` takes {wanted} type parameters, which a declaration through it names, as `box<T>::get`.";
|
||||
text.append(words.view());
|
||||
this.report_text(this.segment_node(receiver, index), ec::generic, &text);
|
||||
}
|
||||
level = this.decls.owners.p[level];
|
||||
break if level == 0 || this.decls.kinds.p[level] == dk::none;
|
||||
}
|
||||
|
||||
# A variable of a generic type would be one for each of its instances, which
|
||||
# nothing makes, so it is declared through an alias of one, as `vec3f::zero`.
|
||||
if this.decls.kinds.p[id] == dk::variable && params.length != 0 {
|
||||
this.report(receiver, ec::invalid,
|
||||
"A generic type has no variables of its own, since each instance would need its own; declare it through an alias of one instance, as `val vec3f::zero`.");
|
||||
this.decls.mark(id, df::failed);
|
||||
}
|
||||
|
||||
val own: u32 = this.decls.params.p[id];
|
||||
params.extend(this.decls.list_view(own));
|
||||
this.decls.params.p[id] = this.decls.make_list(params.view());
|
||||
if params.length != 0 {
|
||||
this.decls.mark(id, df::generic);
|
||||
}
|
||||
|
||||
this.add_member(owner, id);
|
||||
this.decls.top = 0;
|
||||
this.at = saved;
|
||||
return true;
|
||||
}
|
||||
|
||||
#! How many type parameters a type declares of its own, not counting those of
|
||||
#! the type it is nested in.
|
||||
#! @param this The checker.
|
||||
#! @param id The type's declaration.
|
||||
#! @returns How many.
|
||||
pub def checker::own_param_count(&this, id: u32): u32 {
|
||||
return 0 if id == 0 || this.decls.kinds.p[id] == dk::builtin;
|
||||
|
||||
val saved_file: u32 = this.decls.files.p[id];
|
||||
val syntax := &this.units[saved_file].syntax;
|
||||
val node: u32 = this.decls.nodes.p[id];
|
||||
val kind := syntax.node_kinds[node];
|
||||
return 0 if kind != nk::struct_decl && kind != nk::union_decl && kind != nk::trait_decl
|
||||
&& kind != nk::alias && kind != nk::function;
|
||||
|
||||
# A pattern, `def(Ts...): R` or `L[N]`, declares one for each type parameter it
|
||||
# names.
|
||||
val record := syntax.node_lefts[node];
|
||||
var made: u32 = 0;
|
||||
for &each in syntax.run_view(syntax.extras[record as u64 + decl_slot::type_params as u64]) {
|
||||
if syntax.node_kinds[each] == nk::array_pattern {
|
||||
made += syntax.node_rights[each] != 0 ? 2 : 1;
|
||||
continue;
|
||||
}
|
||||
if syntax.node_kinds[each] != nk::type_pattern {
|
||||
made++;
|
||||
continue;
|
||||
}
|
||||
val inner := syntax.node_lefts[each];
|
||||
made += syntax.run_length(inner) + (syntax.node_rights[each] != 0 ? 1 : 0);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The type declaration a receiver names, or 0 where it names none yet.
|
||||
#! @param this The checker.
|
||||
#! @param receiver The receiver's `type_name` node.
|
||||
#! @param last Whether this is the last chance, which reports a receiver
|
||||
#! naming no type.
|
||||
#! @returns The declaration, or 0.
|
||||
def checker::receiver_decl(&mut this, receiver: u32, last: bool): u32 {
|
||||
var at: u32 = 0;
|
||||
var home: u32 = 0;
|
||||
var in_module := false;
|
||||
for i in 0..this.segment_count(receiver) {
|
||||
val name := this.segment_name(receiver, i as u32);
|
||||
if i == 0 {
|
||||
at = this.lookup_global(name, 0);
|
||||
if at == 0 {
|
||||
home = this.lookup_module(name);
|
||||
in_module = home != 0;
|
||||
}
|
||||
} else if in_module {
|
||||
at = this.modules.decl(home, name);
|
||||
if at == 0 {
|
||||
home = this.modules.find(home, name);
|
||||
in_module = home != 0;
|
||||
} else {
|
||||
in_module = false;
|
||||
}
|
||||
} else {
|
||||
at = this.decls.path_member(at, name);
|
||||
}
|
||||
|
||||
if at == 0 && !in_module {
|
||||
if last {
|
||||
this.report(this.segment_node(receiver, i as u32), ec::not_type,
|
||||
"A declaration is made through a type, and this names none.");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return 0 if in_module;
|
||||
if !this.is_type_decl(at) {
|
||||
if last {
|
||||
this.report(receiver, ec::not_type, "A declaration is made through a type, and this names none.");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
#! Whether the declaration declares a type.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns Whether it does.
|
||||
pub def checker::is_type_decl(&this, id: u32): bool {
|
||||
return match this.decls.kinds.p[id] {
|
||||
dk::builtin, dk::struct_type, dk::union_type, dk::enum_type, dk::trait_type,
|
||||
dk::alias_type, dk::type_param, dk::assoc_type => true,
|
||||
else => false
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
#! @file lookup.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains how names are found where they are written. A name is first what
|
||||
#! a scope binds it to, then what the types around it give, as `kind` within
|
||||
#! `token` is `token::kind`, then a declaration of the module it is written in,
|
||||
#! or of the modules holding that one, nearest first, then of the modules its
|
||||
#! file imports, then a built-in type, then a declaration of `core`'s root. The program, where the files declaring
|
||||
#! no module are, holds no module, so a module never names what it declares. A name a type gives that the module or
|
||||
#! a module holding it declares too is ambiguous, as are two imports declaring
|
||||
#! the name, unless they declare the same thing.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! What the name refers to where it is written, or 0 where nothing declares it.
|
||||
#! @param this The checker.
|
||||
#! @param name The ID of the name.
|
||||
#! @param node Where the name is written, for reporting it ambiguous, or 0.
|
||||
#! @returns A local or type parameter with its bit of `ref_local` or `ref_type`,
|
||||
#! a declaration, or 0.
|
||||
pub def checker::lookup(&mut this, name: u32, node: u32): u32 {
|
||||
val bound := this.bound(name);
|
||||
return bound if bound != 0;
|
||||
return this.lookup_global(name, node);
|
||||
}
|
||||
|
||||
#! The declaration the name refers to outside any scope, or 0.
|
||||
#! @param this The checker.
|
||||
#! @param name The ID of the name.
|
||||
#! @param node Where the name is written, for reporting it ambiguous, or 0.
|
||||
#! @returns The declaration, or 0.
|
||||
pub def checker::lookup_global(&mut this, name: u32, node: u32): u32 {
|
||||
return this.lookup_named(name, node, false).decl;
|
||||
}
|
||||
|
||||
#! The declaration the name refers to outside any scope where only a type is
|
||||
#! meant, as in a type, or 0.
|
||||
#! @param this The checker.
|
||||
#! @param name The ID of the name.
|
||||
#! @param node Where the name is written, for reporting it ambiguous, or 0.
|
||||
#! @returns The declaration, or 0.
|
||||
pub def checker::lookup_type(&mut this, name: u32, node: u32): u32 {
|
||||
return this.lookup_named(name, node, true).decl;
|
||||
}
|
||||
|
||||
#! The declaration the name refers to outside any scope, and where a type
|
||||
#! around it gives it, that type, given the arguments it has there.
|
||||
#! @param this The checker.
|
||||
#! @param name The ID of the name.
|
||||
#! @param node Where the name is written, for reporting it ambiguous, or 0.
|
||||
#! @param types Whether only a type is meant, so what else a type around it
|
||||
#! gives is passed over, as a member `u8` of an enum is in `u8`.
|
||||
#! @returns The declaration and the type giving it, or no declaration.
|
||||
pub def checker::lookup_named(&mut this, name: u32, node: u32, types: bool): checker::found {
|
||||
this.depend_name(name);
|
||||
val scoped := this.in_scope(name, types);
|
||||
var home := this.at.home;
|
||||
var steps := 0;
|
||||
while steps < 64 {
|
||||
val found := this.modules.decl(home, name);
|
||||
if found != 0 {
|
||||
if scoped.decl != 0 && scoped.decl != found && node != 0 {
|
||||
this.report_ambiguous(node, name, scoped.decl, found);
|
||||
}
|
||||
return scoped.decl != 0 ? scoped : checker::found { decl = found };
|
||||
}
|
||||
# The program is where the files declaring no module are, so it holds no
|
||||
# module: a module of one segment is within none.
|
||||
break if home == 0 || this.modules.parents[home] == 0;
|
||||
home = this.modules.parents[home];
|
||||
steps++;
|
||||
}
|
||||
return scoped if scoped.decl != 0;
|
||||
|
||||
var found: u32 = 0;
|
||||
var hidden: u32 = 0;
|
||||
val imports: u32 = this.units[this.at.file].imports;
|
||||
for &imported in this.decls.list_view(imports) {
|
||||
val each := this.modules.decl(imported, name);
|
||||
continue if each == 0;
|
||||
if !this.visible(each) {
|
||||
hidden = each;
|
||||
continue;
|
||||
}
|
||||
|
||||
if found != 0 && found != each {
|
||||
if node != 0 {
|
||||
var text := string::from("More than one imported module declares `", nothing {});
|
||||
text.append(this.names.text(name));
|
||||
text.append("`, so write the module it is of, as `io::println`.");
|
||||
this.report_text(node, ec::ambiguous, &text);
|
||||
}
|
||||
return checker::found { decl = found };
|
||||
}
|
||||
found = each;
|
||||
}
|
||||
|
||||
return checker::found { decl = found } if found != 0;
|
||||
if this.builtins.get(&name) is some(got) {
|
||||
return checker::found { decl = got };
|
||||
}
|
||||
|
||||
# Last, the names of `core`'s root, which every file sees, and which anything
|
||||
# declared or imported hides.
|
||||
val core := this.modules.find(0, word::core);
|
||||
if core != 0 && core != this.at.home {
|
||||
val each := this.modules.decl(core, name);
|
||||
if each != 0 {
|
||||
return checker::found { decl = each } if this.visible(each);
|
||||
hidden = hidden != 0 ? hidden : each;
|
||||
}
|
||||
}
|
||||
|
||||
# A declaration only hidden from where it is named is found, so what names
|
||||
# it is told it is not `pub` rather than that it does not exist.
|
||||
return checker::found { decl = hidden };
|
||||
}
|
||||
|
||||
#! What the types around where checking is give the name, innermost first.
|
||||
#! Within a type, and what is declared through it, its nested types and
|
||||
#! associated variables, and an enum's members, are named without it, as
|
||||
#! `kind` is `token::kind` within `token`. A field or method belongs to a value,
|
||||
#! so it is named through one, and a type's functions are named through the
|
||||
#! type, since they are often named for the free functions they implement, as
|
||||
#! `vector<T>::decode` calls `decode::<T>`.
|
||||
#! @param this The checker.
|
||||
#! @param name The ID of the name.
|
||||
#! @param types Whether only a type is meant.
|
||||
#! @returns The member and the type giving it, or no member.
|
||||
pub def checker::in_scope(&mut this, name: u32, types: bool): checker::found {
|
||||
var kind := this.at.scope;
|
||||
var steps := 0;
|
||||
while kind != 0 && steps < 16 {
|
||||
steps++;
|
||||
val decl := this.type_decl(kind);
|
||||
break if decl == 0;
|
||||
val member := this.scope_member(decl, name, types);
|
||||
return checker::found { decl = member, owner = kind } if member != 0;
|
||||
|
||||
# A type nested in another is named within that one, whose arguments are
|
||||
# the first of its own.
|
||||
val outer: u32 = this.decls.owners.p[decl];
|
||||
break if outer == 0 || !this.gives_scope(outer);
|
||||
kind = this.scope_type(outer, kind);
|
||||
}
|
||||
return checker::found {};
|
||||
}
|
||||
|
||||
#! The member of the name a type gives the names within it, or 0.
|
||||
#! @param this The checker.
|
||||
#! @param decl The type's declaration.
|
||||
#! @param name The ID of the name.
|
||||
#! @param types Whether only a type is meant.
|
||||
#! @returns The member, or 0.
|
||||
def checker::scope_member(&mut this, decl: u32, name: u32, types: bool): u32 {
|
||||
val nested := this.decls.member_in(decl, name, true);
|
||||
if nested != 0 {
|
||||
return this.visible(nested) ? nested : 0;
|
||||
}
|
||||
|
||||
val member := types ? 0 : this.decls.member_in(decl, name, false);
|
||||
return 0 if member == 0 || !this.visible(member);
|
||||
return match this.decls.kinds.p[member] {
|
||||
dk::variable, dk::enum_member => member,
|
||||
else => 0
|
||||
};
|
||||
}
|
||||
|
||||
#! Whether a type gives the names within it: a struct, union, or enum, or a
|
||||
#! built-in type. A trait gives its members `self` and the types it asks for.
|
||||
#! @param this The checker.
|
||||
#! @param decl The type's declaration.
|
||||
#! @returns Whether it does.
|
||||
pub def checker::gives_scope(&this, decl: u32): bool {
|
||||
return match this.decls.kinds.p[decl] {
|
||||
dk::struct_type, dk::union_type, dk::enum_type, dk::builtin => true,
|
||||
else => false
|
||||
};
|
||||
}
|
||||
|
||||
#! The type giving the names within a declaration: the type itself, or the
|
||||
#! one it is a member of or is declared through, given the arguments it is
|
||||
#! checked with, or 0.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @param args The pack of its type arguments, or 0 where it is checked as
|
||||
#! itself.
|
||||
#! @returns The type, or 0.
|
||||
pub def checker::scope_of(&mut this, id: u32, args: u32): u32 {
|
||||
var owner: u32 = this.decls.owners.p[id];
|
||||
var holder := id;
|
||||
match this.decls.kinds.p[id] {
|
||||
dk::type_param => return owner == 0 ? 0 : this.scope_of(owner, 0);
|
||||
dk::struct_type, dk::union_type, dk::enum_type => return this.own_scope(id, id, args);
|
||||
dk::field, dk::enum_member => return owner != 0 && this.gives_scope(owner) ? this.decls.types.p[owner] : 0;
|
||||
dk::function, dk::variable, dk::property, dk::alias_type, dk::trait_type => {}
|
||||
else => return 0;
|
||||
}
|
||||
|
||||
# An accessor is checked as a member of its property's type.
|
||||
if owner != 0 && this.decls.kinds.p[owner] == dk::property {
|
||||
holder = owner;
|
||||
owner = this.decls.owners.p[owner];
|
||||
}
|
||||
return 0 if owner == 0 || !this.gives_scope(owner);
|
||||
return this.own_scope(owner, holder, args);
|
||||
}
|
||||
|
||||
#! A type, given the first of the arguments of a declaration within it, which
|
||||
#! names the type's parameters first.
|
||||
#! @param this The checker.
|
||||
#! @param decl The type's declaration.
|
||||
#! @param holder The declaration within it.
|
||||
#! @param args The pack of the holder's type arguments, or 0 where it is
|
||||
#! checked as itself.
|
||||
#! @returns The type.
|
||||
def checker::own_scope(&mut this, decl: u32, holder: u32, args: u32): u32 {
|
||||
return this.decls.types.p[decl] if this.decls.kinds.p[decl] == dk::builtin;
|
||||
val count := this.decls.list_length(this.decls.params.p[decl]);
|
||||
val run: u32 = this.decls.params.p[holder];
|
||||
var given := vector::<u32>::new();
|
||||
for i in 0..count {
|
||||
if args != 0 && i < this.types.part_count(args) {
|
||||
given.append(this.types.part_at(args, i as u32));
|
||||
} else if i < this.decls.list_length(run) {
|
||||
given.append(this.decls.types.p[this.decls.list_at(run, i as u32)]);
|
||||
} else {
|
||||
given.append(bt::error);
|
||||
}
|
||||
}
|
||||
return this.types.named(decl, given.view());
|
||||
}
|
||||
|
||||
#! A type a nested one is declared through, given the first of the nested
|
||||
#! one's arguments.
|
||||
#! @param this The checker.
|
||||
#! @param outer The outer type's declaration.
|
||||
#! @param inner The nested type, given its arguments.
|
||||
#! @returns The outer type.
|
||||
def checker::scope_type(&mut this, outer: u32, inner: u32): u32 {
|
||||
return this.decls.types.p[outer] if this.decls.kinds.p[outer] == dk::builtin;
|
||||
val count := this.decls.list_length(this.decls.params.p[outer]);
|
||||
var given := vector::<u32>::new();
|
||||
for i in 0..count {
|
||||
given.append(this.types.kind_of(inner) == ty::named && i < this.types.part_count(inner)
|
||||
? this.types.part_at(inner, i as u32)
|
||||
: bt::error);
|
||||
}
|
||||
return this.types.named(outer, given.view());
|
||||
}
|
||||
|
||||
#! Reports a name both a type around it and its module give, which only a
|
||||
#! path tells apart.
|
||||
#! @param this The checker.
|
||||
#! @param node Where the name is written.
|
||||
#! @param name The ID of the name.
|
||||
#! @param scoped What the type gives it.
|
||||
#! @param other What the module gives it.
|
||||
def checker::report_ambiguous(&mut this, node: u32, name: u32, scoped: u32, other: u32): void {
|
||||
var text := string::from("`", nothing {});
|
||||
text.append(this.names.text(name));
|
||||
text.append("` names both `");
|
||||
var first := this.path_text(scoped);
|
||||
text.append(first.view());
|
||||
if this.decls.modules.p[other] == 0 && this.decls.owners.p[other] == 0 {
|
||||
text.append("` and the program's own `");
|
||||
text.append(this.names.text(name));
|
||||
text.append("`, so write `");
|
||||
text.append(first.view());
|
||||
text.append("` for the first, or rename one of them.");
|
||||
} else {
|
||||
text.append("` and `");
|
||||
var second := this.path_text(other);
|
||||
text.append(second.view());
|
||||
text.append("`, so write the path of the one meant.");
|
||||
}
|
||||
this.report_text(node, ec::ambiguous, &text);
|
||||
}
|
||||
|
||||
#! The path a declaration is written as from anywhere, as `token::kind` or
|
||||
#! `std::io::println`. One declared outside any module has only its name.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns The path.
|
||||
pub def checker::path_text(&this, id: u32): string {
|
||||
var made := string::new(nothing {});
|
||||
val owner: u32 = this.decls.owners.p[id];
|
||||
if owner != 0 && this.decls.kinds.p[id] != dk::type_param {
|
||||
made = this.path_text(owner);
|
||||
made.append("::");
|
||||
} else {
|
||||
var modules := vector::<u32>::new();
|
||||
var at: u32 = this.decls.modules.p[id];
|
||||
var steps := 0;
|
||||
while at != 0 && steps < 64 {
|
||||
modules.append(at);
|
||||
at = this.modules.parents[at];
|
||||
steps++;
|
||||
}
|
||||
var i := modules.length;
|
||||
while i > 0 {
|
||||
i--;
|
||||
made.append(this.names.text(this.modules.names[modules[i]]));
|
||||
made.append("::");
|
||||
}
|
||||
}
|
||||
made.append(this.names.text(this.decls.names.p[id]));
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Reports a name nothing declares where it is used. A module sees the names of
|
||||
#! those holding it without an import, so where no file of one was read, as a
|
||||
#! library's root left out, the note says so.
|
||||
#! @param this The checker.
|
||||
#! @param node The node naming it.
|
||||
#! @param name The ID of the name.
|
||||
pub def checker::report_undeclared(&mut this, node: u32, name: u32): void {
|
||||
var text := string::from("`", nothing {});
|
||||
text.append(this.names.text(name));
|
||||
text.append("` is not declared where it is used.");
|
||||
var at: u32 = this.at.home == 0 ? 0 : this.modules.parents[this.at.home];
|
||||
var steps := 0;
|
||||
while at != 0 && steps < 64 {
|
||||
if !this.modules.named[at] {
|
||||
text.append(" No file of `");
|
||||
text.append(this.module_text(at).view());
|
||||
text.append("`, which holds this file's module and whose names it sees, was read: is one missing?");
|
||||
break;
|
||||
}
|
||||
at = this.modules.parents[at];
|
||||
steps++;
|
||||
}
|
||||
this.report_text(node, ec::undefined, &text);
|
||||
}
|
||||
|
||||
#! A module's path, as `std::io`.
|
||||
#! @param this The checker.
|
||||
#! @param id The module.
|
||||
#! @returns The path.
|
||||
pub def checker::module_text(&this, id: u32): string {
|
||||
var made := string::new(nothing {});
|
||||
var at := id;
|
||||
var steps := 0;
|
||||
while at != 0 && steps < 64 {
|
||||
var each := string::from(this.names.text(this.modules.names[at]), nothing {});
|
||||
if made.length != 0 {
|
||||
each.append("::");
|
||||
each.append(made.view());
|
||||
}
|
||||
made = move(&mut each);
|
||||
at = this.modules.parents[at];
|
||||
steps++;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The module the name refers to where it is written: one within the module it
|
||||
#! is written in or a module holding it, or the last segment of an import.
|
||||
#! @param this The checker.
|
||||
#! @param name The ID of the name.
|
||||
#! @returns The module, or 0.
|
||||
pub def checker::lookup_module(&mut this, name: u32): u32 {
|
||||
var home := this.at.home;
|
||||
var steps := 0;
|
||||
while steps < 64 {
|
||||
val found := this.modules.find(home, name);
|
||||
return found if found != 0;
|
||||
break if home == 0;
|
||||
home = this.modules.parents[home];
|
||||
steps++;
|
||||
}
|
||||
|
||||
val imports: u32 = this.units[this.at.file].imports;
|
||||
for &imported in this.decls.list_view(imports) {
|
||||
return imported if this.modules.names[imported] == name;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! Whether the declaration can be named where checking is: it is `pub`, or
|
||||
#! declared in the module checked or one holding it.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns Whether it can.
|
||||
pub def checker::visible(&this, id: u32): bool {
|
||||
return true if this.decls.has(id, df::exported) || this.decls.kinds.p[id] == dk::builtin;
|
||||
|
||||
# A property is seen where an accessor of it is `pub`, as `pub get`.
|
||||
if this.decls.kinds.p[id] == dk::property {
|
||||
val run: u32 = this.decls.children.p[id];
|
||||
for &each in this.decls.list_view(run) {
|
||||
return true if this.decls.has(each, df::exported);
|
||||
}
|
||||
}
|
||||
|
||||
# Enum members, and what a trait asks for, are as visible as their type. A
|
||||
# field takes its own `pub`, as a method does.
|
||||
val owner: u32 = this.decls.owners.p[id];
|
||||
val kind: dk = this.decls.kinds.p[id];
|
||||
if owner != 0 && (kind == dk::enum_member
|
||||
|| (this.decls.kinds.p[owner] == dk::trait_type && !this.receiver_declared(id))) {
|
||||
return this.visible(owner);
|
||||
}
|
||||
|
||||
var home: u32 = this.decls.modules.p[id];
|
||||
return this.modules.within(this.at.home, home);
|
||||
}
|
||||
|
||||
#! Whether a trait asks for the declaration: it is declared within the trait,
|
||||
#! or is an accessor of a property that is. A function declared through a
|
||||
#! trait, outside it, as `def real::parse<T>`, is the trait's own instead,
|
||||
#! called through the trait's name as any type's static function is.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns Whether it does.
|
||||
pub def checker::trait_asks(&this, id: u32): bool {
|
||||
var at := id;
|
||||
var owner: u32 = this.decls.owners.p[id];
|
||||
if owner != 0 && this.decls.kinds.p[owner] == dk::property {
|
||||
at = owner;
|
||||
owner = this.decls.owners.p[owner];
|
||||
}
|
||||
return owner != 0 && this.decls.kinds.p[owner] == dk::trait_type && !this.receiver_declared(at);
|
||||
}
|
||||
|
||||
#! Whether a trait's default is compiled for each type taking it, with `self`
|
||||
#! that type, as the type's own methods are: one of a trait that is only a
|
||||
#! bound, which no table calls through. Any other default is compiled once,
|
||||
#! taking `this` as a reference to the trait.
|
||||
#! @param this The checker.
|
||||
#! @param id The method's declaration.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::typed_default(&mut this, id: u32): bool {
|
||||
return false if !this.trait_asks(id) || !this.has_body(id);
|
||||
val holder := this.enclosing_trait(id);
|
||||
return holder != 0 && holder != id && this.bound_only(holder);
|
||||
}
|
||||
|
||||
#! Whether a declaration was made through a type, outside it, rather than
|
||||
#! within it, so it takes its own `pub`.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns Whether it was.
|
||||
pub def checker::receiver_declared(&this, id: u32): bool {
|
||||
val syntax := &this.units[this.decls.files.p[id]].syntax;
|
||||
val node: u32 = this.decls.nodes.p[id];
|
||||
val kind := syntax.node_kinds[node];
|
||||
return false if kind != nk::function && kind != nk::variable && kind != nk::property;
|
||||
return syntax.extras[syntax.node_lefts[node] as u64 + decl_slot::receiver as u64] != 0;
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
#! @file nodes.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains how the checker reads the nodes of the file it is checking: their
|
||||
#! kinds, tokens, slots, records, and runs, and the names and text of tokens.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! The syntax of the file being checked.
|
||||
#! @param this The checker.
|
||||
#! @returns The syntax.
|
||||
pub def checker::syn(&this): &syntax {
|
||||
return this.units[this.at.file].syntax;
|
||||
}
|
||||
|
||||
#! The source of the file being checked.
|
||||
#! @param this The checker.
|
||||
#! @returns The source.
|
||||
pub def checker::src(&this): &source {
|
||||
return this.units[this.at.file].source;
|
||||
}
|
||||
|
||||
#! The kind of a node of the file being checked.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns Its kind.
|
||||
pub def checker::kind_of(&this, node: u32): nk {
|
||||
return this.at.kinds[node];
|
||||
}
|
||||
|
||||
#! The token a node of the file being checked says what it is by.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns The token's index.
|
||||
pub def checker::token_of(&this, node: u32): u32 {
|
||||
return this.at.tokens[node];
|
||||
}
|
||||
|
||||
#! A node's first slot, which its kind's shape says the meaning of.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns The slot.
|
||||
pub def checker::left_of(&this, node: u32): u32 {
|
||||
return this.at.lefts[node];
|
||||
}
|
||||
|
||||
#! A node's second slot, which its kind's shape says the meaning of.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns The slot.
|
||||
pub def checker::right_of(&this, node: u32): u32 {
|
||||
return this.at.rights[node];
|
||||
}
|
||||
|
||||
#! The name the node's token is, as a declaration's name or a `name` node's.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns The name's ID, or 0 where its token is no word.
|
||||
pub def checker::name_of(&this, node: u32): u32 {
|
||||
return this.at.names[this.at.tokens[node]];
|
||||
}
|
||||
|
||||
#! The name a parameter is known by: its own, or of one an accessor implies,
|
||||
#! whose token is the `get` or `set`, `this`, or a `set`'s `value`.
|
||||
#! @param this The checker.
|
||||
#! @param node The parameter's node, or any other.
|
||||
#! @returns The ID of the name.
|
||||
pub def checker::param_name(&this, node: u32): u32 {
|
||||
return this.name_of(node) if this.kind_of(node) != nk::param || !this.node_has(node, nf::implied);
|
||||
return this.name_of(node) == names::set_id && !this.node_has(node, nf::mutable) ? names::value_id : names::this_id;
|
||||
}
|
||||
|
||||
#! The kind of the node's token.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns The kind.
|
||||
pub def checker::token_kind(&this, node: u32): tk {
|
||||
return this.at.tkinds[this.at.tokens[node]];
|
||||
}
|
||||
|
||||
#! The text of the node's token, as it is written.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns The text, which views the file's source.
|
||||
pub def checker::text_of(&this, node: u32): strview {
|
||||
val syntax := &this.syn();
|
||||
val token := this.token_of(node);
|
||||
return this.src().make_lexeme(syntax.token_offsets[token], syntax.token_length(token, this.names));
|
||||
}
|
||||
|
||||
#! The slot of the node's record at the index, in whichever of its slots its
|
||||
#! shape says holds the record.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param index The slot's position in the record.
|
||||
#! @returns The slot, or 0 where the node has no record.
|
||||
pub def checker::record(&this, node: u32, index: u32): u32 {
|
||||
val at: u32 = shapes[this.at.kinds[node] as u64].left == slot::extra ? this.at.lefts[node] : this.at.rights[node];
|
||||
return this.at.extras[at + index];
|
||||
}
|
||||
|
||||
#! The flags of the node, wherever its shape keeps them.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns The flags, as `nf` says, or 0.
|
||||
pub def checker::node_flags(&this, node: u32): u32 {
|
||||
return this.syn().flags_at(node);
|
||||
}
|
||||
|
||||
#! Whether a node has a flag.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param flag The flag.
|
||||
#! @returns Whether it has it.
|
||||
pub def checker::node_has(&this, node: u32, flag: nf): bool {
|
||||
return (this.node_flags(node) & flag as u32) != 0;
|
||||
}
|
||||
|
||||
#! How many nodes a run of the file being checked holds.
|
||||
#! @param this The checker.
|
||||
#! @param run Where the run begins.
|
||||
#! @returns How many nodes it holds.
|
||||
pub def checker::run_length(&this, run: u32): u32 {
|
||||
return this.at.extras[run];
|
||||
}
|
||||
|
||||
#! A node of a run, by its position.
|
||||
#! @param this The checker.
|
||||
#! @param run Where the run begins.
|
||||
#! @param index The position, below its length.
|
||||
#! @returns The node.
|
||||
pub def checker::run_at(&this, run: u32, index: u32): u32 {
|
||||
return this.at.extras[run + 1 + index];
|
||||
}
|
||||
|
||||
#! The nodes of a run of the file being checked, where they are, which checking
|
||||
#! never moves.
|
||||
#! @param this The checker.
|
||||
#! @param run Where the run begins.
|
||||
#! @returns The nodes.
|
||||
pub def checker::run_view(&this, run: u32): span<u32> {
|
||||
return span::<u32>::over(this.at.extras + run + 1, this.at.extras[run] as u64);
|
||||
}
|
||||
|
||||
#! How many segments a `type_name` or `path` has.
|
||||
#! @param this The checker.
|
||||
#! @param node The `type_name` or `path` node.
|
||||
#! @returns How many.
|
||||
pub def checker::segment_count(&this, node: u32): u32 {
|
||||
val run := this.left_of(node);
|
||||
return run == 0 ? 1 : this.run_length(run);
|
||||
}
|
||||
|
||||
#! The name of a segment of a `type_name` or `path`.
|
||||
#! @param this The checker.
|
||||
#! @param node The `type_name` or `path` node.
|
||||
#! @param index The segment's position.
|
||||
#! @returns The ID of its name.
|
||||
pub def checker::segment_name(&this, node: u32, index: u32): u32 {
|
||||
val run := this.left_of(node);
|
||||
return run == 0 ? this.name_of(node) : this.name_of(this.run_at(run, index));
|
||||
}
|
||||
|
||||
#! The node of a segment, where it holds type arguments, or the `type_name`
|
||||
#! itself for one of a single segment.
|
||||
#! @param this The checker.
|
||||
#! @param node The `type_name` or `path` node.
|
||||
#! @param index The segment's position.
|
||||
#! @returns The node.
|
||||
pub def checker::segment_node(&this, node: u32, index: u32): u32 {
|
||||
val run := this.left_of(node);
|
||||
return run == 0 ? node : this.run_at(run, index);
|
||||
}
|
||||
|
||||
#! The run of type arguments a segment is given, or 0.
|
||||
#! @param this The checker.
|
||||
#! @param node The `type_name` or `path` node.
|
||||
#! @param index The segment's position.
|
||||
#! @returns The run, or 0.
|
||||
pub def checker::segment_args(&this, node: u32, index: u32): u32 {
|
||||
val run := this.left_of(node);
|
||||
return run == 0 ? 0 : this.left_of(this.run_at(run, index));
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
#! @file notes.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains how the checker reports what is wrong: at a node of the file being
|
||||
#! checked, or of another, with the instance of a generic it was found in and
|
||||
#! a related place where there is one. A note holds a copy of its text, made
|
||||
#! once the note is admitted, so text made for a note that is dropped, as one
|
||||
#! made while an argument is tried quietly, is let go of with what made it.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! Reports what is wrong at the node of the file being checked.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param code What kind of mistake it is.
|
||||
#! @param detail What the note says.
|
||||
pub def checker::report(&mut this, node: u32, code: ec, detail: strview): void {
|
||||
this.report_in(this.at.file, node, code, detail);
|
||||
}
|
||||
|
||||
#! Reports what is wrong at the node, with text made for it.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param code What kind of mistake it is.
|
||||
#! @param text What the note says, which the note copies.
|
||||
pub def checker::report_text(&mut this, node: u32, code: ec, text: &string): void {
|
||||
this.report_in(this.at.file, node, code, text.view());
|
||||
}
|
||||
|
||||
#! Reports what is wrong at the node of the file.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param node The node.
|
||||
#! @param code What kind of mistake it is.
|
||||
#! @param detail What the note says.
|
||||
pub def checker::report_in(&mut this, file: u32, node: u32, code: ec, detail: strview): void {
|
||||
this.report_place(file, node, code, detail, 0, 0, 0, "");
|
||||
}
|
||||
|
||||
#! Reports what is wrong at the declaration, in its own file, wherever checking
|
||||
#! is.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @param code What kind of mistake it is.
|
||||
#! @param detail What the note says.
|
||||
pub def checker::report_decl(&mut this, id: u32, code: ec, detail: strview): void {
|
||||
this.report_in(this.decls.files.p[id], this.decls.nodes.p[id], code, detail);
|
||||
}
|
||||
|
||||
#! Reports what is wrong at the node of the file, and a place it relates to,
|
||||
#! where it says something of one: to whatever hears the checker's notes, or in
|
||||
#! its notes.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param node The node.
|
||||
#! @param code What kind of mistake it is.
|
||||
#! @param detail What the note says.
|
||||
#! @param related_file The file of the place it relates to.
|
||||
#! @param related_offset Where that place begins.
|
||||
#! @param related_length How many bytes it covers.
|
||||
#! @param related What the note says of it, or empty where it relates
|
||||
#! to none.
|
||||
def checker::report_place(
|
||||
&mut this,
|
||||
file: u32,
|
||||
node: u32,
|
||||
code: ec,
|
||||
detail: strview,
|
||||
related_file: u32,
|
||||
related_offset: u32,
|
||||
related_length: u32,
|
||||
related: strview
|
||||
): void {
|
||||
if this.mute != 0 {
|
||||
this.dropped++;
|
||||
if code == ec::generic && detail.starts_with("Nothing gives") {
|
||||
this.uninferred++;
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.failed = true;
|
||||
this.errors++;
|
||||
return if !this.sink.admits();
|
||||
|
||||
val syntax := &this.units[file].syntax;
|
||||
val token := syntax.node_tokens[node];
|
||||
var made := note {
|
||||
file = file,
|
||||
offset = syntax.token_offsets[token],
|
||||
length = syntax.token_length(token, this.names),
|
||||
code = code,
|
||||
detail = string::from(detail, nothing {}),
|
||||
instance = this.instance_text(),
|
||||
related_file = related_file,
|
||||
related_offset = related_offset,
|
||||
related_length = related_length,
|
||||
related = string::from(related, nothing {}),
|
||||
origin = this.at.decl
|
||||
};
|
||||
this.sink.give(&mut made);
|
||||
}
|
||||
|
||||
#! Warns of what is likely wrong at the node of the file being checked, which
|
||||
#! never stops a program, nor marks what is checked as failed.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param code What kind of mistake it is about.
|
||||
#! @param detail What the note says.
|
||||
pub def checker::warn(&mut this, node: u32, code: ec, detail: strview): void {
|
||||
this.warn_place(node, code, detail, 0);
|
||||
}
|
||||
|
||||
#! Warns of what is likely wrong at the node, with text made for it, and the
|
||||
#! node declaring what it is about, where one is given.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param code What kind of mistake it is about.
|
||||
#! @param text What the note says, which the note copies.
|
||||
#! @param related The node declaring what it is about, in the same file, or 0.
|
||||
pub def checker::warn_text(&mut this, node: u32, code: ec, text: &string, related: u32): void {
|
||||
this.warn_place(node, code, text.view(), related);
|
||||
}
|
||||
|
||||
#! Warns of what is likely wrong at the node: to whatever hears the checker's
|
||||
#! notes, or in its notes.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param code What kind of mistake it is about.
|
||||
#! @param detail What the note says.
|
||||
#! @param related The node declaring what it is about, in the same file, or 0.
|
||||
def checker::warn_place(&mut this, node: u32, code: ec, detail: strview, related: u32): void {
|
||||
return if this.mute != 0 || !this.sink.admits();
|
||||
val file := this.at.file;
|
||||
val syntax := &this.units[file].syntax;
|
||||
val token := syntax.node_tokens[node];
|
||||
var made := note {
|
||||
file = file,
|
||||
offset = syntax.token_offsets[token],
|
||||
length = syntax.token_length(token, this.names),
|
||||
code = code,
|
||||
detail = string::from(detail, nothing {}),
|
||||
warning = true,
|
||||
instance = this.instance_text(),
|
||||
origin = this.at.decl
|
||||
};
|
||||
if related != 0 {
|
||||
val other := syntax.node_tokens[related];
|
||||
made.related_file = file;
|
||||
made.related_offset = syntax.token_offsets[other];
|
||||
made.related_length = syntax.token_length(other, this.names);
|
||||
made.related = string::from("It is declared here.", nothing {});
|
||||
}
|
||||
this.sink.give(&mut made);
|
||||
}
|
||||
|
||||
#! Reports what is wrong at the node, and the place of another it relates to,
|
||||
#! as where a name was first declared.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param code What kind of mistake it is.
|
||||
#! @param detail What the note says.
|
||||
#! @param file The file of the other node.
|
||||
#! @param other The other node.
|
||||
#! @param related What the note says of it.
|
||||
pub def checker::report_related(
|
||||
&mut this,
|
||||
node: u32,
|
||||
code: ec,
|
||||
detail: strview,
|
||||
file: u32,
|
||||
other: u32,
|
||||
related: strview
|
||||
): void {
|
||||
this.report_related_in(this.at.file, node, code, detail, file, other, related);
|
||||
}
|
||||
|
||||
#! Reports what is wrong at the declaration, in its own file, wherever checking
|
||||
#! is, and the place of another declaration it relates to, as where the name
|
||||
#! was first declared.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @param code What kind of mistake it is.
|
||||
#! @param detail What the note says.
|
||||
#! @param other The other declaration.
|
||||
#! @param related What the note says of it.
|
||||
pub def checker::report_decl_related(&mut this, id: u32, code: ec, detail: strview, other: u32, related: strview): void {
|
||||
this.report_related_in(this.decls.files.p[id], this.decls.nodes.p[id], code, detail,
|
||||
this.decls.files.p[other], this.decls.nodes.p[other], related);
|
||||
}
|
||||
|
||||
#! Reports what is wrong at the node of the file, and the place of another node
|
||||
#! it relates to.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param node The node.
|
||||
#! @param code What kind of mistake it is.
|
||||
#! @param detail What the note says.
|
||||
#! @param other_file The file of the other node.
|
||||
#! @param other The other node.
|
||||
#! @param related What the note says of it.
|
||||
def checker::report_related_in(
|
||||
&mut this,
|
||||
file: u32,
|
||||
node: u32,
|
||||
code: ec,
|
||||
detail: strview,
|
||||
other_file: u32,
|
||||
other: u32,
|
||||
related: strview
|
||||
): void {
|
||||
val syntax := &this.units[other_file].syntax;
|
||||
val token := syntax.node_tokens[other];
|
||||
this.report_place(file, node, code, detail, other_file, syntax.token_offsets[token], syntax.token_length(token, this.names), related);
|
||||
}
|
||||
|
||||
#! What notes made in the instance being checked say of it, as "In `max<u8>`",
|
||||
#! or nothing outside an instance.
|
||||
#! @param this The checker.
|
||||
#! @returns The text, or empty text.
|
||||
def checker::instance_text(&mut this): string {
|
||||
return string::new(nothing {}) if this.at.instance == 0;
|
||||
|
||||
val held: instance = this.instances[this.at.instance - 1];
|
||||
var text := string::from("In `", nothing {});
|
||||
text.append(this.names.text(this.decls.names.p[held.decl]));
|
||||
text.append("<");
|
||||
# A pack's types are written as the arguments they are, as `show_all<i64, bool>`.
|
||||
this.describe_args(this.types.parts_view(held.args), &mut text);
|
||||
text.append(">`");
|
||||
return text;
|
||||
}
|
||||
|
||||
#! Counts what the checker met and does not check yet, which it lets through
|
||||
#! rather than reporting, so a program using it is not wrongly refused.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
pub def checker::unsupported(&mut this, node: u32): void {
|
||||
this.skipped++;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,184 @@
|
||||
#! @file ownership.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the rules of owning values: a value of a type that closes, as a
|
||||
#! `string`, has one owner, so it is never copied out of the place holding it
|
||||
#! without saying so, and what a loop iterates is locked while the loop's body
|
||||
#! runs, so the body cannot change it.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! Whether values of the type are closed where their scope ends: the type
|
||||
#! names `owning`, or holds a value that does in its fields or
|
||||
#! elements. A reference or pointer holds nothing of its own.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns Whether they are.
|
||||
pub def checker::closes(&mut this, kind: u32): bool {
|
||||
return false if kind == bt::error || this.types.is_untyped(kind);
|
||||
val flags := this.types.flags.p[kind];
|
||||
return (flags & tf::closes as u8) != 0 if (flags & tf::weighed as u8) != 0;
|
||||
# Weighed as closing nothing while it is worked out, so a type holding
|
||||
# itself through a pointer is met again as one that does not.
|
||||
this.types.flags.p[kind] = flags | tf::weighed as u8;
|
||||
|
||||
val plain := this.unalias(kind);
|
||||
var made := false;
|
||||
match this.types.kind_of(plain) {
|
||||
ty::fixed => made = this.closes(this.types.first_of(plain));
|
||||
ty::named => {
|
||||
val decl := this.types.first_of(plain);
|
||||
val kind_of: dk = this.decls.kinds.p[decl];
|
||||
if kind_of == dk::struct_type || kind_of == dk::union_type {
|
||||
val owning := this.std_decl(word::owning);
|
||||
made = owning != 0 && this.names_trait(plain, owning) && this.has_close(plain);
|
||||
if !made {
|
||||
val fields := this.field_types(plain);
|
||||
for &each in fields {
|
||||
made = made || this.closes(each);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ty::param => {
|
||||
val owning := this.std_decl(word::owning);
|
||||
made = owning != 0 && this.param_bounded(plain, owning);
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
|
||||
if made {
|
||||
this.types.flags.p[kind] |= tf::closes as u8;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Whether the type has the `close(&mut this): void` of `owning`.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns Whether it has.
|
||||
def checker::has_close(&mut this, kind: u32): bool {
|
||||
val found := this.find_member(kind, word::close);
|
||||
return false if found.decl == 0 || this.decls.kinds.p[found.decl] != dk::function;
|
||||
var walk := this.decls.walk_overloads(found.decl);
|
||||
while true {
|
||||
val at := walk.next();
|
||||
break if at == 0;
|
||||
continue if !this.member_seen(at);
|
||||
this.resolve(at);
|
||||
if this.decls.has(at, df::mut_this) && this.types.part_count(this.decls.types.p[at]) == 1 {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Reports a value that closes copied out of the place holding it, where it is
|
||||
#! taken as a value of the type `to`. A new value, as a call gives, is moved.
|
||||
#! What a reference refers to is copied where it is read through as a whole, and
|
||||
#! its owner still holds it.
|
||||
#! @param this The checker.
|
||||
#! @param node The value's node.
|
||||
#! @param to The type it is taken as.
|
||||
pub def checker::check_owned(&mut this, node: u32, to: u32): void {
|
||||
return if node == 0 || to == bt::error;
|
||||
return if this.types.kind_of(this.unalias(to)) == ty::reference;
|
||||
val kind := this.type_at(node);
|
||||
if this.types.kind_of(kind) == ty::reference {
|
||||
return if !this.closes(to);
|
||||
var text := string::from("`", nothing {});
|
||||
val named := this.describe(to);
|
||||
text.append(named.view());
|
||||
text.append("` is closed where its scope ends, so it has one owner, which still holds what the reference refers to. Refer to it with `&` or `&mut`, or copy or move it by name.");
|
||||
this.report_text(node, ec::owned, &text);
|
||||
return;
|
||||
}
|
||||
# The field of a union is read as a copy, but the union still owns what it
|
||||
# holds and closes it, even where the union is only a call's result.
|
||||
if this.union_field(node) && this.closes(kind) && this.closes(to) {
|
||||
var text := string::from("`", nothing {});
|
||||
val named := this.describe(kind);
|
||||
text.append(named.view());
|
||||
text.append("` is closed where its scope ends, so the union holding it owns it and it cannot be copied out. Name it with `match` by `&` or `&mut`, and copy or move it by name.");
|
||||
this.report_text(node, ec::owned, &text);
|
||||
return;
|
||||
}
|
||||
# Taken as a view, as a string lends a `span<u8>` of itself, it is not copied.
|
||||
return if !this.is_place(node) || !this.closes(kind) || !this.closes(to);
|
||||
|
||||
var text := string::from("`", nothing {});
|
||||
val named := this.describe(kind);
|
||||
text.append(named.view());
|
||||
text.append("` is closed where its scope ends, so it has one owner and is not copied out of the place holding it. Refer to it with `&` or `&mut`, or copy or move it by name.");
|
||||
this.report_text(node, ec::owned, &text);
|
||||
}
|
||||
|
||||
#! Whether a node reads a field of a union, as `r.value` does of a `result`.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns Whether it does.
|
||||
def checker::union_field(&mut this, node: u32): bool {
|
||||
return false if this.kind_of(node) != nk::member;
|
||||
val held := this.unalias(this.reached_value(this.type_at(this.left_of(node))));
|
||||
return this.named_kind(held) == dk::union_type;
|
||||
}
|
||||
|
||||
#! Whether a place is part of what a pointer points at, as `p[0]` and
|
||||
#! `(*p).next` are, which the compiler never closes, since a pointer owns
|
||||
#! nothing.
|
||||
#! @param this The checker.
|
||||
#! @param node The place's node.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::pointed_at(&mut this, node: u32): bool {
|
||||
var at := node;
|
||||
var steps := 0;
|
||||
while at != 0 && steps < 64 {
|
||||
steps++;
|
||||
val kind := this.kind_of(at);
|
||||
return false if kind != nk::member && kind != nk::index && !(kind == nk::unary && this.token_kind(at) == tk::star);
|
||||
at = this.left_of(at);
|
||||
return true if this.types.kind_of(this.unalias(this.type_at(at))) == ty::pointer;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! What a place is a part of, followed to the variable it is in: the local or
|
||||
#! declaration it names, or 0 where it is in none, as a new value.
|
||||
#! @param this The checker.
|
||||
#! @param node The place's node.
|
||||
#! @returns What the variable's name refers to, or 0.
|
||||
pub def checker::root_ref(&this, node: u32): u32 {
|
||||
var at := node;
|
||||
var steps := 0;
|
||||
while at != 0 && steps < 64 {
|
||||
steps++;
|
||||
match this.kind_of(at) {
|
||||
nk::name => return this.ref_at(at);
|
||||
nk::member, nk::index, nk::slice => at = this.left_of(at);
|
||||
nk::unary => {
|
||||
return 0 if this.token_kind(at) != tk::star;
|
||||
at = this.left_of(at);
|
||||
}
|
||||
else => return 0;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! Reports a change of what a loop around it iterates.
|
||||
#! @param this The checker.
|
||||
#! @param node The node of what is changed.
|
||||
pub def checker::check_unlocked(&mut this, node: u32): void {
|
||||
return if this.locks.length == 0;
|
||||
val root := this.root_ref(node);
|
||||
return if root == 0;
|
||||
for i in 0..this.locks.length {
|
||||
if this.locks[i] == root {
|
||||
this.report(node, ec::locked, "A loop iterates this, so the loop's body does not change it.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,509 @@
|
||||
#! @file patterns.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains how the type arguments written for a generic type are given to its
|
||||
#! type parameters: one each, a pack the arguments after those before it, and a
|
||||
#! pattern parameter, `def(Ts...): R`, the parts of the function type it is
|
||||
#! given, as `invokable<def(i64, bool): u8>` gives `Ts` the pack `(i64, bool)`
|
||||
#! and `R` the type `u8`. A declaration's type parameters are those its
|
||||
#! patterns name, so everything past writing its arguments sees only them.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! What marks a pattern among the entries of a written shape, as `record_shape`
|
||||
#! makes them: 0 for a type parameter written plainly, 1 for a pack, and for a
|
||||
#! pattern this mark, with how many parameter types it names shifted left by 2,
|
||||
#! 2 where the last of them is a pack, and 1 where it names its result.
|
||||
pub const checker::pattern_mark: u32 = 0x80000000;
|
||||
|
||||
#! What marks a pattern of a fixed array, `L[N]`, beside `pattern_mark`, which
|
||||
#! names its element's type and its length.
|
||||
pub const checker::array_mark: u32 = 0x40000000;
|
||||
|
||||
#! Records the written shape of a declaration's own type parameters where a
|
||||
#! pattern is among them, while the file declaring it is the one checked, so
|
||||
#! its type arguments are given their parameters from any file.
|
||||
#! @param this The checker.
|
||||
#! @param decl The declaration.
|
||||
#! @param run The run of its own type parameters as written.
|
||||
pub def checker::record_shape(&mut this, decl: u32, run: u32): void {
|
||||
var entries := vector::<u32>::new();
|
||||
var any := false;
|
||||
for &each in this.run_view(run) {
|
||||
if this.kind_of(each) == nk::type_pattern {
|
||||
val params := this.left_of(each);
|
||||
val count := this.run_length(params);
|
||||
val packed := count != 0 && this.node_has(this.run_at(params, count - 1), nf::packed);
|
||||
entries.append(checker::pattern_mark | (count << 2) | (packed ? 2 : 0) | (this.right_of(each) != 0 ? 1 : 0));
|
||||
any = true;
|
||||
} else if this.kind_of(each) == nk::array_pattern {
|
||||
entries.append(checker::pattern_mark | checker::array_mark);
|
||||
any = true;
|
||||
} else {
|
||||
entries.append(this.kind_of(each) == nk::type_param && this.node_has(each, nf::packed) ? 1 : 0);
|
||||
}
|
||||
}
|
||||
if any {
|
||||
this.shapes.set(decl, this.decls.make_list(entries.view()));
|
||||
}
|
||||
}
|
||||
|
||||
#! The written shape of a declaration's own type parameters: as recorded where
|
||||
#! a pattern is among them, or else one entry for each, a pack's 1.
|
||||
#! @param this The checker.
|
||||
#! @param decl The declaration.
|
||||
#! @returns The entries, as `pattern_mark` says.
|
||||
def checker::shape_of(&this, decl: u32): vector<u32> {
|
||||
if this.shapes.get(&decl) is some(got) {
|
||||
return this.decls.list_of(got);
|
||||
}
|
||||
var made := vector::<u32>::new();
|
||||
val params: u32 = this.decls.params.p[decl];
|
||||
val wanted := this.decls.list_length(params);
|
||||
val own := this.own_param_count(decl);
|
||||
for k in (wanted >= own ? wanted - own : 0)..wanted {
|
||||
made.append(this.decls.has(this.decls.list_at(params, k as u32), df::packed) ? 1 : 0);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! How many type parameters an entry of a written shape names: a pattern one
|
||||
#! for each of its parameter types and one for its result, or of a fixed array
|
||||
#! its element's and its length's, and anything else itself.
|
||||
#! @param this The checker.
|
||||
#! @param entry The entry.
|
||||
#! @returns How many.
|
||||
def checker::named_count(&this, entry: u32): u32 {
|
||||
return 1 if (entry & checker::pattern_mark) == 0;
|
||||
return 2 if (entry & checker::array_mark) != 0;
|
||||
return ((entry & ~checker::pattern_mark) >> 2) + (entry & 1);
|
||||
}
|
||||
|
||||
#! Whether a declaration is written with a pattern among its own type
|
||||
#! parameters.
|
||||
#! @param this The checker.
|
||||
#! @param decl The declaration.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::has_patterns(&this, decl: u32): bool {
|
||||
return this.shapes.contains(&decl);
|
||||
}
|
||||
|
||||
#! The type parameter a type argument written at a place is given to: one of a
|
||||
#! type the declaration is within, one of its own, or the pack taking the rest,
|
||||
#! or 0 for a pattern, whose type parameters are given the parts of what is
|
||||
#! written.
|
||||
#! @param this The checker.
|
||||
#! @param decl The generic declaration.
|
||||
#! @param index The place of the type argument among those written.
|
||||
#! @returns The type parameter's declaration, or 0.
|
||||
pub def checker::param_written_at(&this, decl: u32, index: u32): u32 {
|
||||
val params: u32 = this.decls.params.p[decl];
|
||||
val wanted := this.decls.list_length(params);
|
||||
var shape := this.shape_of(decl);
|
||||
var own: u32 = 0;
|
||||
for &each in shape {
|
||||
own += this.named_count(each);
|
||||
}
|
||||
val lead: u32 = wanted >= own ? wanted - own : 0;
|
||||
return index < wanted ? this.decls.list_at(params, index) : 0 if index < lead;
|
||||
|
||||
var at := lead;
|
||||
for i in 0..shape.length {
|
||||
val each := shape[i];
|
||||
val packs := each == 1;
|
||||
if i as u32 == index - lead || (packs && index - lead > i as u32) {
|
||||
return (each & checker::pattern_mark) != 0 || at >= wanted ? 0 : this.decls.list_at(params, at);
|
||||
}
|
||||
at += this.named_count(each);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! Gives the type arguments written for a generic type to its type parameters,
|
||||
#! after those of any type it is declared within, which are given one each: one
|
||||
#! each to those written plainly, the rest to a pack, and to a pattern the parts
|
||||
#! of the function type it is given.
|
||||
#! @param this The checker.
|
||||
#! @param decl The generic type's declaration.
|
||||
#! @param args The type arguments as written, those of the types it is
|
||||
#! declared within first.
|
||||
#! @param node The node notes are placed at.
|
||||
#! @param into What each of its type parameters is given, in order.
|
||||
#! @returns Whether they were given, which notes say why not where not.
|
||||
pub def checker::bind_written(&mut this, decl: u32, args: span<u32>, node: u32, into: &mut vector<u32>): bool {
|
||||
val params: u32 = this.decls.params.p[decl];
|
||||
val wanted := this.decls.list_length(params);
|
||||
var shape := this.shape_of(decl);
|
||||
var own: u32 = 0;
|
||||
for &each in shape {
|
||||
own += this.named_count(each);
|
||||
}
|
||||
# A type declared within a generic one takes that one's parameters first.
|
||||
val lead: u32 = wanted >= own ? wanted - own : 0;
|
||||
val count := shape.length as u32;
|
||||
val last_packs := count != 0 && shape[count as u64 - 1] == 1;
|
||||
val written := lead + count;
|
||||
|
||||
var at: u64 = 0;
|
||||
for i in 0..lead {
|
||||
break if at >= args.length;
|
||||
into.append(args[at]);
|
||||
at++;
|
||||
}
|
||||
for i in 0..count {
|
||||
val each := shape[i];
|
||||
if each == 1 {
|
||||
# A pack takes the type arguments after those before it.
|
||||
val pack := this.gather_pack(args, at, node);
|
||||
return false if pack == bt::error;
|
||||
into.append(pack);
|
||||
at = args.length;
|
||||
continue;
|
||||
}
|
||||
break if at >= args.length;
|
||||
if (each & checker::array_mark) != 0 {
|
||||
return false if !this.destructure_array(decl, args[at], node, into);
|
||||
} else if (each & checker::pattern_mark) != 0 {
|
||||
return false if !this.destructure(each, decl, args[at], node, into);
|
||||
} else {
|
||||
if this.types.kind_of(args[at]) == ty::pack {
|
||||
this.report(node, ec::generic, "A pack is passed on with `...` only for a pack parameter, as `Ts` of `box<Ts...>`.");
|
||||
return false;
|
||||
}
|
||||
into.append(args[at]);
|
||||
}
|
||||
at++;
|
||||
}
|
||||
|
||||
if at != args.length || into.length != wanted as u64 {
|
||||
var text := string::from("`", nothing {});
|
||||
text.append(this.decl_text(decl));
|
||||
val words := last_packs
|
||||
? $"` takes at least {written - 1} type arguments, but is given {args.length}."
|
||||
: $"` takes {written} type arguments, but is given {args.length}.";
|
||||
text.append(words.view());
|
||||
this.report_text(node, ec::generic, &text);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Gives a pattern parameter's type parameters the parts of the function type it
|
||||
#! is given: those of its parameters before a pack each take one of the
|
||||
#! function's parameters, the pack the rest, as a variadic function's are where
|
||||
#! it is one, and its result the function's.
|
||||
#! @param this The checker.
|
||||
#! @param pattern The pattern's entry in its declaration's written shape.
|
||||
#! @param decl The generic type's declaration.
|
||||
#! @param arg The type the pattern is given.
|
||||
#! @param node The node notes are placed at.
|
||||
#! @param into What the pattern's type parameters are given, in order.
|
||||
#! @returns Whether the type fits the pattern, which a note says why not where
|
||||
#! not.
|
||||
def checker::destructure(&mut this, pattern: u32, decl: u32, arg: u32, node: u32, into: &mut vector<u32>): bool {
|
||||
val count := (pattern & ~checker::pattern_mark) >> 2;
|
||||
val packed := (pattern & 2) != 0;
|
||||
val result := (pattern & 1) != 0;
|
||||
val fixed := packed ? count - 1 : count;
|
||||
|
||||
# The address of a C function is given as the function type it is of, and a
|
||||
# type parameter that is a `signature`, as `F`, its `F::params` and `F::result`.
|
||||
val plain := this.signature_function(arg);
|
||||
val bare := this.unalias(arg);
|
||||
if plain == 0 && this.types.kind_of(bare) == ty::param {
|
||||
val sig := this.std_decl(word::signature);
|
||||
if sig != 0 && this.satisfies(bare, this.decls.types.p[sig]) {
|
||||
if fixed != 0 || !packed {
|
||||
var text := string::from("`", nothing {});
|
||||
val named := this.describe(arg);
|
||||
text.append(named.view());
|
||||
text.append("` is a signature whose parameters are not known yet, so the pattern of `");
|
||||
text.append(this.decl_text(decl));
|
||||
text.append("` takes it only where it names them as one pack, as `def(Ts...): R`.");
|
||||
this.report_text(node, ec::generic, &text);
|
||||
return false;
|
||||
}
|
||||
into.append(this.projected(bare, this.trait_member(sig, word::params), this.decls.types.p[sig]));
|
||||
if result {
|
||||
into.append(this.projected(bare, this.trait_member(sig, word::result), this.decls.types.p[sig]));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if plain == 0 {
|
||||
var text := string::from("`", nothing {});
|
||||
text.append(this.decl_text(decl));
|
||||
text.append("` is given a function type where it takes `def(...)`, as `def(i64): i64`, and this is `");
|
||||
val named := this.describe(arg);
|
||||
text.append(named.view());
|
||||
text.append("`.");
|
||||
this.report_text(node, ec::generic, &text);
|
||||
return false;
|
||||
}
|
||||
|
||||
# The parameters taking one value each, before any taking the rest.
|
||||
val parts := this.types.part_count(plain);
|
||||
val variadic := this.types.second_of(plain) != 0 && parts != 0;
|
||||
val singles := variadic ? parts - 1 : parts;
|
||||
val open := variadic && this.types.is_open_pack(this.types.part_at(plain, parts - 1));
|
||||
if (packed && singles < fixed) || (!packed && (variadic || singles != fixed)) || (packed && open && singles != fixed) {
|
||||
var text := string::from("`", nothing {});
|
||||
val named := this.describe(arg);
|
||||
text.append(named.view());
|
||||
text.append(open && singles > fixed
|
||||
? "` ends in a pack whose types are not known yet, which a pattern's pack takes only alone."
|
||||
: "` does not have the parameters the pattern of `");
|
||||
if !(open && singles > fixed) {
|
||||
text.append(this.decl_text(decl));
|
||||
text.append(packed
|
||||
? "` asks for: at least as many before any taking the rest as it names before its pack."
|
||||
: "` asks for: as many as it names, none taking the rest.");
|
||||
}
|
||||
this.report_text(node, ec::generic, &text);
|
||||
return false;
|
||||
}
|
||||
|
||||
for k in 0..fixed {
|
||||
into.append(this.types.part_at(plain, k as u32));
|
||||
}
|
||||
if packed {
|
||||
into.append(open ? this.types.part_at(plain, parts - 1) : this.types.params_pack(plain, fixed));
|
||||
}
|
||||
if result {
|
||||
into.append(this.types.first_of(plain));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Gives a pattern parameter, `L[N]`, the parts of the fixed array it is given:
|
||||
#! its element's type to `L`, and its length to `N`, as a `u64`.
|
||||
#! @param this The checker.
|
||||
#! @param decl The generic type's declaration.
|
||||
#! @param arg The type the pattern is given.
|
||||
#! @param node The node notes are placed at.
|
||||
#! @param into What the pattern's type parameters are given, in order.
|
||||
#! @returns Whether the type fits the pattern, which a note says why not where
|
||||
#! not.
|
||||
def checker::destructure_array(&mut this, decl: u32, arg: u32, node: u32, into: &mut vector<u32>): bool {
|
||||
val plain := this.unalias(arg);
|
||||
if this.types.kind_of(plain) != ty::fixed {
|
||||
var text := string::from("`", nothing {});
|
||||
text.append(this.decl_text(decl));
|
||||
text.append("` is given a fixed array where it takes `L[N]`, as `f32[4]`, and this is `");
|
||||
val named := this.describe(arg);
|
||||
text.append(named.view());
|
||||
text.append("`.");
|
||||
this.report_text(node, ec::generic, &text);
|
||||
return false;
|
||||
}
|
||||
into.append(this.types.first_of(plain));
|
||||
# A length only each instance knows is given as it is.
|
||||
if this.types.part_count(plain) != 0 {
|
||||
into.append(this.types.part_at(plain, 0));
|
||||
} else {
|
||||
into.append(this.known_type(this.known_number(constant::integer(this.types.second_of(plain) as u64, false), bt::uint64)));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Writes the type arguments of a type declared with patterns as they are written,
|
||||
#! a function type for each pattern, as `invokable<def(i64): u8>`.
|
||||
#! @param this The checker.
|
||||
#! @param kind The named type.
|
||||
#! @param out What it is written into.
|
||||
#! @param depth How deeply the writing has gone.
|
||||
def checker::describe_written(&this, kind: u32, out: &mut string, depth: u32): void {
|
||||
val decl := this.types.first_of(kind);
|
||||
var shape := this.shape_of(decl);
|
||||
val total := this.types.part_count(kind);
|
||||
var own: u32 = 0;
|
||||
for &each in shape {
|
||||
own += this.named_count(each);
|
||||
}
|
||||
val lead: u32 = total >= own ? total - own : 0;
|
||||
|
||||
var at: u32 = 0;
|
||||
var written := false;
|
||||
for i in 0..lead {
|
||||
this.describe_arg(this.types.part_at(kind, at), out, depth + 1, &mut written);
|
||||
at++;
|
||||
}
|
||||
for i in 0..shape.length {
|
||||
val each := shape[i];
|
||||
break if at >= total;
|
||||
if (each & checker::pattern_mark) == 0 {
|
||||
this.describe_arg(this.types.part_at(kind, at), out, depth + 1, &mut written);
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
out.append(written ? ", " : "");
|
||||
written = true;
|
||||
|
||||
# A fixed array's pattern, as the array it was given the parts of.
|
||||
if (each & checker::array_mark) != 0 {
|
||||
this.describe_into(this.types.part_at(kind, at), out, depth + 1);
|
||||
out.append("[");
|
||||
if at + 1 < total {
|
||||
this.describe_into(this.types.part_at(kind, at + 1), out, depth + 1);
|
||||
}
|
||||
out.append("]");
|
||||
at += 2;
|
||||
continue;
|
||||
}
|
||||
|
||||
# A signature `F` given whole is written as itself.
|
||||
val count := (each & ~checker::pattern_mark) >> 2;
|
||||
val packed := (each & 2) != 0;
|
||||
if count == 1 && packed && (each & 1) != 0 && at + 1 < total {
|
||||
val given := this.signature_given(this.types.part_at(kind, at), this.types.part_at(kind, at + 1));
|
||||
if given != 0 {
|
||||
this.describe_into(given, out, depth + 1);
|
||||
at += 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
# The function type the pattern's type parameters were given the parts of.
|
||||
out.append("def(");
|
||||
for k in 0..count {
|
||||
break if at >= total;
|
||||
out.append(k != 0 ? ", " : "");
|
||||
val part := this.types.part_at(kind, at);
|
||||
if packed && k + 1 == count && this.types.is_known_pack(part) {
|
||||
for j in 0..this.types.part_count(part) {
|
||||
out.append(j != 0 ? ", " : "");
|
||||
this.describe_into(this.types.part_at(part, j as u32), out, depth + 1);
|
||||
}
|
||||
if this.types.second_of(part) != 0 {
|
||||
out.append("...");
|
||||
}
|
||||
} else {
|
||||
this.describe_into(part, out, depth + 1);
|
||||
}
|
||||
at++;
|
||||
}
|
||||
out.append("): ");
|
||||
if (each & 1) != 0 && at < total {
|
||||
this.describe_into(this.types.part_at(kind, at), out, depth + 1);
|
||||
at++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Writes type arguments as notes spell them, each after a comma but the
|
||||
#! first: a pack whose types are known as the types it gives, as `i64, bool`
|
||||
#! of a pack given for `Ts...`, and an empty one as none.
|
||||
#! @param this The checker.
|
||||
#! @param args The type arguments.
|
||||
#! @param out What they are written into.
|
||||
#! @param depth How deeply the writing has gone, at the arguments.
|
||||
pub def checker::describe_args(&this, args: span<u32>, out: &mut string, depth: u32 = 0): void {
|
||||
var written := false;
|
||||
for &arg in args {
|
||||
this.describe_arg(arg, out, depth, &mut written);
|
||||
}
|
||||
}
|
||||
|
||||
#! Writes a type argument after those already written: a pack whose types are
|
||||
#! known as the types it gives, or another type as it is.
|
||||
#! @param this The checker.
|
||||
#! @param arg The type argument.
|
||||
#! @param out What it is written into.
|
||||
#! @param depth How deeply the writing has gone, at the argument.
|
||||
#! @param written Whether a type argument is written before it, which it sets.
|
||||
pub def checker::describe_arg(&this, arg: u32, out: &mut string, depth: u32, written: &mut bool): void {
|
||||
if !this.types.is_known_pack(arg) {
|
||||
out.append(written ? ", " : "");
|
||||
this.describe_into(arg, out, depth);
|
||||
written = true;
|
||||
return;
|
||||
}
|
||||
for &part in this.types.parts_view(arg) {
|
||||
out.append(written ? ", " : "");
|
||||
this.describe_into(part, out, depth);
|
||||
written = true;
|
||||
}
|
||||
}
|
||||
|
||||
#! The type of a value a pack holds: its type, or for the last of a variadic
|
||||
#! function's pack, the view of the rest it holds.
|
||||
#! @param this The checker.
|
||||
#! @param pack The pack's type.
|
||||
#! @param index The value's place.
|
||||
#! @returns The type.
|
||||
pub def checker::pack_value_type(&mut this, pack: u32, index: u32): u32 {
|
||||
val part := this.types.part_at(pack, index);
|
||||
return this.types.second_of(pack) != 0 && index + 1 == this.types.part_count(pack) ? this.span_of(part) : part;
|
||||
}
|
||||
|
||||
#! The function type a signature is: a function type itself, or the one the
|
||||
#! address of a C function, `cfn<def(...): R>`, is of.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns The function type, or 0 where the type is no signature.
|
||||
pub def checker::signature_function(&mut this, kind: u32): u32 {
|
||||
val plain := this.unalias(kind);
|
||||
return plain if this.types.kind_of(plain) == ty::function;
|
||||
if this.is_std(plain, word::cfn) && this.types.part_count(plain) != 0 {
|
||||
val inner := this.unalias(this.types.part_at(plain, 0));
|
||||
return inner if this.types.kind_of(inner) == ty::function;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! What `signature` asks of a type it decides: a function's `result`, and its
|
||||
#! `params`, the pack of its parameters' types, variadic where it is.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param asked The declaration of the type `signature` asks for.
|
||||
#! @returns The type, or 0 where the type is no signature or the trait asking
|
||||
#! is not `signature`.
|
||||
pub def checker::signature_part(&mut this, kind: u32, asked: u32): u32 {
|
||||
val holder: u32 = this.decls.owners.p[asked];
|
||||
return 0 if holder == 0 || this.decls.names.p[holder] != word::signature || this.std_decl(word::signature) != holder;
|
||||
val function := this.signature_function(kind);
|
||||
return 0 if function == 0;
|
||||
return this.types.first_of(function) if this.decls.names.p[asked] == word::result;
|
||||
return this.parameters_of(function, 0) if this.decls.names.p[asked] == word::params;
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! The pack of a function type's parameter types from `from` on, variadic where
|
||||
#! the function is, or where they are only a pack whose types are not known, as
|
||||
#! those of `def(Ts...): R`, that pack.
|
||||
#! @param this The checker.
|
||||
#! @param function The function type.
|
||||
#! @param from The first parameter the pack holds.
|
||||
#! @returns The pack.
|
||||
pub def checker::parameters_of(&mut this, function: u32, from: u32): u32 {
|
||||
val count := this.types.part_count(function);
|
||||
if this.types.second_of(function) != 0 && count == from + 1 && this.types.is_open_pack(this.types.part_at(function, from)) {
|
||||
return this.types.part_at(function, from);
|
||||
}
|
||||
return this.types.params_pack(function, from);
|
||||
}
|
||||
|
||||
#! The type `F` whose `params` and `result` stand in for what a pattern's type
|
||||
#! parameters were given, where they do, so a type it was given `F` is written
|
||||
#! with it, as `invokable<F>`.
|
||||
#! @param this The checker.
|
||||
#! @param pack What the pattern's pack was given.
|
||||
#! @param result What its result was given.
|
||||
#! @returns `F`, or 0.
|
||||
def checker::signature_given(&this, pack: u32, result: u32): u32 {
|
||||
return 0 if !this.types.is_open_pack(pack) || this.types.kind_of(result) != ty::param;
|
||||
var base: u32 = 0;
|
||||
for &each in this.stand_ins {
|
||||
if each.param == this.types.first_of(pack) && this.decls.names.p[each.asked] == word::params {
|
||||
base = each.base;
|
||||
}
|
||||
}
|
||||
return 0 if base == 0;
|
||||
for &each in this.stand_ins {
|
||||
return base if each.param == this.types.first_of(result) && each.base == base && this.decls.names.p[each.asked] == word::result;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,523 @@
|
||||
#! @file reflection.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains reflection: what a program reads of its own declarations while
|
||||
#! compiling. A description names a declaration, or a function's parameter,
|
||||
#! and an expression giving one, or a list of them, as `declarations()` or
|
||||
#! `params_of(d)`, has them as a result of its own. What they say that `if
|
||||
#! const` decides by, as `d.kind` or how many there are, is known while
|
||||
#! checking, and `for const` walks a list, checking its body once for each.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! What reflection describes: a declaration, or one of a function's parameters,
|
||||
#! and where it is in a generic type, the instance it was reached through, as
|
||||
#! `page<int>` of `decl_of::<page<int>>()` and of each of its members.
|
||||
pub struct desc {
|
||||
pub var decl: u32; #! The declaration.
|
||||
pub var param: u32; #! One more than the index of the parameter it is, or 0 for the declaration itself.
|
||||
var owner: u32; #! The instance whose arguments the generic type's parameters take, or 0.
|
||||
var next: u32; #! The description of the same declaration through another instance, or `no_reflection`.
|
||||
}
|
||||
|
||||
#! The kinds of what an expression of reflection gives.
|
||||
pub enum rk : u32 {
|
||||
one = 1, #! A description.
|
||||
list = 2, #! A list of descriptions.
|
||||
}
|
||||
|
||||
#! The description of the declaration, or of its parameter, made where it is
|
||||
#! new.
|
||||
#! @param this The checker.
|
||||
#! @param decl The declaration.
|
||||
#! @param param One more than the index of the parameter, or 0 for the
|
||||
#! declaration itself.
|
||||
#! @returns The description's index in `descs`.
|
||||
pub def checker::describe_decl(&mut this, decl: u32, param: u32): u32 {
|
||||
return this.describe_owned(decl, param, 0);
|
||||
}
|
||||
|
||||
#! The description of the declaration, or of its parameter, reached through the
|
||||
#! instance of the generic type it is in, made where it is new.
|
||||
#! @param this The checker.
|
||||
#! @param decl The declaration.
|
||||
#! @param param One more than the index of the parameter, or 0 for the
|
||||
#! declaration itself.
|
||||
#! @param owner The instance it is reached through, or 0.
|
||||
#! @returns The description's index in `descs`.
|
||||
pub def checker::describe_owned(&mut this, decl: u32, param: u32, owner: u32): u32 {
|
||||
val key := pair_key(decl, param);
|
||||
var first := checker::no_reflection;
|
||||
if this.desc_ids.get(&key) is some(got) {
|
||||
first = got;
|
||||
}
|
||||
var at := first;
|
||||
while at != checker::no_reflection {
|
||||
val held: desc = this.descs[at];
|
||||
return at if held.owner == owner;
|
||||
at = held.next;
|
||||
}
|
||||
|
||||
val id := this.descs.length as u32;
|
||||
this.descs.append(desc { decl = decl, param = param, owner = owner, next = first });
|
||||
this.desc_ids.set(key, id);
|
||||
return id;
|
||||
}
|
||||
|
||||
#! The instance a member of the description's declaration is reached through:
|
||||
#! the description's own, where it describes a generic type through one.
|
||||
#! @param this The checker.
|
||||
#! @param held The description.
|
||||
#! @returns The instance, or 0.
|
||||
def checker::member_owner(&mut this, held: desc): u32 {
|
||||
return 0 if held.owner == 0 || this.type_decl(held.owner) != held.decl;
|
||||
return held.owner;
|
||||
}
|
||||
|
||||
#! Records that the node gives the descriptions, one or a list of them.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param kind Whether it gives one or a list.
|
||||
#! @param items The descriptions' indices in `descs`.
|
||||
pub def checker::set_reflected(&mut this, node: u32, kind: rk, items: span<u32>): void {
|
||||
this.reflected.push(kind as u32);
|
||||
for &each in items {
|
||||
this.reflected.push(each);
|
||||
}
|
||||
this.reflections.set(this.result_key(node), this.reflected.end());
|
||||
this.set_flag(node, rf::reflected);
|
||||
}
|
||||
|
||||
#! Where the descriptions the node gives are recorded, or `no_reflection`.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns Their run in `reflected`, or `no_reflection`.
|
||||
pub def checker::reflected_at(&this, node: u32): u32 {
|
||||
# A node a table holds says whether it gives any, which most give none of.
|
||||
val at := this.slot(node);
|
||||
if at < this.r_flags.length && (this.r_flags.p[at] & rf::reflected as u16) == 0 {
|
||||
return checker::no_reflection;
|
||||
}
|
||||
val key := this.result_key(node);
|
||||
return this.reflections.get_or(&key, checker::no_reflection);
|
||||
}
|
||||
|
||||
#! What says a node gives no descriptions, and a description has no other
|
||||
#! instance.
|
||||
pub const checker::no_reflection: u32 = 0xFFFFFFFF;
|
||||
|
||||
#! Whether what a node gives is one description or a list, as `rk` says.
|
||||
#! @param this The checker.
|
||||
#! @param at Its run in `reflected`.
|
||||
#! @returns The `rk`, as an integer.
|
||||
pub def checker::reflected_kind(&this, at: u32): u32 { return this.reflected.at(at, 0); }
|
||||
|
||||
#! How many descriptions a node gives.
|
||||
#! @param this The checker.
|
||||
#! @param at Their run in `reflected`.
|
||||
#! @returns How many.
|
||||
pub def checker::reflected_count(&this, at: u32): u32 { return (this.reflected.length(at) - 1) as u32; }
|
||||
|
||||
#! One of the descriptions a node gives.
|
||||
#! @param this The checker.
|
||||
#! @param at Their run in `reflected`.
|
||||
#! @param index Its position, below their count.
|
||||
#! @returns The description's index in `descs`.
|
||||
pub def checker::reflected_item(&this, at: u32, index: u32): u32 { return this.reflected.at(at, index as u64 + 1); }
|
||||
|
||||
#! The one description the node gives, or `no_reflection`.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns The description's index in `descs`, or `no_reflection`.
|
||||
pub def checker::reflected_one(&this, node: u32): u32 {
|
||||
val at := this.reflected_at(node);
|
||||
return checker::no_reflection if at == checker::no_reflection || this.reflected_kind(at) != rk::one as u32;
|
||||
return this.reflected_item(at, 0);
|
||||
}
|
||||
|
||||
#! Whether the call is of an intrinsic of reflection, by the name it is.
|
||||
#! @param this The checker.
|
||||
#! @param decl The function called.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::is_reflection(&mut this, decl: u32): bool {
|
||||
return false if !this.decls.has(decl, df::intrinsic);
|
||||
val name := this.names.text(this.decls.names.p[decl]);
|
||||
return name == "declarations" || name == "decl_of" || name == "members_of" || name == "owner_of"
|
||||
|| name == "attributes_of" || name == "attached" || name == "value_of" || name == "params_of"
|
||||
|| name == "name_of" || name == "path_of";
|
||||
}
|
||||
|
||||
#! A call of an intrinsic of reflection.
|
||||
#! @param this The checker.
|
||||
#! @param node The `call` node.
|
||||
#! @param callee The node of what is called.
|
||||
#! @param decl The intrinsic's declaration.
|
||||
#! @param written The run of the type arguments written, as `T` of
|
||||
#! `decl_of::<T>()`.
|
||||
#! @param args The arguments' nodes.
|
||||
#! @param expected The type expected of what it gives, or the error type where
|
||||
#! none is.
|
||||
#! @returns The type it gives.
|
||||
pub def checker::reflect_call(&mut this, node: u32, callee: u32, decl: u32, written: u32, args: span<u32>, expected: u32): u32 {
|
||||
val name := this.names.text(this.decls.names.p[decl]);
|
||||
this.resolve(decl);
|
||||
val result := this.types.first_of(this.decls.types.p[decl]);
|
||||
this.set_ref(callee, decl);
|
||||
|
||||
if name == "value_of" {
|
||||
return bt::error if args.length != 1;
|
||||
this.infer_expr(args[0]);
|
||||
val one := this.described_arg(args[0], "`value_of`");
|
||||
if one == checker::no_reflection {
|
||||
return bt::error;
|
||||
}
|
||||
# What reflection was given, it reaches, as an attribute consents to.
|
||||
val held: desc = this.descs[one];
|
||||
return bt::error if held.param != 0;
|
||||
val saved := this.consent;
|
||||
this.consent = held.decl;
|
||||
val made := this.decl_value_of(node, held.decl, expected);
|
||||
this.consent = saved;
|
||||
return made;
|
||||
}
|
||||
|
||||
if name == "declarations" {
|
||||
var items := vector::<u32>::new();
|
||||
for id in 1..this.decls.count {
|
||||
if this.reflectable(id as u32) {
|
||||
items.append(this.describe_decl(id as u32, 0));
|
||||
}
|
||||
}
|
||||
this.set_reflected(node, rk::list, items.view());
|
||||
return result;
|
||||
}
|
||||
|
||||
if name == "decl_of" || name == "name_of" || name == "path_of" {
|
||||
val kind := this.run_length(written) == 1 ? this.resolve_type(this.run_at(written, 0)) : bt::error;
|
||||
# The type named is kept as the callee's, which lowering spells.
|
||||
if name == "name_of" || name == "path_of" {
|
||||
this.set_type(callee, kind);
|
||||
}
|
||||
val plain := this.unalias(kind);
|
||||
val target := this.type_decl(plain);
|
||||
# A type no declaration makes, as a reference or a number, has none to give.
|
||||
if name == "decl_of" && target == 0 && kind != bt::error && !this.types.is_open(kind) {
|
||||
var text := string::from("`decl_of` takes a type a declaration makes, as a struct, union, enum, or trait, and `", nothing {});
|
||||
val named := this.describe(kind);
|
||||
text.append(named.view());
|
||||
text.append("` is none: `name_of` and `path_of` name any type.");
|
||||
this.report_text(node, ec::invalid, &text);
|
||||
return result;
|
||||
}
|
||||
if name == "decl_of" && target != 0 && !this.types.is_open(kind) {
|
||||
# An instance of a generic type gives its members the types it takes.
|
||||
val owner: u32 = this.decls.params.p[target] != 0 ? plain : 0;
|
||||
var items := vector::<u32>::new();
|
||||
items.append(this.describe_owned(target, 0, owner));
|
||||
this.set_reflected(node, rk::one, items.view());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
# What the rest take is a description.
|
||||
for &each in args {
|
||||
this.infer_expr(each);
|
||||
}
|
||||
var what := string::from("`", nothing {});
|
||||
what.append(name);
|
||||
what.append("`");
|
||||
val one := args.length == 0 ? checker::no_reflection : this.described_arg(args[0], what.view());
|
||||
|
||||
# What `attached` gives is a view of the attribute's type, which is known even
|
||||
# where the declaration is not, as in a generic's own body.
|
||||
if one == checker::no_reflection && name == "attached" {
|
||||
val wanted := this.run_length(written) == 1 ? this.resolve_type(this.run_at(written, 0)) : bt::error;
|
||||
return wanted == bt::error ? bt::error : this.span_of(wanted);
|
||||
}
|
||||
return result if one == checker::no_reflection;
|
||||
val held: desc = this.descs[one];
|
||||
|
||||
if name == "params_of" {
|
||||
var items := vector::<u32>::new();
|
||||
if held.param == 0 && this.decls.kinds.p[held.decl] == dk::function {
|
||||
this.resolve(held.decl);
|
||||
for i in 0..this.types.part_count(this.decls.types.p[held.decl]) {
|
||||
items.append(this.describe_owned(held.decl, i as u32 + 1, held.owner));
|
||||
}
|
||||
}
|
||||
this.set_reflected(node, rk::list, items.view());
|
||||
return result;
|
||||
}
|
||||
|
||||
if name == "members_of" {
|
||||
var items := vector::<u32>::new();
|
||||
if held.param == 0 {
|
||||
val owner := this.member_owner(held);
|
||||
val run: u32 = this.decls.children.p[held.decl];
|
||||
for &member in this.decls.list_view(run) {
|
||||
items.append(this.describe_owned(member, 0, owner));
|
||||
}
|
||||
for &member in this.decls.by_owner.of(held.decl) {
|
||||
if this.decls.owners.p[member] == held.decl && this.receiver_declared(member) && this.visible(member) {
|
||||
items.append(this.describe_owned(member, 0, owner));
|
||||
}
|
||||
}
|
||||
}
|
||||
this.set_reflected(node, rk::list, items.view());
|
||||
return result;
|
||||
}
|
||||
|
||||
if name == "owner_of" {
|
||||
val owner: u32 = held.param != 0 ? held.decl : this.decls.owners.p[held.decl];
|
||||
if owner != 0 {
|
||||
val through: u32 = held.owner != 0 && this.type_decl(held.owner) == owner ? held.owner : 0;
|
||||
var items := vector::<u32>::new();
|
||||
items.append(this.describe_owned(owner, 0, through));
|
||||
this.set_reflected(node, rk::one, items.view());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
if name == "attached" {
|
||||
# A span of the values of the attributes of the type given, of which how
|
||||
# many there are is known.
|
||||
val wanted := this.run_length(written) == 1 ? this.resolve_type(this.run_at(written, 0)) : bt::error;
|
||||
var count := 0u;
|
||||
if held.param == 0 {
|
||||
val kinds := this.attribute_types(held.decl);
|
||||
for &each in kinds {
|
||||
if each == wanted { count++; }
|
||||
}
|
||||
}
|
||||
this.set_known_length(node, count);
|
||||
return wanted == bt::error ? bt::error : this.span_of(wanted);
|
||||
}
|
||||
|
||||
if name == "attributes_of" {
|
||||
var items := vector::<u32>::new();
|
||||
if held.param == 0 {
|
||||
val made := this.attribute_decls(held.decl);
|
||||
for &each in made {
|
||||
items.append(this.describe_decl(each, 0));
|
||||
}
|
||||
}
|
||||
this.set_reflected(node, rk::list, items.view());
|
||||
return result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
#! The attributes written on a declaration, in the order they are written,
|
||||
#! each a declaration of its own, as `attributes_of` gives them: a constant of
|
||||
#! the attribute's type, named as it is written, as `@tag`, whose value is the
|
||||
#! attribute's. Each is made the first time it is asked for.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns The attributes' declarations.
|
||||
def checker::attribute_decls(&mut this, id: u32): vector<u32> {
|
||||
var made := vector::<u32>::new();
|
||||
val kinds := this.attribute_types(id);
|
||||
val file: u32 = this.decls.files.p[id];
|
||||
val saved := this.at;
|
||||
this.use_table(this.units[file].table);
|
||||
val attrs := this.attributes_of(this.decls.nodes.p[id]);
|
||||
var at: u64 = 0;
|
||||
for &attr in this.run_view(attrs) {
|
||||
continue if this.kind_of(attr) != nk::attribute;
|
||||
val kind := at < kinds.length ? kinds[at] : bt::error;
|
||||
at++;
|
||||
continue if kind == bt::error;
|
||||
|
||||
val key := pair_key(file, attr);
|
||||
if this.attr_decls.get(&key) is some(got) {
|
||||
made.append(got);
|
||||
continue;
|
||||
}
|
||||
var name := string::from("@", nothing {});
|
||||
val named := this.describe(kind);
|
||||
name.append(named.view());
|
||||
val decl := this.decls.add(dk::attribute, this.names.intern(&name.view()), file, attr, 0);
|
||||
this.decls.types.p[decl] = kind;
|
||||
this.decls.states.p[decl] = ds::resolved;
|
||||
this.decls.mark(decl, df::constant);
|
||||
this.decls.mark(decl, df::checked);
|
||||
this.attr_decls.set(key, decl);
|
||||
made.append(decl);
|
||||
}
|
||||
this.at = saved;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The description an argument of reflection gives, reporting one giving none
|
||||
#! where checking is not within a generic's own body, which each instance
|
||||
#! checks.
|
||||
#! @param this The checker.
|
||||
#! @param arg The argument's node.
|
||||
#! @param what The intrinsic, as a note names it.
|
||||
#! @returns The description's index in `descs`, or `no_reflection`.
|
||||
def checker::described_arg(&mut this, arg: u32, what: strview): u32 {
|
||||
val one := this.reflected_one(arg);
|
||||
if one == checker::no_reflection && !this.waits_for_instance() && this.type_at(arg) != bt::error {
|
||||
var text := string::from(what, nothing {});
|
||||
text.append(" takes a declaration known while compiling, as the variable of `for const d in declarations()` is.");
|
||||
this.report_text(arg, ec::constant, &text);
|
||||
}
|
||||
return one;
|
||||
}
|
||||
|
||||
#! Records how many values a view an expression of reflection gives holds,
|
||||
#! which its `length` is known as.
|
||||
#! @param this The checker.
|
||||
#! @param node The expression.
|
||||
#! @param count How many values the view holds.
|
||||
def checker::set_known_length(&mut this, node: u32, count: u64): void {
|
||||
this.lengths.set(this.result_key(node), count as u32);
|
||||
}
|
||||
|
||||
#! Whether reflection lists the declaration among `declarations()`: it is
|
||||
#! declared outside any function, and the module checking can name it, or it
|
||||
#! carries an attribute whose type that module declares.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns Whether it does.
|
||||
def checker::reflectable(&mut this, id: u32): bool {
|
||||
val kind: dk = this.decls.kinds.p[id];
|
||||
match kind {
|
||||
dk::function, dk::variable, dk::struct_type, dk::union_type, dk::enum_type,
|
||||
dk::trait_type, dk::alias_type, dk::property => {}
|
||||
else => return false;
|
||||
}
|
||||
return false if this.decls.has(id, df::accessor) || this.decls.nodes.p[id] == 0;
|
||||
val owner: u32 = this.decls.owners.p[id];
|
||||
return false if owner != 0 && !this.receiver_declared(id);
|
||||
|
||||
return true if this.visible(id);
|
||||
val kinds := this.attribute_types(id);
|
||||
for &each in kinds {
|
||||
val decl := this.type_decl(each);
|
||||
return true if decl != 0 && this.decls.modules.p[decl] == this.at.home;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! The types of the attributes written before the declaration, resolved where
|
||||
#! it is declared.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns The attributes' types, in the order they are written.
|
||||
pub def checker::attribute_types(&mut this, id: u32): vector<u32> {
|
||||
var made := vector::<u32>::new();
|
||||
val saved := this.at;
|
||||
this.enter_decl(id, 0);
|
||||
val attrs := this.attributes_of(this.decls.nodes.p[id]);
|
||||
for &attr in this.run_view(attrs) {
|
||||
continue if this.kind_of(attr) != nk::attribute;
|
||||
made.append(this.quiet_type(this.left_of(attr)));
|
||||
}
|
||||
this.leave(saved);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The type a type name names, without reporting what is wrong with it, which
|
||||
#! checking the declaration it is written on reports.
|
||||
#! @param this The checker.
|
||||
#! @param node The `type_name` node.
|
||||
#! @returns The type, or the error type.
|
||||
def checker::quiet_type(&mut this, node: u32): u32 {
|
||||
val name := this.segment_name(node, this.segment_count(node) - 1);
|
||||
val decl := this.segment_count(node) == 1 ? this.lookup_type(name, 0) : 0;
|
||||
return this.decls.types.p[decl] if decl != 0 && this.is_type_decl(decl) && this.decls.params.p[decl] == 0;
|
||||
# What it names wrongly is reported where its declaration's attributes are
|
||||
# checked, once.
|
||||
this.mute++;
|
||||
val kind := this.resolve_type(node);
|
||||
this.mute--;
|
||||
return kind;
|
||||
}
|
||||
|
||||
#! What a description says of itself, read as a field of it: its `kind`, as
|
||||
#! the bit of `core::target`, whether it is `exported` or `generic`, which are
|
||||
#! known, and its `name` and `path`.
|
||||
#! @param this The checker.
|
||||
#! @param node The `member` node, which takes what the field is known to be.
|
||||
#! @param one The description's index in `descs`.
|
||||
#! @param name The ID of the field's name.
|
||||
pub def checker::reflected_field(&mut this, node: u32, one: u32, name: u32): void {
|
||||
val held: desc = this.descs[one];
|
||||
val text := this.names.text(name);
|
||||
if text == "kind" {
|
||||
val bit := held.param != 0 ? 0x2000u : this.target_bit(held.decl);
|
||||
this.set_value(node, constant::integer(bit, false));
|
||||
} else if text == "exported" {
|
||||
this.set_value(node, constant::truth(held.param == 0 && this.decls.has(held.decl, df::exported)));
|
||||
} else if text == "generic" {
|
||||
val own := held.param == 0 && this.own_param_count(held.decl) != 0;
|
||||
this.set_value(node, constant::truth(own));
|
||||
}
|
||||
}
|
||||
|
||||
#! The type of what a description describes: a function's own type, or what a
|
||||
#! variable, field, parameter, or property holds.
|
||||
#! @param this The checker.
|
||||
#! @param one The description's index in `descs`.
|
||||
#! @returns The type.
|
||||
pub def checker::reflected_type(&mut this, one: u32): u32 {
|
||||
val held: desc = this.descs[one];
|
||||
this.resolve(held.decl);
|
||||
var kind: u32 = this.decls.types.p[held.decl];
|
||||
if held.owner != 0 {
|
||||
kind = this.instantiated(kind, this.type_decl(held.owner), held.owner);
|
||||
}
|
||||
if held.param != 0 {
|
||||
return held.param <= this.types.part_count(kind) ? this.types.part_at(kind, held.param - 1) : bt::error;
|
||||
}
|
||||
return kind;
|
||||
}
|
||||
|
||||
#! `for const d in declarations()`, or over any list of descriptions: its body
|
||||
#! is checked once for each, with `d` describing it, each with a result table
|
||||
#! of its own.
|
||||
#! @param this The checker.
|
||||
#! @param node The `for_stmt` node.
|
||||
#! @param variable The node of the loop's variable.
|
||||
#! @param list The list's run in `reflected`.
|
||||
#! @param kind The type of the descriptions, `core::decl`.
|
||||
pub def checker::unroll_reflection(&mut this, node: u32, variable: u32, list: u32, kind: u32): void {
|
||||
val body := this.right_of(node);
|
||||
val outer := this.at.table;
|
||||
val count := this.reflected_count(list);
|
||||
var element: u32 = bt::error;
|
||||
if this.is_std(this.unalias(kind), word::span) {
|
||||
element = this.types.part_at(this.unalias(kind), 0);
|
||||
}
|
||||
|
||||
for i in 0..count {
|
||||
val item := this.reflected_item(list, i as u32);
|
||||
val table := this.add_child_table(variable, body - variable + 1);
|
||||
this.use_table(table);
|
||||
val mark := this.scope_mark();
|
||||
this.declare_local(variable, this.name_of(variable), element);
|
||||
var items := vector::<u32>::new();
|
||||
items.append(item);
|
||||
this.set_reflected(variable, rk::one, items.view());
|
||||
this.at.loops++;
|
||||
this.check_block(body);
|
||||
this.at.loops--;
|
||||
this.unbind_to(mark);
|
||||
this.use_table(outer);
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether checking is within a generic's own body, where what reflection says
|
||||
#! of its type parameters waits for each instance.
|
||||
#! @param this The checker.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::waits_for_instance(&mut this): bool {
|
||||
return false if this.at.instance != 0 || this.at.decl == 0;
|
||||
return true if this.decls.has(this.at.decl, df::generic);
|
||||
# A default compiled for each type taking it is checked as a template too.
|
||||
return this.decls.kinds.p[this.at.decl] == dk::function && this.typed_default(this.at.decl);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,376 @@
|
||||
#! @file results.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the result tables, which hold what the checker works out of each
|
||||
#! node: its type, what it refers to, and its flags, with the constant it is
|
||||
#! and the type it converts to where it has them. A file has a table of all of
|
||||
#! its nodes, and an instance of a generic a table of its template's nodes, so
|
||||
#! the same node has the results of each instance it is checked in.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! What a node's flags hold.
|
||||
pub enum rf : u16 {
|
||||
place = 0x0001, #! It names a place: a variable, parameter, field, element, or what a reference or pointer reaches.
|
||||
writable = 0x0002, #! The place can be written.
|
||||
known = 0x0004, #! Its value is known while compiling, and is in `r_values`.
|
||||
local = 0x0008, #! It declares a local, whose type is the node's type.
|
||||
mutable = 0x0010, #! The local it declares can be written.
|
||||
checked = 0x0020, #! It has been checked, which a node reached twice is checked once for.
|
||||
borrowed = 0x0040, #! A reference to it was taken for a parameter, as `&` before it would.
|
||||
leaves = 0x0080, #! A statement after which the block never goes on: it returns, breaks, or continues.
|
||||
method = 0x0100, #! A member that is a method, which a call gives `this`.
|
||||
narrowed = 0x0200, #! A binding of what an `is` test or match arm names.
|
||||
reflected = 0x0400, #! It gives descriptions of reflection, which are in `reflections`.
|
||||
invokes = 0x0800, #! A call of a value of no function type, through its `invoke`, whose `this` the callee is.
|
||||
valued = 0x1000, #! A reference taken as the value it reaches, as a binding, a pattern, `for`, or inference takes one not written with `&`.
|
||||
relent = 0x2000, #! `&` of a reference, or of a field holding one, which is that reference, since references never stack.
|
||||
adapted = 0x4000, #! A function named as a value of another function type, which a function made for it calls it as, as a call would.
|
||||
}
|
||||
|
||||
#! What a node's reference holds: a declaration, or with one of these bits, the
|
||||
#! node declaring a local, or a type a type parameter is bound to.
|
||||
pub const ref_local: u32 = 0x80000000; #! The node declaring a local, in the bits of `ref_mask`.
|
||||
pub const ref_type: u32 = 0x40000000; #! A type a type parameter is bound to, in the bits of `ref_mask`.
|
||||
pub const ref_mask: u32 = 0x3FFFFFFF; #! The bits holding the declaration, node, or type.
|
||||
|
||||
#! Adds a result table of `count` nodes from `base` of the file.
|
||||
#! @param this The checker.
|
||||
#! @param file The file whose nodes it holds results of.
|
||||
#! @param base The first node it holds.
|
||||
#! @param count How many nodes it holds.
|
||||
#! @param instance One more than the instance it is of, or 0 for the file's
|
||||
#! own.
|
||||
#! @returns Its index.
|
||||
pub def checker::add_table(&mut this, file: u32, base: u32, count: u32, instance: u32): u32 {
|
||||
val index := this.tables.length as u32;
|
||||
this.tables.append(rtable {
|
||||
file = file,
|
||||
base = base,
|
||||
count = count,
|
||||
offset = this.r_types.length as u32,
|
||||
instance = instance
|
||||
});
|
||||
|
||||
this.resize_results(this.r_types.length + count as u64);
|
||||
return index;
|
||||
}
|
||||
|
||||
#! Makes each result column hold a number of nodes' results, the nodes added
|
||||
#! holding none.
|
||||
#! @param this The checker.
|
||||
#! @param total How many nodes' results each holds after.
|
||||
def checker::resize_results(&mut this, total: u64): void {
|
||||
this.r_types.resize(total);
|
||||
this.r_refs.resize(total);
|
||||
this.r_flags.resize(total);
|
||||
}
|
||||
|
||||
#! Copies a node's results, at one row of the results, to another.
|
||||
#! @param this The checker.
|
||||
#! @param from The row to copy from.
|
||||
#! @param to The row to copy to.
|
||||
def checker::copy_results(&mut this, from: u64, to: u64): void {
|
||||
this.r_types.p[to] = this.r_types.p[from];
|
||||
this.r_refs.p[to] = this.r_refs.p[from];
|
||||
this.r_flags.p[to] = this.r_flags.p[from];
|
||||
copy_row(&mut this.r_converts, from, to);
|
||||
copy_row(&mut this.r_values, from, to);
|
||||
}
|
||||
|
||||
# Copies what a map holds of one row to another, or takes what it holds of the
|
||||
# other where it holds nothing of the one.
|
||||
def copy_row(rows: &mut keymap, from: u64, to: u64): void {
|
||||
if rows.get(&from) is some(held) {
|
||||
rows.set(to, held);
|
||||
} else {
|
||||
rows.remove(&to);
|
||||
}
|
||||
}
|
||||
|
||||
#! Lets go of a node's results, at a row of the results.
|
||||
#! @param this The checker.
|
||||
#! @param at The row.
|
||||
def checker::drop_results(&mut this, at: u64): void {
|
||||
this.r_types.p[at] = 0;
|
||||
this.r_refs.p[at] = 0;
|
||||
this.r_flags.p[at] = 0;
|
||||
this.r_converts.remove(&at);
|
||||
this.r_values.remove(&at);
|
||||
}
|
||||
|
||||
#! Adds a result table of the nodes from `base`, within the one being written,
|
||||
#! whose nodes it holds but for its own: what a body checked once for each of
|
||||
#! several things, as `for const`, writes for each.
|
||||
#! @param this The checker.
|
||||
#! @param base The first node it holds.
|
||||
#! @param count How many nodes it holds.
|
||||
#! @returns Its index.
|
||||
pub def checker::add_child_table(&mut this, base: u32, count: u32): u32 {
|
||||
val index := this.add_table(this.at.file, base, count, this.tables.p[this.at.table].instance);
|
||||
this.tables.p[index].parent = this.at.table + 1;
|
||||
return index;
|
||||
}
|
||||
|
||||
#! Makes the table the one results are read from and written to.
|
||||
#! @param this The checker.
|
||||
#! @param table The table's index.
|
||||
pub def checker::use_table(&mut this, table: u32): void {
|
||||
val held: rtable = this.tables.p[table];
|
||||
this.at.table = table;
|
||||
this.at.file = held.file;
|
||||
this.at.base = held.base;
|
||||
this.at.offset = held.offset;
|
||||
this.at.count = held.count;
|
||||
|
||||
val syntax := &this.units[held.file].syntax;
|
||||
this.at.kinds = syntax.node_kinds.view().data;
|
||||
this.at.tokens = syntax.node_tokens.view().data;
|
||||
this.at.lefts = syntax.node_lefts.view().data;
|
||||
this.at.rights = syntax.node_rights.view().data;
|
||||
this.at.extras = syntax.extras.view().data;
|
||||
this.at.names = syntax.token_names.view().data;
|
||||
this.at.tkinds = syntax.token_kinds.view().data;
|
||||
}
|
||||
|
||||
#! The table holding the node's results: the one being written, or the one it
|
||||
#! was made within that holds the node, or `no_table`.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns The table's index, or `no_table`.
|
||||
def checker::holding(&this, node: u32): u32 {
|
||||
return this.at.table if node >= this.at.base && node - this.at.base < this.at.count;
|
||||
|
||||
var table: u32 = this.tables.p[this.at.table].parent;
|
||||
var steps := 0;
|
||||
while table != 0 && steps < 32 {
|
||||
val held: rtable = this.tables.p[table - 1];
|
||||
return table - 1 if node >= held.base && node - held.base < held.count;
|
||||
table = held.parent;
|
||||
steps++;
|
||||
}
|
||||
return checker::no_table;
|
||||
}
|
||||
|
||||
#! What says no table holds a node.
|
||||
pub const checker::no_table: u32 = 0xFFFFFFFF;
|
||||
|
||||
#! Where the node's results are in the result vectors, or past their end where
|
||||
#! no table being written holds the node. Every read and write of a result
|
||||
#! finds it here, so it is copied where it is called.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns The index of its results.
|
||||
@inline
|
||||
def checker::slot(&this, node: u32): u64 {
|
||||
if node >= this.at.base && node - this.at.base < this.at.count {
|
||||
return this.at.offset as u64 + (node - this.at.base) as u64;
|
||||
}
|
||||
return this.slot_elsewhere(node);
|
||||
}
|
||||
|
||||
#! Where the results are of a node the table being written does not hold, as
|
||||
#! `slot` says, which is apart so `slot` stays small where it is copied.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns The index of its results.
|
||||
def checker::slot_elsewhere(&this, node: u32): u64 {
|
||||
val table := this.holding(node);
|
||||
return this.r_types.length if table == checker::no_table;
|
||||
val held: rtable = this.tables.p[table];
|
||||
return held.offset as u64 + (node - held.base) as u64;
|
||||
}
|
||||
|
||||
#! The type checking gave a node.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns Its type, or 0 where it has none, or no table being written holds
|
||||
#! it.
|
||||
@inline
|
||||
pub def checker::type_at(&this, node: u32): u32 {
|
||||
val at := this.slot(node);
|
||||
return at < this.r_types.length ? this.r_types.p[at] : 0;
|
||||
}
|
||||
|
||||
#! Records the type of a node.
|
||||
#! @param this The checker.
|
||||
#! @param node The node, whose type is not recorded where no table being
|
||||
#! written holds it.
|
||||
#! @param kind The type.
|
||||
@inline
|
||||
pub def checker::set_type(&mut this, node: u32, kind: u32): void {
|
||||
val at := this.slot(node);
|
||||
if at < this.r_types.length {
|
||||
this.r_types.p[at] = kind;
|
||||
}
|
||||
}
|
||||
|
||||
#! What a node refers to.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns A declaration, a local or a type with its bit of `ref_local` or
|
||||
#! `ref_type`, or 0.
|
||||
@inline
|
||||
pub def checker::ref_at(&this, node: u32): u32 {
|
||||
val at := this.slot(node);
|
||||
return at < this.r_refs.length ? this.r_refs.p[at] : 0;
|
||||
}
|
||||
|
||||
#! Records what a node refers to.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param ref A declaration, or a local or a type with its bit.
|
||||
@inline
|
||||
pub def checker::set_ref(&mut this, node: u32, ref: u32): void {
|
||||
val at := this.slot(node);
|
||||
if at < this.r_refs.length {
|
||||
this.r_refs.p[at] = ref;
|
||||
}
|
||||
}
|
||||
|
||||
#! The flags of a node, as `rf` says.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns Its flags, or 0.
|
||||
@inline
|
||||
pub def checker::flags_at(&this, node: u32): u32 {
|
||||
val at := this.slot(node);
|
||||
return at < this.r_flags.length ? this.r_flags.p[at] as u32 : 0;
|
||||
}
|
||||
|
||||
#! Whether a node has a flag.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param flag The flag.
|
||||
#! @returns Whether it has it.
|
||||
@inline
|
||||
pub def checker::has_flag(&this, node: u32, flag: rf): bool {
|
||||
return (this.flags_at(node) & flag as u32) != 0;
|
||||
}
|
||||
|
||||
#! Gives a node a flag.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param flag The flag.
|
||||
@inline
|
||||
pub def checker::set_flag(&mut this, node: u32, flag: rf): void {
|
||||
val at := this.slot(node);
|
||||
if at < this.r_flags.length {
|
||||
this.r_flags.p[at] |= flag as u16;
|
||||
}
|
||||
}
|
||||
|
||||
#! Takes a flag from a node.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param flag The flag.
|
||||
@inline
|
||||
pub def checker::clear_flag(&mut this, node: u32, flag: rf): void {
|
||||
val at := this.slot(node);
|
||||
if at < this.r_flags.length {
|
||||
this.r_flags.p[at] &= ~(flag as u16);
|
||||
}
|
||||
}
|
||||
|
||||
#! The key of the node within the current table, for the sparse results.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns The key: `table << 32 | node`.
|
||||
pub def checker::result_key(&this, node: u32): u64 {
|
||||
val table := this.holding(node);
|
||||
return pair_key(table == checker::no_table ? this.at.table : table, node);
|
||||
}
|
||||
|
||||
#! Records that the node's value converts to the type, which is not its own.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param kind The type it converts to.
|
||||
pub def checker::set_convert(&mut this, node: u32, kind: u32): void {
|
||||
val at := this.slot(node);
|
||||
if at < this.r_types.length {
|
||||
if kind != 0 {
|
||||
this.r_converts.set(at, kind);
|
||||
} else {
|
||||
this.r_converts.remove(&at);
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.converts.set(this.result_key(node), kind);
|
||||
}
|
||||
|
||||
#! The type the node's value becomes where it is used: what it converts to, or
|
||||
#! its own type.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns The type.
|
||||
pub def checker::converted(&this, node: u32): u32 {
|
||||
val at := this.slot(node);
|
||||
if at < this.r_types.length {
|
||||
return this.r_converts.get_or(&at, this.r_types.p[at]);
|
||||
}
|
||||
val key := this.result_key(node);
|
||||
return this.converts.get_or(&key, this.type_at(node));
|
||||
}
|
||||
|
||||
#! Records that the node's value is known while compiling.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param value Its value.
|
||||
pub def checker::set_value(&mut this, node: u32, value: constant): void {
|
||||
val id := this.intern_constant(value);
|
||||
val at := this.slot(node);
|
||||
if at < this.r_types.length {
|
||||
this.r_values.set(at, id);
|
||||
this.r_flags.p[at] |= rf::known as u16;
|
||||
return;
|
||||
}
|
||||
this.values.set(this.result_key(node), id);
|
||||
this.set_flag(node, rf::known);
|
||||
}
|
||||
|
||||
#! The ID of a constant among `constants`, which it is added to where it is
|
||||
#! new, so each value is held once however many nodes are it: most are 0, 1,
|
||||
#! or a small number.
|
||||
#! @param this The checker.
|
||||
#! @param value The constant.
|
||||
#! @returns Its ID.
|
||||
pub def checker::intern_constant(&mut this, value: constant): u32 {
|
||||
val hash := mix(mix(value.word, value.negative ? 1 : 0), value.floating ? 1 : 0);
|
||||
var walk := this.constant_index.walk(hash);
|
||||
var at := this.constant_index.next(&mut walk);
|
||||
while at != 0 {
|
||||
return at - 1 if this.constants.p[at - 1].same(&value);
|
||||
at = this.constant_index.next(&mut walk);
|
||||
}
|
||||
val id := this.constants.length as u32;
|
||||
this.constants.append(value);
|
||||
this.constant_index.add(hash, id);
|
||||
return id;
|
||||
}
|
||||
|
||||
#! Whether the node's value is known while compiling.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns Whether it is.
|
||||
@inline
|
||||
pub def checker::is_known(&this, node: u32): bool {
|
||||
return this.has_flag(node, rf::known);
|
||||
}
|
||||
|
||||
#! The node's value, where it is known, or a zero constant: constant 0, which
|
||||
#! stands for none.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns Its value.
|
||||
pub def checker::value_at(&this, node: u32): constant {
|
||||
# A node a table holds says whether it has a value, which most have none of.
|
||||
val at := this.slot(node);
|
||||
if at < this.r_types.length {
|
||||
return (this.r_flags.p[at] & rf::known as u16) != 0 ? this.constants.p[this.r_values.get_or(&at, 0)] : constant {};
|
||||
}
|
||||
val key := this.result_key(node);
|
||||
return this.constants.p[this.values.get_or(&key, 0)];
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
#! @file scopes.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the bindings of names to the locals, parameters, and type
|
||||
#! parameters they refer to. They are one stack, and each name keeps the
|
||||
#! binding of it nearest the top, so finding what a name refers to takes one
|
||||
#! read, and a scope ends by cutting the stack back to where it began.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! Where the bindings are now, which a scope ending cuts them back to.
|
||||
#! @param this The checker.
|
||||
#! @returns The mark.
|
||||
pub def checker::scope_mark(&this): u32 {
|
||||
return this.bind_names.length as u32;
|
||||
}
|
||||
|
||||
#! Binds the name to what it refers to, hiding what it referred to before
|
||||
#! until the scope ends. `_` is never bound, since nothing reads it.
|
||||
#! @param this The checker.
|
||||
#! @param name The ID of the name.
|
||||
#! @param value What it refers to: a local or type parameter with its bit of
|
||||
#! `ref_local` or `ref_type`.
|
||||
pub def checker::bind(&mut this, name: u32, value: u32): void {
|
||||
return if name == names::underscore_id || name == 0;
|
||||
|
||||
if this.innermost.length <= name as u64 {
|
||||
this.innermost.resize(name as u64 + 1);
|
||||
}
|
||||
|
||||
this.bind_names.append(name);
|
||||
this.bind_values.append(value);
|
||||
this.bind_prev.append(this.innermost[name]);
|
||||
this.innermost[name] = this.bind_names.length as u32;
|
||||
}
|
||||
|
||||
#! Ends the scopes begun since the mark.
|
||||
#! @param this The checker.
|
||||
#! @param mark Where the bindings were, as `scope_mark` gave it.
|
||||
pub def checker::unbind_to(&mut this, mark: u32): void {
|
||||
# Each name is given back what it hid from the top down, so a name bound more
|
||||
# than once since the mark is given back what it was bound to before.
|
||||
var top := this.bind_names.length;
|
||||
return if top <= mark as u64;
|
||||
while top > mark as u64 {
|
||||
top--;
|
||||
val name: u32 = this.bind_names[top];
|
||||
this.innermost[name] = this.bind_prev[top];
|
||||
}
|
||||
this.bind_names.resize(mark as u64);
|
||||
this.bind_values.resize(mark as u64);
|
||||
this.bind_prev.resize(mark as u64);
|
||||
}
|
||||
|
||||
#! What the name is bound to, or 0 where it is bound to nothing.
|
||||
#! @param this The checker.
|
||||
#! @param name The ID of the name.
|
||||
#! @returns What it is bound to, or 0.
|
||||
pub def checker::bound(&this, name: u32): u32 {
|
||||
return 0 if name as u64 >= this.innermost.length;
|
||||
|
||||
val at: u32 = this.innermost[name];
|
||||
return at == 0 ? 0 : this.bind_values[at - 1];
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,895 @@
|
||||
#! @file traits.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains traits: what a trait asks for, and whether a type satisfies it. A
|
||||
#! type satisfies a trait by its shape, having each method the trait asks for
|
||||
#! with the signature it asks, where `self` is the type, whether or not the
|
||||
#! type names the trait. A type parameter satisfies what its bounds do. What
|
||||
#! was worked out of a type and a trait is kept, so it is worked out once.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! Resolves the traits a declaration names after its name: those a struct or
|
||||
#! union implements, or a trait composes.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
pub def checker::resolve_composed(&mut this, id: u32): void {
|
||||
return if this.composed.at_or_zero(id) != 0;
|
||||
this.composed.put(id, 1);
|
||||
|
||||
val kind: dk = this.decls.kinds.p[id];
|
||||
return if kind != dk::struct_type && kind != dk::union_type && kind != dk::trait_type;
|
||||
|
||||
val saved := this.at;
|
||||
this.enter_decl(id, 0);
|
||||
var traits := vector::<u32>::new();
|
||||
val run := this.record(this.decls.nodes.p[id], aggregate_slot::traits);
|
||||
for &written in this.run_view(run) {
|
||||
val made := this.resolve_type(written);
|
||||
if made != bt::error && this.named_kind(made) != dk::trait_type {
|
||||
this.report(written, ec::not_type, kind == dk::trait_type
|
||||
? "A trait composes traits."
|
||||
: "A struct or union names the traits it implements.");
|
||||
continue;
|
||||
}
|
||||
if made != bt::error {
|
||||
traits.append(made);
|
||||
}
|
||||
}
|
||||
this.leave(saved);
|
||||
this.composed.put(id, this.decls.make_list(traits.view()) + 1);
|
||||
}
|
||||
|
||||
#! The traits a declaration names after its name, resolved.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns The run of the traits' types, in `lists`.
|
||||
pub def checker::composed_of(&mut this, id: u32): u32 {
|
||||
this.resolve_composed(id);
|
||||
return this.composed.at_or_zero(id) - 1;
|
||||
}
|
||||
|
||||
#! Whether a value of the type satisfies the trait, given its arguments.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param trait_kind The trait's type, given its arguments.
|
||||
#! @returns Whether it does.
|
||||
pub def checker::satisfies(&mut this, kind: u32, trait_kind: u32): bool {
|
||||
return true if kind == bt::error || trait_kind == bt::error;
|
||||
|
||||
# What a type parameter satisfies changes as `if const` proves bounds of it,
|
||||
# so only what holds no parameter is kept.
|
||||
if this.types.is_open(kind) {
|
||||
return this.works_out(kind, trait_kind);
|
||||
}
|
||||
|
||||
val key := pair_key(kind, trait_kind);
|
||||
if this.satisfied.get(&key) is some(got) {
|
||||
return got != 0;
|
||||
}
|
||||
|
||||
# A type asked of again while it is being worked out satisfies the trait so
|
||||
# far, which lets a trait ask for methods taking the trait itself.
|
||||
this.satisfied.set(key, 1);
|
||||
val holds := this.works_out(kind, trait_kind);
|
||||
this.satisfied.set(key, holds ? 1 : 0);
|
||||
return holds;
|
||||
}
|
||||
|
||||
def checker::works_out(&mut this, kind: u32, trait_kind: u32): bool {
|
||||
val holder := this.types.first_of(trait_kind);
|
||||
val name: u32 = this.decls.names.p[holder];
|
||||
val is_std := this.std_decl(name) == holder;
|
||||
val plain := this.unalias(kind);
|
||||
|
||||
# The bounds the compiler decides.
|
||||
if is_std && name == word::integer {
|
||||
return this.types.is_integer(plain) && !this.types.is_untyped(plain) || this.param_bounded(plain, holder);
|
||||
}
|
||||
if is_std && name == word::real {
|
||||
return this.types.is_float(plain) && !this.types.is_untyped(plain) || this.param_bounded(plain, holder);
|
||||
}
|
||||
# Every integer is ordinal, so a type parameter bounded by `integer` is too.
|
||||
if is_std && name == word::ordinal {
|
||||
val integer := this.std_decl(word::integer);
|
||||
return (this.types.is_integer(plain) && !this.types.is_untyped(plain)) || this.named_kind(plain) == dk::enum_type
|
||||
|| this.param_bounded(plain, holder) || (integer != 0 && this.param_bounded(plain, integer));
|
||||
}
|
||||
if is_std && name == word::pointer {
|
||||
return this.types.kind_of(plain) == ty::pointer || this.param_bounded(plain, holder);
|
||||
}
|
||||
# A function type, a variadic one too, and the address of a C function are
|
||||
# signatures, and nothing else is.
|
||||
if is_std && name == word::signature {
|
||||
return this.signature_function(plain) != 0 || this.param_bounded(plain, holder);
|
||||
}
|
||||
|
||||
# A type is `closeable` where its values close, and a type parameter where its
|
||||
# bounds say so, or say it is `owning`.
|
||||
if is_std && name == word::closeable {
|
||||
if this.types.kind_of(plain) == ty::param || this.types.kind_of(plain) == ty::pack {
|
||||
val owning := this.std_decl(word::owning);
|
||||
return this.param_bounded(plain, holder) || (owning != 0 && this.param_bounded(plain, owning));
|
||||
}
|
||||
return this.closes(plain);
|
||||
}
|
||||
|
||||
# A type is `zeroable` where it has a zero value, and a type parameter where
|
||||
# its bounds say so.
|
||||
if is_std && name == word::zeroable {
|
||||
return this.has_zero(plain, 0);
|
||||
}
|
||||
|
||||
# A type is `lockfree` where it is a word or less that every processor reads and
|
||||
# writes whole without a lock: an integer, `bool`, enum, or pointer.
|
||||
if is_std && name == word::lockfree {
|
||||
val of := this.types.kind_of(plain);
|
||||
return (this.types.is_integer(plain) && !this.types.is_untyped(plain)) || plain == bt::boolean
|
||||
|| this.named_kind(plain) == dk::enum_type || of == ty::pointer || this.param_bounded(plain, holder);
|
||||
}
|
||||
|
||||
# A type parameter satisfies what one of its bounds is, or composes.
|
||||
if this.types.kind_of(plain) == ty::param || this.types.kind_of(plain) == ty::pack {
|
||||
return this.param_bounded(plain, holder);
|
||||
}
|
||||
|
||||
# A reference satisfies what its referent does, where the trait asks only for what
|
||||
# can be called through it.
|
||||
if this.types.kind_of(plain) == ty::reference && this.lends(plain, trait_kind, holder) {
|
||||
return true;
|
||||
}
|
||||
|
||||
# A trait reference satisfies the trait it is, and those it composes.
|
||||
if this.named_kind(plain) == dk::trait_type && this.composes(plain, holder, 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
# A type is `owning` only by naming it, so a `close` meant to be called by hand
|
||||
# never makes its values closed by accident.
|
||||
if is_std && name == word::owning && !this.names_trait(plain, holder) {
|
||||
return false;
|
||||
}
|
||||
|
||||
# Only a struct naming it implements `attribute`.
|
||||
if is_std && name == word::attribute {
|
||||
return this.names_trait(plain, holder);
|
||||
}
|
||||
|
||||
return this.has_requirements(kind, trait_kind, holder, 0);
|
||||
}
|
||||
|
||||
#! Whether a reference satisfies a trait through what it refers to, as `&mut
|
||||
#! file` satisfies what `file` does, so a generic can be given either. Its
|
||||
#! methods are its referent's, called through it, so the trait asks only for
|
||||
#! methods taking `this`, and only for ones taking `&this` where it only reads.
|
||||
#! It is compared, ordered, and hashed as what it refers to, so it takes a trait
|
||||
#! naming `self` where `self` is only taken by reference, but none giving or
|
||||
#! taking a `self` by value, since what is made from the referent is no
|
||||
#! reference. It owns nothing, so it is never `owning`. A pointer is an address,
|
||||
#! and takes nothing from what it points at.
|
||||
#! @param this The checker.
|
||||
#! @param kind The reference's type.
|
||||
#! @param trait_kind The trait's type, given its arguments.
|
||||
#! @param holder The trait's declaration.
|
||||
#! @returns Whether it does.
|
||||
def checker::lends(&mut this, kind: u32, trait_kind: u32, holder: u32): bool {
|
||||
return false if this.about_values(holder);
|
||||
return false if this.unreached(holder, this.types.second_of(kind) == 1, 0) != 0;
|
||||
return this.satisfies(this.types.first_of(kind), trait_kind);
|
||||
}
|
||||
|
||||
# Whether a trait of std is one the compiler gives a meaning, which says what a value
|
||||
# itself is.
|
||||
def checker::about_values(&mut this, holder: u32): bool {
|
||||
val name: u32 = this.decls.names.p[holder];
|
||||
return this.std_decl(name) == holder
|
||||
&& (name == word::owning || name == word::attribute
|
||||
|| name == word::integer || name == word::ordinal || name == word::real || name == word::closeable
|
||||
|| name == word::zeroable || name == word::pointer
|
||||
|| name == word::lockfree);
|
||||
}
|
||||
|
||||
# The first member a trait, or a trait it composes, asks for that a reference cannot
|
||||
# reach through it: one not taking `this`, taking `&mut this` where it only reads, or
|
||||
# not reading through to `self`. A type it asks for is the referent's, an `@optional`
|
||||
# method taking `&mut this` is only not there to call through a reference that reads,
|
||||
# and a default compiled for each type is the reference's own, as it is any type's.
|
||||
# Gives 0 where there is none.
|
||||
def checker::unreached(&mut this, holder: u32, writes: bool, depth: u32): u32 {
|
||||
return holder if depth > 16;
|
||||
|
||||
val self_kind := this.types.param(this.self_decl(holder));
|
||||
val run: u32 = this.decls.children.p[holder];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val member := this.decls.list_at(run, i as u32);
|
||||
this.resolve(member);
|
||||
val kind: dk = this.decls.kinds.p[member];
|
||||
if (kind == dk::property && writes) || kind == dk::assoc_type {
|
||||
continue;
|
||||
}
|
||||
if kind == dk::function && !writes && this.decls.has(member, df::mut_this) && this.decls.has(member, df::optional) {
|
||||
continue;
|
||||
}
|
||||
if kind == dk::function && this.typed_default(member) {
|
||||
continue;
|
||||
}
|
||||
return member if kind != dk::function || !this.decls.has(member, df::method);
|
||||
return member if !writes && this.decls.has(member, df::mut_this);
|
||||
return member if !this.reads_through(member, self_kind);
|
||||
}
|
||||
|
||||
val composed := this.composed_of(holder);
|
||||
for i in 0..this.decls.list_length(composed) {
|
||||
val inner := this.unreached(this.types.first_of(this.decls.list_at(composed, i as u32)), writes, depth + 1);
|
||||
return inner if inner != 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
# Whether a method of a trait is called through a reference to what implements it as
|
||||
# it is on what that refers to: `self` is taken only by reference, which a reference
|
||||
# to the reference reads through to, and is never given, since what is made from the
|
||||
# referent is no reference.
|
||||
def checker::reads_through(&mut this, method: u32, self_kind: u32): bool {
|
||||
val kind: u32 = this.decls.types.p[method];
|
||||
return false if this.mentions(this.types.first_of(kind), self_kind, 0);
|
||||
for p in 1..this.types.part_count(kind) {
|
||||
val taken := this.types.part_at(kind, p as u32);
|
||||
continue if !this.mentions(taken, self_kind, 0);
|
||||
return false if this.types.kind_of(taken) != ty::reference || this.types.first_of(taken) != self_kind;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Why a reference or a pointer does not satisfy a trait that what it refers to
|
||||
#! does, or empty text where its referent does not either.
|
||||
#! @param this The checker.
|
||||
#! @param kind The reference's or pointer's type.
|
||||
#! @param trait_kind The trait's type.
|
||||
#! @returns Why, as a note's detail, or empty text.
|
||||
def checker::unlent(&mut this, kind: u32, trait_kind: u32): string {
|
||||
val plain := this.unalias(kind);
|
||||
val held := this.types.kind_of(plain);
|
||||
val holder := this.types.first_of(trait_kind);
|
||||
var why := string::new(nothing {});
|
||||
return move(why) if held != ty::reference && held != ty::pointer;
|
||||
return move(why) if !this.satisfies(this.types.first_of(plain), trait_kind);
|
||||
|
||||
val name: u32 = this.decls.names.p[holder];
|
||||
if held == ty::pointer {
|
||||
why.append("a pointer is an address, so what it points at is reached through `*p`");
|
||||
return move(why);
|
||||
}
|
||||
if this.std_decl(name) == holder && name == word::owning {
|
||||
why.append("it owns nothing it refers to, though `close` can be called through it");
|
||||
return move(why);
|
||||
}
|
||||
if this.about_values(holder) {
|
||||
why.append("the trait says what a value itself is, not what it refers to");
|
||||
return move(why);
|
||||
}
|
||||
|
||||
val writes := this.types.second_of(plain) == 1;
|
||||
val member := this.unreached(holder, writes, 0);
|
||||
return move(why) if member == 0;
|
||||
val self_kind := this.types.param(this.self_decl(this.decls.owners.p[member]));
|
||||
why.append("`");
|
||||
why.append(this.decl_text(member));
|
||||
if this.decls.kinds.p[member] != dk::function || !this.decls.has(member, df::method) {
|
||||
why.append("` takes no `this`, so it is not reached through a reference");
|
||||
} else if !writes && this.decls.has(member, df::mut_this) {
|
||||
why.append("` takes `&mut this`, and the reference only reads");
|
||||
} else if this.mentions(this.types.first_of(this.decls.types.p[member]), self_kind, 0) {
|
||||
why.append("` gives `self`, and what it makes is not a reference");
|
||||
} else {
|
||||
why.append("` takes `self` by value, and a reference reaches only what takes it by reference");
|
||||
}
|
||||
return move(why);
|
||||
}
|
||||
|
||||
#! Whether a type parameter's bounds include the trait, or a trait composing it.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type parameter's type.
|
||||
#! @param holder The trait's declaration.
|
||||
#! @returns Whether they do.
|
||||
def checker::param_bounded(&mut this, kind: u32, holder: u32): bool {
|
||||
return false if this.types.kind_of(kind) != ty::param && this.types.kind_of(kind) != ty::pack;
|
||||
|
||||
val param := this.types.first_of(kind);
|
||||
return false if param == 0;
|
||||
if this.decls.names.p[param] == names::self_id
|
||||
&& (this.decls.owners.p[param] == holder || this.composes(this.decls.types.p[this.decls.owners.p[param]], holder, 0)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return this.bounded_by(param, holder, 0, 0);
|
||||
}
|
||||
|
||||
#! Whether a type parameter is bounded by any of up to three traits, through a
|
||||
#! bound it declares, or one an `if const` proved of it in the branch it guards.
|
||||
#! @param this The checker.
|
||||
#! @param param The parameter's declaration.
|
||||
#! @param first A trait's declaration, or 0.
|
||||
#! @param second Another, or 0.
|
||||
#! @param third Another, or 0.
|
||||
#! @returns Whether it is.
|
||||
def checker::bounded_by(&mut this, param: u32, first: u32, second: u32, third: u32): bool {
|
||||
return false if first == 0 && second == 0 && third == 0;
|
||||
this.resolve(param);
|
||||
val run: u32 = this.decls.children.p[param];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
return true if this.composes_any(this.decls.list_at(run, i as u32), first, second, third);
|
||||
}
|
||||
for i in 0..this.proved_params.length {
|
||||
return true if this.proved_params[i] == param && this.composes_any(this.proved_bounds[i], first, second, third);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Whether a bound composes any of up to three traits.
|
||||
#! @param this The checker.
|
||||
#! @param bound The bound.
|
||||
#! @param first A trait's declaration, or 0.
|
||||
#! @param second Another, or 0.
|
||||
#! @param third Another, or 0.
|
||||
#! @returns Whether it does.
|
||||
def checker::composes_any(&mut this, bound: u32, first: u32, second: u32, third: u32): bool {
|
||||
return (first != 0 && this.composes(bound, first, 0)) || (second != 0 && this.composes(bound, second, 0))
|
||||
|| (third != 0 && this.composes(bound, third, 0));
|
||||
}
|
||||
|
||||
#! Whether the trait type is the trait, or composes it.
|
||||
#! @param this The checker.
|
||||
#! @param trait_kind The trait type asked about.
|
||||
#! @param holder The declaration of the trait looked for.
|
||||
#! @param depth How deeply composition has been followed, which stops one
|
||||
#! composing itself without end.
|
||||
#! @returns Whether it is, or does.
|
||||
pub def checker::composes(&mut this, trait_kind: u32, holder: u32, depth: u32): bool {
|
||||
return false if depth > 16 || this.types.kind_of(trait_kind) != ty::named;
|
||||
|
||||
val decl := this.types.first_of(trait_kind);
|
||||
return true if decl == holder;
|
||||
val run := this.composed_of(decl);
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
return true if this.composes(this.decls.list_at(run, i as u32), holder, depth + 1);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Whether a struct or union names the trait after its name.
|
||||
#! @param this The checker.
|
||||
#! @param kind The struct's or union's type.
|
||||
#! @param holder The trait's declaration.
|
||||
#! @returns Whether it does.
|
||||
def checker::names_trait(&mut this, kind: u32, holder: u32): bool {
|
||||
return false if this.types.kind_of(kind) != ty::named;
|
||||
|
||||
val run := this.composed_of(this.types.first_of(kind));
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
return true if this.composes(this.decls.list_at(run, i as u32), holder, 0);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Whether the type has what the trait asks for, and what each trait it
|
||||
#! composes asks for.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param trait_kind The trait's type, given its arguments.
|
||||
#! @param holder The trait's declaration.
|
||||
#! @param depth How deeply composition has been followed.
|
||||
#! @returns Whether it has.
|
||||
def checker::has_requirements(&mut this, kind: u32, trait_kind: u32, holder: u32, depth: u32): bool {
|
||||
return false if depth > 16;
|
||||
|
||||
val run: u32 = this.decls.children.p[holder];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val wanted := this.decls.list_at(run, i as u32);
|
||||
continue if this.decls.has(wanted, df::optional);
|
||||
# A method the trait writes a body for is its default, which the type may leave out.
|
||||
continue if this.decls.kinds.p[wanted] == dk::function && this.has_body(wanted);
|
||||
return false if !this.meets(kind, trait_kind, wanted);
|
||||
}
|
||||
|
||||
val composed := this.composed_of(holder);
|
||||
for i in 0..this.decls.list_length(composed) {
|
||||
val inner := this.decls.list_at(composed, i as u32);
|
||||
val given := this.trait_in_terms(inner, holder, trait_kind, kind);
|
||||
return false if !this.satisfies(kind, given);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! A type a trait names, given the trait's arguments, `self`, and each type it
|
||||
#! asks for as what implements it gives.
|
||||
#! @param this The checker.
|
||||
#! @param inner The type the trait names.
|
||||
#! @param holder The trait's declaration.
|
||||
#! @param trait_kind The trait's type, given its arguments.
|
||||
#! @param self_kind The type standing for `self`.
|
||||
#! @returns The type in those terms.
|
||||
def checker::trait_in_terms(&mut this, inner: u32, holder: u32, trait_kind: u32, self_kind: u32): u32 {
|
||||
return inner if !this.types.is_open(inner);
|
||||
|
||||
var from := vector::<u32>::new();
|
||||
var to := vector::<u32>::new();
|
||||
from.append(this.self_decl(holder));
|
||||
to.append(self_kind);
|
||||
val params: u32 = this.decls.params.p[holder];
|
||||
for i in 0..this.decls.list_length(params) {
|
||||
from.append(this.decls.list_at(params, i as u32));
|
||||
to.append(i < this.types.part_count(trait_kind) ? this.types.part_at(trait_kind, i as u32) : bt::error);
|
||||
}
|
||||
|
||||
val asked: u32 = this.decls.children.p[holder];
|
||||
for i in 0..this.decls.list_length(asked) {
|
||||
val member := this.decls.list_at(asked, i as u32);
|
||||
continue if this.decls.kinds.p[member] != dk::assoc_type;
|
||||
from.append(member);
|
||||
to.append(this.asked_type(self_kind, member, trait_kind));
|
||||
}
|
||||
return this.substitute(inner, from.view(), to.view());
|
||||
}
|
||||
|
||||
#! The type a type gives for one a trait asks for: its own of the name, or the
|
||||
#! trait's default, or for a type parameter, the parameter standing for it. A
|
||||
#! trait of `core`'s is given what `core` declares through its own types.
|
||||
#! @param this The checker.
|
||||
#! @param self_kind The type implementing the trait.
|
||||
#! @param asked The declaration of the type the trait asks for.
|
||||
#! @param trait_kind The trait's type, given its arguments.
|
||||
#! @returns The type, or the error type where it gives none.
|
||||
def checker::asked_type(&mut this, self_kind: u32, asked: u32, trait_kind: u32): u32 {
|
||||
val cores := this.in_core(this.decls.modules.p[this.decls.owners.p[asked]]);
|
||||
if cores { this.cores_own++; }
|
||||
val made := this.asked_one(self_kind, asked, trait_kind);
|
||||
if cores { this.cores_own--; }
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The type a type gives for one a trait asks for, as `asked_type` says.
|
||||
#! @param this The checker.
|
||||
#! @param self_kind The type implementing the trait.
|
||||
#! @param asked The declaration of the type the trait asks for.
|
||||
#! @param trait_kind The trait's type, given its arguments.
|
||||
#! @returns The type, or the error type where it gives none.
|
||||
def checker::asked_one(&mut this, self_kind: u32, asked: u32, trait_kind: u32): u32 {
|
||||
val plain := this.unalias(self_kind);
|
||||
if this.types.kind_of(plain) == ty::param || self_kind == bt::error {
|
||||
return self_kind == bt::error ? bt::error : this.projected(plain, asked, trait_kind);
|
||||
}
|
||||
val part := this.signature_part(plain, asked);
|
||||
return part if part != 0;
|
||||
|
||||
# A reference gives the types what it refers to gives.
|
||||
val found := this.find_path_member(this.reached(self_kind), this.decls.names.p[asked]);
|
||||
if found.decl != 0 && this.is_type_decl(found.decl) && found.decl != asked {
|
||||
this.resolve(found.decl);
|
||||
return this.instantiated(this.decls.types.p[found.decl], found.decl, found.owner);
|
||||
}
|
||||
|
||||
this.resolve(asked);
|
||||
val fallback: u32 = this.decls.targets.p[asked];
|
||||
return bt::error if fallback == 0;
|
||||
|
||||
val holder: u32 = this.decls.owners.p[asked];
|
||||
var from := vector::<u32>::new();
|
||||
var to := vector::<u32>::new();
|
||||
from.append(this.self_decl(holder));
|
||||
to.append(self_kind);
|
||||
return this.substitute(fallback, from.view(), to.view());
|
||||
}
|
||||
|
||||
#! Whether the type meets one thing a trait asks for: a method of its name and
|
||||
#! signature, a property, or a type. A trait of `core`'s is met by what `core`
|
||||
#! gives its own types, whatever a program declares through them beside it.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param trait_kind The trait's type, given its arguments.
|
||||
#! @param wanted The declaration of what the trait asks for.
|
||||
#! @returns Whether it does.
|
||||
def checker::meets(&mut this, kind: u32, trait_kind: u32, wanted: u32): bool {
|
||||
val cores := this.in_core(this.decls.modules.p[this.decls.owners.p[wanted]]);
|
||||
if cores { this.cores_own++; }
|
||||
val made := this.meets_one(kind, trait_kind, wanted);
|
||||
if cores { this.cores_own--; }
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Whether the type meets one thing a trait asks for, as `meets` says.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param trait_kind The trait's type, given its arguments.
|
||||
#! @param wanted The declaration of what the trait asks for.
|
||||
#! @returns Whether it does.
|
||||
def checker::meets_one(&mut this, kind: u32, trait_kind: u32, wanted: u32): bool {
|
||||
val name: u32 = this.decls.names.p[wanted];
|
||||
match this.decls.kinds.p[wanted] {
|
||||
dk::function => {
|
||||
this.resolve(wanted);
|
||||
val signature := this.requirement_type(wanted, trait_kind, kind);
|
||||
val found := this.find_member(kind, name);
|
||||
if found.decl == 0 || this.decls.kinds.p[found.decl] != dk::function {
|
||||
val given := this.builtin_method(kind, name);
|
||||
return given != 0 && this.same_signature(this.as_writing(given, wanted), signature);
|
||||
}
|
||||
|
||||
# A number's methods from the compiler are asked first, so a number meets a
|
||||
# trait without the program's methods beside them being worked out. One of
|
||||
# those may be what asked, as `def f32::mul(&this, v: &vec3<f32>)` asks
|
||||
# whether `f32` is `numeric` for `vec3<f32>`.
|
||||
if this.types.is_numeric(this.unalias(kind)) {
|
||||
val builtin := this.builtin_method(kind, name);
|
||||
return true if builtin != 0 && this.same_signature(this.as_writing(builtin, wanted), signature);
|
||||
}
|
||||
|
||||
# A default of a trait the type names is its own, taking it as `self`. A
|
||||
# method taking `&this` meets one asked for taking `&mut this`, since what
|
||||
# can be written can be read. `core`'s methods behind a program's on its
|
||||
# type meet what they did.
|
||||
var chain := found.decl;
|
||||
while chain != 0 {
|
||||
var walk := this.decls.walk_overloads(chain);
|
||||
while true {
|
||||
val at := walk.next();
|
||||
break if at == 0;
|
||||
continue if !this.member_seen(at);
|
||||
this.resolve(at);
|
||||
val declarer := this.enclosing_trait(at);
|
||||
var given := declarer != 0
|
||||
? this.requirement_type(at, this.implemented(kind, declarer), kind)
|
||||
: this.method_type(at, found.owner);
|
||||
if this.decls.has(at, df::method) && !this.decls.has(at, df::mut_this) {
|
||||
given = this.as_writing(given, wanted);
|
||||
}
|
||||
if this.decls.has(at, df::method) == this.decls.has(wanted, df::method)
|
||||
&& this.same_signature(given, signature) && this.bounds_met(at, found.owner) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
chain = this.core_behind(chain);
|
||||
}
|
||||
# A method a program declares on a built-in type is beside those the
|
||||
# compiler gives it, which still meet what they did.
|
||||
val given := this.builtin_method(kind, name);
|
||||
return given != 0 && this.same_signature(this.as_writing(given, wanted), signature);
|
||||
}
|
||||
dk::property => {
|
||||
val found := this.find_member(kind, name);
|
||||
return found.decl != 0 && this.decls.kinds.p[found.decl] == dk::property;
|
||||
}
|
||||
dk::assoc_type => {
|
||||
val found := this.find_member(kind, name);
|
||||
return (found.decl != 0 && this.is_type_decl(found.decl)) || this.decls.targets.p[wanted] != 0;
|
||||
}
|
||||
dk::variable => {
|
||||
val found := this.find_member(kind, name);
|
||||
return found.decl != 0 && this.decls.kinds.p[found.decl] == dk::variable;
|
||||
}
|
||||
else => return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Whether a type has a method whose `where` bounds the type's parameters
|
||||
#! further: whether its arguments meet those bounds. Any other method it has
|
||||
#! always.
|
||||
#! @param this The checker.
|
||||
#! @param method The method's declaration.
|
||||
#! @param owner The type it is a member of, given its arguments.
|
||||
#! @returns Whether they do.
|
||||
pub def checker::bounds_met(&mut this, method: u32, owner: u32): bool {
|
||||
return true if !this.decls.has(method, df::bounding);
|
||||
val plain := this.unalias(owner);
|
||||
return true if this.types.kind_of(plain) != ty::named || this.types.is_open(plain);
|
||||
var params := this.decls.list_of(this.decls.params.p[method]);
|
||||
var args := this.types.parts_of(plain);
|
||||
if params.length > args.length {
|
||||
params.resize(args.length);
|
||||
}
|
||||
return true if params.length == 0;
|
||||
|
||||
val dropped := this.dropped;
|
||||
val uninferred := this.uninferred;
|
||||
this.mute++;
|
||||
val met := this.check_bounds_of(method, params.view(), args.view(), 0);
|
||||
this.mute--;
|
||||
this.dropped = dropped;
|
||||
this.uninferred = uninferred;
|
||||
return met;
|
||||
}
|
||||
|
||||
#! A method's type as one asked for taking `&mut this` sees it, where the method
|
||||
#! takes `&this`: taking `&mut this` too, since what can be written can be read.
|
||||
#! @param this The checker.
|
||||
#! @param given The method's type, `this` first.
|
||||
#! @param wanted The declaration of the method asked for.
|
||||
#! @returns The type, as it is where the method asked for takes `&this`.
|
||||
def checker::as_writing(&mut this, given: u32, wanted: u32): u32 {
|
||||
return given if !this.decls.has(wanted, df::mut_this) || this.types.kind_of(given) != ty::function
|
||||
|| this.types.part_count(given) == 0 || this.types.kind_of(this.types.part_at(given, 0)) != ty::reference;
|
||||
var parts := this.types.parts_of(given);
|
||||
parts[0] = this.types.reference(this.types.first_of(parts[0]), true);
|
||||
return this.types.function(parts.view(), this.types.first_of(given), this.types.second_of(given) != 0);
|
||||
}
|
||||
|
||||
#! Whether two function types are the same but for aliases.
|
||||
#! @param this The checker.
|
||||
#! @param a One function type.
|
||||
#! @param b The other.
|
||||
#! @returns Whether they are.
|
||||
def checker::same_signature(&mut this, a: u32, b: u32): bool {
|
||||
return a == b || (this.types.kind_of(a) == ty::function && this.types.kind_of(b) == ty::function
|
||||
&& this.types.second_of(a) == this.types.second_of(b) && this.same_function(a, b));
|
||||
}
|
||||
|
||||
#! The type of a method a trait asks for, given the trait's arguments and the
|
||||
#! type standing for `self`.
|
||||
#! @param this The checker.
|
||||
#! @param method The method's declaration.
|
||||
#! @param trait_kind The trait's type, given its arguments.
|
||||
#! @param self_kind The type standing for `self`.
|
||||
#! @returns The method's type.
|
||||
pub def checker::requirement_type(&mut this, method: u32, trait_kind: u32, self_kind: u32): u32 {
|
||||
this.resolve(method);
|
||||
val holder: u32 = this.decls.owners.p[method];
|
||||
return this.trait_in_terms(this.decls.types.p[method], holder, trait_kind, self_kind);
|
||||
}
|
||||
|
||||
#! The type of a trait's method called on a value of the type: through a bound
|
||||
#! of a type parameter, or through a trait reference.
|
||||
#! @param this The checker.
|
||||
#! @param method The method's declaration.
|
||||
#! @param kind The type of the value it is called on.
|
||||
#! @returns The method's type, or the error type where the value's type gives no
|
||||
#! trait declaring it.
|
||||
pub def checker::trait_method_type(&mut this, method: u32, kind: u32): u32 {
|
||||
val plain := this.unalias(kind);
|
||||
return this.requirement_type(method, this.trait_reached(method, plain), plain);
|
||||
}
|
||||
|
||||
#! The trait declaring a method, given its arguments, as a value of the type it
|
||||
#! is called on reaches it: through a bound of a type parameter, through a
|
||||
#! trait reference, or as the trait the type implements.
|
||||
#! @param this The checker.
|
||||
#! @param method The method's declaration.
|
||||
#! @param kind The type of the value it is called on.
|
||||
#! @returns The trait's type.
|
||||
pub def checker::trait_reached(&mut this, method: u32, kind: u32): u32 {
|
||||
val holder: u32 = this.decls.owners.p[method];
|
||||
val plain := this.unalias(kind);
|
||||
# A trait reference has the methods of the traits it composes, in terms of
|
||||
# its own arguments.
|
||||
if this.named_kind(plain) == dk::trait_type {
|
||||
return this.bound_for(plain, this.enclosing_trait(method));
|
||||
}
|
||||
|
||||
if this.types.kind_of(plain) == ty::param {
|
||||
val param := this.types.first_of(plain);
|
||||
this.resolve(param);
|
||||
val run: u32 = this.decls.children.p[param];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val bound := this.decls.list_at(run, i as u32);
|
||||
if this.composes(bound, holder, 0) {
|
||||
return this.bound_for(bound, holder);
|
||||
}
|
||||
}
|
||||
# What an `if const` proved of it, in the branch it guards, given its arguments.
|
||||
for i in 0..this.proved_params.length {
|
||||
continue if this.proved_params[i] != param;
|
||||
val bound: u32 = this.proved_bounds[i];
|
||||
if this.composes(bound, holder, 0) {
|
||||
return this.bound_for(bound, holder);
|
||||
}
|
||||
}
|
||||
# Within a trait, `self` has the members of the traits it composes, in terms
|
||||
# of its own arguments.
|
||||
if this.decls.names.p[param] == names::self_id {
|
||||
val declarer: u32 = this.decls.owners.p[param];
|
||||
if declarer != 0 && declarer != holder && this.decls.kinds.p[declarer] == dk::trait_type {
|
||||
val own: u32 = this.decls.types.p[declarer];
|
||||
if this.composes(own, holder, 0) {
|
||||
return this.bound_for(own, holder);
|
||||
}
|
||||
}
|
||||
return this.decls.types.p[holder];
|
||||
}
|
||||
}
|
||||
return this.implemented(plain, this.enclosing_trait(method));
|
||||
}
|
||||
|
||||
#! The trait, given its arguments, that a type implements where it has a
|
||||
#! trait's member: the trait the type names that is the one declaring it, or
|
||||
#! composes it, in terms of the type's arguments, as `pair<i64>` for `one:
|
||||
#! pair<i64>`, or the trait's own type where it names none.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param holder The declaration of the trait declaring the member.
|
||||
#! @returns The trait's type.
|
||||
pub def checker::implemented(&mut this, kind: u32, holder: u32): u32 {
|
||||
val plain := this.unalias(kind);
|
||||
if this.types.kind_of(plain) == ty::named {
|
||||
val decl := this.types.first_of(plain);
|
||||
val run := this.composed_of(decl);
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val named := this.instantiated(this.decls.list_at(run, i as u32), decl, plain);
|
||||
return this.bound_for(named, holder) if this.composes(named, holder, 0);
|
||||
}
|
||||
}
|
||||
return this.decls.types.p[holder];
|
||||
}
|
||||
|
||||
#! The trait a bound is, or the trait it composes that declares a member, given
|
||||
#! the bound's arguments.
|
||||
#! @param this The checker.
|
||||
#! @param bound The bound's type.
|
||||
#! @param holder The declaration of the trait declaring the member.
|
||||
#! @returns That trait's type, given the bound's arguments, or the bound itself
|
||||
#! where no trait it composes declares the member.
|
||||
pub def checker::bound_for(&mut this, bound: u32, holder: u32): u32 {
|
||||
return bound if this.types.first_of(bound) == holder;
|
||||
val decl := this.types.first_of(bound);
|
||||
val run := this.composed_of(decl);
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val inner := this.trait_in_terms(this.decls.list_at(run, i as u32), decl, bound, bt::error);
|
||||
return this.bound_for(inner, holder) if this.composes(inner, holder, 0);
|
||||
}
|
||||
return bound;
|
||||
}
|
||||
|
||||
#! Whether a type parameter is bounded by `ordinal`, `integer`, or `real`, which
|
||||
#! only numbers and enums satisfy, so its values are ordered as theirs are.
|
||||
#! @param this The checker.
|
||||
#! @param param The parameter's declaration.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::param_ordinal(&mut this, param: u32): bool {
|
||||
return this.bounded_by(param, this.std_decl(word::ordinal), this.std_decl(word::integer), this.std_decl(word::real));
|
||||
}
|
||||
|
||||
#! Whether the type parameter's bounds let numbers stand in for it.
|
||||
#! @param this The checker.
|
||||
#! @param param The type parameter's type.
|
||||
#! @returns Whether they do.
|
||||
pub def checker::param_has_numeric(&mut this, param: u32): bool {
|
||||
return this.bounded_by(param, this.std_decl(word::numeric), this.std_decl(word::integer), this.std_decl(word::real));
|
||||
}
|
||||
|
||||
#! Checks that each type argument of a named type satisfies the bounds of its
|
||||
#! parameter.
|
||||
#! @param this The checker.
|
||||
#! @param decl The declaration of the generic type.
|
||||
#! @param kind The named type, given its arguments.
|
||||
#! @param node The node notes are placed at.
|
||||
pub def checker::check_bounds(&mut this, decl: u32, kind: u32, node: u32): void {
|
||||
val params: u32 = this.decls.params.p[decl];
|
||||
var args := this.types.parts_of(kind);
|
||||
this.check_args_bounds(decl, params, args.view(), node);
|
||||
if this.is_std(kind, word::simd) || this.is_std(kind, word::mask) {
|
||||
this.check_lanes(decl, kind, node);
|
||||
}
|
||||
}
|
||||
|
||||
#! Checks that a vector, or a mask of one, holds 16 or 32 bytes of numbers, or
|
||||
#! 64 bytes of at most 32, as the processor's vector instructions take them: a
|
||||
#! mask's bits are a `u32`.
|
||||
#! @param this The checker.
|
||||
#! @param decl `simd` or `mask`.
|
||||
#! @param kind The vector's type, given its lanes.
|
||||
#! @param node The node notes are placed at.
|
||||
def checker::check_lanes(&mut this, decl: u32, kind: u32, node: u32): void {
|
||||
return if this.types.part_count(kind) < 2;
|
||||
val lane := this.unalias(this.types.part_at(kind, 0));
|
||||
val count := this.types.part_at(kind, 1);
|
||||
# Within a template, what it is given is known only in each instance.
|
||||
return if this.types.is_open(lane) || this.types.kind_of(count) != ty::value;
|
||||
val held: known = this.knowns.p[this.types.second_of(count)];
|
||||
val number := this.types.kind_of(lane) == ty::signed || this.types.kind_of(lane) == ty::unsigned
|
||||
|| this.types.kind_of(lane) == ty::floating;
|
||||
val bytes := number && held.kind == kk::number ? held.value.magnitude * (this.types.first_of(lane) as u64 / 8) : 0;
|
||||
return if bytes == 16 || bytes == 32 || (bytes == 64 && held.value.magnitude <= 32);
|
||||
var text := string::from("`", nothing {});
|
||||
text.append(this.decl_text(decl));
|
||||
text.append("` holds 16 or 32 bytes of numbers, as `f32[4]` or `u8[32]`, or 64 of at most 32, as `f32[16]`, and is given `");
|
||||
val named := this.describe(this.types.part_at(kind, 0));
|
||||
text.append(named.view());
|
||||
text.append("[");
|
||||
val length := this.describe(count);
|
||||
text.append(length.view());
|
||||
text.append("]`.");
|
||||
this.report_text(node, ec::generic, &text);
|
||||
}
|
||||
|
||||
#! Checks that each type argument satisfies the bounds of its parameter, each
|
||||
#! bound given the arguments for the parameters it names.
|
||||
#! @param this The checker.
|
||||
#! @param decl The generic declaration.
|
||||
#! @param params The run of its type parameters.
|
||||
#! @param args The type arguments.
|
||||
#! @param node The node notes are placed at.
|
||||
#! @returns Whether each satisfies them.
|
||||
pub def checker::check_args_bounds(&mut this, decl: u32, params: u32, args: span<u32>, node: u32): bool {
|
||||
val from := this.decls.list_of(params);
|
||||
return this.check_bounds_of(decl, from.view(), args, node);
|
||||
}
|
||||
|
||||
#! Checks that each type argument satisfies the bounds of its parameter, as
|
||||
#! `check_args_bounds` does, given the parameters themselves.
|
||||
#! @param this The checker.
|
||||
#! @param decl The generic declaration.
|
||||
#! @param from Its type parameters.
|
||||
#! @param args The type arguments, one for each.
|
||||
#! @param node The node a note is placed at.
|
||||
#! @returns Whether every argument satisfies its bounds.
|
||||
pub def checker::check_bounds_of(&mut this, decl: u32, from: span<u32>, args: span<u32>, node: u32): bool {
|
||||
var valid := true;
|
||||
for i in 0..from.length {
|
||||
break if i >= args.length;
|
||||
val param: u32 = from[i];
|
||||
val given := args[i];
|
||||
continue if given == bt::error;
|
||||
|
||||
# A pack's bounds are each of its types'.
|
||||
var each := vector::<u32>::new();
|
||||
if this.types.is_known_pack(given) {
|
||||
each.extend(this.types.parts_view(given));
|
||||
} else {
|
||||
each.append(given);
|
||||
}
|
||||
|
||||
this.resolve(param);
|
||||
val run: u32 = this.decls.children.p[param];
|
||||
for j in 0..this.decls.list_length(run) {
|
||||
val bound := this.substitute(this.decls.list_at(run, j as u32), from, args);
|
||||
for &arg in each {
|
||||
continue if this.satisfies(arg, bound);
|
||||
|
||||
valid = false;
|
||||
var text := string::from("`", nothing {});
|
||||
val named_arg := this.describe(arg);
|
||||
text.append(named_arg.view());
|
||||
|
||||
# What has no zero value is named, since the type may be one holding it.
|
||||
if this.types.first_of(bound) == this.std_decl(word::zeroable) {
|
||||
val lacking := this.zero_lacking(arg);
|
||||
text.append("` is not `zeroable`, which `");
|
||||
text.append(this.decl_text(param));
|
||||
text.append("` of `");
|
||||
text.append(this.decl_text(decl));
|
||||
text.append("` requires: ");
|
||||
text.append(lacking.view());
|
||||
text.append(".");
|
||||
this.report_text(node, ec::bound, &text);
|
||||
continue;
|
||||
}
|
||||
val named := this.describe(bound);
|
||||
text.append("` does not implement `");
|
||||
text.append(named.view());
|
||||
|
||||
# A reference whose referent satisfies the trait says why it does not.
|
||||
val why := this.unlent(arg, bound);
|
||||
if why.length > 0 {
|
||||
text.append("`, though what it refers to does: ");
|
||||
text.append(why.view());
|
||||
text.append(". `");
|
||||
text.append(this.decl_text(param));
|
||||
text.append("` of `");
|
||||
text.append(this.decl_text(decl));
|
||||
text.append("` requires it.");
|
||||
this.report_text(node, ec::bound, &text);
|
||||
continue;
|
||||
}
|
||||
text.append("`, which `");
|
||||
text.append(this.decl_text(param));
|
||||
text.append("` of `");
|
||||
text.append(this.decl_text(decl));
|
||||
text.append("` requires.");
|
||||
this.report_text(node, ec::bound, &text);
|
||||
}
|
||||
}
|
||||
}
|
||||
return valid;
|
||||
}
|
||||
@@ -0,0 +1,581 @@
|
||||
#! @file types.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the type table, which gives every type the checker meets an ID of
|
||||
#! its own. A type is interned by its kind, two numbers, and its parts, so two
|
||||
#! types are the same exactly where their IDs are, and the parts of each are a
|
||||
#! run of one vector, as the runs of a syntax are.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! The kinds of type.
|
||||
pub enum ty : u8 {
|
||||
error, #! What a mistake gives, which fits anywhere, so a mistake is reported once.
|
||||
void_type, #! `void`, which a function giving nothing gives.
|
||||
null_type, #! The type of `null`, which becomes any pointer.
|
||||
boolean, #! `bool`.
|
||||
signed, #! `first` is its bits.
|
||||
unsigned, #! `first` is its bits.
|
||||
floating, #! `first` is its bits.
|
||||
untyped_int, #! An integer constant, an `i64` unless another number type is expected.
|
||||
untyped_uint, #! An integer written with `u`, a `uint` unless another unsigned type is expected.
|
||||
untyped_char, #! A character, a `u32` unless another integer type is expected.
|
||||
untyped_float, #! A float constant, an `f64` unless another float type is expected.
|
||||
untyped_float32, #! A float constant written with `f`, an `f32` unless an `f64` is expected.
|
||||
untyped_bool, #! A constant `true` or `false`.
|
||||
untyped_text, #! Text, a `span<u8>` or a `string`, whichever is expected.
|
||||
empty, #! The element of `[]`, which becomes any element.
|
||||
reference, #! `first` is what it refers to, and `second` is 1 where it writes.
|
||||
pointer, #! `first` is what it points at, and `second` is 1 where it writes.
|
||||
fixed, #! `first` is its element, and `second` how many it holds, or within a template its one part, a constant only each instance knows.
|
||||
function, #! `first` is its result, `parts` its parameters, and `second` 1 where the last is variadic.
|
||||
named, #! `first` is its declaration, and `parts` its type arguments.
|
||||
param, #! `first` is the declaration of the type parameter it is.
|
||||
pack, #! `parts` are its types, or `first` is the declaration of the pack it is, while unknown.
|
||||
value, #! A constant type argument: `first` is the type of its value, `second` its ID among the checker's known values, and `parts` the constant parameters it is worked out from, within a template.
|
||||
}
|
||||
|
||||
#! What a type's `flags` hold: what is so of it, which interning it works out,
|
||||
#! and what the checker worked out of it and keeps, which `forget` lets go of.
|
||||
pub enum tf : u8 {
|
||||
open = 0x01, #! It holds a type parameter anywhere within.
|
||||
holds = 0x02, #! It holds a constant, or a fixed array whose length is one, anywhere within.
|
||||
asked = 0x04, #! Whether it is an alias was worked out, which `alias` says.
|
||||
alias = 0x08, #! It is an alias.
|
||||
weighed = 0x10, #! Whether values of it close was worked out, which `closes` says.
|
||||
closes = 0x20, #! Values of it close, or hold what does.
|
||||
}
|
||||
|
||||
#! Lets go of what the checker worked out of each type and kept in its flags,
|
||||
#! which a change may have changed.
|
||||
#! @param this The type table.
|
||||
pub def type_table::forget(&mut this): void {
|
||||
val kept := tf::open as u8 | tf::holds as u8;
|
||||
for id in 0..this.flags.length {
|
||||
this.flags.p[id] &= kept;
|
||||
}
|
||||
}
|
||||
|
||||
#! The IDs of the types every program has, which the type table interns first
|
||||
#! and in this order.
|
||||
pub enum bt : u32 {
|
||||
#! The error type.
|
||||
error,
|
||||
#! `void`.
|
||||
void_type,
|
||||
#! The type of `null`.
|
||||
null_type,
|
||||
#! `bool`.
|
||||
boolean,
|
||||
#! `i8`.
|
||||
int8,
|
||||
#! `i16`.
|
||||
int16,
|
||||
#! `i32`.
|
||||
int32,
|
||||
#! `i64`.
|
||||
int64,
|
||||
#! `u8`.
|
||||
uint8,
|
||||
#! `u16`.
|
||||
uint16,
|
||||
#! `u32`.
|
||||
uint32,
|
||||
#! `u64`.
|
||||
uint64,
|
||||
#! `f32`.
|
||||
float32,
|
||||
#! `f64`.
|
||||
float64,
|
||||
#! An integer constant.
|
||||
untyped_int,
|
||||
#! An integer constant written with `u`.
|
||||
untyped_uint,
|
||||
#! A character.
|
||||
untyped_char,
|
||||
#! A float constant.
|
||||
untyped_float,
|
||||
#! A float constant written with `f`.
|
||||
untyped_float32,
|
||||
#! A constant `true` or `false`.
|
||||
untyped_bool,
|
||||
#! Text written as a literal.
|
||||
untyped_text,
|
||||
#! The element of `[]`.
|
||||
empty,
|
||||
#! How many built-in types there are, which is the ID of the first other type.
|
||||
count,
|
||||
}
|
||||
|
||||
#! Every type, by its ID, a field in a column of its own.
|
||||
pub struct type_table {
|
||||
var kinds: column<ty>; #! The kind of each type.
|
||||
var firsts: column<u32>; #! The first number of each type, which its kind says the meaning of.
|
||||
var seconds: column<u32>; #! The second number of each type.
|
||||
var parts: column<u32>; #! The run of each type's parts in `runs`, 0 where it has none.
|
||||
pub var flags: column<u8>; #! What is so of each type, as `tf` says: what it holds, and what was worked out of it.
|
||||
var runs: column<u32>; #! The runs of parts, each a count and then the parts.
|
||||
var index: id_index; #! The types of each hash, which interning finds them by.
|
||||
var scratch: column<u32>; #! The parts of the types substituting is making, those of each inner one past those of the ones around it.
|
||||
}
|
||||
|
||||
#! Makes a type table holding the types every program has.
|
||||
#! @returns The table, in which the IDs of `bt` are those types.
|
||||
pub def type_table::new(): type_table {
|
||||
var made := type_table {
|
||||
kinds = column::<ty>::new(),
|
||||
firsts = column::<u32>::new(),
|
||||
seconds = column::<u32>::new(),
|
||||
parts = column::<u32>::new(),
|
||||
flags = column::<u8>::new(),
|
||||
runs = column::<u32>::new(),
|
||||
index = id_index::new(),
|
||||
scratch = column::<u32>::new()
|
||||
};
|
||||
|
||||
made.runs.append(0);
|
||||
val none := span::<u32>::empty();
|
||||
made.intern(ty::error, 0, 0, none);
|
||||
made.intern(ty::void_type, 0, 0, none);
|
||||
made.intern(ty::null_type, 0, 0, none);
|
||||
made.intern(ty::boolean, 8, 0, none);
|
||||
made.intern(ty::signed, 8, 0, none);
|
||||
made.intern(ty::signed, 16, 0, none);
|
||||
made.intern(ty::signed, 32, 0, none);
|
||||
made.intern(ty::signed, 64, 0, none);
|
||||
made.intern(ty::unsigned, 8, 0, none);
|
||||
made.intern(ty::unsigned, 16, 0, none);
|
||||
made.intern(ty::unsigned, 32, 0, none);
|
||||
made.intern(ty::unsigned, 64, 0, none);
|
||||
made.intern(ty::floating, 32, 0, none);
|
||||
made.intern(ty::floating, 64, 0, none);
|
||||
made.intern(ty::untyped_int, 0, 0, none);
|
||||
made.intern(ty::untyped_uint, 0, 0, none);
|
||||
made.intern(ty::untyped_char, 0, 0, none);
|
||||
made.intern(ty::untyped_float, 0, 0, none);
|
||||
made.intern(ty::untyped_float32, 0, 0, none);
|
||||
made.intern(ty::untyped_bool, 0, 0, none);
|
||||
made.intern(ty::untyped_text, 0, 0, none);
|
||||
made.intern(ty::empty, 0, 0, none);
|
||||
expects(made.kinds.length == bt::count as u64);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! How many types there are.
|
||||
#! @param this The type table.
|
||||
#! @returns The number of types, which is one more than the newest's ID.
|
||||
pub val type_table::count: u64 { get => this.kinds.length; }
|
||||
|
||||
#! The ID of the type of the kind, numbers, and parts, made where it is new.
|
||||
#! @param this The type table.
|
||||
#! @param kind The type's kind.
|
||||
#! @param first Its first number, which its kind says the meaning of.
|
||||
#! @param second Its second number.
|
||||
#! @param items Its parts, in order.
|
||||
#! @returns The type's ID.
|
||||
pub def type_table::intern(&mut this, kind: ty, first: u32, second: u32, items: span<u32>): u32 {
|
||||
var hash := mix(mix(mix(items.length, kind as u64), first as u64), second as u64);
|
||||
for &item in items {
|
||||
hash = mix(hash, item as u64);
|
||||
}
|
||||
|
||||
var walk := this.index.walk(hash);
|
||||
var at := this.index.next(&mut walk);
|
||||
while at != 0 {
|
||||
val id := at - 1;
|
||||
if this.kinds.p[id] == kind && this.firsts.p[id] == first && this.seconds.p[id] == second
|
||||
&& this.same_parts(id, items) {
|
||||
return id;
|
||||
}
|
||||
at = this.index.next(&mut walk);
|
||||
}
|
||||
|
||||
# A type is open where it is a type parameter, or holds one.
|
||||
var open := kind == ty::param || (kind == ty::pack && items.length == 0 && first != 0);
|
||||
if kind == ty::reference || kind == ty::pointer || kind == ty::fixed || kind == ty::function
|
||||
|| kind == ty::value {
|
||||
open = open || this.is_open(first);
|
||||
}
|
||||
# A type holds a constant where it is one, is a fixed array whose length is one,
|
||||
# or holds either, which only substituting within it may work out.
|
||||
var held := kind == ty::value || (kind == ty::fixed && items.length != 0);
|
||||
if kind == ty::reference || kind == ty::pointer || kind == ty::fixed || kind == ty::function {
|
||||
held = held || this.holds_value(first);
|
||||
}
|
||||
for &item in items {
|
||||
open = open || this.is_open(item as u32);
|
||||
held = held || this.holds_value(item as u32);
|
||||
}
|
||||
|
||||
var run: u32 = 0;
|
||||
if items.length != 0 {
|
||||
run = this.runs.length as u32;
|
||||
this.runs.append(items.length as u32);
|
||||
this.runs.extend(items);
|
||||
}
|
||||
|
||||
val id := this.kinds.length as u32;
|
||||
this.kinds.append(kind);
|
||||
this.firsts.append(first);
|
||||
this.seconds.append(second);
|
||||
this.parts.append(run);
|
||||
this.flags.append((open ? tf::open as u8 : 0) | (held ? tf::holds as u8 : 0));
|
||||
this.index.add(hash, id);
|
||||
return id;
|
||||
}
|
||||
|
||||
def type_table::same_parts(&this, id: u32, items: span<u32>): bool {
|
||||
val run: u32 = this.parts.p[id];
|
||||
val count: u32 = run == 0 ? 0 : this.runs.p[run];
|
||||
return false if count as u64 != items.length;
|
||||
for i in 0..items.length {
|
||||
return false if this.runs.p[run as u64 + 1 + i] != items[i];
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! The kind of a type.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @returns Its kind.
|
||||
pub def type_table::kind_of(&this, id: u32): ty { return this.kinds.p[id]; }
|
||||
#! The first number of a type, which its kind says the meaning of.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @returns The number.
|
||||
pub def type_table::first_of(&this, id: u32): u32 { return this.firsts.p[id]; }
|
||||
#! The second number of a type, which its kind says the meaning of.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @returns The number.
|
||||
pub def type_table::second_of(&this, id: u32): u32 { return this.seconds.p[id]; }
|
||||
#! Whether a type holds a type parameter anywhere within, so it stands for other
|
||||
#! types once the parameter is known.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @returns Whether it holds one.
|
||||
pub def type_table::is_open(&this, id: u32): bool { return (this.flags.p[id] & tf::open as u8) != 0; }
|
||||
#! Whether a type holds a constant, or a fixed array whose length is one,
|
||||
#! anywhere within.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @returns Whether it holds one.
|
||||
pub def type_table::holds_value(&this, id: u32): bool { return (this.flags.p[id] & tf::holds as u8) != 0; }
|
||||
|
||||
#! How many parts the type has: the parameters of a function, the type
|
||||
#! arguments of a named type, or the types of a pack.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @returns How many parts it has.
|
||||
pub def type_table::part_count(&this, id: u32): u32 {
|
||||
val run: u32 = this.parts.p[id];
|
||||
return run == 0 ? 0 : this.runs.p[run];
|
||||
}
|
||||
|
||||
#! A part of a type, by its position.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @param index The part's position, below `part_count`.
|
||||
#! @returns The part's ID.
|
||||
pub def type_table::part_at(&this, id: u32, index: u32): u32 {
|
||||
return this.runs.p[this.parts.p[id] as u64 + 1 + index as u64];
|
||||
}
|
||||
|
||||
#! The parts of the type, where they are.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @returns The IDs of its parts, in order, a view only good until a type with
|
||||
#! parts is interned, so a loop that may intern one walks them by
|
||||
#! `part_at`, or copies them by `parts_of`.
|
||||
pub def type_table::parts_view(&this, id: u32): span<u32> {
|
||||
val run: u32 = this.parts.p[id];
|
||||
return span::<u32>::over(this.runs.p + run + 1, run == 0 ? 0 : this.runs.p[run] as u64);
|
||||
}
|
||||
|
||||
#! The parts of the type, copied, since interning may move where they are.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @returns The IDs of its parts, in order.
|
||||
pub def type_table::parts_of(&this, id: u32): vector<u32> {
|
||||
var made := vector::<u32>::new();
|
||||
made.extend(this.parts_view(id));
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The type of a reference.
|
||||
#! @param this The type table.
|
||||
#! @param referent The type it refers to.
|
||||
#! @param mutable Whether it writes, as `&mut` does.
|
||||
#! @returns The reference's ID.
|
||||
pub def type_table::reference(&mut this, referent: u32, mutable: bool): u32 {
|
||||
return this.intern(ty::reference, referent, mutable ? 1 : 0, span::<u32>::empty());
|
||||
}
|
||||
|
||||
#! The type of a pointer.
|
||||
#! @param this The type table.
|
||||
#! @param pointee The type it points at.
|
||||
#! @param mutable Whether it writes, as `*mut` does.
|
||||
#! @returns The pointer's ID.
|
||||
pub def type_table::pointer(&mut this, pointee: u32, mutable: bool): u32 {
|
||||
return this.intern(ty::pointer, pointee, mutable ? 1 : 0, span::<u32>::empty());
|
||||
}
|
||||
|
||||
#! The type of a fixed array.
|
||||
#! @param this The type table.
|
||||
#! @param element The type of its elements.
|
||||
#! @param count How many it holds.
|
||||
#! @returns The array's ID.
|
||||
pub def type_table::fixed(&mut this, element: u32, count: u32): u32 {
|
||||
return this.intern(ty::fixed, element, count, span::<u32>::empty());
|
||||
}
|
||||
|
||||
#! The type of a fixed array whose length only each instance of a template knows.
|
||||
#! @param this The type table.
|
||||
#! @param element The type of its elements.
|
||||
#! @param length The constant parameter or value it holds as many as.
|
||||
#! @returns The array's ID.
|
||||
pub def type_table::fixed_of(&mut this, element: u32, length: u32): u32 {
|
||||
var parts := vector::<u32>::new();
|
||||
parts.append(length);
|
||||
return this.intern(ty::fixed, element, 0, parts.view());
|
||||
}
|
||||
|
||||
#! The type of a function.
|
||||
#! @param this The type table.
|
||||
#! @param params The types of its parameters, in order.
|
||||
#! @param result The type it gives.
|
||||
#! @param variadic Whether its last parameter takes any number of values.
|
||||
#! @returns The function's ID.
|
||||
pub def type_table::function(&mut this, params: span<u32>, result: u32, variadic: bool): u32 {
|
||||
return this.intern(ty::function, result, variadic ? 1 : 0, params);
|
||||
}
|
||||
|
||||
#! The type a declaration names, given its type arguments.
|
||||
#! @param this The type table.
|
||||
#! @param decl The declaration of the struct, union, enum, trait, or alias.
|
||||
#! @param args Its type arguments, or none where it is not generic.
|
||||
#! @returns The type's ID.
|
||||
pub def type_table::named(&mut this, decl: u32, args: span<u32>): u32 {
|
||||
return this.intern(ty::named, decl, 0, args);
|
||||
}
|
||||
|
||||
#! The type a type parameter is, while what it stands for is not known.
|
||||
#! @param this The type table.
|
||||
#! @param decl The type parameter's declaration.
|
||||
#! @returns The type's ID.
|
||||
pub def type_table::param(&mut this, decl: u32): u32 {
|
||||
return this.intern(ty::param, decl, 0, span::<u32>::empty());
|
||||
}
|
||||
|
||||
#! The pack of the types, or while they are unknown, the pack of the parameter.
|
||||
#! @param this The type table.
|
||||
#! @param items The types the pack holds, or none while they are unknown.
|
||||
#! @param decl The declaration of the pack parameter, while its types are
|
||||
#! unknown.
|
||||
#! @returns The pack's ID.
|
||||
pub def type_table::pack(&mut this, items: span<u32>, decl: u32): u32 {
|
||||
return this.intern(ty::pack, items.length == 0 ? decl : 0, 0, items);
|
||||
}
|
||||
|
||||
#! The pack of the parameters of a variadic function, whose last takes any number
|
||||
#! of values of its type, as `(str, i64...)` of `def(str, i64...): void`. Spread
|
||||
#! into a function's parameters, it makes the function variadic.
|
||||
#! @param this The type table.
|
||||
#! @param items The types of the parameters, the last that of the values it
|
||||
#! takes.
|
||||
#! @returns The pack's ID.
|
||||
pub def type_table::variadic_pack(&mut this, items: span<u32>): u32 {
|
||||
return this.intern(ty::pack, 0, 1, items);
|
||||
}
|
||||
|
||||
#! The pack of a function type's parameters, variadic where it is.
|
||||
#! @param this The type table.
|
||||
#! @param id The function type's ID.
|
||||
#! @param from The first parameter the pack holds.
|
||||
#! @returns The pack's ID.
|
||||
pub def type_table::params_pack(&mut this, id: u32, from: u32): u32 {
|
||||
var items := vector::<u32>::new();
|
||||
for i in from..this.part_count(id) {
|
||||
items.append(this.part_at(id, i as u32));
|
||||
}
|
||||
return this.seconds.p[id] != 0 && items.length != 0 ? this.variadic_pack(items.view()) : this.pack(items.view(), 0);
|
||||
}
|
||||
|
||||
#! Whether the type is an integer of a known size, or an integer constant.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @returns Whether it is one.
|
||||
pub def type_table::is_integer(&this, id: u32): bool {
|
||||
return match this.kinds.p[id] {
|
||||
ty::signed, ty::unsigned, ty::untyped_int, ty::untyped_uint, ty::untyped_char => true,
|
||||
else => false
|
||||
};
|
||||
}
|
||||
|
||||
#! Whether a type is a float of a known size, or a float constant.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @returns Whether it is one.
|
||||
pub def type_table::is_float(&this, id: u32): bool {
|
||||
return match this.kinds.p[id] {
|
||||
ty::floating, ty::untyped_float, ty::untyped_float32 => true,
|
||||
else => false
|
||||
};
|
||||
}
|
||||
|
||||
#! Whether a type is a number: an integer or a float, of a known size or a
|
||||
#! constant.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @returns Whether it is one.
|
||||
pub def type_table::is_numeric(&this, id: u32): bool {
|
||||
return this.is_integer(id) || this.is_float(id);
|
||||
}
|
||||
|
||||
#! Whether a type is `bool`, or a constant `true` or `false`.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @returns Whether it is one.
|
||||
pub def type_table::is_boolean(&this, id: u32): bool {
|
||||
val kind: ty = this.kinds.p[id];
|
||||
return kind == ty::boolean || kind == ty::untyped_bool;
|
||||
}
|
||||
|
||||
#! Whether the type is a constant's, which takes the type expected of it.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @returns Whether it is one.
|
||||
pub def type_table::is_untyped(&this, id: u32): bool {
|
||||
return match this.kinds.p[id] {
|
||||
ty::untyped_int, ty::untyped_uint, ty::untyped_char, ty::untyped_float,
|
||||
ty::untyped_float32, ty::untyped_bool, ty::untyped_text, ty::empty, ty::null_type => true,
|
||||
else => false
|
||||
};
|
||||
}
|
||||
|
||||
#! Whether the type is a signed integer, of a known size or not.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @returns Whether it is one.
|
||||
pub def type_table::is_signed(&this, id: u32): bool {
|
||||
val kind: ty = this.kinds.p[id];
|
||||
return kind == ty::signed || kind == ty::untyped_int;
|
||||
}
|
||||
|
||||
#! The numeric type an untyped one becomes where nothing else is expected.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @returns The type it becomes, or the type itself where it is not untyped.
|
||||
pub def type_table::settled(&this, id: u32): u32 {
|
||||
return match this.kinds.p[id] {
|
||||
ty::untyped_int => bt::int64,
|
||||
ty::untyped_uint => bt::uint64,
|
||||
ty::untyped_char => bt::uint32,
|
||||
ty::untyped_float => bt::float64,
|
||||
ty::untyped_float32 => bt::float32,
|
||||
ty::untyped_bool => bt::boolean,
|
||||
else => id
|
||||
};
|
||||
}
|
||||
|
||||
#! The type with each type parameter `from` names replaced by the type `to`
|
||||
#! gives at the same index. A type holding no parameter is itself.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @param from The type parameters to replace.
|
||||
#! @param to The types to replace each with.
|
||||
#! @returns The type made.
|
||||
pub def type_table::substitute(&mut this, id: u32, from: span<u32>, to: span<u32>): u32 {
|
||||
return id if !this.is_open(id) || from.length == 0;
|
||||
|
||||
val kind: ty = this.kinds.p[id];
|
||||
val first: u32 = this.firsts.p[id];
|
||||
match kind {
|
||||
ty::param => {
|
||||
for i in 0..from.length {
|
||||
return to[i] if from[i] == first && i < to.length;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
ty::reference, ty::pointer => {
|
||||
val inner := this.substitute(first, from, to);
|
||||
return this.intern(kind, inner, this.seconds.p[id], span::<u32>::empty());
|
||||
}
|
||||
# A length only each instance knows is given its parameter's argument, which the
|
||||
# checker then works out.
|
||||
ty::fixed => {
|
||||
val inner := this.substitute(first, from, to);
|
||||
val mark := this.scratch.length;
|
||||
for i in 0..this.part_count(id) {
|
||||
val part := this.substitute(this.part_at(id, i as u32), from, to);
|
||||
this.scratch.append(part);
|
||||
}
|
||||
return this.intern_scratch(kind, inner, this.seconds.p[id], mark);
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
|
||||
# A pack parameter stands for the pack it is given, whose types it spreads into
|
||||
# the parts around it, as `Ts` in `def(Ts...): void`.
|
||||
if kind == ty::pack && this.part_count(id) == 0 {
|
||||
for i in 0..from.length {
|
||||
return to[i] if from[i] == first && i < to.length;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
# A pack given for a pack parameter among a function's parameters becomes a
|
||||
# parameter for each of its types, so the function is no longer variadic,
|
||||
# unless the pack is a variadic function's parameters. A named type holds the
|
||||
# pack as the one argument it is, as `Ts` of `box<Ts...>`. The parts are put
|
||||
# on the scratch column past those of the substitutions around this one, each
|
||||
# part's own substitution taking what it put there off again, so they lie
|
||||
# together where interning them reads them.
|
||||
val mark := this.scratch.length;
|
||||
var spread := false;
|
||||
var rest: u32 = 0;
|
||||
for i in 0..this.part_count(id) {
|
||||
val written: u32 = this.part_at(id, i as u32);
|
||||
val part := this.substitute(written, from, to);
|
||||
val known_pack := this.kinds.p[part] == ty::pack && this.firsts.p[part] == 0;
|
||||
if known_pack && this.kinds.p[written] == ty::pack && kind == ty::function {
|
||||
this.scratch.extend(this.parts_view(part));
|
||||
spread = true;
|
||||
rest = this.seconds.p[part];
|
||||
continue;
|
||||
}
|
||||
this.scratch.append(part);
|
||||
}
|
||||
|
||||
val result := kind == ty::function ? this.substitute(first, from, to) : first;
|
||||
val second: u32 = kind == ty::function && spread ? rest : this.seconds.p[id];
|
||||
return this.intern_scratch(kind, result, second, mark);
|
||||
}
|
||||
|
||||
# Interns a type whose parts are those on the scratch column from `mark`, then
|
||||
# takes them off it.
|
||||
def type_table::intern_scratch(&mut this, kind: ty, first: u32, second: u32, mark: u64): u32 {
|
||||
val made := this.intern(kind, first, second, span::<u32>::over(this.scratch.p + mark, this.scratch.length - mark));
|
||||
this.scratch.resize(mark);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Whether the type is a pack whose types are not yet known: a pack parameter.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @returns Whether it is one.
|
||||
pub def type_table::is_open_pack(&this, id: u32): bool {
|
||||
return this.kinds.p[id] == ty::pack && this.part_count(id) == 0 && this.firsts.p[id] != 0;
|
||||
}
|
||||
|
||||
#! Whether the type is a pack whose types are known: one a pack parameter was
|
||||
#! given, which is written as the types it gives.
|
||||
#! @param this The type table.
|
||||
#! @param id The type's ID.
|
||||
#! @returns Whether it is one.
|
||||
pub def type_table::is_known_pack(&this, id: u32): bool {
|
||||
return this.kinds.p[id] == ty::pack && !this.is_open_pack(id);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
#! @file column.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the column, which holds one field of the rows of a table, as the
|
||||
#! kind of every type or the owner of every declaration, with a pointer to its
|
||||
#! elements that it keeps where they are, so hot code reads and writes them
|
||||
#! without a call and never through a pointer gone stale.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! One field of the rows of a table, by row: the field's values, one after
|
||||
#! another in a block of the program's heap, and where they are.
|
||||
#!
|
||||
#! Tables keep each field in a column of its own, so a pass reading one field
|
||||
#! reads only that, and code that reads them often does so through `p`, as
|
||||
#! `kinds.p[id]`, without a call or a check. Whatever moves the values makes
|
||||
#! `p` again, so only the column that grew is pointed again, and never another.
|
||||
#! A column is no more than the pointer and two counts, so the pointers of a
|
||||
#! table's columns, which hot code reads one after another, lie close together.
|
||||
#! It owns its block, which it gives back as it closes, so a table that closes,
|
||||
#! as a checker the language server makes for each check does, keeps nothing.
|
||||
#! @tparam T The type of the field, which closes nothing.
|
||||
pub struct column<T> : owning {
|
||||
pub var p: *mut T; #! Where the values are, which the column keeps; read and written as `p[row]`, below `length`.
|
||||
var count: u64; #! How many rows it holds.
|
||||
var room: u64; #! How many rows the block has room for.
|
||||
}
|
||||
|
||||
#! Makes a column holding no rows, which takes memory once one is added.
|
||||
#! @returns The column.
|
||||
pub def column<T>::new(): column<T> {
|
||||
return column::<T> { p = null, count = 0, room = 0 };
|
||||
}
|
||||
|
||||
#! Gives back the column's block, leaving it holding no rows.
|
||||
#! @param this The column.
|
||||
pub def column<T>::close(&mut this): void {
|
||||
dispose::<T>(nothing {}, this.p, this.room);
|
||||
this.p = null;
|
||||
this.count = 0;
|
||||
this.room = 0;
|
||||
}
|
||||
|
||||
#! How many rows the column holds.
|
||||
#! @param this The column.
|
||||
#! @returns The number of rows.
|
||||
pub val column<T>::length: u64 { get => this.count; }
|
||||
|
||||
#! Adds a row's value after the last.
|
||||
#! @param this The column.
|
||||
#! @param item The value.
|
||||
pub def column<T>::append(&mut this, item: T): void {
|
||||
if this.count == this.room {
|
||||
this.grow();
|
||||
}
|
||||
this.p[this.count] = item;
|
||||
this.count++;
|
||||
}
|
||||
|
||||
#! Adds the values of a view after the last, in order.
|
||||
#! @param this The column.
|
||||
#! @param items The values.
|
||||
pub def column<T>::extend(&mut this, items: span<T>): void {
|
||||
return if items.length == 0;
|
||||
val wanted := this.count + items.length;
|
||||
if wanted > this.room {
|
||||
this.grow(wanted > this.room * 2 ? wanted : this.room * 2);
|
||||
}
|
||||
memcpy((this.p + this.count) as *mut u8, items.data as *u8, bytes_of::<T>(items.length));
|
||||
this.count = wanted;
|
||||
}
|
||||
|
||||
#! Makes the column hold a number of rows, adding zeroed ones or letting go of
|
||||
#! those past it.
|
||||
#! @param this The column.
|
||||
#! @param size How many rows it holds after.
|
||||
pub def column<T>::resize(&mut this, size: u64): void {
|
||||
# Growing doubles at least, so resizing a little at a time copies little.
|
||||
if size > this.room {
|
||||
this.grow(size > this.room * 2 ? size : this.room * 2);
|
||||
}
|
||||
if size > this.count {
|
||||
memset((this.p + this.count) as *mut u8, 0, bytes_of::<T>(size - this.count));
|
||||
}
|
||||
this.count = size;
|
||||
}
|
||||
|
||||
#! The value of a row, or a zero value past the last, as of a column by ID
|
||||
#! that grows only as it is written.
|
||||
#! @param this The column.
|
||||
#! @param row The row.
|
||||
#! @returns Its value.
|
||||
pub def column<T>::at_or_zero(&this, row: u64): T where T: zeroable {
|
||||
if row < this.count {
|
||||
return this.p[row];
|
||||
}
|
||||
var none: T;
|
||||
return none;
|
||||
}
|
||||
|
||||
#! Writes the value of a row, growing the column to hold it where it is past
|
||||
#! the last, the rows between holding zero values.
|
||||
#! @param this The column.
|
||||
#! @param row The row.
|
||||
#! @param item Its value.
|
||||
pub def column<T>::put(&mut this, row: u64, item: T): void {
|
||||
if row >= this.count {
|
||||
this.resize(row + 1);
|
||||
}
|
||||
this.p[row] = item;
|
||||
}
|
||||
|
||||
# Gives the column room for twice as many rows, which is apart from `append`, so
|
||||
# `append` is small enough to be inlined.
|
||||
def column<T>::grow(&mut this): void {
|
||||
this.grow(this.room == 0 ? 4 : this.room * 2);
|
||||
}
|
||||
|
||||
# Gives the column room for a number of rows, moving its values, which `p`
|
||||
# follows.
|
||||
def column<T>::grow(&mut this, size: u64): void {
|
||||
this.p = this.p == null ? acquire::<T>(nothing {}, size) : resize::<T>(nothing {}, this.p, this.room, size);
|
||||
this.room = size;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
#! @file errors.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains `ec`, the codes of the notes the analyzer makes, which say what kind
|
||||
#! of mistake each note is about.
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! The codes of the notes the analyzer makes, which say what kind of mistake
|
||||
#! each is about.
|
||||
pub enum ec {
|
||||
# Lexing and parsing
|
||||
syntax, #! Source nested deeper than the parser allows.
|
||||
token, #! A token the parser does not expect where it is.
|
||||
expr, #! An expression missing where one is expected.
|
||||
ident, #! A name missing where one is expected.
|
||||
kind, #! A type missing where one is expected.
|
||||
decl, #! A declaration written wrongly, or missing what it must have.
|
||||
escape, #! An escape that is none of those text and characters allow.
|
||||
char, #! A character literal that is not one character or escape.
|
||||
block, #! A text block, `"""`, laid out wrongly.
|
||||
|
||||
# Checking
|
||||
undefined, #! A name nothing declares where it is used, or a module nothing declares.
|
||||
duplicate, #! A name declared twice in one place.
|
||||
ambiguous, #! A name more than one import declares, or a call more than one overload fits as well.
|
||||
hidden, #! A declaration that is not `pub`, used from outside the modules that see it.
|
||||
not_type, #! A name used as a type that names no type.
|
||||
not_value, #! A name used as a value that names no value.
|
||||
mismatch, #! A value of one type where another is expected.
|
||||
operands, #! An operator applied to what it does not take.
|
||||
overflow, #! A constant outside the range of its type.
|
||||
conversion, #! `as` between types that do not convert.
|
||||
callable, #! A call of what is not a function.
|
||||
arguments, #! Too few or too many arguments, or none fitting any overload.
|
||||
member, #! A member a type does not have.
|
||||
assignable, #! An assignment to what cannot be written.
|
||||
generic, #! Type arguments wrong in number, given where none are taken, or that cannot be inferred.
|
||||
bound, #! A type argument that does not satisfy a bound of its parameter.
|
||||
cycle, #! A declaration that depends on itself.
|
||||
limit, #! Something nested or repeated past what the checker allows.
|
||||
control, #! `break` or `continue` outside a loop, or a function that can end without returning.
|
||||
arms, #! A match missing cases, or with an arm that is not one of them.
|
||||
constant, #! A value that must be known while compiling, and is not.
|
||||
zero_value, #! A variable or field left without a value, whose type has no zero value.
|
||||
invalid, #! A declaration that is not allowed as written, or where it is written.
|
||||
recursive, #! A struct or union that holds itself, other than through a pointer or reference.
|
||||
unhandled, #! What is `@nodiscard`, let go of where it is made.
|
||||
locked, #! What a loop iterates, changed by the loop's body.
|
||||
owned, #! A value that closes, copied out of the place holding it.
|
||||
|
||||
# Warnings, which never stop a program
|
||||
lifetime, #! A reference, view, or closure kept past what it refers to.
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
#! @file idindex.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the ID index, which interning finds values by their hash with: the
|
||||
#! type table its types, and the checker its known values and constants.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! The IDs of interned values by their hash, held open: a power of two of
|
||||
#! slots, a quarter of them free at least, each holding the top half of a
|
||||
#! value's hash beside one more than its ID, or 0 where it is free. A value's
|
||||
#! search begins at the slot its hash's top half says, and goes on to the next
|
||||
#! until a free one, so it reads only eight bytes for each value it passes, and
|
||||
#! compares only those whose hash shares its top half.
|
||||
#!
|
||||
#! What is interned keeps its own fields, which the one interning compares for
|
||||
#! each ID a walk gives, and gives its values IDs in the order they are made,
|
||||
#! which no hash decides.
|
||||
pub struct id_index : owning {
|
||||
var slots: *mut u64; #! Each slot's hash's top half and one more than its ID, or 0.
|
||||
var count: u64; #! How many IDs it holds.
|
||||
var room: u64; #! How many slots there are, a power of two, or 0.
|
||||
}
|
||||
|
||||
#! Where a walk over the IDs of one hash is.
|
||||
pub struct id_walk {
|
||||
var at: u64; #! The slot it reads next.
|
||||
var tag: u64; #! The top half of the hash, as each slot holds it.
|
||||
}
|
||||
|
||||
#! Makes an index holding no ID, which takes no memory until it holds one.
|
||||
#! @returns The index.
|
||||
pub def id_index::new(): id_index {
|
||||
return id_index { slots = null, count = 0, room = 0 };
|
||||
}
|
||||
|
||||
#! Gives back the index's block, leaving it empty.
|
||||
#! @param this The index.
|
||||
pub def id_index::close(&mut this): void {
|
||||
dispose::<u64>(nothing {}, this.slots, this.room);
|
||||
this.slots = null;
|
||||
this.count = 0;
|
||||
this.room = 0;
|
||||
}
|
||||
|
||||
#! How many IDs the index holds.
|
||||
#! @param this The index.
|
||||
#! @returns How many.
|
||||
pub val id_index::length: u64 { get => this.count; }
|
||||
|
||||
#! How many slots the index has, which is more than it holds.
|
||||
#! @param this The index.
|
||||
#! @returns How many.
|
||||
pub val id_index::capacity: u64 { get => this.room; }
|
||||
|
||||
#! A walk over the IDs whose values may have the hash, which `next` gives.
|
||||
#! @param this The index.
|
||||
#! @param hash The hash.
|
||||
#! @returns The walk.
|
||||
@inline
|
||||
pub def id_index::walk(&this, hash: u64): id_walk {
|
||||
val tag := hash >> 32;
|
||||
return id_walk { at = this.room == 0 ? 0 : tag & (this.room - 1), tag = tag };
|
||||
}
|
||||
|
||||
#! One more than the next ID whose value may have the walk's hash, or 0 where
|
||||
#! there are no more.
|
||||
#! @param this The index.
|
||||
#! @param walk The walk.
|
||||
#! @returns One more than the ID, or 0.
|
||||
@inline
|
||||
pub def id_index::next(&this, walk: &mut id_walk): u32 {
|
||||
return 0 if this.room == 0;
|
||||
val mask := this.room - 1;
|
||||
while true {
|
||||
val held := this.slots[walk.at];
|
||||
return 0 if held == 0;
|
||||
walk.at = (walk.at + 1) & mask;
|
||||
if (held >> 32) == walk.tag {
|
||||
return (held & 0xFFFFFFFF) as u32;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! Adds the ID of a value of the hash, which it does not hold yet.
|
||||
#! @param this The index.
|
||||
#! @param hash The value's hash.
|
||||
#! @param id Its ID.
|
||||
pub def id_index::add(&mut this, hash: u64, id: u32): void {
|
||||
if (this.count + 1) * 4 > this.room * 3 {
|
||||
this.grow(this.room == 0 ? 64 : this.room * 2);
|
||||
}
|
||||
this.put((hash >> 32) << 32 | (id as u64 + 1));
|
||||
this.count++;
|
||||
}
|
||||
|
||||
# Puts a slot's word in the first free slot from where its hash's top half
|
||||
# says, which there is.
|
||||
def id_index::put(&mut this, word: u64): void {
|
||||
val mask := this.room - 1;
|
||||
var at := (word >> 32) & mask;
|
||||
while this.slots[at] != 0 {
|
||||
at = (at + 1) & mask;
|
||||
}
|
||||
this.slots[at] = word;
|
||||
}
|
||||
|
||||
# Moves the IDs into a block of a number of slots, a power of two.
|
||||
def id_index::grow(&mut this, size: u64): void {
|
||||
val old := this.slots;
|
||||
val old_room := this.room;
|
||||
this.slots = acquire_zeroed::<u64>(nothing {}, size);
|
||||
this.room = size;
|
||||
for i in 0..old_room {
|
||||
if old[i] != 0 {
|
||||
this.put(old[i]);
|
||||
}
|
||||
}
|
||||
if old_room != 0 {
|
||||
dispose::<u64>(nothing {}, old, old_room);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
#! @file keymap.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the key map, which finds a `u32` by a `u64` key, as the instance a
|
||||
#! call uses by its table and node, in twelve bytes a slot, where a dictionary
|
||||
#! takes forty: the key, its value, and nothing more, as an integer's hash is
|
||||
#! quickly made again.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! A map of `u64` keys to `u32` values, held open: a power of two of slots, a
|
||||
#! quarter of them free at least, and each key in the first slot from where its
|
||||
#! hash begins that is free or holds it. Keys and values are each kept in a
|
||||
#! block of their own, slot by slot, so finding a key reads only keys. A key of
|
||||
#! all ones stands for a free slot, which no key the checker makes is: a
|
||||
#! `pair_key` of two IDs, an index, or an ID.
|
||||
pub struct keymap : owning {
|
||||
var keys: *mut u64; #! Each slot's key, or `keymap::free`.
|
||||
var values: *mut u32; #! Each slot's value.
|
||||
var count: u64; #! How many keys it holds.
|
||||
var room: u64; #! How many slots there are, a power of two, or 0.
|
||||
}
|
||||
|
||||
#! The key of a free slot.
|
||||
pub const keymap::free: u64 = 0xFFFFFFFFFFFFFFFF;
|
||||
|
||||
#! Makes a map holding nothing, which takes no memory until it holds a key.
|
||||
#! @returns The map.
|
||||
pub def keymap::new(): keymap {
|
||||
return keymap { keys = null, values = null, count = 0, room = 0 };
|
||||
}
|
||||
|
||||
#! Gives back the map's blocks, leaving it empty.
|
||||
#! @param this The map.
|
||||
pub def keymap::close(&mut this): void {
|
||||
dispose::<u64>(nothing {}, this.keys, this.room);
|
||||
dispose::<u32>(nothing {}, this.values, this.room);
|
||||
this.keys = null;
|
||||
this.values = null;
|
||||
this.count = 0;
|
||||
this.room = 0;
|
||||
}
|
||||
|
||||
#! How many keys the map holds.
|
||||
#! @param this The map.
|
||||
#! @returns How many.
|
||||
pub val keymap::length: u64 { get => this.count; }
|
||||
|
||||
#! How many slots the map has, which is more than it holds.
|
||||
#! @param this The map.
|
||||
#! @returns How many.
|
||||
pub val keymap::capacity: u64 { get => this.room; }
|
||||
|
||||
#! The value of a key, where the map holds it.
|
||||
#! @param this The map.
|
||||
#! @param key The key.
|
||||
#! @returns The value, or nothing.
|
||||
pub def keymap::get(&this, key: &u64): maybe<u32> {
|
||||
val at := this.find(key);
|
||||
return nothing {} if at == this.room;
|
||||
return this.values[at];
|
||||
}
|
||||
|
||||
#! The value of a key, or another where the map does not hold it.
|
||||
#! @param this The map.
|
||||
#! @param key The key.
|
||||
#! @param missing What is given where it does not.
|
||||
#! @returns The value.
|
||||
pub def keymap::get_or(&this, key: &u64, missing: u32): u32 {
|
||||
val at := this.find(key);
|
||||
return at == this.room ? missing : this.values[at];
|
||||
}
|
||||
|
||||
#! Whether the map holds a key.
|
||||
#! @param this The map.
|
||||
#! @param key The key.
|
||||
#! @returns Whether it does.
|
||||
pub def keymap::contains(&this, key: &u64): bool {
|
||||
return this.find(key) != this.room;
|
||||
}
|
||||
|
||||
#! Gives a key a value, the one it held replaced.
|
||||
#! @param this The map.
|
||||
#! @param key The key, which is not `keymap::free`.
|
||||
#! @param value The value.
|
||||
pub def keymap::set(&mut this, key: u64, value: u32): void {
|
||||
val at := this.place(key);
|
||||
this.values[at] = value;
|
||||
}
|
||||
|
||||
#! Gives a key a value where the map does not hold it already.
|
||||
#! @param this The map.
|
||||
#! @param key The key, which is not `keymap::free`.
|
||||
#! @param value The value.
|
||||
#! @returns Whether the key was new and took the value. A key the map already
|
||||
#! holds keeps the value it has.
|
||||
pub def keymap::insert(&mut this, key: u64, value: u32): bool {
|
||||
val held := this.count;
|
||||
val at := this.place(key);
|
||||
return false if this.count == held;
|
||||
this.values[at] = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Takes a key and its value from the map, where it holds it.
|
||||
#! @param this The map.
|
||||
#! @param key The key.
|
||||
pub def keymap::remove(&mut this, key: &u64): void {
|
||||
var at := this.find(key);
|
||||
return if at == this.room;
|
||||
|
||||
# Each key after the gap that would be found past it moves back into it, so
|
||||
# every key is still found from where its hash begins, and no slot is marked
|
||||
# as having held one.
|
||||
val mask := this.room - 1;
|
||||
var next := (at + 1) & mask;
|
||||
while this.keys[next] != keymap::free {
|
||||
val home := keymap::home(this.keys[next], mask);
|
||||
if ((next - home) & mask) >= ((next - at) & mask) {
|
||||
this.keys[at] = this.keys[next];
|
||||
this.values[at] = this.values[next];
|
||||
at = next;
|
||||
}
|
||||
next = (next + 1) & mask;
|
||||
}
|
||||
this.keys[at] = keymap::free;
|
||||
this.count--;
|
||||
}
|
||||
|
||||
#! The key a slot holds, or `keymap::free`, for walking every key the map
|
||||
#! holds, as each of its `capacity` slots: in no order the keys were given in.
|
||||
#! @param this The map.
|
||||
#! @param slot The slot, below `capacity`.
|
||||
#! @returns The key.
|
||||
pub def keymap::key_at(&this, slot: u64): u64 {
|
||||
return this.keys[slot];
|
||||
}
|
||||
|
||||
#! The value a slot holds, where it holds a key.
|
||||
#! @param this The map.
|
||||
#! @param slot The slot, below `capacity`.
|
||||
#! @returns The value.
|
||||
pub def keymap::value_at(&this, slot: u64): u32 {
|
||||
return this.values[slot];
|
||||
}
|
||||
|
||||
#! Takes every key from the map, keeping its slots.
|
||||
#! @param this The map.
|
||||
pub def keymap::clear(&mut this): void {
|
||||
if this.room != 0 {
|
||||
memset(this.keys as *mut u8, 0xFF, bytes_of::<u64>(this.room));
|
||||
}
|
||||
this.count = 0;
|
||||
}
|
||||
|
||||
# The slot a key's search begins at: its bits mixed, as `mix` does, then
|
||||
# masked.
|
||||
def keymap::home(key: u64, mask: u64): u64 {
|
||||
val bits := key * 0x9E3779B97F4A7C15;
|
||||
return (bits ^ (bits >> 29)) & mask;
|
||||
}
|
||||
|
||||
# The slot holding a key, or `room` where none does.
|
||||
def keymap::find(&this, key: u64): u64 {
|
||||
return this.room if this.count == 0;
|
||||
val mask := this.room - 1;
|
||||
var at := keymap::home(key, mask);
|
||||
while true {
|
||||
val held := this.keys[at];
|
||||
return at if held == key;
|
||||
return this.room if held == keymap::free;
|
||||
at = (at + 1) & mask;
|
||||
}
|
||||
return this.room;
|
||||
}
|
||||
|
||||
# The slot holding a key, which it is put in where it is new, growing the map
|
||||
# first where a quarter of its slots would no longer be free.
|
||||
def keymap::place(&mut this, key: u64): u64 {
|
||||
if (this.count + 1) * 4 > this.room * 3 {
|
||||
this.grow(this.room == 0 ? 16 : this.room * 2);
|
||||
}
|
||||
val mask := this.room - 1;
|
||||
var at := keymap::home(key, mask);
|
||||
while true {
|
||||
val held := this.keys[at];
|
||||
return at if held == key;
|
||||
if held == keymap::free {
|
||||
this.keys[at] = key;
|
||||
this.count++;
|
||||
return at;
|
||||
}
|
||||
at = (at + 1) & mask;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
# Moves the keys into blocks of a number of slots, a power of two.
|
||||
def keymap::grow(&mut this, size: u64): void {
|
||||
val old_keys := this.keys;
|
||||
val old_values := this.values;
|
||||
val old_room := this.room;
|
||||
this.keys = acquire::<u64>(nothing {}, size);
|
||||
this.values = acquire::<u32>(nothing {}, size);
|
||||
this.room = size;
|
||||
memset(this.keys as *mut u8, 0xFF, bytes_of::<u64>(size));
|
||||
|
||||
val mask := size - 1;
|
||||
for i in 0..old_room {
|
||||
val key := old_keys[i];
|
||||
continue if key == keymap::free;
|
||||
var at := keymap::home(key, mask);
|
||||
while this.keys[at] != keymap::free {
|
||||
at = (at + 1) & mask;
|
||||
}
|
||||
this.keys[at] = key;
|
||||
this.values[at] = old_values[i];
|
||||
}
|
||||
if old_room != 0 {
|
||||
dispose::<u64>(nothing {}, old_keys, old_room);
|
||||
dispose::<u32>(nothing {}, old_values, old_room);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,668 @@
|
||||
#! @file lexer.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the lexer, which reads the text of a source into tokens. It notes
|
||||
#! what is wrong with the text as it goes, keeps the comments and documentation
|
||||
#! for the tokens they are written before, and follows the holes of interpolated
|
||||
#! strings, so the parser is given tokens alone.
|
||||
|
||||
import std::containers;
|
||||
import core::swar;
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! Represents a structure capable of lexically analyzing a source object.
|
||||
#!
|
||||
#! The lexer reports what is wrong with the text it reads itself: numbers and
|
||||
#! quotes that are malformed, escapes that do not exist, character literals of
|
||||
#! more or less than one character, and text spanning lines that is laid out
|
||||
#! wrong. A character that is no part of the language is reported and dropped,
|
||||
#! so the parser never sees it.
|
||||
#!
|
||||
#! A `>` begins the longest operator it can, as `>>`, `>=`, or `>>=`, and a
|
||||
#! token is made at each `>` and `=` after its first as well, holding what is
|
||||
#! left of it: `>>=` is `>>=`, `>=`, then `=`. An operator is the first of those
|
||||
#! tokens, and the parser moves past the rest with it, while type arguments
|
||||
#! closed by `>>` take its tokens one `>` at a time. So no token is ever split,
|
||||
#! and the tokens of a file are always those the lexer made.
|
||||
pub struct lexer {
|
||||
var source: &source; #! The file being lexed.
|
||||
var names: &mut names; #! The names it interns words into.
|
||||
var holes: stack<lexer::hole>; #! The holes of interpolated strings it is within, innermost on top.
|
||||
var text: *u8; #! The bytes of the source's text, read where they are.
|
||||
var size: u32; #! How many bytes the text holds.
|
||||
var file: u32; #! The index of the file, which its notes give.
|
||||
var index: u32; #! The byte it is at.
|
||||
var within: u32; #! Where the `>` operator the index is within ends, past which none of its tokens reach.
|
||||
var name: u32; #! The ID of the last word scanned.
|
||||
|
||||
# Where what it finds wrong is noted, which `max_notes` bounds: kept, or
|
||||
# heard as it is made, as where another thread reports it.
|
||||
pub var sink: note_sink; #! Where what it finds wrong is noted.
|
||||
}
|
||||
|
||||
#! A hole of an interpolated string that the lexer is within.
|
||||
#!
|
||||
#! The braces opened within the hole are counted, so that the `}` closing it is
|
||||
#! told apart from one closing a block or a struct literal inside it.
|
||||
pub struct lexer::hole {
|
||||
var braces: u32; #! How many braces are open within it.
|
||||
var block: bool; #! Whether its string is a text block, `$"""`.
|
||||
var text: u32; #! Where the text of the string begins, past its `$"` or `$"""`.
|
||||
}
|
||||
|
||||
#! The maximum depth that the lexer allows the nesting of interpolated strings.
|
||||
pub const lexer::max_depth := 16;
|
||||
|
||||
#! The most notes the lexer makes for one file.
|
||||
pub const lexer::max_notes: u32 = 100;
|
||||
|
||||
#! Creates a new lexer from the provided source and names references.
|
||||
#! @param source The source that this lexer will be tokenizing.
|
||||
#! @param names A place to store and track already known names.
|
||||
#! @param notes Where the lexer reports what is wrong with the text.
|
||||
#! @param file The index of the file the source is.
|
||||
#! @returns The instantiated lexer.
|
||||
pub def lexer::new(
|
||||
source: &source,
|
||||
names: &mut names,
|
||||
notes: &mut vector<note>,
|
||||
file: u32
|
||||
): lexer {
|
||||
return lexer {
|
||||
source = source,
|
||||
names = names,
|
||||
sink = note_sink::new(notes, lexer::max_notes),
|
||||
holes = stack::<lexer::hole>::new(),
|
||||
text = source.text.view().data,
|
||||
size = source.length as u32,
|
||||
file = file
|
||||
};
|
||||
}
|
||||
|
||||
#! Tokenizes the whole source into the syntax, through the `eof` that ends it,
|
||||
#! with the comments and documentation lines written before each token.
|
||||
#! @param this The lexer.
|
||||
#! @param syntax The syntax the tokens and comments are written to.
|
||||
pub def lexer::tokenize_all(&mut this, syntax: &mut syntax): void {
|
||||
syntax.reserve_for_text(this.size);
|
||||
while true {
|
||||
this.skip_fluff(syntax);
|
||||
this.name = 0;
|
||||
|
||||
val start := this.index;
|
||||
val kind := this.scan();
|
||||
if kind == tk::unknown {
|
||||
this.report(start, this.index - start, ec::token, "The character is no part of the language.");
|
||||
continue;
|
||||
}
|
||||
|
||||
# What follows the first `>` of an operator is read again, as the tokens of
|
||||
# what is left of it.
|
||||
val end := this.index;
|
||||
if kind.has(tt::angle) && end - start > 1 {
|
||||
this.within = end;
|
||||
this.index = start + 1;
|
||||
}
|
||||
|
||||
syntax.add_token(kind, start, end - start, this.name);
|
||||
break if kind == tk::eof;
|
||||
}
|
||||
syntax.fit_tokens();
|
||||
}
|
||||
|
||||
val lexer::curr: u8 { get => this.peek(0); }
|
||||
val lexer::next: u8 { get => this.peek(1); }
|
||||
val lexer::ahead: u8 { get => this.peek(2); }
|
||||
val lexer::eof: bool { get => this.index >= this.size; }
|
||||
val lexer::eol: bool { get => this.eof || this.curr.is_eol; }
|
||||
|
||||
#! Whether the current byte is of the class.
|
||||
#! @param this The lexer.
|
||||
#! @param class The class of byte.
|
||||
#! @returns Whether it is.
|
||||
def lexer::curr_is(&this, class: cc): bool {
|
||||
return (char_classes[this.curr as u64] & class as u8) != 0;
|
||||
}
|
||||
|
||||
val lexer::at_block_quote: bool {
|
||||
get {
|
||||
return this.curr.is_dquote &&
|
||||
this.next.is_dquote &&
|
||||
this.ahead.is_dquote;
|
||||
}
|
||||
}
|
||||
|
||||
val lexer::in_line_hole: bool {
|
||||
get {
|
||||
return this.holes.length > 0 &&
|
||||
!this.holes.peek().block;
|
||||
}
|
||||
}
|
||||
|
||||
def lexer::advance(&mut this): void {
|
||||
if this.index < this.size {
|
||||
this.index++;
|
||||
}
|
||||
}
|
||||
|
||||
def lexer::advance_for(&mut this, count: u64): void {
|
||||
for _ in 0..count { this.advance(); }
|
||||
}
|
||||
|
||||
def lexer::skip_line(&mut this): void {
|
||||
val text := this.text;
|
||||
val size := this.size;
|
||||
var at := this.index;
|
||||
# Sixteen bytes at a time while none is `\n` where vectors are held in
|
||||
# registers, then eight, as `source::find_lines` finds them.
|
||||
if lanes_held() {
|
||||
val newline := u8x16::splat('\n');
|
||||
while at + 16 <= size {
|
||||
val chunk: u8x16 = *((text + at) as *u8x16);
|
||||
val marks := chunk.equal(&newline).bits();
|
||||
if marks != 0 {
|
||||
this.index = at + trailing_zeros(marks);
|
||||
return;
|
||||
}
|
||||
at += 16;
|
||||
}
|
||||
}
|
||||
while at + 8 <= size {
|
||||
val word := *((text + at) as *u64) ^ 0x0A0A0A0A0A0A0A0A;
|
||||
break if ((word - 0x0101010101010101) & ~word & 0x8080808080808080) != 0;
|
||||
at += 8;
|
||||
}
|
||||
while at < size && text[at] != '\n' {
|
||||
at++;
|
||||
}
|
||||
this.index = at;
|
||||
}
|
||||
|
||||
#! Skips spacing and comments, keeping each comment in the syntax: a `#!` line
|
||||
#! as documentation, and any other as a comment, each for the token after it.
|
||||
#! @param this The lexer.
|
||||
#! @param syntax The syntax the comments are written to.
|
||||
def lexer::skip_fluff(&mut this, syntax: &mut syntax): void {
|
||||
# The index is held here, and written back for a comment and where it ends.
|
||||
val text := this.text;
|
||||
val size := this.size;
|
||||
var at := this.index;
|
||||
while at < size {
|
||||
val byte: u8 = text[at];
|
||||
if (char_classes[byte as u64] & cc::space as u8) != 0 {
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
|
||||
break if !byte.is_cmnt;
|
||||
val start := at;
|
||||
this.index = at;
|
||||
this.skip_line();
|
||||
at = this.index;
|
||||
|
||||
val token := syntax.token_count as u32;
|
||||
val length := at - start;
|
||||
if this.byte_at(start + 1) == '!' {
|
||||
syntax.docs.append(doc { offset = start, length = length, token = token });
|
||||
} else {
|
||||
syntax.comments.append(comment { offset = start, length = length, token = token });
|
||||
}
|
||||
}
|
||||
this.index = at;
|
||||
}
|
||||
|
||||
def lexer::peek(&this, offset: u32): u8 {
|
||||
val index := this.index + offset;
|
||||
return index < this.size ? this.text[index] : '\0';
|
||||
}
|
||||
|
||||
#! The byte of the source text at the offset, or `\0` past its end.
|
||||
#! @param this The lexer.
|
||||
#! @param offset The byte's offset.
|
||||
#! @returns The byte.
|
||||
def lexer::byte_at(&this, offset: u32): u8 {
|
||||
return offset < this.size ? this.text[offset] : '\0';
|
||||
}
|
||||
|
||||
def lexer::scan(&mut this): tk {
|
||||
return tk::eof if this.eof;
|
||||
|
||||
val byte := this.curr;
|
||||
val class := char_classes[byte as u64];
|
||||
return this.close_hole() if byte.is_eol && this.in_line_hole;
|
||||
return this.scan_word() if (class & cc::start as u8) != 0;
|
||||
return this.scan_number() if (class & cc::digit as u8) != 0;
|
||||
return this.scan_quoted('\"', this.at_block_quote) if byte.is_dquote;
|
||||
return this.scan_quoted('\'', false) if byte.is_squote;
|
||||
return this.scan_istring() if byte.is_format && this.next.is_dquote;
|
||||
return this.scan_brace() if this.holes.length != 0 && byte.is_brace;
|
||||
return this.scan_foreign() if byte >= 0x80;
|
||||
return this.scan_punct();
|
||||
}
|
||||
|
||||
def lexer::scan_word(&mut this): tk {
|
||||
val start := this.index;
|
||||
val text := this.text;
|
||||
val size := this.size;
|
||||
var at := start;
|
||||
while at < size && (char_classes[text[at] as u64] & cc::word as u8) != 0 {
|
||||
at++;
|
||||
}
|
||||
this.index = at;
|
||||
|
||||
val lex := strview::over(text + start, (at - start) as u64);
|
||||
val id := this.names.intern(&lex);
|
||||
this.name = id;
|
||||
return id <= tk::kw_end as u32 ? id as tk : tk::name;
|
||||
}
|
||||
|
||||
def lexer::scan_number(&mut this): tk {
|
||||
var base: u8 = 10;
|
||||
var valid: bool = true;
|
||||
var start: u32 = this.index;
|
||||
if this.curr.is_zero {
|
||||
base = match this.next {
|
||||
'x' => 16,
|
||||
'o' => 8,
|
||||
'b' => 2,
|
||||
else => 10
|
||||
};
|
||||
}
|
||||
|
||||
var sym := tk::signed;
|
||||
if base != 10 {
|
||||
this.advance();
|
||||
this.advance();
|
||||
while this.curr.is_base_digit(base) {
|
||||
this.advance();
|
||||
}
|
||||
valid = this.index > start + 2;
|
||||
|
||||
# `u` makes an integer unsigned, in any base: `0xFFu`.
|
||||
if this.curr == 'u' {
|
||||
sym = tk::unsigned;
|
||||
this.advance();
|
||||
}
|
||||
} else {
|
||||
while this.curr_is(cc::digit) { this.advance(); }
|
||||
if this.curr.is_dot && this.next.is_digit {
|
||||
sym = tk::float;
|
||||
this.advance();
|
||||
while this.curr_is(cc::digit) {
|
||||
this.advance();
|
||||
}
|
||||
}
|
||||
|
||||
# An exponent makes a float too: `e` or `E`, an optional sign, then digits, as
|
||||
# `6.02e23` and `1e-9`. An `e` without digits after it is left to the check below.
|
||||
val signed := this.next == '+' || this.next == '-';
|
||||
val digit := signed ? this.ahead.is_digit : this.next.is_digit;
|
||||
if (this.curr == 'e' || this.curr == 'E') && digit {
|
||||
sym = tk::float;
|
||||
this.advance();
|
||||
if signed {
|
||||
this.advance();
|
||||
}
|
||||
while this.curr_is(cc::digit) {
|
||||
this.advance();
|
||||
}
|
||||
}
|
||||
|
||||
# A fraction cannot be unsigned, so `1.5u` is left to the check below.
|
||||
if this.curr == 'f' {
|
||||
sym = tk::float;
|
||||
this.advance();
|
||||
} else if this.curr == 'u' && sym != tk::float {
|
||||
sym = tk::unsigned;
|
||||
this.advance();
|
||||
}
|
||||
}
|
||||
|
||||
if this.curr_is(cc::word) {
|
||||
valid = false;
|
||||
while this.curr_is(cc::word) {
|
||||
this.advance();
|
||||
}
|
||||
}
|
||||
|
||||
return sym if valid;
|
||||
this.report(start, this.index - start, ec::token,
|
||||
"The number is malformed, as a digit outside its base or letters after it.");
|
||||
return tk::bad_number;
|
||||
}
|
||||
|
||||
def lexer::scan_istring(&mut this): tk {
|
||||
val start := this.index;
|
||||
this.advance();
|
||||
val block := this.at_block_quote;
|
||||
this.advance_for(block ? 3 : 1);
|
||||
|
||||
val text := this.index;
|
||||
val stop := this.scan_text(block);
|
||||
return this.open_hole(block, text) if stop == tk::lbrace;
|
||||
if stop != tk::string {
|
||||
return this.unclosed(start);
|
||||
}
|
||||
|
||||
if block {
|
||||
this.check_block(text, this.index - 3);
|
||||
}
|
||||
return tk::istring;
|
||||
}
|
||||
|
||||
def lexer::scan_quoted(&mut this, quote: u8, block: bool): tk {
|
||||
val start := this.index;
|
||||
val quotes: u64 = block ? 3 : 1;
|
||||
this.advance_for(quotes);
|
||||
|
||||
# A character literal holds one character, which is one or more bytes, or one
|
||||
# escape, so what it holds is counted as it is read.
|
||||
var count: u32 = 0;
|
||||
while true {
|
||||
# A string's bytes are passed eight at a time to the next that may end it,
|
||||
# since only a character literal counts what it holds.
|
||||
if quote == '"' {
|
||||
this.index = quoted_run(this.text, this.index, this.size, false);
|
||||
}
|
||||
return this.unclosed(start) if this.eof;
|
||||
return this.unclosed(start) if this.eol && !block;
|
||||
|
||||
# Happy path break aways.
|
||||
break if block && this.at_block_quote;
|
||||
break if !block && this.curr == quote;
|
||||
|
||||
if !this.curr.is_continuation {
|
||||
count++;
|
||||
}
|
||||
|
||||
if this.curr.is_escape {
|
||||
this.check_escape();
|
||||
} else {
|
||||
this.advance();
|
||||
}
|
||||
}
|
||||
|
||||
val end := this.index;
|
||||
this.advance_for(quotes);
|
||||
if quote == '\'' && count != 1 {
|
||||
this.report(start, this.index - start, ec::char,
|
||||
"Character literals must contain exactly one character or escape.");
|
||||
}
|
||||
|
||||
if block {
|
||||
this.check_block(start + 3, end);
|
||||
}
|
||||
|
||||
return match quote {
|
||||
'\"' => tk::string,
|
||||
'\'' => tk::char,
|
||||
else => tk::unknown
|
||||
};
|
||||
}
|
||||
|
||||
def lexer::scan_brace(&mut this): tk {
|
||||
val hole := &mut this.holes.peek();
|
||||
if this.curr.is_lbrace {
|
||||
hole.braces++;
|
||||
return this.scan_punct();
|
||||
}
|
||||
|
||||
if hole.braces != 0 {
|
||||
hole.braces--;
|
||||
return this.scan_punct();
|
||||
}
|
||||
|
||||
val start := this.index;
|
||||
this.advance();
|
||||
val stop := this.scan_text(hole.block);
|
||||
return tk::istring_mid if stop == tk::lbrace;
|
||||
if stop != tk::string {
|
||||
this.unclosed(start);
|
||||
return this.close_hole();
|
||||
}
|
||||
|
||||
if hole.block {
|
||||
this.check_block(hole.text, this.index - 3);
|
||||
}
|
||||
return this.close_hole(tk::istring_end);
|
||||
}
|
||||
|
||||
#! Reads the text of an interpolated string through the `{` opening a hole, or
|
||||
#! through its closing quotes.
|
||||
#! @param this The lexer.
|
||||
#! @param block Whether the text is a text block, `"""`.
|
||||
#! @returns `lbrace` at a hole, `string` at its end, or `bad_quote` where it is
|
||||
#! never closed.
|
||||
def lexer::scan_text(&mut this, block: bool): tk {
|
||||
while true {
|
||||
this.index = quoted_run(this.text, this.index, this.size, true);
|
||||
return tk::bad_quote if this.eof;
|
||||
return tk::bad_quote if this.eol && !block;
|
||||
if block && this.at_block_quote {
|
||||
this.advance_for(3);
|
||||
return tk::string;
|
||||
}
|
||||
|
||||
if this.curr.is_escape {
|
||||
this.check_escape();
|
||||
continue;
|
||||
}
|
||||
|
||||
val curr := this.curr;
|
||||
this.advance();
|
||||
return tk::string if !block && curr.is_dquote;
|
||||
return tk::lbrace if curr.is_lbrace;
|
||||
}
|
||||
|
||||
return tk::bad_quote;
|
||||
}
|
||||
|
||||
#! Where the bytes of quoted text from a place stop needing a look one at a
|
||||
#! time: at the next `"`, `\`, line break, or, in interpolated text, `{`, found
|
||||
#! eight bytes at a time. Fewer than eight left are looked at one at a time.
|
||||
#! @param text The source's bytes.
|
||||
#! @param from Where to begin.
|
||||
#! @param size How many bytes the source has.
|
||||
#! @param holes Whether `{` opens a hole, as in interpolated text.
|
||||
#! @returns Where the first such byte is, or where fewer than eight are left.
|
||||
def quoted_run(text: *u8, from: u64, size: u64, holes: bool): u32 {
|
||||
var at := from;
|
||||
while at + 8 <= size {
|
||||
val word := swar::load(text + at);
|
||||
var stops: swar::mask8 = word.equal('"') | word.equal('\\') | word.equal('\n');
|
||||
if holes {
|
||||
stops = stops | word.equal('{');
|
||||
}
|
||||
return (at + stops.first()) as u32 if stops.any();
|
||||
at += 8;
|
||||
}
|
||||
return at as u32;
|
||||
}
|
||||
|
||||
#! Reports text that begins at `start` and is never closed.
|
||||
#! @param this The lexer.
|
||||
#! @param start Where the text begins.
|
||||
#! @returns `bad_quote`.
|
||||
def lexer::unclosed(&mut this, start: u32): tk {
|
||||
this.report(start, 1, ec::token, "The text is not closed before the end of its line, or of the file.");
|
||||
return tk::bad_quote;
|
||||
}
|
||||
|
||||
#! Moves past the escape at the current `\`, reporting it where it is not one of
|
||||
#! the language's.
|
||||
#! @param this The lexer.
|
||||
def lexer::check_escape(&mut this): void {
|
||||
val start := this.index;
|
||||
this.advance();
|
||||
if this.eol {
|
||||
this.report(start, 1, ec::escape, "Valid escapes are \\n, \\t, \\r, \\0, \\\\, \\', \\\", \\{, \\}, and \\xHH.");
|
||||
return;
|
||||
}
|
||||
|
||||
val which := this.curr;
|
||||
this.advance();
|
||||
match which {
|
||||
'n', 't', 'r', '0', '\\', '\'', '\"', '{', '}' => return;
|
||||
'x' => {
|
||||
if this.curr.is_base_digit(16) && this.next.is_base_digit(16) {
|
||||
this.advance_for(2);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.report(start, 2, ec::escape, "Valid escapes are \\n, \\t, \\r, \\0, \\\\, \\', \\\", \\{, \\}, and \\xHH.");
|
||||
}
|
||||
|
||||
#! Checks how text spanning lines is laid out, between `text`, past the quotes
|
||||
#! opening it, and `end`, where the quotes closing it begin.
|
||||
#!
|
||||
#! Nothing but the line break follows the opening quotes, the closing quotes
|
||||
#! stand on a line of their own, and every line of the text is indented at least
|
||||
#! as far as they are, or holds only whitespace, since that much is taken off.
|
||||
#! @param this The lexer.
|
||||
#! @param text Where the text begins, past the quotes opening it.
|
||||
#! @param end Where the quotes closing it begin.
|
||||
def lexer::check_block(&mut this, text: u32, end: u32): void {
|
||||
var first := text;
|
||||
while first < end && this.byte_at(first).is_blank { first++; }
|
||||
if first == end || !this.byte_at(first).is_eol {
|
||||
this.report(text - 3, 3, ec::block,
|
||||
"The text of a block begins on the line below the `\"\"\"` that opens it, so nothing else is written there.");
|
||||
return;
|
||||
}
|
||||
|
||||
var last := end;
|
||||
while last > first && !this.byte_at(last - 1).is_eol { last--; }
|
||||
for at in last..end {
|
||||
if !this.byte_at(at as u32).is_blank {
|
||||
this.report(last, end - last + 3, ec::block,
|
||||
"The `\"\"\"` that closes a block is written on a line of its own, and how far it is indented is how far its text is.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
val indent := end - last;
|
||||
var line := first + 1;
|
||||
while line < last {
|
||||
var stop := line;
|
||||
while stop < last && !this.byte_at(stop).is_eol { stop++; }
|
||||
|
||||
var at := line;
|
||||
while at < stop && at - line < indent && this.byte_at(at).is_blank { at++; }
|
||||
if at < stop && at - line < indent {
|
||||
this.report(line, stop - line, ec::block,
|
||||
"This line is indented less than the `\"\"\"` that closes the block, so the block cannot take that much off it.");
|
||||
return;
|
||||
}
|
||||
line = stop + 1;
|
||||
}
|
||||
}
|
||||
|
||||
#! A punctuator, as long as it can be. One within a `>` operator ends where the
|
||||
#! operator does, as what is left of it.
|
||||
#! @param this The lexer.
|
||||
#! @returns The punctuator's kind, or `unknown` where no punctuator begins
|
||||
#! there.
|
||||
def lexer::scan_punct(&mut this): tk {
|
||||
val limit := this.index < this.within ? this.within : this.size;
|
||||
val text := this.text;
|
||||
var at := this.index;
|
||||
var kind: tk = punct_firsts[text[at] as u64];
|
||||
at++;
|
||||
while (punct_longer[kind as u64] & 1) != 0 && at < limit {
|
||||
val longer := kind.from(text[at]);
|
||||
break if longer == tk::unknown;
|
||||
kind = longer;
|
||||
at++;
|
||||
}
|
||||
this.index = at;
|
||||
return kind;
|
||||
}
|
||||
|
||||
#! The punctuator each byte begins, worked out while compiling, or `unknown`.
|
||||
const punct_firsts: tk[256] = make_punct_firsts();
|
||||
|
||||
#! Whether each kind of token is a punctuator a byte may make longer, as `1`.
|
||||
const punct_longer: u8[tk::count as u64] = make_punct_longer();
|
||||
|
||||
const def make_punct_firsts(): tk[256] {
|
||||
var made: tk[256];
|
||||
for each in 0..256 {
|
||||
made[each] = tk::unknown.from(each as u8);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
const def make_punct_longer(): u8[tk::count as u64] {
|
||||
var made: u8[tk::count as u64];
|
||||
for kind in 0..tk::count as u64 {
|
||||
continue if kind == tk::unknown as u64;
|
||||
for each in 0..256 {
|
||||
if (kind as tk).from(each as u8) != tk::unknown {
|
||||
made[kind] = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A character beyond ASCII, which the language has no use for outside text and
|
||||
#! comments. All of its bytes are read, so it is reported once.
|
||||
#! @param this The lexer.
|
||||
#! @returns `unknown`.
|
||||
def lexer::scan_foreign(&mut this): tk {
|
||||
this.advance();
|
||||
while this.curr.is_continuation {
|
||||
this.advance();
|
||||
}
|
||||
return tk::unknown;
|
||||
}
|
||||
|
||||
def lexer::open_hole(
|
||||
&mut this,
|
||||
block: bool,
|
||||
text: u32
|
||||
): tk {
|
||||
if this.holes.length == lexer::max_depth {
|
||||
this.report(text, 1, ec::token, "Interpolated strings are nested within each other's holes too deeply.");
|
||||
return tk::bad_quote;
|
||||
}
|
||||
|
||||
this.holes.push(lexer::hole {
|
||||
braces = 0,
|
||||
block = block,
|
||||
text = text
|
||||
});
|
||||
return tk::istring_beg;
|
||||
}
|
||||
|
||||
def lexer::close_hole(
|
||||
&mut this,
|
||||
kind: tk = tk::bad_quote
|
||||
): tk {
|
||||
this.holes.pop();
|
||||
return kind;
|
||||
}
|
||||
|
||||
#! Reports what is wrong with the text from `offset`, for `length` bytes.
|
||||
#! @param this The lexer.
|
||||
#! @param offset Where the text begins.
|
||||
#! @param length How many bytes it covers.
|
||||
#! @param code What kind of mistake it is.
|
||||
#! @param detail What the note says.
|
||||
def lexer::report(&mut this, offset: u32, length: u32, code: ec, detail: strview): void {
|
||||
return if !this.sink.admits();
|
||||
var made := note {
|
||||
file = this.file,
|
||||
offset = offset,
|
||||
length = length,
|
||||
code = code,
|
||||
detail = string::from(detail, nothing {}),
|
||||
lexed = true
|
||||
};
|
||||
this.sink.give(&mut made);
|
||||
}
|
||||
@@ -0,0 +1,756 @@
|
||||
#! @file libraries.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains how the files of a program's libraries are found: those of each
|
||||
#! module its files refer to, and of each module those refer to, until nothing
|
||||
#! new is, so a program reads the modules it uses and none it does not.
|
||||
#!
|
||||
#! A library is a folder, and its modules are its folders and files by their
|
||||
#! paths: in the library `std`, the module `std::a::b` is the folder `a/b`, or
|
||||
#! the one file `a/b.sakura`, and the root `std` is the folder itself. A file or
|
||||
#! folder within a module's folder belongs to it where its first `module` line
|
||||
#! says so, and is otherwise a module of its own, as `std/testing.sakura` and
|
||||
#! `std/io/` are; a folder is of each module a file within it is of.
|
||||
#!
|
||||
#! A library's name is the module its folder is, which may be within another,
|
||||
#! as `std::yaml` or `sakura::analyzer`. A module is found in the library whose
|
||||
#! name is the most of its path, so the library `std::yaml` holds `std::yaml`
|
||||
#! and what is within it, and `std` the rest of `std`. A module holding a
|
||||
#! library and in none itself, as `sakura` of `sakura::analyzer`, has no files.
|
||||
#!
|
||||
#! A file refers to each module it imports, to the modules its sections are
|
||||
#! of and those holding them, whose names it sees, and to the module each path
|
||||
#! it writes begins with, as `system` of `system::fd` or `std::io` of
|
||||
#! `std::io::println`. A path's first segment is found as name lookup finds a
|
||||
#! module: within the module the file is of or one holding it, then a library.
|
||||
#! A segment naming no module's folder or file, as a type's, reads nothing.
|
||||
|
||||
import std::io;
|
||||
import system;
|
||||
import std::containers;
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! A library a program may read: its name, which its root module is, and its
|
||||
#! folder.
|
||||
pub struct library {
|
||||
pub var name: string; #! The library's name, as `std` or `std::yaml`.
|
||||
pub var folder: string; #! Its folder.
|
||||
pub var whole: bool; #! Whether it is read whole, as `core` is, rather than by what refers to it.
|
||||
}
|
||||
|
||||
#! What finds the files of the modules a program's files refer to, keeping
|
||||
#! which it found, so each file is read once.
|
||||
pub struct resolver {
|
||||
var libraries: vector<library>; #! The libraries modules are found in.
|
||||
var files: dict<string, bool>; #! The files found or read before, by path.
|
||||
var modules: dict<string, bool>; #! The modules whose files were found, by path, as `std::io`.
|
||||
var exists: dict<string, bool>; #! Whether each module looked for has a file or folder of its own, by path.
|
||||
|
||||
# The paths files write, by the IDs of their names, as a tree, the empty path
|
||||
# first: what was worked out of each is kept with it.
|
||||
var paths: vector<module_path>; #! Each path written, by its node.
|
||||
var path_ids: keymap; #! Each path's node, by its parent's and its last name's: `parent << 32 | name`.
|
||||
}
|
||||
|
||||
#! A path a file writes, as the tree of them holds it: the path without its
|
||||
#! last name, the name, and what was worked out of it.
|
||||
struct module_path {
|
||||
var parent: u32; #! The node of the path without its last name.
|
||||
var name: u32; #! The ID of its last name.
|
||||
var depth: u32; #! How many names it has.
|
||||
var named: u8; #! Whether it names a module: 0 not yet asked, 1 where it does not, and 2 where it does.
|
||||
var found: bool; #! Whether the files of the module it names were found.
|
||||
}
|
||||
|
||||
#! Makes a resolver of no library yet, which has found nothing.
|
||||
#! @returns The resolver.
|
||||
pub def resolver::new(): resolver {
|
||||
var made := resolver {
|
||||
libraries = vector::<library>::new(),
|
||||
files = dict::<string, bool>::new(),
|
||||
modules = dict::<string, bool>::new(),
|
||||
exists = dict::<string, bool>::new(),
|
||||
paths = vector::<module_path>::new(),
|
||||
path_ids = keymap::new()
|
||||
};
|
||||
# The empty path, which every path is within.
|
||||
made.paths.append(module_path {});
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Adds a library modules are found in, unless one of its name was added
|
||||
#! before, which is the one found by the name.
|
||||
#! @param this The resolver.
|
||||
#! @param name The library's name, as `std` or `std::yaml`.
|
||||
#! @param folder Its folder.
|
||||
pub def resolver::add_library(&mut this, name: strview, folder: strview): void {
|
||||
return if this.library_of(name) is some(_);
|
||||
this.libraries.append(library { name = string::from(name, nothing {}), folder = string::from(folder, nothing {}) });
|
||||
}
|
||||
|
||||
#! Adds a library read whole, as `core` is, whose files the caller reads, so
|
||||
#! none is found by what refers to it.
|
||||
#! @param this The resolver.
|
||||
#! @param name The library's name.
|
||||
#! @param folder Its folder.
|
||||
pub def resolver::whole(&mut this, name: strview, folder: strview): void {
|
||||
return if this.library_of(name) is some(_);
|
||||
this.libraries.append(library {
|
||||
name = string::from(name, nothing {}), folder = string::from(folder, nothing {}), whole = true
|
||||
});
|
||||
}
|
||||
|
||||
#! The libraries modules are found in.
|
||||
#! @param this The resolver.
|
||||
#! @returns A copy of each.
|
||||
pub def resolver::held(&this): vector<library> {
|
||||
var made := vector::<library>::new();
|
||||
for &each in this.libraries {
|
||||
made.append(library { name = string::copy_of(&each.name), folder = string::copy_of(&each.folder), whole = each.whole });
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! How many files the libraries not read whole hold, which is the most what
|
||||
#! refers to them can bring.
|
||||
#! @param this The resolver.
|
||||
#! @returns How many.
|
||||
pub def resolver::files_held(&this): u64 {
|
||||
var total: u64 = 0;
|
||||
for &each in this.libraries {
|
||||
total += each.whole ? 0 : count_files(each.folder.view());
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
#! Notes a file read whatever it refers to, as a program's own and `core`'s
|
||||
#! are, so no module brings it again.
|
||||
#! @param this The resolver.
|
||||
#! @param path The file's path.
|
||||
pub def resolver::mark(&mut this, path: strview): void {
|
||||
this.files.set(string::from(path, nothing {}), true);
|
||||
}
|
||||
|
||||
#! Finds the files of a module asked for by its path, as `runtime` is for
|
||||
#! an executable, and of the modules holding it.
|
||||
#! @param this The resolver.
|
||||
#! @param wanted The module's path.
|
||||
#! @param into Where the paths of the files not found before are added.
|
||||
pub def resolver::want(&mut this, wanted: strview, into: &mut vector<string>): void {
|
||||
var segments := vector::<string>::new();
|
||||
for piece in wanted.split(':') {
|
||||
continue if piece.length == 0;
|
||||
segments.append(string::from(piece, nothing {}));
|
||||
}
|
||||
for count in 1..segments.length + 1 {
|
||||
this.find_module(segments.view()[0:count], into);
|
||||
}
|
||||
}
|
||||
|
||||
#! Finds the files of the modules a file refers to: those it imports, those its
|
||||
#! sections are of and those holding them, and the module each path it writes
|
||||
#! begins with.
|
||||
#!
|
||||
#! Each path is looked for by the IDs of its names, in a tree of the paths every
|
||||
#! file wrote, so a path written again, in this file or another, is looked for
|
||||
#! once, and its text is made only where it is asked whether it names a module.
|
||||
#! @param this The resolver.
|
||||
#! @param syntax The file, parsed.
|
||||
#! @param names The names it was read with, which are those of every file
|
||||
#! the resolver is given.
|
||||
#! @param into Where the paths of the files not found before are added, in
|
||||
#! the order they are first referred to.
|
||||
pub def resolver::refer(&mut this, syntax: &syntax, names: &names, into: &mut vector<string>): void {
|
||||
# The modules its sections are of, whose names, and those of the modules
|
||||
# holding them, the file sees.
|
||||
var homes := vector::<u32>::new();
|
||||
for node in 0..syntax.node_count {
|
||||
val kind: nk = syntax.node_kinds[node];
|
||||
continue if kind != nk::module_decl && kind != nk::extern_module;
|
||||
val made := this.path_node(syntax, syntax.node_lefts[node]);
|
||||
continue if made == 0;
|
||||
this.find_prefixes(made, names, into);
|
||||
homes.append(made);
|
||||
}
|
||||
|
||||
# A file writes the same paths again and again, as `nk::name`, so each is
|
||||
# found once, by its node.
|
||||
var tried := keymap::new();
|
||||
for node in 0..syntax.node_count {
|
||||
val kind: nk = syntax.node_kinds[node];
|
||||
var path: u32 = 0;
|
||||
if kind == nk::import_decl {
|
||||
path = syntax.node_lefts[node];
|
||||
} else if kind == nk::path || kind == nk::type_name {
|
||||
continue if syntax.node_lefts[node] == 0 || syntax.extras[syntax.node_lefts[node]] < 2;
|
||||
path = node as u32;
|
||||
}
|
||||
continue if path == 0;
|
||||
val written := this.path_node(syntax, path);
|
||||
continue if written == 0 || !tried.insert(written as u64, 1);
|
||||
this.find_path(written, homes.view(), names, into);
|
||||
}
|
||||
}
|
||||
|
||||
#! The node of the path of a `path`, `type_name`, or `name` node's segments,
|
||||
#! made where it is new.
|
||||
#! @param this The resolver.
|
||||
#! @param syntax The file.
|
||||
#! @param node The node, or 0.
|
||||
#! @returns The path's node, or 0 where the node is none of those.
|
||||
def resolver::path_node(&mut this, syntax: &syntax, node: u32): u32 {
|
||||
return 0 if node == 0;
|
||||
val kind: nk = syntax.node_kinds[node];
|
||||
return 0 if kind != nk::path && kind != nk::type_name && kind != nk::name;
|
||||
val run: u32 = syntax.node_lefts[node];
|
||||
if kind == nk::name || run == 0 {
|
||||
return this.child(0, syntax.token_names[syntax.node_tokens[node]]);
|
||||
}
|
||||
var at: u32 = 0;
|
||||
val count: u32 = syntax.extras[run];
|
||||
for i in 0..count {
|
||||
val segment: u32 = syntax.extras[run as u64 + 1 + i];
|
||||
at = this.child(at, syntax.token_names[syntax.node_tokens[segment]]);
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
#! The node of the path that is another's with one more name, made where it is
|
||||
#! new.
|
||||
#! @param this The resolver.
|
||||
#! @param parent The other path's node, 0 for the empty path.
|
||||
#! @param name The name's ID.
|
||||
#! @returns The node.
|
||||
def resolver::child(&mut this, parent: u32, name: u32): u32 {
|
||||
val key := pair_key(parent, name);
|
||||
val held := this.path_ids.get_or(&key, 0);
|
||||
return held if held != 0;
|
||||
val made := this.paths.length as u32;
|
||||
this.paths.append(module_path { parent = parent, name = name, depth = this.paths[parent].depth + 1 });
|
||||
this.path_ids.set(key, made);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The names of a path, by their text, its first first.
|
||||
#! @param this The resolver.
|
||||
#! @param node The path's node.
|
||||
#! @param names The names its IDs are of.
|
||||
#! @returns The names.
|
||||
def resolver::segments_of(&this, node: u32, names: &names): vector<string> {
|
||||
var made := vector::<string>::new();
|
||||
made.resize(this.paths[node].depth as u64);
|
||||
var at := node;
|
||||
while at != 0 {
|
||||
val held: module_path = this.paths[at];
|
||||
made[held.depth as u64 - 1] = string::from(names.text(held.name), nothing {});
|
||||
at = held.parent;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Whether a path names a module, as `module_exists` says, asked once.
|
||||
#! @param this The resolver.
|
||||
#! @param node The path's node.
|
||||
#! @param names The names its IDs are of.
|
||||
#! @returns Whether it does.
|
||||
def resolver::names_module(&mut this, node: u32, names: &names): bool {
|
||||
if this.paths[node].named == 0 {
|
||||
val segments := this.segments_of(node, names);
|
||||
this.paths[node].named = this.module_exists(segments.view()) ? 2 : 1;
|
||||
}
|
||||
return this.paths[node].named == 2;
|
||||
}
|
||||
|
||||
#! Finds the files of the module a path names, once.
|
||||
#! @param this The resolver.
|
||||
#! @param node The path's node.
|
||||
#! @param names The names its IDs are of.
|
||||
#! @param into Where the paths of the files not found before are added.
|
||||
def resolver::find_node(&mut this, node: u32, names: &names, into: &mut vector<string>): void {
|
||||
return if this.paths[node].found;
|
||||
this.paths[node].found = true;
|
||||
val segments := this.segments_of(node, names);
|
||||
this.find_module(segments.view(), into);
|
||||
}
|
||||
|
||||
#! Finds the files of the modules a path and each path that begins it name, the
|
||||
#! shortest first, as a file's `module` line refers to them.
|
||||
#! @param this The resolver.
|
||||
#! @param node The path's node.
|
||||
#! @param names The names its IDs are of.
|
||||
#! @param into Where the paths of the files not found before are added.
|
||||
def resolver::find_prefixes(&mut this, node: u32, names: &names, into: &mut vector<string>): void {
|
||||
var chain := vector::<u32>::new();
|
||||
var at := node;
|
||||
while at != 0 {
|
||||
chain.append(at);
|
||||
at = this.paths[at].parent;
|
||||
}
|
||||
var i := chain.length;
|
||||
while i > 0 {
|
||||
i--;
|
||||
this.find_node(chain[i], names, into);
|
||||
}
|
||||
}
|
||||
|
||||
#! Finds the files of the modules a path names as many of its names as name
|
||||
#! modules: from the first, within a module the file is of or one holding it,
|
||||
#! nearest first, then as a library.
|
||||
#! @param this The resolver.
|
||||
#! @param written The path's node.
|
||||
#! @param homes The nodes of the modules the file's sections are of.
|
||||
#! @param names The names its IDs are of.
|
||||
#! @param into Where the paths of the files not found before are added.
|
||||
def resolver::find_path(&mut this, written: u32, homes: span<u32>, names: &names, into: &mut vector<string>): void {
|
||||
# The path's names, its first first.
|
||||
var rest := vector::<u32>::new();
|
||||
rest.resize(this.paths[written].depth as u64);
|
||||
var at := written;
|
||||
while at != 0 {
|
||||
rest[this.paths[at].depth as u64 - 1] = this.paths[at].name;
|
||||
at = this.paths[at].parent;
|
||||
}
|
||||
return if rest.length == 0;
|
||||
|
||||
for &home in homes {
|
||||
var holder := home;
|
||||
while holder != 0 {
|
||||
val tried := this.child(holder, rest[0]);
|
||||
if this.names_module(tried, names) {
|
||||
this.find_deeper(tried, rest.view()[1:], names, into);
|
||||
return;
|
||||
}
|
||||
holder = this.paths[holder].parent;
|
||||
}
|
||||
}
|
||||
|
||||
val tried := this.child(0, rest[0]);
|
||||
return if !this.names_module(tried, names);
|
||||
this.find_deeper(tried, rest.view()[1:], names, into);
|
||||
}
|
||||
|
||||
#! Finds the files of a module the path's first name found, then of those
|
||||
#! within it its next names name, while they name any.
|
||||
#! @param this The resolver.
|
||||
#! @param found The node of the module found, which grows by each name.
|
||||
#! @param rest The IDs of the path's names after the first.
|
||||
#! @param names The names its IDs are of.
|
||||
#! @param into Where the paths of the files not found before are added.
|
||||
def resolver::find_deeper(&mut this, found: u32, rest: span<u32>, names: &names, into: &mut vector<string>): void {
|
||||
this.find_node(found, names, into);
|
||||
var at := found;
|
||||
for &name in rest {
|
||||
at = this.child(at, name);
|
||||
return if !this.names_module(at, names);
|
||||
this.find_node(at, names, into);
|
||||
}
|
||||
}
|
||||
|
||||
#! The library of a name, or none.
|
||||
#! @param this The resolver.
|
||||
#! @param name The name.
|
||||
#! @returns The library's index, or none.
|
||||
def resolver::library_of(&this, name: strview): maybe<u64> {
|
||||
for i in 0..this.libraries.length {
|
||||
return i if this.libraries[i].name.view() == name;
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! The library a module is found in, and how much of its path the library's
|
||||
#! name is.
|
||||
struct shelf {
|
||||
var index: u64; #! The library's index.
|
||||
var depth: u64; #! How many of the module's segments its name is.
|
||||
}
|
||||
|
||||
#! The library a module is found in: the one whose name is the most of the
|
||||
#! module's path, from its start.
|
||||
#! @param this The resolver.
|
||||
#! @param segments The module's path.
|
||||
#! @returns The library, or none where no library's name begins the path.
|
||||
def resolver::library_for(&this, segments: span<string>): maybe<shelf> {
|
||||
var found: u64 = 0;
|
||||
var deepest: u64 = 0;
|
||||
for i in 0..this.libraries.length {
|
||||
val depth := covered(this.libraries[i].name.view(), segments);
|
||||
if depth > deepest {
|
||||
found = i;
|
||||
deepest = depth;
|
||||
}
|
||||
}
|
||||
return nothing {} if deepest == 0;
|
||||
return shelf { index = found, depth = deepest };
|
||||
}
|
||||
|
||||
#! Whether a module holds a library within it, as `sakura` holds
|
||||
#! `sakura::analyzer`.
|
||||
#! @param this The resolver.
|
||||
#! @param segments The module's path.
|
||||
#! @returns Whether it does.
|
||||
def resolver::holds_library(&this, segments: span<string>): bool {
|
||||
for &each in this.libraries {
|
||||
return true if holds(each.name.view(), segments);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! How many of a module's segments a library's name is, where the name is the
|
||||
#! module's path or its start, as `std::yaml` is two of `std::yaml::text`.
|
||||
#! @param name The library's name.
|
||||
#! @param segments The module's path.
|
||||
#! @returns How many, or 0 where the name does not begin the path.
|
||||
def covered(name: strview, segments: span<string>): u64 {
|
||||
var at: u64 = 0;
|
||||
for count in 0..segments.length {
|
||||
val piece := segments[count].view();
|
||||
return 0 if name.length - at < piece.length || name.substr(at, piece.length) != piece;
|
||||
at += piece.length;
|
||||
return count + 1 if at == name.length;
|
||||
return 0 if name.length - at < 2 || name[at] != ':' || name[at + 1] != ':';
|
||||
at += 2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! Whether a library's name is within a module, as `sakura::analyzer` is within
|
||||
#! `sakura`.
|
||||
#! @param name The library's name.
|
||||
#! @param segments The module's path.
|
||||
#! @returns Whether it is.
|
||||
def holds(name: strview, segments: span<string>): bool {
|
||||
var at: u64 = 0;
|
||||
for &each in segments {
|
||||
val piece := each.view();
|
||||
return false if name.length - at < piece.length + 2 || name.substr(at, piece.length) != piece;
|
||||
at += piece.length;
|
||||
return false if name[at] != ':' || name[at + 1] != ':';
|
||||
at += 2;
|
||||
}
|
||||
return segments.length != 0;
|
||||
}
|
||||
|
||||
#! Whether a module's path names a library, or a folder or file within one of
|
||||
#! that module, as its first `module` line says, or holds a library. Each is
|
||||
#! looked at once.
|
||||
#! @param this The resolver.
|
||||
#! @param segments The module's path.
|
||||
#! @returns Whether it does.
|
||||
def resolver::module_exists(&mut this, segments: span<string>): bool {
|
||||
val found := this.library_for(segments) else { return this.holds_library(segments); };
|
||||
return true if segments.length == found.depth;
|
||||
var key := module_key(segments);
|
||||
if this.exists.get(&key) is some(&known) {
|
||||
return known;
|
||||
}
|
||||
var at := this.within(&found, segments);
|
||||
var named := is_folder(at.view()) && folder_of(at.view(), key.view());
|
||||
if !named {
|
||||
at.append(".sakura");
|
||||
named = is_file(at.view()) && first_module(at.view()).view() == key.view();
|
||||
}
|
||||
named = named || this.holds_library(segments);
|
||||
this.exists.set(move(&mut key), named);
|
||||
return named;
|
||||
}
|
||||
|
||||
#! A module's path as text, as `std::io`.
|
||||
#! @param segments The path's segments.
|
||||
#! @returns The text.
|
||||
def module_key(segments: span<string>): string {
|
||||
var made := string::new(nothing {});
|
||||
for i in 0..segments.length {
|
||||
if i != 0 {
|
||||
made.append("::");
|
||||
}
|
||||
made.append(segments[i].view());
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The path of a module's folder within its library, as `std/io` of `std::io`.
|
||||
#! @param this The resolver.
|
||||
#! @param found The library, and how much of the path its name is.
|
||||
#! @param segments The module's path, its library first.
|
||||
#! @returns The path.
|
||||
def resolver::within(&this, found: &shelf, segments: span<string>): string {
|
||||
var made := string::copy_of(&this.libraries[found.index].folder);
|
||||
for i in found.depth..segments.length {
|
||||
made.push('/');
|
||||
made.append(segments[i].view());
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Finds the files of a module, once: its file, as `a/b.sakura`, and those of
|
||||
#! its folder, as `a/b`, that are of the module, with the folders within it
|
||||
#! that are.
|
||||
#! @param this The resolver.
|
||||
#! @param segments The module's path.
|
||||
#! @param into Where the paths of the files not found before are added.
|
||||
def resolver::find_module(&mut this, segments: span<string>, into: &mut vector<string>): void {
|
||||
val found := this.library_for(segments) else { return; };
|
||||
return if this.libraries[found.index].whole;
|
||||
var key := module_key(segments);
|
||||
return if this.modules.get(&key) is some(_);
|
||||
this.modules.set(string::copy_of(&key), true);
|
||||
|
||||
var at := this.within(&found, segments);
|
||||
if segments.length > found.depth {
|
||||
var file := $"{at}.sakura";
|
||||
if is_file(file.view()) && first_module(file.view()).view() == key.view() {
|
||||
this.add_file(file.view(), into);
|
||||
}
|
||||
}
|
||||
if is_folder(at.view()) {
|
||||
this.find_in_folder(at.view(), key.view(), into);
|
||||
}
|
||||
}
|
||||
|
||||
#! Finds the files of a folder that are of a module, and those of the folders
|
||||
#! within it that are, each in the order of its name.
|
||||
#! @param this The resolver.
|
||||
#! @param folder The folder.
|
||||
#! @param of The module's path, as `std::io`.
|
||||
#! @param into Where the paths of the files not found before are added.
|
||||
def resolver::find_in_folder(&mut this, folder: strview, of: strview, into: &mut vector<string>): void {
|
||||
var listed := listing(folder);
|
||||
for &each in listed {
|
||||
if each.folder {
|
||||
if folder_of(each.path.view(), of) {
|
||||
this.find_in_folder(each.path.view(), of, into);
|
||||
}
|
||||
} else if first_module(each.path.view()).view() == of {
|
||||
this.add_file(each.path.view(), into);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Adds a file's path, unless it was found or read before.
|
||||
#! @param this The resolver.
|
||||
#! @param path The path.
|
||||
#! @param into Where it is added.
|
||||
def resolver::add_file(&mut this, path: strview, into: &mut vector<string>): void {
|
||||
var key := string::from(path, nothing {});
|
||||
return if this.files.get(&key) is some(_);
|
||||
this.files.set(string::copy_of(&key), true);
|
||||
into.append(move(&mut key));
|
||||
}
|
||||
|
||||
#! The names of the modules within a module of a library, by its folder, as
|
||||
#! completion offers them after `std::`, without reading their files whole,
|
||||
#! with those of the libraries within it, as `yaml` of `std::yaml`.
|
||||
#! @param libraries The libraries.
|
||||
#! @param segments The module's path, its library first.
|
||||
#! @returns The names, as `io` of `std::io`.
|
||||
pub def modules_within(libraries: span<library>, segments: span<string>): vector<string> {
|
||||
var made := vector::<string>::new();
|
||||
return made if segments.length == 0;
|
||||
|
||||
# The libraries within it give their next segments.
|
||||
val outer := module_key(segments);
|
||||
for &each in libraries {
|
||||
continue if !holds(each.name.view(), segments);
|
||||
val rest := each.name.view().substr(outer.length + 2, each.name.length - outer.length - 2);
|
||||
val next := rest.index_of(&':') else rest.length;
|
||||
val name := rest.substr(0, next);
|
||||
var known := false;
|
||||
for &each in made {
|
||||
known = known || each.view() == name;
|
||||
}
|
||||
if !known {
|
||||
made.append(string::from(name, nothing {}));
|
||||
}
|
||||
}
|
||||
|
||||
# Its library's folder gives the rest.
|
||||
var folder := string::new(nothing {});
|
||||
var deepest: u64 = 0;
|
||||
for &each in libraries {
|
||||
val depth := covered(each.name.view(), segments);
|
||||
if depth > deepest {
|
||||
folder = string::copy_of(&each.folder);
|
||||
deepest = depth;
|
||||
}
|
||||
}
|
||||
return made if folder.length == 0;
|
||||
for i in deepest..segments.length {
|
||||
folder.push('/');
|
||||
folder.append(segments[i].view());
|
||||
}
|
||||
for &each in listing(folder.view()) {
|
||||
# The name is the entry's own, less its `.sakura`.
|
||||
var name := each.path.view().substr(folder.length + 1, each.path.length - folder.length - 1);
|
||||
if !each.folder {
|
||||
name = name.substr(0, name.length - 7);
|
||||
}
|
||||
val inner := $"{outer}::{name}";
|
||||
val of := each.folder ? folder_of(each.path.view(), inner.view()) : first_module(each.path.view()).view() == inner.view();
|
||||
if of {
|
||||
made.append(string::from(name, nothing {}));
|
||||
}
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A name a folder holds: a `.sakura` file or a folder, which hidden ones are
|
||||
#! not.
|
||||
struct listed_entry {
|
||||
var path: string; #! The folder and the name joined.
|
||||
var folder: bool; #! Whether it is a folder.
|
||||
}
|
||||
|
||||
#! What a folder holds that a library is read from: its `.sakura` files and
|
||||
#! its folders, in the order of their names, so the same files are read in the
|
||||
#! same order whatever order the system lists them in.
|
||||
#! @param folder The folder.
|
||||
#! @returns What it holds.
|
||||
def listing(folder: strview): vector<listed_entry> {
|
||||
var made := vector::<listed_entry>::new();
|
||||
var at := path::parse(folder) else (_) { return made; };
|
||||
var opened := io::directory::open(&at) else (_) { return made; };
|
||||
var names := vector::<string>::new();
|
||||
var kinds := vector::<bool>::new();
|
||||
while opened.next() is some(each) {
|
||||
continue if each.name.length == 0 || each.name[0] == '.';
|
||||
var joined := $"{folder}/{each.name}";
|
||||
var is_dir := each.kind == file_kind::directory;
|
||||
if each.kind == file_kind::link {
|
||||
is_dir = is_folder(joined.view());
|
||||
}
|
||||
continue if !is_dir && !each.name.ends_with(".sakura");
|
||||
made.append(listed_entry { path = move(&mut joined), folder = is_dir });
|
||||
}
|
||||
made.sort_by(def(a: &listed_entry, b: &listed_entry): bool { return a.path.compare(b.path.view()) < 0; });
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The paths of every `.sakura` file within a folder and the folders within it,
|
||||
#! each folder's in the order of their names, as `core` is read whole.
|
||||
#! @param folder The folder.
|
||||
#! @param into Where the paths are added.
|
||||
pub def every_file(folder: strview, into: &mut vector<string>): void {
|
||||
var listed := listing(folder);
|
||||
for &mut each in listed {
|
||||
if each.folder {
|
||||
every_file(each.path.view(), into);
|
||||
} else {
|
||||
into.append(move(&mut each.path));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! How many `.sakura` files are within a folder and those within it, which is
|
||||
#! the most a program reads of it.
|
||||
#! @param folder The folder.
|
||||
#! @returns How many.
|
||||
pub def count_files(folder: strview): u64 {
|
||||
var made := vector::<string>::new();
|
||||
every_file(folder, &mut made);
|
||||
return made.length;
|
||||
}
|
||||
|
||||
#! Whether a folder holds a file of a module, or a folder within it does. Any
|
||||
#! file says, not only the first by name, so a file of a module within it, as
|
||||
#! `a/b/c.sakura` of `a::b::c` beside the files of `a::b`, hides nothing.
|
||||
#! @param folder The folder.
|
||||
#! @param of The module's path, as `std::io`.
|
||||
#! @returns Whether it does.
|
||||
def folder_of(folder: strview, of: strview): bool {
|
||||
val listed := listing(folder);
|
||||
for &each in listed {
|
||||
return true if !each.folder && first_module(each.path.view()).view() == of;
|
||||
}
|
||||
for &each in listed {
|
||||
return true if each.folder && folder_of(each.path.view(), of);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! The module of a file's first `module` or `extern module` line, read from the
|
||||
#! start of its text, past its comments and imports.
|
||||
#! @param at The file's path.
|
||||
#! @returns The module's path, as `std::io`, or empty where the file declares
|
||||
#! anything before such a line, or cannot be read.
|
||||
pub def first_module(at: strview): string {
|
||||
var found := path::parse(at) else (_) { return string::new(nothing {}); };
|
||||
var file := io::file::open(&found) else (_) { return string::new(nothing {}); };
|
||||
var buffer: u8[4096];
|
||||
val count := file.read(slice::<u8>::over((&mut buffer) as *mut u8, 4096)) else (_) { return string::new(nothing {}); };
|
||||
var text := strview::over((&buffer) as *u8, count);
|
||||
var made := module_named(text);
|
||||
# A file whose first lines run past what was read is read whole.
|
||||
if made.length == 0 && count == 4096 {
|
||||
var whole := io::read_file(&found) else (_) { return made; };
|
||||
made = module_named(whole.view());
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The module the first `module` or `extern module` line of a text names, past
|
||||
#! its comments, imports, and `extern import` lines.
|
||||
#! @param text The text.
|
||||
#! @returns The module's path, or empty where none comes first.
|
||||
def module_named(text: strview): string {
|
||||
var at: u64 = 0;
|
||||
while at < text.length {
|
||||
val byte := text[at];
|
||||
if byte == ' ' || byte == '\t' || byte == '\r' || byte == '\n' {
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
if byte == '#' {
|
||||
while at < text.length && text[at] != '\n' { at++; }
|
||||
continue;
|
||||
}
|
||||
var word := word_at(text, at);
|
||||
if word == "extern" {
|
||||
at += word.length;
|
||||
while at < text.length && (text[at] == ' ' || text[at] == '\t') { at++; }
|
||||
word = word_at(text, at);
|
||||
}
|
||||
if word == "import" {
|
||||
while at < text.length && text[at] != ';' { at++; }
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
break if word != "module";
|
||||
at += word.length;
|
||||
while at < text.length && (text[at] == ' ' || text[at] == '\t') { at++; }
|
||||
val start := at;
|
||||
while at < text.length && (text[at].is_alnum || text[at] == '_' || text[at] == ':') { at++; }
|
||||
return string::from(text.substr(start, at - start), nothing {});
|
||||
}
|
||||
return string::new(nothing {});
|
||||
}
|
||||
|
||||
#! The word, letters, digits, and underscores, beginning at a place of a text.
|
||||
#! @param text The text.
|
||||
#! @param at The place.
|
||||
#! @returns The word, which is empty where none begins there.
|
||||
def word_at(text: strview, at: u64): strview {
|
||||
var end := at;
|
||||
while end < text.length && (text[end].is_alnum || text[end] == '_') { end++; }
|
||||
return text.substr(at, end - at);
|
||||
}
|
||||
|
||||
#! Whether a path names a file, following a link it ends in.
|
||||
#! @param at The path.
|
||||
#! @returns Whether it does.
|
||||
def is_file(at: strview): bool {
|
||||
var found := path::parse(at) else (_) { return false; };
|
||||
val info := io::info(&found) else (_) { return false; };
|
||||
return info.kind == file_kind::regular;
|
||||
}
|
||||
|
||||
#! Whether a path names a folder, following a link it ends in.
|
||||
#! @param at The path.
|
||||
#! @returns Whether it does.
|
||||
def is_folder(at: strview): bool {
|
||||
var found := path::parse(at) else (_) { return false; };
|
||||
val info := io::info(&found) else (_) { return false; };
|
||||
return info.kind == file_kind::directory;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
#! @file lines.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains `lines`, where each line of a source begins, and `place`, the line
|
||||
#! and column an offset within the source is at.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
#! Defines a place within a source file.
|
||||
#!
|
||||
#! This is useful for diagnostics and debugging, especially within something
|
||||
#! like a language server protocol.
|
||||
pub struct place {
|
||||
pub val line: u32; #! The line, counted from 1.
|
||||
pub val column: u32; #! The byte within the line, counted from 1.
|
||||
}
|
||||
|
||||
#! Stores the starting offsets of the lines of a given source file.
|
||||
#!
|
||||
#! The length of the `starts` vector is the number of lines in the file and then
|
||||
#! the value at a given line (index) is the offset within the file that the line
|
||||
#! starts.
|
||||
pub type lines = vector<u32>;
|
||||
|
||||
#! Provides the place of a given offset within some source code.
|
||||
#!
|
||||
#! This is a binary search that will seek out a specific line and then mark the
|
||||
#! column within the line, given the offset. Lines are stored in order by their
|
||||
#! offset within the file, so the length of the `starts` vector is the number of
|
||||
#! lines in the file and the value at that index is the offset within the file.
|
||||
#! The line is the last starting at or before the offset, the one before the
|
||||
#! first starting after it; the first line starts at 0, so there is always one.
|
||||
#! @param this The lines structure to get the place of an offset.
|
||||
#! @param offset The offset from the file to get the place of.
|
||||
#! @returns The line and column of the given offset for a given file.
|
||||
pub def lines::place_of(&this, offset: u32): place {
|
||||
val low := this.view().upper_bound(&offset) - 1;
|
||||
return place {
|
||||
line = (low + 1) as u32,
|
||||
column = offset - this[low] + 1
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
#! @file names.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the table of names, which gives every word written in a source an
|
||||
#! ID of its own. The keywords are given theirs first, so a keyword's ID is its
|
||||
#! token kind, and the reserved words and the words the parser knows by ID
|
||||
#! follow them, in the order their lists give.
|
||||
|
||||
import std::containers;
|
||||
module sakura::analyzer;
|
||||
|
||||
#! Responsible for keeping and tracking the names of non-punctuator tokens of
|
||||
#! a given, or multiple, source code file(s).
|
||||
#!
|
||||
#! Each name's text is copied into a block of names, so a name outlives the
|
||||
#! source it was first read in, as one an editor replaces does. A block is
|
||||
#! filled but never grown, so a name's text stays where it was copied, and its
|
||||
#! view, by its ID, is good for as long as the table is. A name is found by its
|
||||
#! text through the IDs of its hash, comparing only those whose hash shares its
|
||||
#! top half, and those by their length before their bytes.
|
||||
pub struct names {
|
||||
var views: vector<strview>; #! The text of each name, by its ID, where a block holds it.
|
||||
var blocks: vector<string>; #! The blocks the texts are copied into, the last being filled.
|
||||
var index: id_index; #! The names of each hash, which finding a name's ID by its text walks.
|
||||
}
|
||||
|
||||
#! How many bytes a block of names holds, but for one of a name longer than a
|
||||
#! sixteenth of that, which is a block of its own.
|
||||
const names::block_size: u64 = 16384;
|
||||
|
||||
#! Makes a new instance of the `names` structure to be used by the various
|
||||
#! stages of the Sakura analyzer.
|
||||
#! @returns The created names instance pre-containing the language keywords.
|
||||
pub def names::new(): names {
|
||||
var made := names {
|
||||
views = vector::<strview>::new(),
|
||||
blocks = vector::<string>::new(),
|
||||
index = id_index::new()
|
||||
};
|
||||
made.views.reserve(512);
|
||||
|
||||
# The lexer reads a keyword's ID as its token kind, so a list out of step with
|
||||
# `tk` stops here rather than lexing one word as another.
|
||||
for &word in _keywords {
|
||||
val id := made.intern(word.text);
|
||||
expects(id == word.kind as u32);
|
||||
}
|
||||
|
||||
# The parser knows these words by where they are interned, which a word listed
|
||||
# twice would move.
|
||||
for &word in _reserved { made.intern(word); }
|
||||
for &word in _words { made.intern(word); }
|
||||
|
||||
# The checker knows these by their members of `word`, which follow those.
|
||||
for &each in _known {
|
||||
expects(made.intern(each.text) == each.id);
|
||||
}
|
||||
expects(made.intern("this") == names::this_id);
|
||||
expects(made.intern("get") == names::get_id);
|
||||
expects(made.intern("set") == names::set_id);
|
||||
expects(made.intern("type_of") == names::type_of_id);
|
||||
expects(made.intern("old") == names::old_id);
|
||||
expects(made.intern("self") == names::self_id);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Maps names that are seen in the source code to a specific integer to reduce
|
||||
#! copies and save memory.
|
||||
#! @param this The names instance to copy the name into.
|
||||
#! @param text The name to copy and mark by an ID.
|
||||
#! @returns The newly created ID or an existing ID for the given name.
|
||||
pub def names::intern(&mut this, text: &strview): u32 {
|
||||
val hash := text.hash();
|
||||
var walk := this.index.walk(hash);
|
||||
var at := this.index.next(&mut walk);
|
||||
while at != 0 {
|
||||
return at - 1 if same_text(this.views[at - 1], text);
|
||||
at = this.index.next(&mut walk);
|
||||
}
|
||||
|
||||
val id := this.views.length as u32;
|
||||
this.views.append(this.copy_text(text));
|
||||
this.index.add(hash, id);
|
||||
return id;
|
||||
}
|
||||
|
||||
# A copy of a name's text in a block, which a new block is made for where the
|
||||
# last has no room, or where the name is long.
|
||||
def names::copy_text(&mut this, text: strview): strview {
|
||||
if text.length * 16 > names::block_size {
|
||||
this.blocks.append(string::from(text, nothing {}));
|
||||
return this.blocks.last().view();
|
||||
}
|
||||
if this.blocks.length == 0 || this.blocks.last().length + text.length > this.blocks.last().capacity {
|
||||
var made := string::new(nothing {});
|
||||
made.reserve(names::block_size);
|
||||
this.blocks.append(move(&mut made));
|
||||
}
|
||||
val block := &mut this.blocks.last();
|
||||
val at := block.length;
|
||||
block.append(text);
|
||||
return strview::over(block.view().data + at, text.length);
|
||||
}
|
||||
|
||||
# Whether two texts are the same, their lengths first, then their bytes, a
|
||||
# word at a time, the last word ending where they do, so a text of a few
|
||||
# words is compared in as many loads, as `hash_bytes` reads one.
|
||||
@inline
|
||||
def same_text(a: strview, b: strview): bool {
|
||||
val count := a.length;
|
||||
return false if count != b.length;
|
||||
val x := a.data;
|
||||
val y := b.data;
|
||||
if count >= 8 {
|
||||
var at: u64 = 0;
|
||||
while at + 8 < count {
|
||||
return false if *((x + at) as *u64) != *((y + at) as *u64);
|
||||
at += 8;
|
||||
}
|
||||
return *((x + count - 8) as *u64) == *((y + count - 8) as *u64);
|
||||
}
|
||||
if count >= 4 {
|
||||
return *(x as *u32) == *(y as *u32) && *((x + count - 4) as *u32) == *((y + count - 4) as *u32);
|
||||
}
|
||||
if count >= 2 {
|
||||
return *(x as *u16) == *(y as *u16) && *((x + count - 2) as *u16) == *((y + count - 2) as *u16);
|
||||
}
|
||||
return count == 0 || x[0] == y[0];
|
||||
}
|
||||
|
||||
#! The text of the name of the ID.
|
||||
#! @param this The table of names.
|
||||
#! @param id The name's ID.
|
||||
#! @returns The text, which lives as long as the table does.
|
||||
pub def names::text(&this, id: u32): strview {
|
||||
return this.views[id];
|
||||
}
|
||||
|
||||
#! How many names there are.
|
||||
#! @param this The table of names.
|
||||
#! @returns The number of names, which is one more than the newest's ID.
|
||||
pub val names::count: u64 { get => this.views.length; }
|
||||
|
||||
#! Whether a name is one of the language's keywords.
|
||||
#! @param this The table of names.
|
||||
#! @param id The name's ID.
|
||||
#! @returns Whether it is.
|
||||
pub def names::is_keyword(&this, id: u32): bool {
|
||||
return id >= tk::kw_beg && id <= tk::kw_end;
|
||||
}
|
||||
|
||||
#! Determines if the given ID corresponds to one of the language reserved words.
|
||||
#! @param this The names instance to compare against.
|
||||
#! @param id The ID of the name to check.
|
||||
#! @returns Whether the ID belongs to a reserved word.
|
||||
pub def names::is_reserved(&this, id: u32): bool {
|
||||
return id >= names::this_id && id < names::get_id;
|
||||
}
|
||||
|
||||
#! A keyword, and the token kind it lexes as.
|
||||
struct names::keyword {
|
||||
val text: strview;
|
||||
val kind: tk;
|
||||
}
|
||||
|
||||
const _keywords: names::keyword[31] = [
|
||||
names::keyword { text = "import", kind = tk::kw_imp },
|
||||
names::keyword { text = "module", kind = tk::kw_mod },
|
||||
names::keyword { text = "extern", kind = tk::kw_extern },
|
||||
names::keyword { text = "pub", kind = tk::kw_pub },
|
||||
names::keyword { text = "const", kind = tk::kw_const },
|
||||
names::keyword { text = "var", kind = tk::kw_var },
|
||||
names::keyword { text = "val", kind = tk::kw_val },
|
||||
names::keyword { text = "def", kind = tk::kw_def },
|
||||
names::keyword { text = "mut", kind = tk::kw_mut },
|
||||
names::keyword { text = "return", kind = tk::kw_ret },
|
||||
names::keyword { text = "if", kind = tk::kw_if },
|
||||
names::keyword { text = "else", kind = tk::kw_else },
|
||||
names::keyword { text = "for", kind = tk::kw_for },
|
||||
names::keyword { text = "in", kind = tk::kw_in },
|
||||
names::keyword { text = "while", kind = tk::kw_while },
|
||||
names::keyword { text = "break", kind = tk::kw_break },
|
||||
names::keyword { text = "continue", kind = tk::kw_cont },
|
||||
names::keyword { text = "type", kind = tk::kw_type },
|
||||
names::keyword { text = "enum", kind = tk::kw_enum },
|
||||
names::keyword { text = "struct", kind = tk::kw_struct },
|
||||
names::keyword { text = "union", kind = tk::kw_union },
|
||||
names::keyword { text = "trait", kind = tk::kw_trait },
|
||||
names::keyword { text = "as", kind = tk::kw_as },
|
||||
names::keyword { text = "is", kind = tk::kw_is },
|
||||
names::keyword { text = "not", kind = tk::kw_not },
|
||||
names::keyword { text = "match", kind = tk::kw_match },
|
||||
names::keyword { text = "when", kind = tk::kw_when },
|
||||
names::keyword { text = "where", kind = tk::kw_where },
|
||||
names::keyword { text = "true", kind = tk::kw_true },
|
||||
names::keyword { text = "false", kind = tk::kw_false },
|
||||
names::keyword { text = "null", kind = tk::kw_null },
|
||||
];
|
||||
|
||||
# Words that name what the language gives, which nothing may declare. `this`
|
||||
# comes first, which the parser knows by ID.
|
||||
const _reserved: strview[18] = [
|
||||
"this", "bool", "int", "uint", "float", "i8", "i16", "i32", "i64",
|
||||
"u8", "u16", "u32", "u64", "f32", "f64", "void", "self", "_"
|
||||
];
|
||||
|
||||
# Identifiers the grammar gives a meaning in one place each, which stay names
|
||||
# everywhere else, so the parser knows them by ID.
|
||||
const _words: strview[9] = [
|
||||
"get", "set", "type_of", "expects", "asserts", "ensures", "old", "undefined", "value"
|
||||
];
|
||||
|
||||
#! The IDs of the names the parser reads as words, by where `names::new` interns
|
||||
#! them: the reserved words right after the keywords, then `_words`.
|
||||
pub const names::this_id: u32 = tk::kw_end as u32 + 1; #! `this`.
|
||||
pub const names::get_id: u32 = names::this_id + _reserved.length as u32; #! `get`.
|
||||
pub const names::set_id: u32 = names::get_id + 1; #! `set`.
|
||||
pub const names::type_of_id: u32 = names::get_id + 2; #! `type_of`.
|
||||
pub const names::expects_id: u32 = names::get_id + 3; #! `expects`, a contract at a statement's start.
|
||||
pub const names::asserts_id: u32 = names::get_id + 4; #! `asserts`, a contract at a statement's start.
|
||||
pub const names::ensures_id: u32 = names::get_id + 5; #! `ensures`, a contract at a statement's start.
|
||||
pub const names::old_id: u32 = names::get_id + 6; #! `old`, an earlier value within an `ensures`.
|
||||
pub const names::undefined_id: u32 = names::get_id + 7; #! `undefined`, a variable's value that opts out of zeroing.
|
||||
pub const names::value_id: u32 = names::get_id + 8; #! `value`, what a `set` is given.
|
||||
pub const names::self_id: u32 = names::this_id + 16; #! `self`, among the reserved words.
|
||||
pub const names::underscore_id: u32 = names::this_id + 17; #! `_`, the last of the reserved words.
|
||||
|
||||
#! The words the checker knows by ID, which `names::new` interns after the
|
||||
#! parser's, in this order, so each is a constant. A member's name is its word.
|
||||
pub enum word : u32 {
|
||||
std = names::value_id + 1, #! `std`.
|
||||
core, #! `core`, the library of the language's own, whose root every file sees.
|
||||
system, #! `system`, the library of the platforms.
|
||||
string, #! `string`.
|
||||
strview, #! `strview`.
|
||||
span, #! `span`.
|
||||
simd, #! `simd`.
|
||||
mask, #! `mask`.
|
||||
slice, #! `slice`.
|
||||
maybe, #! `maybe`.
|
||||
result, #! `result`.
|
||||
nothing, #! `nothing`.
|
||||
equatable, #! `equatable`.
|
||||
ordered, #! `ordered`.
|
||||
numeric, #! `numeric`.
|
||||
integer, #! `integer`.
|
||||
ordinal, #! `ordinal`.
|
||||
real, #! `real`.
|
||||
hashable, #! `hashable`.
|
||||
owning, #! `owning`.
|
||||
closeable, #! `closeable`.
|
||||
zeroable, #! `zeroable`.
|
||||
lockfree, #! `lockfree`.
|
||||
pointer, #! `pointer`.
|
||||
copyable, #! `copyable`.
|
||||
moveable, #! `moveable`.
|
||||
indexable, #! `indexable`.
|
||||
signature, #! `signature`.
|
||||
params, #! `params`.
|
||||
invokable, #! `invokable`.
|
||||
invoke, #! `invoke`.
|
||||
iterable, #! `iterable`.
|
||||
iterator, #! `iterator`.
|
||||
range, #! `range`.
|
||||
attribute, #! `attribute`.
|
||||
usage, #! `usage`.
|
||||
optional, #! `optional`.
|
||||
intrinsic, #! `intrinsic`.
|
||||
foreign, #! `foreign`, an attribute C's declarations no longer take.
|
||||
link, #! `link`, an attribute C's declarations no longer take.
|
||||
nodiscard, #! `nodiscard`.
|
||||
allow, #! `allow`.
|
||||
inline, #! `inline`.
|
||||
cfn, #! `cfn`.
|
||||
equals, #! `equals`.
|
||||
hash, #! `hash`.
|
||||
compare, #! `compare`.
|
||||
add, #! `add`.
|
||||
sub, #! `sub`.
|
||||
mul, #! `mul`.
|
||||
div, #! `div`.
|
||||
rem, #! `rem`.
|
||||
negate, #! `negate`.
|
||||
bit_and, #! `bit_and`.
|
||||
bit_or, #! `bit_or`.
|
||||
bit_xor, #! `bit_xor`.
|
||||
bit_not, #! `bit_not`.
|
||||
shift_left, #! `shift_left`.
|
||||
shift_right, #! `shift_right`.
|
||||
add_assign, #! `add_assign`, which `+=` calls where a type has it.
|
||||
sub_assign, #! `sub_assign`.
|
||||
mul_assign, #! `mul_assign`.
|
||||
div_assign, #! `div_assign`.
|
||||
rem_assign, #! `rem_assign`.
|
||||
bit_and_assign, #! `bit_and_assign`.
|
||||
bit_or_assign, #! `bit_or_assign`.
|
||||
bit_xor_assign, #! `bit_xor_assign`.
|
||||
shift_left_assign, #! `shift_left_assign`.
|
||||
shift_right_assign, #! `shift_right_assign`.
|
||||
close, #! `close`.
|
||||
at, #! `at`.
|
||||
iter, #! `iter`.
|
||||
next, #! `next`.
|
||||
next_back, #! `next_back`.
|
||||
length, #! `length`.
|
||||
data, #! `data`.
|
||||
view, #! `view`.
|
||||
main, #! `main`.
|
||||
some, #! `some`.
|
||||
none, #! `none`.
|
||||
error, #! `error`.
|
||||
os, #! `os`.
|
||||
arch, #! `arch`.
|
||||
backend, #! `backend`.
|
||||
}
|
||||
|
||||
#! A word the checker knows, and its member of `word`.
|
||||
struct names::known {
|
||||
val text: strview;
|
||||
val id: word;
|
||||
}
|
||||
|
||||
# The text of each word the checker knows, which is its member's name, listed
|
||||
# as `word` lists them, so `names::new` stops where the two are out of step.
|
||||
const _known: names::known[84] = [
|
||||
names::known { text = "std", id = word::std },
|
||||
names::known { text = "core", id = word::core },
|
||||
names::known { text = "system", id = word::system },
|
||||
names::known { text = "string", id = word::string },
|
||||
names::known { text = "strview", id = word::strview },
|
||||
names::known { text = "span", id = word::span },
|
||||
names::known { text = "simd", id = word::simd },
|
||||
names::known { text = "mask", id = word::mask },
|
||||
names::known { text = "slice", id = word::slice },
|
||||
names::known { text = "maybe", id = word::maybe },
|
||||
names::known { text = "result", id = word::result },
|
||||
names::known { text = "nothing", id = word::nothing },
|
||||
names::known { text = "equatable", id = word::equatable },
|
||||
names::known { text = "ordered", id = word::ordered },
|
||||
names::known { text = "numeric", id = word::numeric },
|
||||
names::known { text = "integer", id = word::integer },
|
||||
names::known { text = "ordinal", id = word::ordinal },
|
||||
names::known { text = "real", id = word::real },
|
||||
names::known { text = "hashable", id = word::hashable },
|
||||
names::known { text = "owning", id = word::owning },
|
||||
names::known { text = "closeable", id = word::closeable },
|
||||
names::known { text = "zeroable", id = word::zeroable },
|
||||
names::known { text = "lockfree", id = word::lockfree },
|
||||
names::known { text = "pointer", id = word::pointer },
|
||||
names::known { text = "copyable", id = word::copyable },
|
||||
names::known { text = "moveable", id = word::moveable },
|
||||
names::known { text = "indexable", id = word::indexable },
|
||||
names::known { text = "signature", id = word::signature },
|
||||
names::known { text = "params", id = word::params },
|
||||
names::known { text = "invokable", id = word::invokable },
|
||||
names::known { text = "invoke", id = word::invoke },
|
||||
names::known { text = "iterable", id = word::iterable },
|
||||
names::known { text = "iterator", id = word::iterator },
|
||||
names::known { text = "range", id = word::range },
|
||||
names::known { text = "attribute", id = word::attribute },
|
||||
names::known { text = "usage", id = word::usage },
|
||||
names::known { text = "optional", id = word::optional },
|
||||
names::known { text = "intrinsic", id = word::intrinsic },
|
||||
names::known { text = "foreign", id = word::foreign },
|
||||
names::known { text = "link", id = word::link },
|
||||
names::known { text = "nodiscard", id = word::nodiscard },
|
||||
names::known { text = "allow", id = word::allow },
|
||||
names::known { text = "inline", id = word::inline },
|
||||
names::known { text = "cfn", id = word::cfn },
|
||||
names::known { text = "equals", id = word::equals },
|
||||
names::known { text = "hash", id = word::hash },
|
||||
names::known { text = "compare", id = word::compare },
|
||||
names::known { text = "add", id = word::add },
|
||||
names::known { text = "sub", id = word::sub },
|
||||
names::known { text = "mul", id = word::mul },
|
||||
names::known { text = "div", id = word::div },
|
||||
names::known { text = "rem", id = word::rem },
|
||||
names::known { text = "negate", id = word::negate },
|
||||
names::known { text = "bit_and", id = word::bit_and },
|
||||
names::known { text = "bit_or", id = word::bit_or },
|
||||
names::known { text = "bit_xor", id = word::bit_xor },
|
||||
names::known { text = "bit_not", id = word::bit_not },
|
||||
names::known { text = "shift_left", id = word::shift_left },
|
||||
names::known { text = "shift_right", id = word::shift_right },
|
||||
names::known { text = "add_assign", id = word::add_assign },
|
||||
names::known { text = "sub_assign", id = word::sub_assign },
|
||||
names::known { text = "mul_assign", id = word::mul_assign },
|
||||
names::known { text = "div_assign", id = word::div_assign },
|
||||
names::known { text = "rem_assign", id = word::rem_assign },
|
||||
names::known { text = "bit_and_assign", id = word::bit_and_assign },
|
||||
names::known { text = "bit_or_assign", id = word::bit_or_assign },
|
||||
names::known { text = "bit_xor_assign", id = word::bit_xor_assign },
|
||||
names::known { text = "shift_left_assign", id = word::shift_left_assign },
|
||||
names::known { text = "shift_right_assign", id = word::shift_right_assign },
|
||||
names::known { text = "close", id = word::close },
|
||||
names::known { text = "at", id = word::at },
|
||||
names::known { text = "iter", id = word::iter },
|
||||
names::known { text = "next", id = word::next },
|
||||
names::known { text = "next_back", id = word::next_back },
|
||||
names::known { text = "length", id = word::length },
|
||||
names::known { text = "data", id = word::data },
|
||||
names::known { text = "view", id = word::view },
|
||||
names::known { text = "main", id = word::main },
|
||||
names::known { text = "some", id = word::some },
|
||||
names::known { text = "none", id = word::none },
|
||||
names::known { text = "error", id = word::error },
|
||||
names::known { text = "os", id = word::os },
|
||||
names::known { text = "arch", id = word::arch },
|
||||
names::known { text = "backend", id = word::backend },
|
||||
];
|
||||
@@ -0,0 +1,136 @@
|
||||
#! @file node.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the node of a syntax tree, as gathered from a `syntax`, with `nk`,
|
||||
#! the kinds of node, and `nf`, the flags a node may hold.
|
||||
module sakura::analyzer;
|
||||
|
||||
#! A node of a syntax tree: its kind, the token it says what it is by, its two
|
||||
#! slots, and the last token of what it was parsed from.
|
||||
#!
|
||||
#! A syntax keeps each field of its nodes in a vector of its own, and this is
|
||||
#! the value `syntax::node` gathers from them. What the slots hold is what the
|
||||
#! kind's shape says. Node 0 stands for no node, wherever an index may be
|
||||
#! absent.
|
||||
pub struct node {
|
||||
val kind: nk; #! Its kind.
|
||||
val token: u32; #! The token it says what it is by.
|
||||
val left: u32; #! Its first slot, which its shape says the meaning of.
|
||||
val right: u32; #! Its second slot.
|
||||
val end: u32; #! The last token of what it was parsed from.
|
||||
}
|
||||
|
||||
#! Defines the different types of nodes.
|
||||
#!
|
||||
#! What the `left` and `right` of each kind hold is described by its entry in
|
||||
#! `shapes`, which lists the kinds in this order. `count` is not a kind: it is
|
||||
#! how many there are, which sizes that table.
|
||||
pub enum nk : u8 {
|
||||
# Structure
|
||||
error, #! Where the parser made no sense of the source, holding what it did parse. Also node 0, which stands for "no node" wherever an index may be absent.
|
||||
document, #! A file, whose run is its declarations.
|
||||
block, #! A block, whose run is its statements.
|
||||
|
||||
# Declarations
|
||||
import_decl, #! `import`, of the module's `path`.
|
||||
module_decl, #! `module`, of its `path` and any `when` condition.
|
||||
extern_import, #! `extern import`, of the library's `string` and any `when` condition.
|
||||
extern_module, #! `extern module`, of its `path` and any `when` condition: a section whose functions without a body, structs, and unions are C's.
|
||||
when_block, #! At the top level, of declarations, or within a function, of statements.
|
||||
function, #! A function, with its record and flags.
|
||||
param, #! A parameter: its type, and a record of its default and flags.
|
||||
variable, #! A variable or constant, with its record and flags.
|
||||
field, #! A field of a struct or union, with its record and flags.
|
||||
spread, #! A struct spread into another, as `...pair`, with its renames.
|
||||
rename, #! A field a spread renames: its token the old name, and the node the new.
|
||||
property, #! A property, with its record and its accessors.
|
||||
accessor, #! A property's `get` or `set`: its parameters, and a record of its body and flags.
|
||||
struct_decl, #! A struct, with its record and fields.
|
||||
union_decl, #! A union, with its record and fields.
|
||||
trait_decl, #! A trait, with its record and members.
|
||||
assoc_type, #! A trait's associated type, with its record and default.
|
||||
enumeration, #! An enum, with its record and members.
|
||||
enumerator, #! A member of an enum: its attributes and its value.
|
||||
alias, #! A type alias, with its record and the type it aliases.
|
||||
attribute, #! An attribute: its `type_name` and its field inits.
|
||||
type_param, #! A type parameter: its bounds, and whether it is a pack.
|
||||
const_param, #! A constant parameter, `const N: u64`: its bounds, which it may not have, and its type.
|
||||
type_pattern, #! A pattern parameter, `def(Ts...): R`: the type parameters its parameter types name, and the one its result names.
|
||||
array_pattern, #! A pattern parameter, `L[N]`: the type parameter its element is, and the constant parameter its length is.
|
||||
|
||||
# Types
|
||||
segment, #! A segment of a type's name, with its type arguments or parameters.
|
||||
type_name, #! A type's name, as its segments.
|
||||
type_ref, #! A reference type: what it refers to, and whether it writes.
|
||||
type_ptr, #! A pointer type: what it points at, and whether it writes.
|
||||
type_fixed, #! A fixed array type: its element, and its length.
|
||||
type_func, #! A function type: its parameter types, and its result.
|
||||
type_spread, #! `T...`: a function type's variadic last parameter, or a pack passed on among type arguments.
|
||||
type_of, #! `type_of(d)`, the type a declaration of reflection names.
|
||||
|
||||
# Statements
|
||||
if_stmt, #! `if`: its condition, and a record of its branches.
|
||||
if_const, #! `if const`: its condition, and a record of its branches.
|
||||
while_stmt, #! `while`: its condition and body.
|
||||
for_stmt, #! `for`, with its record and body.
|
||||
match_stmt, #! A `match` statement: its subject and arms.
|
||||
match_arm, #! An arm of a match: its patterns, which are none for `else`, and its body.
|
||||
return_stmt, #! `return`, with the value it gives.
|
||||
break_stmt, #! `break`.
|
||||
continue_stmt, #! `continue`.
|
||||
expr_stmt, #! An expression as a statement.
|
||||
contract, #! `expects`, `asserts`, or `ensures`: its condition, and a record of the name it gives what is returned, its text, and which it is.
|
||||
|
||||
# Expressions
|
||||
name, #! A name, which its token is.
|
||||
path, #! A path of segments, as `std::io`.
|
||||
number, #! A number, which its token is.
|
||||
character, #! A character, which its token is.
|
||||
string, #! Text, which its token is.
|
||||
istring, #! Interpolated text: its pieces of text and its holes.
|
||||
boolean, #! `true` or `false`.
|
||||
null_lit, #! `null`.
|
||||
unary, #! A prefix operator, its token, on its operand: also `*p` and `...xs`.
|
||||
postfix, #! `++` or `--` after their operand.
|
||||
reference, #! `&` or `&mut` before their operand.
|
||||
binary, #! A binary operator, its token, on its left and right.
|
||||
assign, #! An assignment, plain or compound: its target and value.
|
||||
ternary, #! `c ? a : b`: its condition, and a record of its branches.
|
||||
fallback, #! `x else y`: its value, and a record of its error's name and the fallback.
|
||||
call, #! A call: its callee and arguments.
|
||||
type_args, #! A value given type arguments after it, as `value_of(d)::<i64>`.
|
||||
index, #! `x[i]`: its object and index.
|
||||
slice, #! `x[a:b]`: its object, and a record of its start and count.
|
||||
member, #! `x.name`, with any type arguments.
|
||||
member_of, #! `x.(d)`: its object and the declaration of reflection.
|
||||
cast, #! `x as T`: its value and type.
|
||||
is_test, #! `x is T`, which is a bound test where `x` names a type, as `T is copyable`.
|
||||
construct, #! A struct literal: its `type_name` and field inits.
|
||||
field_init, #! A field given in a struct literal, whose token is the field where it is named.
|
||||
array, #! An array literal, as its elements.
|
||||
lambda, #! An anonymous function: its parameters, and a record of its result and body.
|
||||
match_value, #! A `match` used as a value: its subject and arms.
|
||||
range, #! `a..b`, or `a..=b` where its token is `..=`: its start and end.
|
||||
old_value, #! `old(e)` within an `ensures`: what `e` was where the `ensures` was reached.
|
||||
undefined, #! `undefined` as a variable's value: its memory left as it is, which nothing zeroes.
|
||||
|
||||
count, #! How many kinds there are, which sizes `shapes`; not a kind itself.
|
||||
}
|
||||
|
||||
#! The bits a node's `flags` slot holds, where its kind has one.
|
||||
pub enum nf : u32 {
|
||||
exported = 0x0001, #! `pub`.
|
||||
mutable = 0x0002, #! `var`, `&mut`, `*mut`, `&mut this`, and `for &mut x`.
|
||||
constant = 0x0004, #! `const`, `const def`, and `for const`.
|
||||
reference = 0x0008, #! `for &x`.
|
||||
variadic = 0x0010, #! A parameter `name: T...`.
|
||||
packed = 0x0020, #! A type parameter `Ts...`.
|
||||
negated = 0x0040, #! `is not`.
|
||||
computed = 0x0080, #! `x is (d)`.
|
||||
function = 0x0100, #! A local declared with `def`, whose value is a `lambda`.
|
||||
named = 0x0200, #! A `field_init` naming its field, as `x = 1`.
|
||||
inclusive = 0x0400, #! A `for` loop's range written `a..=b`, which includes its end.
|
||||
implied = 0x0800, #! A parameter of an accessor the syntax leaves out: `this` of a `get` or `set`, and a `set`'s `value`.
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
#! @file note.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains `note`, a diagnostic the lexer, parser, or checker makes of what is
|
||||
#! wrong with a file, the message it reads as, and `note_sink`, where each of
|
||||
#! them puts the notes it makes.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! A diagnostic reported while including or checking source files.
|
||||
#!
|
||||
#! It holds its text, so it is good for as long as it is kept, whatever made
|
||||
#! it, and it has one owner: it is moved, as from where it was made to where it
|
||||
#! is kept, rather than copied. This information can be used to present
|
||||
#! warnings and errors for source code that failed stages of compilation.
|
||||
pub struct note {
|
||||
pub var file: u32; #! The index of the file it is about.
|
||||
pub var offset: u32; #! Where what it is about begins in the source text.
|
||||
pub var length: u32; #! How many bytes of the source text it is about, for underlining them.
|
||||
pub var code: ec; #! What kind of mistake it is about.
|
||||
pub var warning: bool; #! Whether it is a warning, which never stops a program, rather than an error.
|
||||
var detail: string; #! What it says.
|
||||
var found: bool; #! Whether it says what was expected, so the text it is about was found instead.
|
||||
var lexed: bool; #! Whether the lexer made it, rather than the parser.
|
||||
|
||||
# The instance of a generic the checker found it in, as "In `max<u8>`", which
|
||||
# is empty where it was found in what was written.
|
||||
pub var instance: string; #! The instance of a generic it was found in, as "In `max<u8>`", or empty.
|
||||
|
||||
# A place the note refers to besides its own, as where a name was first
|
||||
# declared, and what it says of it. Its detail is empty where there is none.
|
||||
pub var related_file: u32; #! The file of a place it refers to besides its own.
|
||||
pub var related_offset: u32; #! Where that place begins.
|
||||
pub var related_length: u32; #! How many bytes it covers.
|
||||
pub var related: string; #! What it says of that place, or empty where there is none.
|
||||
|
||||
# The declaration the checker found it checking, whose notes are made again
|
||||
# where it is checked again, or 0.
|
||||
var origin: u32; #! The declaration being checked where it was made, or 0.
|
||||
}
|
||||
|
||||
#! What the note says, with what was found where it expected something else, as
|
||||
#! "Expected `;` after the statement. Found `}`."
|
||||
#! @param this The note.
|
||||
#! @param source The source the note is about.
|
||||
#! @returns The message.
|
||||
pub def note::message(&this, source: &source): string {
|
||||
var made := string::copy_of(&this.detail);
|
||||
return made if !this.found;
|
||||
|
||||
if this.length == 0 {
|
||||
made.append(" Found the end of the file.");
|
||||
return made;
|
||||
}
|
||||
|
||||
made.append(" Found `");
|
||||
made.append(source.make_lexeme(this.offset, this.length));
|
||||
made.append("`.");
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Where the lexer, the parser, or the checker puts the notes it makes: kept in
|
||||
#! a vector of notes, or handed to what hears them as they are made, up to the
|
||||
#! most notes it makes.
|
||||
#!
|
||||
#! A note is admitted before it is made, which counts it, so one past the limit
|
||||
#! is never made at all, nor its text copied; one admitted is then given, to
|
||||
#! what hears notes where something does, or kept.
|
||||
pub struct note_sink {
|
||||
var notes: &mut vector<note>; #! Where notes are kept, where nothing hears them.
|
||||
pub var heard: maybe<def(&mut note): void>; #! What hears each note as it is made, which may move it, as where another thread reports them, or nothing.
|
||||
pub var count: u32; #! How many notes were made, which `limit` bounds.
|
||||
val limit: u32; #! The most notes made.
|
||||
}
|
||||
|
||||
#! Makes a sink keeping notes in `notes`, which nothing hears yet.
|
||||
#! @param notes Where the notes are kept.
|
||||
#! @param limit The most notes made.
|
||||
#! @returns The sink.
|
||||
pub def note_sink::new(notes: &mut vector<note>, limit: u32): note_sink {
|
||||
return note_sink {
|
||||
notes = notes,
|
||||
limit = limit
|
||||
};
|
||||
}
|
||||
|
||||
#! Whether as many notes were made as the limit allows.
|
||||
#! @param this The sink.
|
||||
#! @returns Whether they were.
|
||||
pub val note_sink::full: bool { get => this.count >= this.limit; }
|
||||
|
||||
#! Counts a note about to be made, unless as many were made as the limit allows.
|
||||
#! @param this The sink.
|
||||
#! @returns Whether the note is to be made.
|
||||
pub def note_sink::admits(&mut this): bool {
|
||||
return false if this.count >= this.limit;
|
||||
this.count++;
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Gives a note admitted to what hears notes, or keeps it where nothing does.
|
||||
#! @param this The sink.
|
||||
#! @param made The note, which is moved from.
|
||||
pub def note_sink::give(&mut this, made: &mut note): void {
|
||||
if this.heard is some(hear) {
|
||||
hear(made);
|
||||
return;
|
||||
}
|
||||
this.notes.append(move(made));
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
#! @file parser.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the parser, which builds the syntax tree of a file from its tokens,
|
||||
#! and `parse`, where it begins. What it parses is split across the files of the
|
||||
#! `parser` directory, one for each part of the language.
|
||||
|
||||
import std::containers;
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! The sakura language parser structure.
|
||||
#!
|
||||
#! This is responsible for taking a freshly lexed input syntax and to structure
|
||||
#! it into an abstract syntax tree. It will assure that any syntax issues are
|
||||
#! noted and reported to the next stage. The syntax tree produced is checked by
|
||||
#! the next compiler step for semantic analysis.
|
||||
#!
|
||||
#! The parsing functions are split by what they parse across `parser/`: each
|
||||
#! returns the index of the node it made, or of an `error` node where it found
|
||||
#! none, and 0 where what it parses may be left out and was.
|
||||
pub struct parser {
|
||||
var syntax: &mut syntax; #! Reads tokens and appends nodes and extras.
|
||||
var names: &names; #! The names the tokens were lexed with, which give a name's length.
|
||||
var scratch: stack<u32>; #! A scratchpad when the parser needs to hold onto things.
|
||||
var depth: u32; #! Cleanly stops heavily nested constructs.
|
||||
var file: u32; #! Current file index.
|
||||
var index: u32; #! Current token index.
|
||||
var kind: tk; #! The kind of the current token, or `eof` at the limit.
|
||||
var limit: u32; #! Where the tokens seem to end, short of their end while giving up on a declaration.
|
||||
var panic: bool; #! Silences notes until the parser resynchronizes.
|
||||
var halted: bool; #! Gave up on the declaration it is within, so notes nothing more of it.
|
||||
var begun: u32; #! The token the top-level declaration being parsed begins at.
|
||||
var cut: bool; #! Ran into the limit with something left open, while reparsing.
|
||||
# Whether a constant argument is being parsed between `<` and `>`, outside any
|
||||
# bracket it opens, where `>` closes the arguments rather than comparing.
|
||||
var angled: bool;
|
||||
# Whether a trait's members are being parsed, and the trait's type parameters,
|
||||
# which a member's `where` may bound beside its own, as `self` may be.
|
||||
var in_members: bool;
|
||||
var member_params: u32;
|
||||
# Whether an `ensures`'s condition is being parsed, where `old(e)` is what `e`
|
||||
# was where it was reached.
|
||||
var in_ensures: bool;
|
||||
|
||||
# Where the parser puts its notes, which `max_notes` bounds: kept with the
|
||||
# lexer's, or heard as each is made, as where another thread reports them.
|
||||
pub var sink: note_sink; #! Where the parser puts its notes.
|
||||
}
|
||||
|
||||
#! The deepest the parser nests before it gives up on the declaration.
|
||||
pub const parser::max_depth: u32 = 100;
|
||||
|
||||
#! The most notes the parser makes for one file.
|
||||
pub const parser::max_notes: u32 = 100;
|
||||
|
||||
#! Creates a new parser from the provided information.
|
||||
#! @param syntax Where the parser will store the nodes and extras that it
|
||||
#! creates.
|
||||
#! @param names The names the tokens were lexed with.
|
||||
#! @param notes Where the parser will store the notes.
|
||||
#! @param file The index of the file that it's parsing.
|
||||
#! @returns The instantiated parser.
|
||||
pub def parser::new(
|
||||
syntax: &mut syntax,
|
||||
names: &names,
|
||||
notes: &mut vector<note>,
|
||||
file: u32
|
||||
): parser {
|
||||
return parser {
|
||||
syntax = syntax,
|
||||
names = names,
|
||||
sink = note_sink::new(notes, parser::max_notes),
|
||||
scratch = stack::<u32>::new(),
|
||||
file = file
|
||||
};
|
||||
}
|
||||
|
||||
#! Parses the token stream.
|
||||
#!
|
||||
#! This generates the abstract syntax tree within the `syntax` variable, such
|
||||
#! that when the parser ends, the syntax can be evaluated by a checker. The
|
||||
#! token stream must end with `tk::eof`.
|
||||
#! @param this The parser.
|
||||
#! @returns The index of the `document` node, the first the parser makes.
|
||||
pub def parser::parse(&mut this): u32 {
|
||||
this.syntax.reserve_for_tokens();
|
||||
this.limit = this.syntax.token_count as u32;
|
||||
this.sync();
|
||||
|
||||
# The run is made before it is stored: making it appends nodes, which may move
|
||||
# the vector a reference into it was taken from.
|
||||
val document := this.make_node(nk::document, this.index);
|
||||
val declared := this.declarations(this.limit);
|
||||
this.syntax.node_lefts[document] = declared;
|
||||
this.syntax.set_node_end(document, this.limit - 1);
|
||||
this.syntax.whole_nodes = this.syntax.node_count;
|
||||
this.syntax.whole_extras = this.syntax.extras.length;
|
||||
this.syntax.fit_nodes();
|
||||
return document;
|
||||
}
|
||||
|
||||
#! The declarations from the current token through the limit, each recovered
|
||||
#! from on its own.
|
||||
#! @param this The parser.
|
||||
#! @param limit The last token to parse.
|
||||
#! @returns Their run.
|
||||
def parser::declarations(&mut this, limit: u32): u32 {
|
||||
val mark := this.mark;
|
||||
while !this.check(tk::eof) {
|
||||
this.begun = this.index;
|
||||
this.push(this.declaration());
|
||||
if this.halted {
|
||||
this.resume(limit);
|
||||
}
|
||||
|
||||
if this.panic {
|
||||
this.synchronize(parser::scope::document);
|
||||
}
|
||||
}
|
||||
|
||||
return this.make_run(mark);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
#! @file attribute.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the parsing of attributes, written `@name` or `@name{ fields }`
|
||||
#! before a declaration.
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! The attributes before a declaration, as `@name` or `@name{ fields }`.
|
||||
#! @param this The parser.
|
||||
#! @returns The run of `attribute` nodes, empty when there are none.
|
||||
def parser::attributes(&mut this): u32 {
|
||||
val mark := this.mark;
|
||||
while this.check(tk::attr) {
|
||||
val made := this.attribute();
|
||||
break if made == 0;
|
||||
this.push(made);
|
||||
}
|
||||
|
||||
return this.make_run(mark);
|
||||
}
|
||||
|
||||
#! One attribute, from its `@`, whose value is the struct literal written, so
|
||||
#! `@name` is `name{}`.
|
||||
#! @param this The parser.
|
||||
#! @returns The `attribute` node, or 0 where no type follows the `@`.
|
||||
def parser::attribute(&mut this): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
val type_name := this.type_name();
|
||||
return 0 if this.syntax.node_kinds[type_name] == nk::error;
|
||||
|
||||
|
||||
return this.make_node(
|
||||
nk::attribute,
|
||||
token,
|
||||
type_name,
|
||||
this.check(tk::lbrace)
|
||||
? this.field_list()
|
||||
: 0
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,889 @@
|
||||
#! @file declarations.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the parsing of declarations: functions and their parameters and
|
||||
#! where clauses, variables, properties and their accessors, structs, unions,
|
||||
#! traits and their members, enums, and type aliases.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! The name of a declaration, as `name`, `name<T>`, or `box<T>::name`.
|
||||
struct parser::declared {
|
||||
var receiver: u32; #! The type it is declared through, a `type_name` of every segment but the last, or 0.
|
||||
var name: u32; #! The token of its name.
|
||||
var params: u32; #! The run of its own type parameters.
|
||||
}
|
||||
|
||||
#! The parameters and result of a function or lambda.
|
||||
struct parser::signature {
|
||||
var params: u32; #! The run of `param` nodes.
|
||||
var result: u32; #! The result type, 0 where a lambda leaves it out.
|
||||
}
|
||||
|
||||
#! A declaration at the top level of a file, or within a `when` there, with the
|
||||
#! attributes and `pub` before it. A declaration's token is its name.
|
||||
#! @param this The parser.
|
||||
#! @returns The declaration's node, or an `error` node holding its attributes
|
||||
#! where it is none.
|
||||
def parser::declaration(&mut this): u32 {
|
||||
var lead := parser::lead { start = this.index, attrs = this.attributes() };
|
||||
return this.error(this.index, lead.attrs) if this.panic;
|
||||
|
||||
if this.accept(tk::kw_pub) {
|
||||
lead.exported = true;
|
||||
if this.check(tk::attr) {
|
||||
this.report(ec::token, "Attributes are written before `pub`, as `@name pub def f(): void {}`.");
|
||||
lead.attrs = this.join_runs(lead.attrs, this.attributes());
|
||||
return this.error(this.index, lead.attrs) if this.panic;
|
||||
}
|
||||
|
||||
if this.check(tk::kw_pub) {
|
||||
this.fail(ec::token, "A declaration is `pub` once.");
|
||||
return this.error(this.index, lead.attrs);
|
||||
}
|
||||
}
|
||||
|
||||
# An import, a module, and the `when` around declarations name nothing of their
|
||||
# own, so nothing describes them or exports them.
|
||||
val unnamed := this.check(tk::kw_imp) || this.check(tk::kw_mod) || this.check(tk::kw_extern) || this.check(tk::kw_when);
|
||||
if unnamed && lead.exported {
|
||||
this.report(ec::token, "Only a declaration of a name can be `pub`, and this declares none.");
|
||||
} else if unnamed && lead.attrs != 0 {
|
||||
this.report(ec::token, "Attributes describe a declaration of a name, and this declares none.");
|
||||
}
|
||||
|
||||
val made := match this.kind {
|
||||
tk::kw_imp => this.path_decl(nk::import_decl),
|
||||
tk::kw_mod => this.path_decl(nk::module_decl),
|
||||
tk::kw_extern => this.extern_decl(),
|
||||
tk::kw_when => this.when_block(true),
|
||||
tk::kw_def => this.function(&lead, false, parser::place::top),
|
||||
tk::kw_const => this.peek(1) == tk::kw_def
|
||||
? this.const_function(&lead, parser::place::top)
|
||||
: this.variable(&lead, parser::place::top),
|
||||
tk::kw_val, tk::kw_var => this.variable(&lead, parser::place::top),
|
||||
tk::kw_struct, tk::kw_union, tk::kw_trait => this.aggregate(&lead),
|
||||
tk::kw_enum => this.enumeration(&lead),
|
||||
tk::kw_type => this.alias(&lead),
|
||||
else => this.no_declaration()
|
||||
};
|
||||
return this.declared_at(made, &lead);
|
||||
}
|
||||
|
||||
def parser::no_declaration(&mut this): u32 {
|
||||
this.fail(ec::decl,
|
||||
"Expected an import, module, `extern`, `when`, function, struct, enum, trait, type, variable, or constant.");
|
||||
return this.error_here();
|
||||
}
|
||||
|
||||
#! `import path;`, or `module path;` and `module path when condition;`.
|
||||
#! @param this The parser.
|
||||
#! @param kind `import_decl` or `module_decl`.
|
||||
#! @returns The node.
|
||||
def parser::path_decl(&mut this, kind: nk): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
|
||||
val path := this.path();
|
||||
var condition: u32 = 0;
|
||||
if kind == nk::module_decl && this.accept(tk::kw_when) {
|
||||
condition = this.condition();
|
||||
}
|
||||
|
||||
this.expect(tk::semicolon, "Expected `;` after the path.");
|
||||
return this.make_node(kind, token, path, condition);
|
||||
}
|
||||
|
||||
#! `extern import "library";` or `extern module path;`, each with a `when`
|
||||
#! condition where it is written. A section without one is parsed, so the
|
||||
#! checker says what it lacks.
|
||||
#! @param this The parser.
|
||||
#! @returns The `extern_import` or `extern_module` node, or an `error` node.
|
||||
def parser::extern_decl(&mut this): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
if this.check(tk::kw_mod) {
|
||||
this.advance();
|
||||
val path := this.path();
|
||||
val condition := this.accept(tk::kw_when) ? this.condition() : 0;
|
||||
this.expect(tk::semicolon, "Expected `;` after the path.");
|
||||
return this.make_node(nk::extern_module, token, path, condition);
|
||||
}
|
||||
|
||||
if !this.accept(tk::kw_imp) {
|
||||
this.fail(ec::token, "Expected `import` or `module` after `extern`: `extern import \"library\";` names a library, and `extern module path when ...;` begins C's declarations.");
|
||||
return this.error_here();
|
||||
}
|
||||
if !this.check(tk::string) {
|
||||
this.fail(ec::token, "Expected the library, as `\"libvulkan.so.1\"` or `\"kernel32.dll\"`.");
|
||||
return this.error_here();
|
||||
}
|
||||
val library := this.literal(nk::string);
|
||||
val condition := this.accept(tk::kw_when) ? this.condition() : 0;
|
||||
this.expect(tk::semicolon, "Expected `;` after the library.");
|
||||
return this.make_node(nk::extern_import, token, library, condition);
|
||||
}
|
||||
|
||||
#! The name of a declaration. Where receivers are allowed, `T::name` gives the
|
||||
#! receiver as a `type_name` of every segment but the last, whose type
|
||||
#! parameters are each segment's, as `T` of `box<T>::get`.
|
||||
#! @param this The parser.
|
||||
#! @param receivers Whether the name may be declared through a type.
|
||||
#! @returns The receiver, the name's token, and the type parameters.
|
||||
def parser::decl_name(&mut this, receivers: bool): parser::declared {
|
||||
if !this.check(tk::name) {
|
||||
this.fail(ec::ident, "Expected a name for the declaration.");
|
||||
return parser::declared { name = this.index };
|
||||
}
|
||||
|
||||
var last := this.index;
|
||||
this.advance();
|
||||
|
||||
val mark := this.mark;
|
||||
var params := this.check(tk::less) ? this.type_params() : 0;
|
||||
while receivers && this.check(tk::scope) {
|
||||
this.advance();
|
||||
if !this.check(tk::name) {
|
||||
this.fail(ec::ident, "Expected a name after `::`.");
|
||||
break;
|
||||
}
|
||||
|
||||
this.push(this.make_node(nk::segment, last, params));
|
||||
last = this.index;
|
||||
this.advance();
|
||||
params = this.check(tk::less) ? this.type_params() : 0;
|
||||
}
|
||||
|
||||
# The receiver ends where its last segment does, short of the name after it.
|
||||
var receiver: u32 = 0;
|
||||
if this.mark > mark {
|
||||
val segments := this.scratch.view();
|
||||
val first: u32 = this.syntax.node_tokens[segments[mark]];
|
||||
val end: u32 = this.syntax.node_end(segments[this.mark - 1]);
|
||||
receiver = this.make_node(nk::type_name, first, this.make_run(mark));
|
||||
this.syntax.set_node_end(receiver, end);
|
||||
}
|
||||
|
||||
return parser::declared {
|
||||
receiver = receiver,
|
||||
name = last,
|
||||
params = params
|
||||
};
|
||||
}
|
||||
|
||||
#! `const def`, a function constants can call.
|
||||
#! @param this The parser.
|
||||
#! @param lead What came before it.
|
||||
#! @param place Where it is written.
|
||||
#! @returns The `function` node.
|
||||
def parser::const_function(&mut this, lead: &parser::lead, place: parser::place): u32 {
|
||||
this.advance();
|
||||
return this.function(lead, true, place);
|
||||
}
|
||||
|
||||
#! A function, from its `def`. One ending at its signature, rather than a body,
|
||||
#! is one a trait requires, one the compiler gives, or one of C's, which the
|
||||
#! checker tells apart by its attributes. A method of a trait takes no receiver.
|
||||
#! @param this The parser.
|
||||
#! @param lead What came before it.
|
||||
#! @param constant Whether it is a `const def`.
|
||||
#! @param place Where it is written.
|
||||
#! @returns The `function` node, or an `error` node.
|
||||
def parser::function(&mut this, lead: &parser::lead, constant: bool, place: parser::place): u32 {
|
||||
this.advance();
|
||||
|
||||
val in_trait := place == parser::place::member;
|
||||
val declared := this.decl_name(!in_trait);
|
||||
val signature := this.params(false, in_trait || declared.receiver != 0);
|
||||
val outer := this.where_clause(declared.params, declared.receiver);
|
||||
|
||||
val body := this.accept(tk::semicolon) ? 0 : this.block();
|
||||
val record := this.make_record(lead.attrs, declared.receiver, declared.params, signature.params, signature.result, body, outer);
|
||||
val flags := parser::bit(lead.exported, nf::exported) | parser::bit(constant, nf::constant);
|
||||
return this.make_node(nk::function, declared.name, record, flags);
|
||||
}
|
||||
|
||||
#! The parameters and result of a function, from `(` through the result type. A
|
||||
#! lambda may leave out its parameter types and its result, and a method may
|
||||
#! begin with `&this` or `&mut this`.
|
||||
#! @param this The parser.
|
||||
#! @param lambda Whether they are a lambda's.
|
||||
#! @param methods Whether they are a method's, which may take `this`.
|
||||
#! @returns The run of parameters and the result type.
|
||||
def parser::params(&mut this, lambda: bool, methods: bool): parser::signature {
|
||||
if !this.expect(tk::lparen, "Expected `(` to begin the parameters.") {
|
||||
return parser::signature {};
|
||||
}
|
||||
|
||||
val mark := this.mark;
|
||||
if !lambda && this.check(tk::bitand) {
|
||||
this.push(this.this_param(methods));
|
||||
if !this.check(tk::rparen) {
|
||||
this.expect(tk::comma, "Expected `,` or `)` after `this`.");
|
||||
}
|
||||
}
|
||||
|
||||
var defaulted := false;
|
||||
var variadic := false;
|
||||
while !this.check(tk::rparen) && !this.check(tk::eof) {
|
||||
if !this.check(tk::name) {
|
||||
this.fail(ec::ident, "Expected a parameter name.");
|
||||
break if !this.skip_item(tk::rparen) || !this.accept(tk::comma);
|
||||
continue;
|
||||
}
|
||||
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
if variadic {
|
||||
this.report_at(token, ec::token,
|
||||
"A variadic parameter takes every argument after the parameters before it, so it is the last.");
|
||||
}
|
||||
|
||||
var type_expr: u32 = 0;
|
||||
if !lambda || this.check(tk::colon) {
|
||||
this.expect(tk::colon, "Expected `:` followed by the parameter type.");
|
||||
type_expr = this.type_expr();
|
||||
}
|
||||
|
||||
# `name: T...` takes the arguments after the parameters before it.
|
||||
var flags: u32 = 0;
|
||||
if type_expr != 0 && this.check(tk::spread) {
|
||||
if lambda {
|
||||
this.report(ec::token,
|
||||
"Only a function declared by name takes a variadic parameter; an anonymous function takes a `span<T>`.");
|
||||
}
|
||||
|
||||
this.advance();
|
||||
flags = parser::bit(!lambda, nf::variadic);
|
||||
variadic = variadic || !lambda;
|
||||
}
|
||||
|
||||
# A parameter may be given the value a call takes where it leaves the argument
|
||||
# out. Every parameter after one is given one too, so the arguments a call does
|
||||
# give are always the first parameters.
|
||||
var value: u32 = 0;
|
||||
if flags != 0 && this.check(tk::assign) {
|
||||
this.report(ec::token,
|
||||
"A variadic parameter takes no default value, since a call giving no arguments for it gives it none.");
|
||||
this.advance();
|
||||
value = this.expression();
|
||||
} else if this.accept(tk::assign) {
|
||||
value = this.expression();
|
||||
defaulted = true;
|
||||
} else if defaulted && flags == 0 {
|
||||
this.report_at(token, ec::token,
|
||||
"A parameter after one with a default value is given one too, so a call leaving arguments out always leaves out the last.");
|
||||
}
|
||||
|
||||
this.push(this.make_node(nk::param, token, type_expr, this.make_record(value, flags)));
|
||||
break if this.panic && !this.skip_item(tk::rparen);
|
||||
break if !this.accept(tk::comma);
|
||||
}
|
||||
|
||||
val params := this.make_run(mark);
|
||||
this.expect(tk::rparen, "Expected `)` to close the parameters.");
|
||||
if lambda && !this.check(tk::colon) {
|
||||
return parser::signature { params = params };
|
||||
}
|
||||
|
||||
this.expect(tk::colon, "Expected `:` followed by the return type.");
|
||||
return parser::signature {
|
||||
params = params,
|
||||
result = this.type_expr()
|
||||
};
|
||||
}
|
||||
|
||||
#! `&this` or `&mut this`, the first parameter of a method, from its `&`. Its
|
||||
#! type is left out, since it is a reference to the receiver.
|
||||
#! @param this The parser.
|
||||
#! @param methods Whether it is a method's, which may take `this`.
|
||||
#! @returns The `param` node, or an `error` node.
|
||||
def parser::this_param(&mut this, methods: bool): u32 {
|
||||
this.advance();
|
||||
val mutable := this.accept(tk::kw_mut);
|
||||
if !this.check_word(names::this_id) {
|
||||
this.fail(ec::ident, "Expected `this`; other parameters are written `name: type`.");
|
||||
return this.error_here();
|
||||
}
|
||||
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
if !methods {
|
||||
this.report_at(token, ec::token, "Only methods, declared as `type::name`, take `this`.");
|
||||
}
|
||||
|
||||
return this.make_node(nk::param, token, 0, this.make_record(0, parser::bit(mutable, nf::mutable)));
|
||||
}
|
||||
|
||||
#! The `where` clauses of a declaration, one for each type parameter it bounds,
|
||||
#! as `where K: hashable, equatable where V: Show`. The bounds become those of
|
||||
#! the `type_param` nodes of the declaration, or of its receiver, as `T` of
|
||||
#! `box<T>::get`. A trait's method may also bound the trait's type parameters
|
||||
#! and `self`, which only that method then asks of them, as `where self:
|
||||
#! backward_iterator<T>`: each is a `type_param` of the name, made here.
|
||||
#! @param this The parser.
|
||||
#! @param params The run of the declaration's type parameters.
|
||||
#! @param receiver The receiver's `type_name`, or 0.
|
||||
#! @returns The run of the bounds a trait's method puts on the trait's type
|
||||
#! parameters and `self`, or 0.
|
||||
def parser::where_clause(&mut this, params: u32, receiver: u32): u32 {
|
||||
val outer_mark := this.mark;
|
||||
var outer := vector::<u32>::new();
|
||||
while this.accept(tk::kw_where) {
|
||||
if !this.check(tk::name) {
|
||||
this.fail(ec::ident, "Expected the name of a type parameter to bound.");
|
||||
break;
|
||||
}
|
||||
|
||||
val name := this.index;
|
||||
val word: u32 = this.syntax.token_names[this.index];
|
||||
var param := this.find_param(params, receiver, word);
|
||||
if param == 0 && this.in_members && (word == names::self_id || this.find_in(this.member_params, word) != 0) {
|
||||
for &each in outer {
|
||||
param = this.name_of(each) == word ? each : param;
|
||||
}
|
||||
if param == 0 {
|
||||
param = this.make_node(nk::type_param, name);
|
||||
outer.append(param);
|
||||
}
|
||||
}
|
||||
if param == 0 {
|
||||
this.report(ec::token, this.in_members
|
||||
? "Only the type parameters of the method, of its trait, and `self` are bounded here."
|
||||
: "Only the type parameters of the declaration, and of its receiver, are bounded here.");
|
||||
}
|
||||
this.advance();
|
||||
|
||||
# A pack's bounds are each of its types', written `where Ts...: Show`.
|
||||
val dotted := this.accept(tk::spread);
|
||||
val packed := param != 0 && this.syntax.node_kinds[param] == nk::type_param
|
||||
&& (this.syntax.node_rights[param] & nf::packed as u32) != 0;
|
||||
if dotted && param != 0 && !packed {
|
||||
this.report_at(name, ec::token, "Only a pack, declared `Ts...`, is bounded as `Ts...`.");
|
||||
} else if packed && !dotted {
|
||||
this.report_at(name, ec::token, "A pack's bounds are each of its types', written `where Ts...: Show`.");
|
||||
}
|
||||
this.expect(tk::colon, "Expected `:` followed by the bounds.");
|
||||
|
||||
# The bounds it already has come first, since each `where` adds to them.
|
||||
val mark := this.mark;
|
||||
if param != 0 {
|
||||
val had := this.syntax.node_lefts[param];
|
||||
for &node in this.run_view(had) {
|
||||
this.push(node);
|
||||
}
|
||||
}
|
||||
|
||||
while true {
|
||||
this.push(this.type_name());
|
||||
break if !this.accept(tk::comma);
|
||||
}
|
||||
|
||||
if param != 0 {
|
||||
val bounds := this.make_run(mark);
|
||||
this.syntax.node_lefts[param] = bounds;
|
||||
} else {
|
||||
this.drop(mark);
|
||||
}
|
||||
}
|
||||
|
||||
return 0 if outer.length == 0;
|
||||
for &each in outer {
|
||||
this.push(each);
|
||||
}
|
||||
return this.make_run(outer_mark);
|
||||
}
|
||||
|
||||
#! The `type_param` of the name among the type parameters, or those of the
|
||||
#! receiver's segments, or 0 where there is none.
|
||||
#! @param this The parser.
|
||||
#! @param params The run of the declaration's type parameters.
|
||||
#! @param receiver The receiver's `type_name`, or 0.
|
||||
#! @param name The ID of the name.
|
||||
#! @returns The `type_param` node, or 0.
|
||||
def parser::find_param(&this, params: u32, receiver: u32, name: u32): u32 {
|
||||
val own := this.find_in(params, name);
|
||||
return own if own != 0 || receiver == 0;
|
||||
|
||||
val segments := this.syntax.node_lefts[receiver];
|
||||
for &segment in this.run_view(segments) {
|
||||
val found := this.find_in(this.syntax.node_lefts[segment], name);
|
||||
return found if found != 0;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
def parser::find_in(&this, params: u32, name: u32): u32 {
|
||||
for ¶m in this.run_view(params) {
|
||||
# A pattern's type parameters are its own parameters' and its result's.
|
||||
if this.syntax.node_kinds[param] == nk::type_pattern {
|
||||
val inner := this.find_in(this.syntax.node_lefts[param], name);
|
||||
return inner if inner != 0;
|
||||
val result := this.syntax.node_rights[param];
|
||||
return result if result != 0 && this.name_of(result) == name;
|
||||
continue;
|
||||
}
|
||||
# An array pattern's are its element's and its length's.
|
||||
if this.syntax.node_kinds[param] == nk::array_pattern {
|
||||
val element := this.syntax.node_lefts[param];
|
||||
return element if this.name_of(element) == name;
|
||||
val length := this.syntax.node_rights[param];
|
||||
return length if length != 0 && this.name_of(length) == name;
|
||||
continue;
|
||||
}
|
||||
return param if this.name_of(param) == name;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! A variable, constant, or field, from its `val`, `var`, or `const`, or the
|
||||
#! property it begins where `{` follows its type. Where it is written says what
|
||||
#! it may be: one at the top level may be declared through a type, as
|
||||
#! `rect::unit`, one of a struct or union is a `field`, and one at the top level
|
||||
#! or of a trait may be a property.
|
||||
#! @param this The parser.
|
||||
#! @param lead What came before it.
|
||||
#! @param place Where it is written.
|
||||
#! @returns The `variable`, `field`, or `property` node, or an `error` node.
|
||||
def parser::variable(&mut this, lead: &parser::lead, place: parser::place): u32 {
|
||||
val mutable := this.check(tk::kw_var);
|
||||
val constant := this.check(tk::kw_const);
|
||||
val kind := place == parser::place::field ? nk::field : nk::variable;
|
||||
this.advance();
|
||||
|
||||
val declared := this.decl_name(place == parser::place::top);
|
||||
if declared.params != 0 {
|
||||
this.report_at(declared.name, ec::token,
|
||||
"Only functions, types, and aliases take type parameters of their own; a member of a generic type is declared through it, as `box<T>::empty`.");
|
||||
}
|
||||
|
||||
this.expect(tk::colon, "Expected `:` after the name, followed by a type, `=`, or both.");
|
||||
var type_expr: u32 = 0;
|
||||
if !this.check(tk::assign) && !this.check(tk::semicolon) {
|
||||
type_expr = kind == nk::field && this.check(tk::spread)
|
||||
? this.spread()
|
||||
: this.type_expr();
|
||||
}
|
||||
|
||||
# `{` after the type opens the accessors of a property.
|
||||
val properties := place == parser::place::top || place == parser::place::member;
|
||||
if properties && !constant && type_expr != 0 && this.check(tk::lbrace) {
|
||||
if place == parser::place::top && declared.receiver == 0 {
|
||||
this.report_at(declared.name, ec::token,
|
||||
"A property belongs to a type, so it is declared as `type::name`.");
|
||||
}
|
||||
return this.property(lead, declared, type_expr, mutable, place);
|
||||
}
|
||||
|
||||
# `= undefined;` leaves a variable's memory as it is, and is a word only there.
|
||||
var value: u32 = 0;
|
||||
if this.accept(tk::assign) {
|
||||
val left := this.check_word(names::undefined_id) && this.peek(1) == tk::semicolon;
|
||||
value = left ? this.literal(nk::undefined) : this.expression();
|
||||
}
|
||||
if type_expr == 0 && value == 0 {
|
||||
this.fail(ec::kind, "Expected a type or `=` followed by a value to infer it from.");
|
||||
}
|
||||
|
||||
this.expect(tk::semicolon, "Expected `;` after the declaration.");
|
||||
val record := this.make_record(lead.attrs, declared.receiver, type_expr, value);
|
||||
val flags := parser::bit(lead.exported, nf::exported)
|
||||
| parser::bit(mutable, nf::mutable)
|
||||
| parser::bit(constant, nf::constant);
|
||||
return this.make_node(kind, declared.name, record, flags);
|
||||
}
|
||||
|
||||
#! The `{ get ... set ... }` of a property, from its `{`. Each accessor is as
|
||||
#! visible as the property unless it takes its own `pub`, which is how a
|
||||
#! property reads everywhere but is written only where it is declared.
|
||||
#! @param this The parser.
|
||||
#! @param lead What came before it.
|
||||
#! @param declared Its name and receiver.
|
||||
#! @param type_expr Its type's node.
|
||||
#! @param mutable Whether it is declared `var`.
|
||||
#! @param place Where it is written.
|
||||
#! @returns The `property` node.
|
||||
def parser::property(
|
||||
&mut this,
|
||||
lead: &parser::lead,
|
||||
declared: parser::declared,
|
||||
type_expr: u32,
|
||||
mutable: bool,
|
||||
place: parser::place
|
||||
): u32 {
|
||||
this.advance();
|
||||
|
||||
val in_trait := place == parser::place::member;
|
||||
val methods := in_trait || declared.receiver != 0;
|
||||
val mark := this.mark;
|
||||
var getter := false;
|
||||
var setter := false;
|
||||
while !this.check(tk::rbrace) && !this.check(tk::eof) {
|
||||
# A trait's members are as visible as the trait, so it takes none.
|
||||
val marker := this.index;
|
||||
var own := this.accept(tk::kw_pub);
|
||||
if own && in_trait {
|
||||
this.report_at(marker, ec::token,
|
||||
"A trait's members are as visible as the trait, so its accessors are never `pub`.");
|
||||
own = false;
|
||||
}
|
||||
|
||||
val get := this.check_word(names::get_id);
|
||||
val set := this.check_word(names::set_id);
|
||||
if !get && !set {
|
||||
this.fail(ec::token, own
|
||||
? "Expected `get` or `set` after `pub`, the accessors of a property."
|
||||
: "Expected `get` or `set`, the accessors of a property.");
|
||||
break;
|
||||
}
|
||||
|
||||
if (get && getter) || (set && setter) {
|
||||
this.fail(ec::token, get
|
||||
? "The property already has a `get`."
|
||||
: "The property already has a `set`.");
|
||||
break;
|
||||
}
|
||||
|
||||
if set && !mutable {
|
||||
this.fail(ec::token,
|
||||
"A `val` property only reads, so it has no `set`; declare it with `var` to write it.");
|
||||
break;
|
||||
}
|
||||
|
||||
this.push(this.accessor(own, methods, get));
|
||||
getter = getter || get;
|
||||
setter = setter || set;
|
||||
break if this.panic;
|
||||
}
|
||||
|
||||
# Past a malformed accessor, skip to the brace closing them, so what follows
|
||||
# is read as the declarations it is rather than as more of the property.
|
||||
if this.panic {
|
||||
this.skip_to_close();
|
||||
}
|
||||
|
||||
val accessors := this.make_run(mark);
|
||||
this.expect(tk::rbrace, "Expected `}` to close the accessors.");
|
||||
if !getter {
|
||||
this.report_at(declared.name, ec::decl, "A property is read through `get`, which it must declare.");
|
||||
}
|
||||
|
||||
val flags := parser::bit(mutable, nf::mutable) | parser::bit(lead.exported, nf::exported);
|
||||
val record := this.make_record(lead.attrs, declared.receiver, type_expr, flags);
|
||||
return this.make_node(nk::property, declared.name, record, accessors);
|
||||
}
|
||||
|
||||
#! One accessor of a property, `get` or `set`, from its name, followed by its
|
||||
#! body: a block, `=> expression;`, or `;` where a trait asks for it. Its
|
||||
#! parameters are implied, and made here: `this`, which a `get` reads and a
|
||||
#! `set` writes, and a `set`'s `value`, of the property's type. `=>` gives what
|
||||
#! a `get` returns, and is what a `set` does.
|
||||
#! @param this The parser.
|
||||
#! @param exported Whether the property is `pub`.
|
||||
#! @param methods Whether it is declared through a type, so its accessors
|
||||
#! take `this`.
|
||||
#! @param get Whether it is the getter.
|
||||
#! @returns The `accessor` node, or an `error` node.
|
||||
def parser::accessor(&mut this, exported: bool, methods: bool, get: bool): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
|
||||
val mark := this.mark;
|
||||
if this.check(tk::lparen) {
|
||||
# The form before, read on so what follows is checked as it means.
|
||||
this.report(ec::token, get
|
||||
? "A `get` takes no parameters written: it has `this`, as `get => this.w;` or `get { return this.w; }`."
|
||||
: "A `set` takes no parameters written: it has `this`, and `value` of the property's type, as `set => this.w = value;` or `set { this.w = value; }`.");
|
||||
this.written_params(methods, get);
|
||||
} else {
|
||||
this.push(this.make_node(nk::param, token, 0, this.make_record(0, parser::bit(!get, nf::mutable) | nf::implied as u32)));
|
||||
if !get {
|
||||
this.push(this.make_node(nk::param, token, 0, this.make_record(0, nf::implied as u32)));
|
||||
}
|
||||
}
|
||||
val params := this.make_run(mark);
|
||||
|
||||
var body: u32 = 0;
|
||||
if this.check(tk::arrow) {
|
||||
val arrow := this.index;
|
||||
this.advance();
|
||||
val made := this.expression();
|
||||
this.expect(tk::semicolon, "Expected `;` after the accessor's expression.");
|
||||
val stated := this.make_node(get ? nk::return_stmt : nk::expr_stmt, arrow, made);
|
||||
body = this.make_node(nk::block, arrow, this.run_of(stated));
|
||||
} else if !this.accept(tk::semicolon) {
|
||||
body = this.block();
|
||||
}
|
||||
return this.make_node(nk::accessor, token, params, this.make_record(body, parser::bit(exported, nf::exported)));
|
||||
}
|
||||
|
||||
#! The parameters of an accessor written out, `(&this)` or `(&mut this, to)`,
|
||||
#! as they were before they were implied, from its `(`, which a note refuses.
|
||||
#! @param this The parser.
|
||||
#! @param methods Whether it is declared through a type, so it takes `this`.
|
||||
#! @param get Whether it is the getter.
|
||||
def parser::written_params(&mut this, methods: bool, get: bool): void {
|
||||
this.advance();
|
||||
if this.check(tk::bitand) {
|
||||
this.push(this.this_param(methods));
|
||||
if !this.check(tk::rparen) {
|
||||
this.expect(tk::comma, "Expected `,` or `)` after `this`.");
|
||||
}
|
||||
} else {
|
||||
this.report(ec::token, get
|
||||
? "A getter reads the value it belongs to, so it takes `&this`."
|
||||
: "A setter changes the value it belongs to, so it takes `&mut this` and the value to store.");
|
||||
}
|
||||
|
||||
while !this.check(tk::rparen) && !this.check(tk::eof) {
|
||||
if !this.check(tk::name) {
|
||||
this.fail(ec::ident, "Expected a parameter name.");
|
||||
break if !this.skip_item(tk::rparen) || !this.accept(tk::comma);
|
||||
continue;
|
||||
}
|
||||
|
||||
val name := this.index;
|
||||
this.advance();
|
||||
val type_expr := this.accept(tk::colon) ? this.type_expr() : 0;
|
||||
this.push(this.make_node(nk::param, name, type_expr));
|
||||
break if this.panic && !this.skip_item(tk::rparen);
|
||||
break if !this.accept(tk::comma);
|
||||
}
|
||||
this.expect(tk::rparen, "Expected `)` to close the parameters of the accessor.");
|
||||
}
|
||||
|
||||
#! A struct, union, or trait, from its keyword. A struct or union names the
|
||||
#! traits it implements, and a trait names the traits it composes.
|
||||
#! @param this The parser.
|
||||
#! @param lead What came before it.
|
||||
#! @returns The `struct_decl`, `union_decl`, or `trait_decl` node.
|
||||
def parser::aggregate(&mut this, lead: &parser::lead): u32 {
|
||||
val kind := match this.kind {
|
||||
tk::kw_struct => nk::struct_decl,
|
||||
tk::kw_union => nk::union_decl,
|
||||
else => nk::trait_decl
|
||||
};
|
||||
val in_trait := kind == nk::trait_decl;
|
||||
this.advance();
|
||||
|
||||
val declared := this.decl_name(true);
|
||||
var traits: u32 = 0;
|
||||
if this.accept(tk::colon) {
|
||||
val mark := this.mark;
|
||||
while true {
|
||||
this.push(this.type_name());
|
||||
break if !this.accept(tk::comma);
|
||||
}
|
||||
traits = this.make_run(mark);
|
||||
}
|
||||
|
||||
this.where_clause(declared.params, 0);
|
||||
|
||||
val flags := parser::bit(lead.exported, nf::exported);
|
||||
val record := this.make_record(lead.attrs, declared.receiver, declared.params, traits, flags);
|
||||
if !this.expect(tk::lbrace, "Expected `{` to begin the members.") {
|
||||
return this.make_node(kind, declared.name, record);
|
||||
}
|
||||
|
||||
val scope := in_trait ? parser::scope::members : parser::scope::fields;
|
||||
val mark := this.mark;
|
||||
val was_in_members := this.in_members;
|
||||
val was_params := this.member_params;
|
||||
this.in_members = in_trait;
|
||||
this.member_params = in_trait ? declared.params : 0;
|
||||
while !this.check(tk::rbrace) && !this.check(tk::eof) {
|
||||
var member_lead := parser::lead { start = this.index, attrs = this.attributes() };
|
||||
if this.panic {
|
||||
this.push(this.error(this.index, member_lead.attrs));
|
||||
this.synchronize(scope);
|
||||
continue;
|
||||
}
|
||||
|
||||
val member := in_trait
|
||||
? this.trait_member(&member_lead)
|
||||
: this.field_member(&mut member_lead);
|
||||
if member != 0 {
|
||||
this.push(this.declared_at(member, &member_lead));
|
||||
}
|
||||
|
||||
if this.panic {
|
||||
this.synchronize(scope);
|
||||
}
|
||||
}
|
||||
|
||||
this.in_members = was_in_members;
|
||||
this.member_params = was_params;
|
||||
val members := this.make_run(mark);
|
||||
this.expect(tk::rbrace, "Expected `}` to close the members.");
|
||||
return this.make_node(kind, declared.name, record, members);
|
||||
}
|
||||
|
||||
#! A field of a struct or union, which `pub` lets modules other than its own
|
||||
#! reach.
|
||||
#! @param this The parser.
|
||||
#! @param lead What came before it, which `pub` is added to.
|
||||
#! @returns The `field` node, or an `error` node holding the attributes before
|
||||
#! what is not one, or 0 where there were none.
|
||||
def parser::field_member(&mut this, lead: &mut parser::lead): u32 {
|
||||
if this.accept(tk::kw_pub) {
|
||||
lead.exported = true;
|
||||
if this.check(tk::attr) {
|
||||
this.report(ec::token, "Attributes are written before `pub`, as `@name pub var x: T;`.");
|
||||
lead.attrs = this.join_runs(lead.attrs, this.attributes());
|
||||
return this.error(this.index, lead.attrs) if this.panic;
|
||||
}
|
||||
if this.check(tk::kw_pub) {
|
||||
this.fail(ec::token, "A declaration is `pub` once.");
|
||||
return this.error(this.index, lead.attrs);
|
||||
}
|
||||
}
|
||||
if this.check(tk::kw_var) || this.check(tk::kw_val) {
|
||||
return this.variable(lead, parser::place::field);
|
||||
}
|
||||
|
||||
this.fail(ec::token, "Expected a field declared with `var` or `val`.");
|
||||
return lead.attrs != 0 ? this.error(this.index, lead.attrs) : 0;
|
||||
}
|
||||
|
||||
#! A member of a trait: a method, which `;` leaves to the implementer, a
|
||||
#! constant, a property, or a type it asks for.
|
||||
#! @param this The parser.
|
||||
#! @param lead What came before it.
|
||||
#! @returns The member's node, or an `error` node holding what was parsed of
|
||||
#! what is not one, or 0 where nothing was.
|
||||
def parser::trait_member(&mut this, lead: &parser::lead): u32 {
|
||||
val place := parser::place::member;
|
||||
match this.kind {
|
||||
tk::kw_def => return this.function(lead, false, place);
|
||||
tk::kw_type => return this.assoc_type(lead);
|
||||
tk::kw_const => {
|
||||
return this.const_function(lead, place) if this.peek(1) == tk::kw_def;
|
||||
return this.variable(lead, place);
|
||||
}
|
||||
|
||||
# A trait requires a property by declaring its accessors without bodies, and
|
||||
# `var` and `val` declare nothing else of a trait.
|
||||
tk::kw_var, tk::kw_val => {
|
||||
val keyword := this.index;
|
||||
val member := this.variable(lead, place);
|
||||
return member if this.syntax.node_kinds[member] == nk::property;
|
||||
|
||||
this.fail_at(keyword, ec::token,
|
||||
"A trait declares a property with its accessors, as `val area: int { get; }`, and a constant with `const`.");
|
||||
return this.error(keyword, this.run_of(member));
|
||||
}
|
||||
tk::kw_pub => this.fail(ec::token, "A trait's members are as visible as the trait, so they are never `pub`.");
|
||||
else => this.fail(ec::token,
|
||||
"Expected a method signature declared with `def`, a property with `var` or `val`, a constant with `const`, or a type with `type`.");
|
||||
}
|
||||
|
||||
return lead.attrs != 0 ? this.error(this.index, lead.attrs) : 0;
|
||||
}
|
||||
|
||||
#! `type name: A, B = T;`, a type a trait asks of what implements it, which the
|
||||
#! bounds constrain and the default stands in for where the implementer gives
|
||||
#! none.
|
||||
#! @param this The parser.
|
||||
#! @param lead What came before it.
|
||||
#! @returns The `assoc_type` node.
|
||||
def parser::assoc_type(&mut this, lead: &parser::lead): u32 {
|
||||
this.advance();
|
||||
if !this.check(tk::name) {
|
||||
this.fail(ec::ident, "Expected the name of the type the trait asks for.");
|
||||
return this.error_here();
|
||||
}
|
||||
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
# `type params...;` asks for a pack, which only the compiler gives.
|
||||
val packed := this.accept(tk::spread);
|
||||
|
||||
var bounds: u32 = 0;
|
||||
if this.accept(tk::colon) {
|
||||
val mark := this.mark;
|
||||
while true {
|
||||
this.push(this.type_name());
|
||||
break if !this.accept(tk::comma);
|
||||
}
|
||||
bounds = this.make_run(mark);
|
||||
}
|
||||
|
||||
val fallback := this.accept(tk::assign) ? this.type_expr() : 0;
|
||||
this.expect(tk::semicolon, "Expected `;` after the type the trait asks for.");
|
||||
return this.make_node(nk::assoc_type, token, this.make_record(lead.attrs, bounds, parser::bit(packed, nf::packed)), fallback);
|
||||
}
|
||||
|
||||
#! `enum name: type { member, member = value, ... }`, whose type may be left
|
||||
#! out. An enum is never generic, but it may be nested in a type that is, as
|
||||
#! `enum list<T>::state`, naming that type's parameters.
|
||||
#! @param this The parser.
|
||||
#! @param lead What came before it.
|
||||
#! @returns The `enumeration` node.
|
||||
def parser::enumeration(&mut this, lead: &parser::lead): u32 {
|
||||
this.advance();
|
||||
if !this.check(tk::name) {
|
||||
this.fail(ec::ident, "Expected the name of the enumeration.");
|
||||
return this.error_here();
|
||||
}
|
||||
|
||||
val declared := this.decl_name(true);
|
||||
if declared.params != 0 {
|
||||
this.report_at(declared.name, ec::token, "An enum is never generic, though it may be nested in a type that is.");
|
||||
}
|
||||
|
||||
val integer := this.accept(tk::colon) ? this.type_expr() : 0;
|
||||
val record := this.make_record(lead.attrs, declared.receiver, integer, parser::bit(lead.exported, nf::exported));
|
||||
if !this.accept(tk::lbrace) {
|
||||
this.fail(ec::token, "Expected `{` to begin the members.");
|
||||
return this.make_node(nk::enumeration, declared.name, record);
|
||||
}
|
||||
|
||||
val members := this.list(parser::item::enumerator, tk::rbrace, "Expected `,` between the members, or `}` to close them.");
|
||||
return this.make_node(nk::enumeration, declared.name, record, members);
|
||||
}
|
||||
|
||||
#! `type name<T> = type where T: bound;`.
|
||||
#! @param this The parser.
|
||||
#! @param lead What came before it.
|
||||
#! @returns The `alias` node.
|
||||
def parser::alias(&mut this, lead: &parser::lead): u32 {
|
||||
this.advance();
|
||||
|
||||
val declared := this.decl_name(true);
|
||||
this.expect(tk::assign, "Expected `=` followed by the aliased type.");
|
||||
val aliased := this.type_expr();
|
||||
this.where_clause(declared.params, 0);
|
||||
if this.check(tk::bitor) {
|
||||
this.fail(ec::token,
|
||||
"A value that is one of several types is a `union`, as `union name { var a: A; var b: B; }`.");
|
||||
} else if this.check(tk::bitand) {
|
||||
this.fail(ec::token,
|
||||
"Types are combined as the fields of a `struct`, as `struct name { var a: A; var b: B; }`.");
|
||||
} else {
|
||||
this.expect(tk::semicolon, "Expected `;` after the type.");
|
||||
}
|
||||
|
||||
val record := this.make_record(lead.attrs, declared.receiver, declared.params, parser::bit(lead.exported, nf::exported));
|
||||
return this.make_node(nk::alias, declared.name, record, aliased);
|
||||
}
|
||||
|
||||
#! A member of an enum, with the attributes before it, and the value it is
|
||||
#! given, which may be left out.
|
||||
#! @param this The parser.
|
||||
#! @returns The `enumerator` node, or an `error` node.
|
||||
def parser::enumerator(&mut this): u32 {
|
||||
val lead := parser::lead { start = this.index, attrs = this.attributes() };
|
||||
return this.error(this.index, lead.attrs) if this.panic;
|
||||
if !this.check(tk::name) {
|
||||
this.fail(ec::ident, "Expected the name of a member.");
|
||||
return this.error(this.index, lead.attrs);
|
||||
}
|
||||
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
val value := this.accept(tk::assign) ? this.expression() : 0;
|
||||
return this.declared_at(this.make_node(nk::enumerator, token, lead.attrs, value), &lead);
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
#! @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.");
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
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());
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
#! @file fields.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the parsing of the fields of struct literals and attributes, with
|
||||
#! their spreads and renames.
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! The fields of a struct literal or an attribute, from its `{` to its `}`.
|
||||
#! @param this The parser.
|
||||
#! @returns The run of `field_init` nodes.
|
||||
def parser::field_list(&mut this): u32 {
|
||||
this.advance();
|
||||
return this.list(parser::item::field, tk::rbrace, "Expected `}` to close the structure literal.");
|
||||
}
|
||||
|
||||
#! A field of a struct literal or an attribute, a `field_init`, whose token is
|
||||
#! the field where it is named, as `x` of `x = 1`, which its `named` flag says,
|
||||
#! and the first of its value where it is given by position.
|
||||
#! @param this The parser.
|
||||
#! @returns The `field_init` node.
|
||||
def parser::field_init(&mut this): u32 {
|
||||
val token := this.index;
|
||||
val named := this.check(tk::name) && this.peek(1) == tk::assign;
|
||||
if named {
|
||||
this.advance();
|
||||
this.advance();
|
||||
}
|
||||
|
||||
return this.make_node(nk::field_init, token, this.expression(), parser::bit(named, nf::named));
|
||||
}
|
||||
|
||||
#! The type of a field that spreads another's fields into its own, as `...T` or
|
||||
#! `...T{ a as b }`, from its `...`.
|
||||
#! @param this The parser.
|
||||
#! @returns The `spread` node.
|
||||
def parser::spread(&mut this): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
|
||||
val type_name := this.type_name();
|
||||
return this.make_node(nk::spread, token, type_name) if !this.accept(tk::lbrace);
|
||||
|
||||
val renames := this.list(parser::item::rename, tk::rbrace, "Expected `}` to close the renames.");
|
||||
return this.make_node(nk::spread, token, type_name, renames);
|
||||
}
|
||||
|
||||
#! `old as new`, which gives a spread field another name.
|
||||
#! @param this The parser.
|
||||
#! @returns The `rename` node, or an `error` node.
|
||||
def parser::rename(&mut this): u32 {
|
||||
if !this.check(tk::name) {
|
||||
this.fail(ec::ident, "Expected the name of a field to rename.");
|
||||
return this.error_here();
|
||||
}
|
||||
|
||||
val old := this.index;
|
||||
this.advance();
|
||||
this.expect(tk::kw_as, "Expected `as` followed by the new name.");
|
||||
return this.make_node(nk::rename, old, this.name_node("Expected the new field name."));
|
||||
}
|
||||
@@ -0,0 +1,633 @@
|
||||
#! @file helpers.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains what the rest of the parser is made from: moving through the tokens,
|
||||
#! making nodes, records, and runs, starting declarations, making notes, lists,
|
||||
#! and recovering from what is wrong to parse what follows.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
# Tokens
|
||||
|
||||
#! Reads the kind of the current token into `kind`, which is `eof` at the limit.
|
||||
#! @param this The parser.
|
||||
def parser::sync(&mut this): void {
|
||||
this.kind = this.index < this.limit
|
||||
? this.syntax.token_kinds[this.index]
|
||||
: tk::eof;
|
||||
}
|
||||
|
||||
#! The kind of the token `ahead` past the current one, or `eof` past the limit.
|
||||
#! @param this The parser.
|
||||
#! @param ahead How many tokens past the current one, where 0 is the current
|
||||
#! one.
|
||||
#! @returns The token's kind.
|
||||
def parser::peek(&this, ahead: u32): tk {
|
||||
val at := this.index + ahead;
|
||||
return at < this.limit
|
||||
? this.syntax.token_kinds[at]
|
||||
: tk::eof;
|
||||
}
|
||||
|
||||
#! Moves to the next token, staying on the `eof` that ends them.
|
||||
#!
|
||||
#! A `>>`, `>=`, or `>>=` is followed by a token at each `>` and `=` after its
|
||||
#! first, which `close_angle` takes one at a time, and which an operator is
|
||||
#! moved past with, as one token for each byte it spans.
|
||||
#! @param this The parser.
|
||||
def parser::advance(&mut this): void {
|
||||
return if this.kind == tk::eof;
|
||||
if this.kind.has(tt::angle) {
|
||||
this.index += this.kind.width;
|
||||
} else {
|
||||
this.index++;
|
||||
}
|
||||
this.sync();
|
||||
}
|
||||
|
||||
def parser::check(&this, kind: tk): bool {
|
||||
return this.kind == kind;
|
||||
}
|
||||
|
||||
#! Whether the current token is the name of the ID, as `names::this_id`.
|
||||
#! @param this The parser.
|
||||
#! @param word The ID of the name.
|
||||
#! @returns Whether the current token is that name.
|
||||
def parser::check_word(&this, word: u32): bool {
|
||||
return this.kind == tk::name && this.syntax.token_names[this.index] == word;
|
||||
}
|
||||
|
||||
#! Whether the current token's kind has the trait.
|
||||
#! @param this The parser.
|
||||
#! @param which The trait to ask of the token's kind.
|
||||
#! @returns Whether its kind has it.
|
||||
def parser::at(&this, which: tt): bool {
|
||||
return this.kind.has(which);
|
||||
}
|
||||
|
||||
#! Moves past the current token when it is of the kind.
|
||||
#! @param this The parser.
|
||||
#! @param kind The kind of token to move past.
|
||||
#! @returns Whether it was, and so was moved past.
|
||||
def parser::accept(&mut this, kind: tk): bool {
|
||||
return false if this.kind != kind;
|
||||
this.advance();
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Moves past the current token when it is of the kind, or else reports the
|
||||
#! detail and panics.
|
||||
#! @param this The parser.
|
||||
#! @param kind The kind of token wanted.
|
||||
#! @param detail What the note says where it is not, as `Expected ";" after
|
||||
#! the statement.`.
|
||||
#! @returns Whether it was of the kind.
|
||||
def parser::expect(&mut this, kind: tk, detail: strview): bool {
|
||||
return true if this.accept(kind);
|
||||
this.fail(ec::token, detail);
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Moves past the `>` closing type arguments or parameters, which may be the
|
||||
#! first of `>>`, `>=`, or `>>=`. The lexer made a token of what is left of
|
||||
#! those, which becomes the current token: `>`, `=`, or `>=`.
|
||||
#! @param this The parser.
|
||||
#! @param detail What the note says where no `>` is there.
|
||||
#! @returns Whether a `>` was moved past.
|
||||
def parser::close_angle(&mut this, detail: strview): bool {
|
||||
if !this.at(tt::angle) {
|
||||
this.fail(ec::token, detail);
|
||||
return false;
|
||||
}
|
||||
|
||||
this.index++;
|
||||
this.sync();
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Whether the type whose `<` is at the token follows `as` or `is`, where a `<`
|
||||
#! always begins type arguments, so what looks like a comparison is not one.
|
||||
#! @param this The parser.
|
||||
#! @param at The token of the `<`.
|
||||
#! @returns Whether `as` or `is` comes before the type.
|
||||
def parser::follows_cast(&this, at: u32): bool {
|
||||
var back := at;
|
||||
while back > 0 {
|
||||
back--;
|
||||
val kind := this.syntax.token_kinds[back];
|
||||
return kind == tk::kw_as || kind == tk::kw_is if !kind.has(tt::piece);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
# Nodes
|
||||
|
||||
#! Appends a node, whose last token is the last the parser moved past, or its
|
||||
#! own where it moved past none since.
|
||||
#! @param this The parser.
|
||||
#! @param kind The node's kind.
|
||||
#! @param token Its token.
|
||||
#! @param left Its first slot, which its kind's shape says the meaning of.
|
||||
#! @param right Its second slot.
|
||||
#! @returns The node.
|
||||
def parser::make_node(
|
||||
&mut this,
|
||||
kind: nk,
|
||||
token: u32,
|
||||
left: u32 = 0,
|
||||
right: u32 = 0
|
||||
): u32 {
|
||||
val end := this.index > token ? this.index - 1 : token;
|
||||
return this.syntax.add_node(kind, token, left, right, end);
|
||||
}
|
||||
|
||||
#! An `error` node at the token, standing where the parser made no sense of the
|
||||
#! source, holding the run of what it did parse there, so that tools still find
|
||||
#! what is within it.
|
||||
#! @param this The parser.
|
||||
#! @param token The token it stands at.
|
||||
#! @param held The run of what was parsed there, or 0.
|
||||
#! @returns The node.
|
||||
def parser::error(&mut this, token: u32, held: u32 = 0): u32 {
|
||||
return this.make_node(nk::error, token, held);
|
||||
}
|
||||
|
||||
#! An `error` node at the current token, holding nothing.
|
||||
#! @param this The parser.
|
||||
#! @returns The node.
|
||||
def parser::error_here(&mut this): u32 {
|
||||
return this.error(this.index);
|
||||
}
|
||||
|
||||
#! A `when_block`, `if_stmt`, `if_const`, or `ternary`: a condition, and what is
|
||||
#! taken where it holds and where it does not.
|
||||
#! @param this The parser.
|
||||
#! @param kind The node's kind.
|
||||
#! @param token Its token.
|
||||
#! @param condition The condition.
|
||||
#! @param then What is taken where it holds.
|
||||
#! @param other What is taken where it does not, or 0.
|
||||
#! @returns The node.
|
||||
def parser::branch(&mut this, kind: nk, token: u32, condition: u32, then: u32, other: u32): u32 {
|
||||
return this.make_node(kind, token, condition, this.make_record(then, other));
|
||||
}
|
||||
|
||||
#! A `name` node of the current token, which is moved past.
|
||||
#! @param this The parser.
|
||||
#! @param detail What the note says where the current token is no name.
|
||||
#! @returns The node, or an `error` node where the token is no name.
|
||||
def parser::name_node(&mut this, detail: strview): u32 {
|
||||
if !this.check(tk::name) {
|
||||
this.fail(ec::ident, detail);
|
||||
return this.error_here();
|
||||
}
|
||||
|
||||
this.advance();
|
||||
return this.make_node(nk::name, this.index - 1);
|
||||
}
|
||||
|
||||
#! Writes a record of a node's slots to `extras`, unless every slot is 0, where
|
||||
#! the zeros `extras` begins with stand for it.
|
||||
#! @param this The parser.
|
||||
#! @param slots The node's slots, in the order its shape lists them.
|
||||
#! @returns Where the record begins, for the slot of the node holding it.
|
||||
def parser::make_record(&mut this, slots: u32...): u32 {
|
||||
var empty := true;
|
||||
for slot in slots {
|
||||
empty = empty && slot == 0;
|
||||
}
|
||||
return 0 if empty;
|
||||
|
||||
val at := this.syntax.extras.length as u32;
|
||||
this.syntax.extras.extend(slots);
|
||||
return at;
|
||||
}
|
||||
|
||||
#! Where the nodes of a run begin on the scratchpad, for `make_run`.
|
||||
#! @param this The parser.
|
||||
#! @returns The scratchpad's length.
|
||||
val parser::mark: u64 { get => this.scratch.length; }
|
||||
|
||||
#! Holds a node of a run being parsed on the scratchpad.
|
||||
#! @param this The parser.
|
||||
#! @param node The node.
|
||||
def parser::push(&mut this, node: u32): void {
|
||||
this.scratch.push(node);
|
||||
}
|
||||
|
||||
#! Moves the nodes held on the scratchpad since the mark to a run in `extras`.
|
||||
#! @param this The parser.
|
||||
#! @param mark Where the nodes begin, as `mark` gave it.
|
||||
#! @returns Where the run begins, or 0 for a run of no nodes.
|
||||
def parser::make_run(&mut this, mark: u64): u32 {
|
||||
val count := this.scratch.length - mark;
|
||||
return 0 if count == 0;
|
||||
|
||||
val at := this.syntax.extras.length as u32;
|
||||
this.syntax.extras.append(count as u32);
|
||||
this.syntax.extras.extend(span::<u32>::over(this.scratch.view().data + mark, count));
|
||||
|
||||
this.drop(mark);
|
||||
return at;
|
||||
}
|
||||
|
||||
#! A run of the nodes given, leaving out those that are absent.
|
||||
#! @param this The parser.
|
||||
#! @param nodes The nodes, of which 0 is left out.
|
||||
#! @returns Where the run begins, or 0 where it holds none.
|
||||
def parser::run_of(&mut this, nodes: u32...): u32 {
|
||||
val mark := this.mark;
|
||||
for node in nodes {
|
||||
if node != 0 {
|
||||
this.push(node);
|
||||
}
|
||||
}
|
||||
return this.make_run(mark);
|
||||
}
|
||||
|
||||
#! Lets go of the nodes held on the scratchpad since the mark.
|
||||
#! @param this The parser.
|
||||
#! @param mark Where the nodes begin, as `mark` gave it.
|
||||
def parser::drop(&mut this, mark: u64): void {
|
||||
this.scratch.resize(mark);
|
||||
}
|
||||
|
||||
#! A run of the nodes of `first` followed by those of `second`.
|
||||
#! @param this The parser.
|
||||
#! @param first The run whose nodes come first.
|
||||
#! @param second The run whose nodes come after.
|
||||
#! @returns The joined run, or 0 where both are empty.
|
||||
def parser::join_runs(&mut this, first: u32, second: u32): u32 {
|
||||
return second if first == 0;
|
||||
return first if second == 0;
|
||||
|
||||
val mark := this.mark;
|
||||
for &node in this.run_view(first) { this.push(node); }
|
||||
for &node in this.run_view(second) { this.push(node); }
|
||||
return this.make_run(mark);
|
||||
}
|
||||
|
||||
#! How many nodes the run holds.
|
||||
#! @param this The parser.
|
||||
#! @param run Where the run begins.
|
||||
#! @returns How many nodes it holds.
|
||||
def parser::run_length(&this, run: u32): u32 {
|
||||
return this.syntax.run_length(run);
|
||||
}
|
||||
|
||||
#! The node at the index of the run.
|
||||
#! @param this The parser.
|
||||
#! @param run Where the run begins.
|
||||
#! @param index The position, below its length.
|
||||
#! @returns The node.
|
||||
def parser::run_at(&this, run: u32, index: u32): u32 {
|
||||
return this.syntax.run_at(run, index);
|
||||
}
|
||||
|
||||
#! The nodes of the run, where they are.
|
||||
#! @param this The parser.
|
||||
#! @param run Where the run begins.
|
||||
#! @returns The nodes, a view only good until another run or record is made.
|
||||
def parser::run_view(&this, run: u32): span<u32> {
|
||||
return this.syntax.run_view(run);
|
||||
}
|
||||
|
||||
#! The ID of the name the node's token is.
|
||||
#! @param this The parser.
|
||||
#! @param node The node.
|
||||
#! @returns The name's ID.
|
||||
def parser::name_of(&this, node: u32): u32 {
|
||||
return this.syntax.token_names[this.syntax.node_tokens[node]];
|
||||
}
|
||||
|
||||
#! The bit of a flag when it is on, to be or'd with others into a mask, as a
|
||||
#! `flags` slot.
|
||||
#! @tparam T The enum of flags.
|
||||
#! @param on Whether the flag is on.
|
||||
#! @param flag The flag.
|
||||
#! @returns The flag's bit, or 0 where it is off.
|
||||
def parser::bit<T>(on: bool, flag: T): u32 where T: ordinal {
|
||||
return on ? flag as u32 : 0;
|
||||
}
|
||||
|
||||
|
||||
# Declarations
|
||||
|
||||
#! What comes before a declaration: its attributes, `pub`, and the token it
|
||||
#! begins at, which its documentation is written before.
|
||||
struct parser::lead {
|
||||
var attrs: u32; #! The run of its attributes.
|
||||
var exported: bool; #! `pub`.
|
||||
var start: u32; #! The token it begins at.
|
||||
}
|
||||
|
||||
#! Where a declaration is written, which says what it may be.
|
||||
enum parser::place {
|
||||
top, #! At the top level of a file, or within a `when` there.
|
||||
local, #! Within a function.
|
||||
field, #! Within a struct or union.
|
||||
member, #! Within a trait.
|
||||
}
|
||||
|
||||
#! The lead of a declaration beginning at the current token, with nothing before
|
||||
#! it.
|
||||
#! @param this The parser.
|
||||
#! @returns The lead.
|
||||
def parser::bare_lead(&this): parser::lead {
|
||||
return parser::lead { start = this.index };
|
||||
}
|
||||
|
||||
#! Records where a declaration began, which says what documents it.
|
||||
#! @param this The parser.
|
||||
#! @param made The declaration's node.
|
||||
#! @param lead What came before it: where it began, and its documentation.
|
||||
#! @returns The declaration.
|
||||
def parser::declared_at(&mut this, made: u32, lead: &parser::lead): u32 {
|
||||
if made != 0 && this.syntax.node_kinds[made] != nk::error {
|
||||
this.syntax.starts.set(made as u64, lead.start);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
|
||||
# Notes
|
||||
|
||||
#! Reports an error at the current token, then panics, which silences notes
|
||||
#! until the parser resynchronizes so that one mistake is one note.
|
||||
#! @param this The parser.
|
||||
#! @param code What kind of error it is.
|
||||
#! @param detail What the note says.
|
||||
def parser::fail(&mut this, code: ec, detail: strview): void {
|
||||
this.fail_at(this.index, code, detail);
|
||||
}
|
||||
|
||||
def parser::fail_at(&mut this, token: u32, code: ec, detail: strview): void {
|
||||
# Failing at a limit short of the end of the tokens says a reparse cut what it
|
||||
# parsed short, which a whole parse would have read on past.
|
||||
if this.kind == tk::eof && this.limit + 1 < this.syntax.token_count as u32 {
|
||||
this.cut = true;
|
||||
}
|
||||
|
||||
return if this.panic;
|
||||
this.report_at(token, code, detail);
|
||||
this.panic = true;
|
||||
}
|
||||
|
||||
#! Reports an error at the current token without panicking, for mistakes the
|
||||
#! parser reads past knowing what was meant.
|
||||
#! @param this The parser.
|
||||
#! @param code What kind of error it is.
|
||||
#! @param detail What the note says.
|
||||
def parser::report(&mut this, code: ec, detail: strview): void {
|
||||
this.report_at(this.index, code, detail);
|
||||
}
|
||||
|
||||
#! Reports an error at the token. A note saying what was expected says what was
|
||||
#! found instead, the token it is at, which `note::message` spells.
|
||||
#! @param this The parser.
|
||||
#! @param token The token the error is at.
|
||||
#! @param code What kind of error it is.
|
||||
#! @param detail What the note says.
|
||||
def parser::report_at(&mut this, token: u32, code: ec, detail: strview): void {
|
||||
return if this.panic || this.halted || !this.sink.admits();
|
||||
var made := note {
|
||||
file = this.file,
|
||||
offset = this.syntax.token_offsets[token],
|
||||
length = this.syntax.token_length(token, this.names),
|
||||
code = code,
|
||||
detail = string::from(detail, nothing {}),
|
||||
found = detail.starts_with("Expected")
|
||||
};
|
||||
this.sink.give(&mut made);
|
||||
}
|
||||
|
||||
|
||||
# Nesting
|
||||
|
||||
#! Goes one level deeper, unless that is past `max_depth`, where the rest of the
|
||||
#! declaration is given up on: the tokens seem to end where it does, so that
|
||||
#! everything parsing it returns, and the top level resumes after it.
|
||||
#! @param this The parser.
|
||||
#! @returns Whether the parser went deeper, and must `leave` again.
|
||||
def parser::enter(&mut this): bool {
|
||||
if this.depth < parser::max_depth {
|
||||
this.depth++;
|
||||
return true;
|
||||
}
|
||||
|
||||
if !this.halted {
|
||||
this.panic = false;
|
||||
this.fail(ec::syntax, "Nesting exceeds the maximum depth.");
|
||||
|
||||
val end := this.declaration_end();
|
||||
this.index = end;
|
||||
this.limit = end;
|
||||
this.halted = true;
|
||||
this.sync();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
def parser::leave(&mut this): void {
|
||||
this.depth--;
|
||||
}
|
||||
|
||||
#! Where the top-level declaration the parser is within ends, from where it
|
||||
#! began: past the `}` closing the braces it opens, or the `;` ending it outside
|
||||
#! any, whichever comes past the current token.
|
||||
#! @param this The parser.
|
||||
#! @returns The token after the declaration.
|
||||
def parser::declaration_end(&this): u32 {
|
||||
val last := this.syntax.token_count as u32 - 1;
|
||||
var braces: u32 = 0;
|
||||
for at in this.begun..last {
|
||||
val kind := this.syntax.token_kinds[at];
|
||||
if kind == tk::lbrace {
|
||||
braces++;
|
||||
} else if kind == tk::rbrace {
|
||||
return at + 1 if braces <= 1 && at >= this.index;
|
||||
braces = braces > 0 ? braces - 1 : 0;
|
||||
} else if kind == tk::semicolon && braces == 0 && at >= this.index {
|
||||
return at + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return last;
|
||||
}
|
||||
|
||||
#! Takes up the tokens after a declaration given up on, through the limit.
|
||||
#! @param this The parser.
|
||||
#! @param limit The last token to take up.
|
||||
def parser::resume(&mut this, limit: u32): void {
|
||||
this.limit = limit;
|
||||
this.halted = false;
|
||||
this.panic = false;
|
||||
this.sync();
|
||||
}
|
||||
|
||||
|
||||
# Recovery
|
||||
|
||||
#! Where the parser resumes after an error, which decides the tokens it stops
|
||||
#! at.
|
||||
enum parser::scope {
|
||||
document, #! The top level of a file.
|
||||
declarations, #! Within a `when` at the top level.
|
||||
block, #! Statements.
|
||||
fields, #! The members of a struct or union.
|
||||
members, #! The members of a trait.
|
||||
}
|
||||
|
||||
#! Whether the current token begins the next item of the scope.
|
||||
#! @param this The parser.
|
||||
#! @param scope What the parser is within.
|
||||
#! @returns Whether the token begins an item of it.
|
||||
def parser::resumes(&this, scope: parser::scope): bool {
|
||||
return match scope {
|
||||
parser::scope::document => this.at(tt::declares) || this.at(tt::imports),
|
||||
parser::scope::declarations => this.at(tt::declares),
|
||||
parser::scope::block => this.at(tt::states),
|
||||
parser::scope::fields => this.at(tt::fields),
|
||||
parser::scope::members => this.at(tt::members),
|
||||
else => false
|
||||
};
|
||||
}
|
||||
|
||||
#! Skips tokens until one that can begin the next item of the scope, stepping
|
||||
#! over balanced braces, then stops panicking. Every token it stops on is
|
||||
#! consumed by the item parser, or ends the enclosing loop, so parsing always
|
||||
#! makes progress.
|
||||
#! @param this The parser.
|
||||
#! @param scope What the parser is within.
|
||||
def parser::synchronize(&mut this, scope: parser::scope): void {
|
||||
var braces: u32 = 0;
|
||||
while !this.check(tk::eof) {
|
||||
if braces == 0 {
|
||||
break if this.resumes(scope);
|
||||
if this.check(tk::semicolon) {
|
||||
this.advance();
|
||||
break;
|
||||
}
|
||||
|
||||
if this.check(tk::rbrace) {
|
||||
if scope == parser::scope::document {
|
||||
this.advance();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if this.check(tk::lbrace) {
|
||||
braces++;
|
||||
} else if this.check(tk::rbrace) {
|
||||
braces--;
|
||||
if braces == 0 {
|
||||
this.advance();
|
||||
break;
|
||||
}
|
||||
}
|
||||
this.advance();
|
||||
}
|
||||
|
||||
this.panic = false;
|
||||
}
|
||||
|
||||
#! Skips to the `}` closing the braces the parser is within, without moving
|
||||
#! past it, then stops panicking.
|
||||
#! @param this The parser.
|
||||
def parser::skip_to_close(&mut this): void {
|
||||
var braces: u32 = 0;
|
||||
while !this.check(tk::eof) {
|
||||
if this.check(tk::lbrace) {
|
||||
braces++;
|
||||
} else if this.check(tk::rbrace) {
|
||||
break if braces == 0;
|
||||
braces--;
|
||||
}
|
||||
this.advance();
|
||||
}
|
||||
|
||||
this.panic = false;
|
||||
}
|
||||
|
||||
|
||||
# Lists
|
||||
|
||||
#! What a list holds, which `list_item` parses one of.
|
||||
enum parser::item {
|
||||
argument, #! Of a call.
|
||||
element, #! Of an array.
|
||||
field, #! Of a struct literal or an attribute.
|
||||
param_type, #! Of a function type.
|
||||
rename, #! Of a spread field.
|
||||
enumerator, #! Of an enum.
|
||||
value_arm, #! Of a match used as a value.
|
||||
}
|
||||
|
||||
def parser::list_item(&mut this, kind: parser::item): u32 {
|
||||
return match kind {
|
||||
parser::item::argument => this.argument(),
|
||||
parser::item::element => this.expression(),
|
||||
parser::item::field => this.field_init(),
|
||||
parser::item::param_type => this.spread_type(),
|
||||
parser::item::rename => this.rename(),
|
||||
parser::item::enumerator => this.enumerator(),
|
||||
parser::item::value_arm => this.arm(true),
|
||||
else => this.error_here()
|
||||
};
|
||||
}
|
||||
|
||||
#! The items of a list separated by commas, which may end with one, through the
|
||||
#! token closing it. An item that fails is skipped to the comma or closing token
|
||||
#! after it, so one mistake leaves the rest of the list parsed.
|
||||
#! @param this The parser.
|
||||
#! @param kind What the items are.
|
||||
#! @param close The kind of token closing the list.
|
||||
#! @param detail What the note says where the closing token is missing.
|
||||
#! @returns The run of items.
|
||||
def parser::list(&mut this, kind: parser::item, close: tk, detail: strview): u32 {
|
||||
val angled := this.angled;
|
||||
this.angled = false;
|
||||
val mark := this.mark;
|
||||
while !this.check(close) && !this.check(tk::eof) {
|
||||
this.push(this.list_item(kind));
|
||||
break if this.panic && !this.skip_item(close);
|
||||
break if !this.accept(tk::comma);
|
||||
}
|
||||
|
||||
val items := this.make_run(mark);
|
||||
this.expect(close, detail);
|
||||
this.angled = angled;
|
||||
return items;
|
||||
}
|
||||
|
||||
#! Skips what is left of an item that failed, stepping over what is nested in
|
||||
#! it, to the comma or closing token after it, then stops panicking. It gives up
|
||||
#! at a `;`, or at a closing token of something outside the list, which the
|
||||
#! enclosing parser recovers at instead.
|
||||
#! @param this The parser.
|
||||
#! @param close The kind of token closing the list.
|
||||
#! @returns Whether the list goes on.
|
||||
def parser::skip_item(&mut this, close: tk): bool {
|
||||
var depth: u32 = 0;
|
||||
while !this.check(tk::eof) {
|
||||
if depth == 0 && (this.check(tk::comma) || this.check(close)) {
|
||||
this.panic = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
val closes := this.at(tt::closes);
|
||||
return false if depth == 0 && (closes || this.check(tk::semicolon) || this.check(tk::istring_mid));
|
||||
|
||||
if this.at(tt::opens) { depth++; }
|
||||
if closes { depth--; }
|
||||
this.advance();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
#! @file primary.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the parsing of primaries, which operators are applied to: literals,
|
||||
#! interpolated strings, names and paths with their struct literals, arrays,
|
||||
#! lambdas, `type_of`, and expressions in parentheses.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! What an expression is built from: a literal, a name or path, a struct
|
||||
#! literal, an expression in parentheses, a lambda, an array, a match used as a
|
||||
#! value, or `type_of(d)`, a type named to test it with `is`.
|
||||
#! @param this The parser.
|
||||
#! @param structs Whether a name followed by `{` is a struct literal.
|
||||
#! @returns The node, or an `error` node.
|
||||
def parser::primary(&mut this, structs: bool): u32 {
|
||||
# `type_of(d)` is a type, which an expression names only to test it, as
|
||||
# `type_of(d) is copyable`.
|
||||
if this.check_word(names::type_of_id) && this.peek(1) == tk::lparen {
|
||||
return this.type_primary();
|
||||
}
|
||||
# Within an `ensures`, `old(e)` is what `e` was where it was reached.
|
||||
if this.in_ensures && this.check_word(names::old_id) && this.peek(1) == tk::lparen {
|
||||
return this.old_value();
|
||||
}
|
||||
|
||||
val token := this.index;
|
||||
match this.kind {
|
||||
tk::signed, tk::unsigned, tk::float => return this.literal(nk::number);
|
||||
tk::char => return this.literal(nk::character);
|
||||
tk::string => return this.literal(nk::string);
|
||||
tk::kw_true, tk::kw_false => return this.literal(nk::boolean);
|
||||
tk::kw_null => return this.literal(nk::null_lit);
|
||||
tk::istring, tk::istring_beg => return this.istring();
|
||||
tk::kw_match => return this.match_expr(true);
|
||||
tk::kw_def => return this.lambda();
|
||||
tk::lbracket => return this.array();
|
||||
tk::name => return this.named(structs);
|
||||
|
||||
# What is between parentheses may be a struct literal.
|
||||
tk::lparen => {
|
||||
val angled := this.angled;
|
||||
this.angled = false;
|
||||
this.advance();
|
||||
val inner := this.expression();
|
||||
this.expect(tk::rparen, "Expected `)` to close the expression.");
|
||||
this.angled = angled;
|
||||
return inner;
|
||||
}
|
||||
|
||||
# The lexer reported what is wrong with a malformed literal, so it stands as
|
||||
# an error with nothing more said.
|
||||
tk::bad_number, tk::bad_quote => {}
|
||||
else => {
|
||||
this.fail(ec::expr, "Expected an expression.");
|
||||
return this.error_here();
|
||||
}
|
||||
}
|
||||
|
||||
this.advance();
|
||||
return this.error(token);
|
||||
}
|
||||
|
||||
#! `old(e)` within an `ensures`: what `e` was where the `ensures` was reached.
|
||||
#! @param this The parser.
|
||||
#! @returns The `old_value` node.
|
||||
def parser::old_value(&mut this): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
this.advance();
|
||||
val inner := this.expression();
|
||||
this.expect(tk::rparen, "Expected `)` to close `old`, which takes one expression.");
|
||||
return this.make_node(nk::old_value, token, inner);
|
||||
}
|
||||
|
||||
#! A literal of the kind, which its token alone describes.
|
||||
#! @param this The parser.
|
||||
#! @param kind The node's kind.
|
||||
#! @returns The node.
|
||||
def parser::literal(&mut this, kind: nk): u32 {
|
||||
this.advance();
|
||||
return this.make_node(kind, this.index - 1);
|
||||
}
|
||||
|
||||
#! An interpolated string, whose run holds its text as `string` nodes, the token
|
||||
#! of each a piece of it, between which come the expressions of its holes: the
|
||||
#! `istring_beg` before the first hole, an `istring_mid` between two holes, and
|
||||
#! the `istring_end` after the last. One with no holes is one `istring` piece.
|
||||
#! @param this The parser.
|
||||
#! @returns The `istring` node.
|
||||
def parser::istring(&mut this): u32 {
|
||||
val token := this.index;
|
||||
val mark := this.mark;
|
||||
this.push(this.literal(nk::string));
|
||||
val angled := this.angled;
|
||||
this.angled = false;
|
||||
if this.syntax.token_kinds[token] == tk::istring_beg {
|
||||
while true {
|
||||
this.push(this.expression());
|
||||
if this.check(tk::istring_mid) {
|
||||
this.push(this.literal(nk::string));
|
||||
continue;
|
||||
}
|
||||
|
||||
if this.check(tk::istring_end) {
|
||||
this.push(this.literal(nk::string));
|
||||
break;
|
||||
}
|
||||
|
||||
this.fail(ec::token, "Expected `}` after the interpolated expression.");
|
||||
this.skip_hole();
|
||||
break;
|
||||
}
|
||||
}
|
||||
this.angled = angled;
|
||||
|
||||
return this.make_node(nk::istring, token, this.make_run(mark));
|
||||
}
|
||||
|
||||
#! Skips past the end of the interpolated string whose hole the parser is
|
||||
#! within, stepping over the strings within it.
|
||||
#! @param this The parser.
|
||||
def parser::skip_hole(&mut this): void {
|
||||
var depth: u32 = 0;
|
||||
while !this.check(tk::eof) {
|
||||
if this.check(tk::istring_beg) {
|
||||
depth++;
|
||||
} else if this.check(tk::istring_end) {
|
||||
if depth == 0 {
|
||||
this.advance();
|
||||
break;
|
||||
}
|
||||
depth--;
|
||||
}
|
||||
this.advance();
|
||||
}
|
||||
}
|
||||
|
||||
#! A name, a path, as `math::max::<u8>`, or a struct literal of either, where
|
||||
#! they are allowed.
|
||||
#! @param this The parser.
|
||||
#! @param structs Whether a struct literal may follow.
|
||||
#! @returns The `name`, `path`, or `construct` node.
|
||||
def parser::named(&mut this, structs: bool): u32 {
|
||||
val token := this.index;
|
||||
var made: u32 = 0;
|
||||
if this.peek(1) == tk::scope {
|
||||
made = this.make_node(nk::path, token, this.segments(parser::args::values));
|
||||
} else {
|
||||
this.advance();
|
||||
made = this.make_node(nk::name, token);
|
||||
}
|
||||
|
||||
return made if !structs || !this.check(tk::lbrace);
|
||||
|
||||
# The literal's type is the name read as a type: a path's segments are a type
|
||||
# name's, and a name is a type name of one segment, which holds no run.
|
||||
this.syntax.node_kinds[made] = nk::type_name;
|
||||
|
||||
val brace := this.index;
|
||||
return this.make_node(nk::construct, brace, made, this.field_list());
|
||||
}
|
||||
|
||||
#! `[a, b, c]`.
|
||||
#! @param this The parser.
|
||||
#! @returns The `array` node.
|
||||
def parser::array(&mut this): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
|
||||
val elements := this.list(parser::item::element, tk::rbracket, "Expected `]` to close the array.");
|
||||
return this.make_node(nk::array, token, elements);
|
||||
}
|
||||
|
||||
#! `def(params): result { body }`, or `def(params) => value`, which returns the
|
||||
#! value, or evaluates it for `void`. Its parameter types and result may be left
|
||||
#! out.
|
||||
#! @param this The parser.
|
||||
#! @returns The `lambda` node.
|
||||
def parser::lambda(&mut this): u32 {
|
||||
val token := this.index;
|
||||
val angled := this.angled;
|
||||
this.angled = false;
|
||||
# A lambda's body is checked where it is called, which no `old` reaches back
|
||||
# from.
|
||||
val ensures := this.in_ensures;
|
||||
this.in_ensures = false;
|
||||
this.advance();
|
||||
|
||||
val signature := this.params(true, false);
|
||||
val body := this.accept(tk::arrow)
|
||||
? this.expression()
|
||||
: this.block();
|
||||
this.angled = angled;
|
||||
this.in_ensures = ensures;
|
||||
return this.make_node(nk::lambda, token, signature.params, this.make_record(signature.result, body));
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
#! @file reparse.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains `syntax::reparse`, which parses only the top-level declarations an
|
||||
#! edit touched, and keeps the trees of the rest.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! Reparses a file after an edit, keeping the trees of the top-level
|
||||
#! declarations the edit did not touch, and parsing again only those it did.
|
||||
#!
|
||||
#! The edited text is lexed whole into `fresh`, which is cheap, and its tokens
|
||||
#! are compared with the old ones from each end to find what changed. The
|
||||
#! declarations around the change are parsed again from the fresh tokens, and
|
||||
#! those after it keep their nodes, whose tokens move by how many the edit added
|
||||
#! or took away. Where a declaration parsed again runs into where the change
|
||||
#! ends, as one that lost its closing `}` does, the file is parsed whole
|
||||
#! instead, so the tree is always the one a whole parse makes.
|
||||
#!
|
||||
#! The nodes of the declarations parsed again are left behind, unreachable. Once
|
||||
#! there are as many nodes or extras again as the last whole parse made, the
|
||||
#! file is parsed whole, which lets go of them, so a file edited for a long
|
||||
#! while does not keep growing. The indexes of every node change when it does.
|
||||
#! @param this The syntax tree.
|
||||
#! @param fresh The edited text, lexed: its tokens, documentation, and
|
||||
#! comments.
|
||||
#! @param names The names `fresh` was lexed with.
|
||||
#! @param document The `document` node of this syntax.
|
||||
#! @param notes The notes of this file, both the lexer's and the
|
||||
#! parser's.
|
||||
#! @param fresh_notes What the lexer noted of the edited text, which are moved
|
||||
#! into `notes`.
|
||||
#! @param file The index of the file.
|
||||
#! @returns The `document` node.
|
||||
pub def syntax::reparse(
|
||||
&mut this,
|
||||
fresh: &mut syntax,
|
||||
names: &names,
|
||||
document: u32,
|
||||
notes: &mut vector<note>,
|
||||
fresh_notes: &mut vector<note>,
|
||||
file: u32
|
||||
): u32 {
|
||||
val old_count := this.token_count as u32;
|
||||
val new_count := fresh.token_count as u32;
|
||||
val bytes := fresh.token_offsets[new_count - 1] as i64 - this.token_offsets[old_count - 1] as i64;
|
||||
val shift := new_count as i64 - old_count as i64;
|
||||
|
||||
# What is the same before the change, and after it, where it has moved.
|
||||
var same_before: u32 = 0;
|
||||
while same_before < old_count - 1 && same_before < new_count - 1
|
||||
&& this.same_token(fresh, same_before, same_before, 0) {
|
||||
same_before++;
|
||||
}
|
||||
|
||||
var same_after: u32 = 0;
|
||||
while same_after < old_count - 1 - same_before && same_after < new_count - 1 - same_before
|
||||
&& this.same_token(fresh, old_count - 2 - same_after, new_count - 2 - same_after, bytes) {
|
||||
same_after++;
|
||||
}
|
||||
|
||||
val changed_end := old_count - 1 - same_after;
|
||||
|
||||
# The declarations the change touches, from `first` through `last`, and the
|
||||
# tokens they and the change span.
|
||||
val decls: u32 = this.node_lefts[document];
|
||||
val count := this.run_length(decls);
|
||||
var first := count;
|
||||
for i in 0..count {
|
||||
if this.node_end(this.run_at(decls, i as u32)) >= same_before {
|
||||
first = i as u32;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
var last := first;
|
||||
for i in first..count {
|
||||
break if this.start_of(this.run_at(decls, i as u32)) >= changed_end && i > first;
|
||||
last = i as u32;
|
||||
}
|
||||
|
||||
var from := same_before;
|
||||
var to := changed_end;
|
||||
if first < count {
|
||||
val start := this.start_of(this.run_at(decls, first));
|
||||
val end := this.node_end(this.run_at(decls, last)) + 1;
|
||||
from = start < from ? start : from;
|
||||
to = end > to ? end : to;
|
||||
}
|
||||
|
||||
# The notes of what is parsed again, and all of the lexer's, are made again.
|
||||
# They are put back in the order a whole parse makes them: the lexer's, then
|
||||
# the parser's along the text, those after the change moving with it.
|
||||
val from_byte := this.token_offsets[from];
|
||||
val to_byte := this.token_offsets[to < old_count - 1 ? to : old_count - 1];
|
||||
var before := vector::<note>::new();
|
||||
var after := vector::<note>::new();
|
||||
for &mut each in notes {
|
||||
continue if each.lexed;
|
||||
if each.offset < from_byte {
|
||||
before.append(move(each));
|
||||
continue;
|
||||
}
|
||||
|
||||
continue if each.offset < to_byte;
|
||||
each.offset = (each.offset as i64 + bytes) as u32;
|
||||
after.append(move(each));
|
||||
}
|
||||
|
||||
notes.clear();
|
||||
for &mut each in fresh_notes { notes.append(move(each)); }
|
||||
val kept := before.length + after.length;
|
||||
for &mut each in before { notes.append(move(each)); }
|
||||
|
||||
# The nodes after the change move with their tokens, and their ends with
|
||||
# them, which are held as how far past their tokens they are.
|
||||
for at in 1..this.node_count {
|
||||
if this.node_tokens[at] >= to {
|
||||
this.node_tokens[at] = (this.node_tokens[at] as i64 + shift) as u32;
|
||||
}
|
||||
}
|
||||
|
||||
var moved := vector::<u64>::new();
|
||||
for at in 0..this.starts.capacity {
|
||||
if this.starts.key_at(at) != keymap::free && this.starts.value_at(at) >= to {
|
||||
moved.append(this.starts.key_at(at));
|
||||
}
|
||||
}
|
||||
for key in moved {
|
||||
this.starts.set(key, (this.starts.get_or(&key, 0) as i64 + shift) as u32);
|
||||
}
|
||||
|
||||
this.take_tokens(fresh);
|
||||
|
||||
# The declarations around the change are parsed again, and their run takes
|
||||
# the place of theirs among the rest.
|
||||
val limit := (to as i64 + shift) as u32;
|
||||
var parsing := parser::new(this, names, notes, file);
|
||||
parsing.index = from;
|
||||
parsing.limit = limit;
|
||||
parsing.sink.count = kept as u32;
|
||||
parsing.sync();
|
||||
|
||||
val mark := parsing.mark;
|
||||
for i in 0..first { parsing.push(this.run_at(decls, i as u32)); }
|
||||
|
||||
# Where the parser reached as many notes as it makes, a whole parse would have
|
||||
# stopped somewhere else, so it is what tells which are made.
|
||||
val made := parsing.declarations(limit);
|
||||
if parsing.cut || parsing.sink.full {
|
||||
return this.parse_again(document, names, notes, file);
|
||||
}
|
||||
|
||||
for &mut each in after { notes.append(move(each)); }
|
||||
|
||||
for &node in this.run_view(made) { parsing.push(node); }
|
||||
for i in (last + 1)..count { parsing.push(this.run_at(decls, i as u32)); }
|
||||
|
||||
val declared := parsing.make_run(mark);
|
||||
this.node_lefts[document] = declared;
|
||||
this.set_node_end(document, this.token_count as u32 - 1);
|
||||
|
||||
if this.node_count > this.whole_nodes * 2 || this.extras.length > this.whole_extras * 2 {
|
||||
return this.parse_again(document, names, notes, file);
|
||||
}
|
||||
return document;
|
||||
}
|
||||
|
||||
#! Whether the old token and the fresh one are the same, the fresh one having
|
||||
#! moved `bytes` along the text.
|
||||
#! @param this The syntax tree.
|
||||
#! @param fresh The syntax lexed again.
|
||||
#! @param old The old token.
|
||||
#! @param now The fresh token.
|
||||
#! @param bytes How far the edit moved the fresh one, which is negative where
|
||||
#! text was taken out.
|
||||
#! @returns Whether they are.
|
||||
def syntax::same_token(&this, fresh: &syntax, old: u32, now: u32, bytes: i64): bool {
|
||||
val kind := this.token_kinds[old];
|
||||
return kind == fresh.token_kinds[now]
|
||||
&& this.token_names[old] == fresh.token_names[now]
|
||||
&& this.token_offsets[old] as i64 + bytes == fresh.token_offsets[now] as i64
|
||||
&& (kind == tk::name || kind.width != 0 || this.literal_length(old) == fresh.literal_length(now));
|
||||
}
|
||||
|
||||
#! Takes the tokens, documentation, and comments of `fresh` for its own.
|
||||
#! @param this The syntax tree.
|
||||
#! @param fresh The syntax lexed again, which is left without them.
|
||||
def syntax::take_tokens(&mut this, fresh: &mut syntax): void {
|
||||
this.token_kinds = move(&mut fresh.token_kinds);
|
||||
this.token_offsets = move(&mut fresh.token_offsets);
|
||||
this.token_names = move(&mut fresh.token_names);
|
||||
this.literal_tokens = move(&mut fresh.literal_tokens);
|
||||
this.literal_lengths = move(&mut fresh.literal_lengths);
|
||||
this.docs = move(&mut fresh.docs);
|
||||
this.comments = move(&mut fresh.comments);
|
||||
}
|
||||
|
||||
#! Parses the whole file again, from the tokens it already took.
|
||||
#! @param this The syntax tree.
|
||||
#! @param document The `document` node to parse into.
|
||||
#! @param names The names its tokens were lexed with.
|
||||
#! @param notes The file's notes, the lexer's first, which are kept, and
|
||||
#! then the parser's, which are made again.
|
||||
#! @param file The file's index.
|
||||
#! @returns The `document` node.
|
||||
def syntax::parse_again(
|
||||
&mut this,
|
||||
document: u32,
|
||||
names: &names,
|
||||
notes: &mut vector<note>,
|
||||
file: u32
|
||||
): u32 {
|
||||
this.reset();
|
||||
this.parses++;
|
||||
var lexed: u64 = 0;
|
||||
while lexed < notes.length && notes[lexed].lexed {
|
||||
lexed++;
|
||||
}
|
||||
while notes.length > lexed {
|
||||
notes.truncate();
|
||||
}
|
||||
|
||||
var parsing := parser::new(this, names, notes, file);
|
||||
return parsing.parse();
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
#! @file statements.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the parsing of blocks and the statements within them: `if`, `while`,
|
||||
#! `for`, `match`, jumps, contracts, local functions, local variables, and the
|
||||
#! expressions and assignments written as statements.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! `{ statements }`.
|
||||
#! @param this The parser.
|
||||
#! @returns The `block` node.
|
||||
def parser::block(&mut this): u32 {
|
||||
if !this.check(tk::lbrace) {
|
||||
this.fail(ec::token, "Expected `{` to begin a block.");
|
||||
return this.error_here();
|
||||
}
|
||||
|
||||
val token := this.index;
|
||||
val angled := this.angled;
|
||||
this.angled = false;
|
||||
this.advance();
|
||||
|
||||
val mark := this.mark;
|
||||
while !this.check(tk::rbrace) && !this.check(tk::eof) {
|
||||
this.push(this.statement());
|
||||
if this.panic {
|
||||
this.synchronize(parser::scope::block);
|
||||
}
|
||||
}
|
||||
|
||||
val statements := this.make_run(mark);
|
||||
this.expect(tk::rbrace, "Expected `}` to close the block.");
|
||||
this.angled = angled;
|
||||
return this.make_node(nk::block, token, statements);
|
||||
}
|
||||
|
||||
def parser::statement(&mut this): u32 {
|
||||
return this.error_here() if !this.enter();
|
||||
|
||||
var made: u32 = 0;
|
||||
match this.kind {
|
||||
tk::kw_pub => {
|
||||
this.report(ec::token,
|
||||
"Only a declaration outside a function is `pub`, since nothing within one is reached by name from elsewhere.");
|
||||
this.advance();
|
||||
made = this.statement();
|
||||
}
|
||||
# The statement is kept with the attributes, within an `error` node.
|
||||
tk::attr => {
|
||||
val token := this.index;
|
||||
this.report(ec::token,
|
||||
"Attributes describe declarations outside a function, since nothing within one is reached by name from elsewhere.");
|
||||
val attrs := this.attributes();
|
||||
val held := this.panic ? 0 : this.statement();
|
||||
made = this.error(token, this.join_runs(attrs, this.run_of(held)));
|
||||
}
|
||||
tk::kw_val, tk::kw_var => {
|
||||
val lead := this.bare_lead();
|
||||
made = this.variable(&lead, parser::place::local);
|
||||
}
|
||||
tk::kw_const => {
|
||||
# A function within a block lives in its frame, which no constant can reach.
|
||||
if this.peek(1) == tk::kw_def {
|
||||
this.report(ec::token, "A `const def` is declared outside any function, where constants can call it.");
|
||||
this.advance();
|
||||
made = this.peek(1) == tk::name ? this.local_function() : this.simple();
|
||||
} else {
|
||||
val lead := this.bare_lead();
|
||||
made = this.variable(&lead, parser::place::local);
|
||||
}
|
||||
}
|
||||
tk::kw_if => made = this.if_stmt();
|
||||
tk::kw_when => made = this.when_block(false);
|
||||
tk::kw_while => made = this.while_stmt();
|
||||
tk::kw_for => made = this.for_stmt();
|
||||
tk::kw_match => made = this.match_expr(false);
|
||||
tk::kw_ret => made = this.jump(nk::return_stmt);
|
||||
tk::kw_break => made = this.jump(nk::break_stmt);
|
||||
tk::kw_cont => made = this.jump(nk::continue_stmt);
|
||||
tk::lbrace => made = this.block();
|
||||
tk::kw_def => made = this.peek(1) == tk::name ? this.local_function() : this.simple();
|
||||
else => made = this.contract_word() ? this.contract() : this.simple();
|
||||
}
|
||||
|
||||
this.leave();
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Whether the statement is a contract: `expects`, `asserts`, or `ensures`
|
||||
#! before `(`. Anywhere else, each is a name, as `t.expects(x)` calls a method.
|
||||
#! @param this The parser.
|
||||
#! @returns Whether it is.
|
||||
def parser::contract_word(&this): bool {
|
||||
return false if this.kind != tk::name || this.peek(1) != tk::lparen;
|
||||
val word := this.syntax.token_names[this.index];
|
||||
return word == names::expects_id || word == names::asserts_id || word == names::ensures_id;
|
||||
}
|
||||
|
||||
#! A contract, `expects(cond)`, `asserts(cond)`, or `ensures(cond)`, each of
|
||||
#! which may say what failed in place of the condition, as
|
||||
#! `expects(n != 0, "A count is not zero.")`, and an `ensures` may name what the
|
||||
#! function returns, as `ensures(r: r > 0)`, within which `old(e)` is what `e`
|
||||
#! was where it was reached.
|
||||
#! @param this The parser.
|
||||
#! @returns The `contract` node.
|
||||
def parser::contract(&mut this): u32 {
|
||||
val token := this.index;
|
||||
val ensures := this.syntax.token_names[token] == names::ensures_id;
|
||||
this.advance();
|
||||
this.advance();
|
||||
|
||||
var bound: u32 = 0;
|
||||
if ensures && this.check(tk::name) && this.peek(1) == tk::colon {
|
||||
bound = this.name_node("Expected the name of what the function returns.");
|
||||
this.advance();
|
||||
}
|
||||
val within := this.in_ensures;
|
||||
this.in_ensures = ensures;
|
||||
val condition := this.expression();
|
||||
this.in_ensures = within;
|
||||
var text: u32 = 0;
|
||||
if this.accept(tk::comma) {
|
||||
text = this.expression();
|
||||
}
|
||||
this.expect(tk::rparen, "Expected `)` to close the contract, which takes its condition and what it says failed.");
|
||||
this.expect(tk::semicolon, "Expected `;` after the statement.");
|
||||
return this.make_node(nk::contract, token, condition, this.make_record(bound, text));
|
||||
}
|
||||
|
||||
#! An expression followed by `;`.
|
||||
#! @param this The parser.
|
||||
#! @returns The `expr_stmt` node.
|
||||
def parser::simple(&mut this): u32 {
|
||||
val token := this.index;
|
||||
val made := this.expression();
|
||||
this.expect(tk::semicolon, "Expected `;` after the statement.");
|
||||
return this.make_node(nk::expr_stmt, token, made);
|
||||
}
|
||||
|
||||
#! `if cond { } else if cond { } else { }`, and `if const`.
|
||||
#! @param this The parser.
|
||||
#! @returns The `if_stmt` or `if_const` node.
|
||||
def parser::if_stmt(&mut this): u32 {
|
||||
return this.error_here() if !this.enter();
|
||||
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
|
||||
val constant := this.accept(tk::kw_const);
|
||||
val condition := this.condition_expr();
|
||||
val then := this.block();
|
||||
var other: u32 = 0;
|
||||
if this.accept(tk::kw_else) {
|
||||
other = this.check(tk::kw_if)
|
||||
? this.if_stmt()
|
||||
: this.block();
|
||||
}
|
||||
|
||||
this.leave();
|
||||
return this.branch(constant ? nk::if_const : nk::if_stmt, token, condition, then, other);
|
||||
}
|
||||
|
||||
def parser::while_stmt(&mut this): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
|
||||
val condition := this.condition_expr();
|
||||
return this.make_node(nk::while_stmt, token, condition, this.block());
|
||||
}
|
||||
|
||||
#! `for x in xs`, `for i, x in xs`, `for &x in xs`, `for &mut x in xs`,
|
||||
#! `for i in a..b`, and `for const x in args`, which is unrolled over a pack
|
||||
#! while compiling.
|
||||
#! @param this The parser.
|
||||
#! @returns The `for_stmt` node.
|
||||
def parser::for_stmt(&mut this): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
|
||||
val constant := this.accept(tk::kw_const);
|
||||
var index: u32 = 0;
|
||||
if this.check(tk::name) && this.peek(1) == tk::comma {
|
||||
index = this.name_node("Expected a name for the index.");
|
||||
this.advance();
|
||||
}
|
||||
|
||||
val reference := this.accept(tk::bitand);
|
||||
val mutable := reference && this.accept(tk::kw_mut);
|
||||
val variable := this.name_node("Expected a name for the loop variable.");
|
||||
this.expect(tk::kw_in, "Expected `in` after the loop variable.");
|
||||
|
||||
# A range is the loop's own, so `for i in 0..n` counts, rather than walking a
|
||||
# range made as a value.
|
||||
var iterated := this.condition_expr();
|
||||
var end: u32 = 0;
|
||||
var inclusive := false;
|
||||
if this.syntax.node_kinds[iterated] == nk::range {
|
||||
inclusive = this.syntax.token_kinds[this.syntax.node_tokens[iterated]] == tk::cascadeeq;
|
||||
end = this.syntax.node_rights[iterated];
|
||||
iterated = this.syntax.node_lefts[iterated];
|
||||
}
|
||||
val flags := parser::bit(constant, nf::constant)
|
||||
| parser::bit(reference, nf::reference)
|
||||
| parser::bit(mutable, nf::mutable)
|
||||
| parser::bit(inclusive, nf::inclusive);
|
||||
val record := this.make_record(index, variable, iterated, end, flags);
|
||||
return this.make_node(nk::for_stmt, token, record, this.block());
|
||||
}
|
||||
|
||||
#! A match statement, or a match used as a value, whose arms are separated by
|
||||
#! commas.
|
||||
#! @param this The parser.
|
||||
#! @param value Whether it is used as a value.
|
||||
#! @returns The `match_stmt` or `match_value` node.
|
||||
def parser::match_expr(&mut this, value: bool): u32 {
|
||||
return this.error_here() if !this.enter();
|
||||
|
||||
val kind := value ? nk::match_value : nk::match_stmt;
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
|
||||
val subject := this.condition_expr();
|
||||
if !this.accept(tk::lbrace) {
|
||||
this.fail(ec::token, "Expected `{` to begin the arms of the match.");
|
||||
this.leave();
|
||||
return this.make_node(kind, token, subject);
|
||||
}
|
||||
|
||||
# A match used as a value separates its arms with commas, and one as a
|
||||
# statement ends each with the block or statement it does.
|
||||
val arms := value
|
||||
? this.list(parser::item::value_arm, tk::rbrace, "Expected `,` between the arms, or `}` to close the match.")
|
||||
: this.arms();
|
||||
this.leave();
|
||||
return this.make_node(kind, token, subject, arms);
|
||||
}
|
||||
|
||||
#! The arms of a match statement, through its `}`.
|
||||
#! @param this The parser.
|
||||
#! @returns The run of `match_arm` nodes.
|
||||
def parser::arms(&mut this): u32 {
|
||||
val mark := this.mark;
|
||||
while !this.check(tk::rbrace) && !this.check(tk::eof) {
|
||||
this.push(this.arm(false));
|
||||
if this.panic {
|
||||
this.synchronize(parser::scope::block);
|
||||
}
|
||||
}
|
||||
|
||||
val arms := this.make_run(mark);
|
||||
this.expect(tk::rbrace, "Expected `}` to close the match.");
|
||||
return arms;
|
||||
}
|
||||
|
||||
#! An arm of a match: its patterns, or `else`, then what it does, which is a
|
||||
#! block or a statement, or in a match used as a value, an expression. A pattern
|
||||
#! is an expression: a value compared with the subject, or the name of the field
|
||||
#! of a union the subject holds, as `error` or `error(code)`.
|
||||
#! @param this The parser.
|
||||
#! @param value Whether the match is used as a value.
|
||||
#! @returns The `match_arm` node, or an `error` node.
|
||||
def parser::arm(&mut this, value: bool): u32 {
|
||||
val token := this.index;
|
||||
var patterns: u32 = 0;
|
||||
if !this.accept(tk::kw_else) {
|
||||
if this.check(tk::name) && this.peek(1) == tk::colon {
|
||||
this.fail(ec::token,
|
||||
"An arm names the field of a union it matches, as `field =>`, or `field(value) =>` to use its value.");
|
||||
} else {
|
||||
val mark := this.mark;
|
||||
while true {
|
||||
this.push(this.condition_expr());
|
||||
break if !this.accept(tk::comma);
|
||||
}
|
||||
patterns = this.make_run(mark);
|
||||
}
|
||||
}
|
||||
|
||||
this.expect(tk::arrow, "Expected `=>` followed by what the arm does.");
|
||||
var body: u32 = 0;
|
||||
if value && this.check(tk::kw_ret) {
|
||||
this.fail(ec::token,
|
||||
"Each arm of a match used as a value is the expression it gives, as `2 => x,`, so leave out `return` and `;`.");
|
||||
} else if value {
|
||||
body = this.expression();
|
||||
} else if this.check(tk::lbrace) {
|
||||
body = this.block();
|
||||
} else {
|
||||
# A single statement is the body, as a block of its own.
|
||||
val first := this.index;
|
||||
body = this.make_node(nk::block, first, this.run_of(this.statement()));
|
||||
}
|
||||
|
||||
return this.make_node(nk::match_arm, token, patterns, body);
|
||||
}
|
||||
|
||||
#! `return`, `break`, or `continue`, each of which may be followed by `if`.
|
||||
#! `return value if cond;` is the `if` it reads as, built here so that nothing
|
||||
#! below the parser tells the two apart.
|
||||
#! @param this The parser.
|
||||
#! @param kind `return_stmt`, `break_stmt`, or `continue_stmt`.
|
||||
#! @returns The node, or the `if_stmt` holding it.
|
||||
def parser::jump(&mut this, kind: nk): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
|
||||
var value: u32 = 0;
|
||||
if kind == nk::return_stmt && !this.check(tk::semicolon) && !this.check(tk::kw_if) {
|
||||
value = this.expression();
|
||||
}
|
||||
|
||||
var made := this.make_node(kind, token, value);
|
||||
if this.check(tk::kw_if) {
|
||||
val guard := this.index;
|
||||
this.advance();
|
||||
|
||||
val constant := this.accept(tk::kw_const);
|
||||
val condition := this.condition_expr();
|
||||
val then := this.make_node(nk::block, token, this.run_of(made));
|
||||
made = this.branch(constant ? nk::if_const : nk::if_stmt, guard, condition, then, 0);
|
||||
}
|
||||
|
||||
this.expect(tk::semicolon, "Expected `;` after the statement.");
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A function declared within a block, `def name(params): type { body }`, which
|
||||
#! is a local holding the function as a `lambda`, named before its body so it
|
||||
#! can call itself. It gives the types of its parameters and its result, as any
|
||||
#! other named function does.
|
||||
#! @param this The parser.
|
||||
#! @returns The `variable` node, or an `error` node.
|
||||
def parser::local_function(&mut this): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
|
||||
val name := this.index;
|
||||
this.advance();
|
||||
if this.check(tk::less) {
|
||||
this.fail(ec::token, "Functions declared within a block cannot be generic.");
|
||||
return this.error_here();
|
||||
}
|
||||
|
||||
val signature := this.params(false, false);
|
||||
val body := this.block();
|
||||
val lambda := this.make_node(nk::lambda, token, signature.params, this.make_record(signature.result, body));
|
||||
return this.make_node(nk::variable, name, this.make_record(0, 0, 0, lambda), nf::function as u32);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
#! @file tables.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the tables the parser reads tokens by, built while compiling: the
|
||||
#! traits of each kind of token, as whether it begins a declaration or closes a
|
||||
#! list, and the binding power of each operator.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! What the parser asks of a kind of token, as bits of `tk::traits`. Each kind's
|
||||
#! answers are worked out once, while compiling, so asking is one load.
|
||||
enum tt : u32 {
|
||||
assigns = 0x0001, #! `=`, `+=`, and the rest.
|
||||
declares = 0x0002, #! Begins a declaration at the top level of a file.
|
||||
imports = 0x0004, #! `import` or `module`.
|
||||
states = 0x0008, #! Begins a statement a block resumes at after an error.
|
||||
fields = 0x0010, #! Begins a member a struct or union resumes at.
|
||||
members = 0x0020, #! Begins a member a trait resumes at.
|
||||
opens = 0x0040, #! Opens what a later token closes.
|
||||
closes = 0x0080, #! Closes what an earlier token opened.
|
||||
text = 0x0100, #! Its text says something its node's kind does not: a name, a literal, or an operator.
|
||||
piece = 0x0200, #! May be part of a type before its `<`, as `&mut a::b`.
|
||||
angle = 0x0400, #! Begins with a `>` that may close type arguments: `>`, `>>`, `>=`, or `>>=`.
|
||||
}
|
||||
|
||||
#! What the parser asks of each kind of token.
|
||||
const token_traits: u32[tk::count as u64] = make_token_traits();
|
||||
|
||||
#! How tightly each kind of token binds as an operator, `none` where it is not
|
||||
#! one.
|
||||
const token_powers: parser::bp[tk::count as u64] = make_token_powers();
|
||||
|
||||
#! The answers of a kind of token, as bits of `tt`.
|
||||
#! @param this The kind of token.
|
||||
#! @returns The bits.
|
||||
val tk::traits: u32 { get => token_traits[this as u64]; }
|
||||
|
||||
#! Whether a kind of token has the trait.
|
||||
#! @param this The kind of token.
|
||||
#! @param which The trait.
|
||||
#! @returns Whether it has.
|
||||
def tk::has(&this, which: tt): bool {
|
||||
return (this.traits & which as u32) != 0;
|
||||
}
|
||||
|
||||
const def make_token_traits(): u32[tk::count as u64] {
|
||||
var made: u32[tk::count as u64];
|
||||
for each in [
|
||||
tk::assign, tk::pluseq, tk::minuseq, tk::stareq, tk::slasheq, tk::moduloeq,
|
||||
tk::bitandeq, tk::bitoreq, tk::bitxoreq, tk::lshifteq, tk::rshifteq
|
||||
] { made[each as u64] |= tt::assigns as u32; }
|
||||
|
||||
for each in [
|
||||
tk::kw_pub, tk::attr, tk::kw_when, tk::kw_enum, tk::kw_def, tk::kw_const,
|
||||
tk::kw_struct, tk::kw_union, tk::kw_trait, tk::kw_type, tk::kw_val, tk::kw_var
|
||||
] { made[each as u64] |= tt::declares as u32; }
|
||||
|
||||
for each in [tk::kw_imp, tk::kw_mod, tk::kw_extern] { made[each as u64] |= tt::imports as u32; }
|
||||
|
||||
for each in [
|
||||
tk::kw_val, tk::kw_var, tk::kw_const, tk::kw_if, tk::kw_while, tk::kw_for,
|
||||
tk::kw_match, tk::kw_when, tk::kw_ret, tk::kw_break, tk::kw_cont
|
||||
] { made[each as u64] |= tt::states as u32; }
|
||||
|
||||
for each in [tk::kw_val, tk::kw_var, tk::attr, tk::kw_pub] { made[each as u64] |= tt::fields as u32; }
|
||||
for each in [tk::kw_def, tk::kw_const, tk::attr] { made[each as u64] |= tt::members as u32; }
|
||||
for each in [tk::lparen, tk::lbracket, tk::lbrace, tk::istring_beg] { made[each as u64] |= tt::opens as u32; }
|
||||
for each in [tk::rparen, tk::rbracket, tk::rbrace, tk::istring_end] { made[each as u64] |= tt::closes as u32; }
|
||||
|
||||
for each in [
|
||||
tk::name, tk::unknown, tk::signed, tk::unsigned, tk::float, tk::char, tk::string,
|
||||
tk::istring, tk::istring_beg, tk::istring_mid, tk::istring_end,
|
||||
tk::kw_true, tk::kw_false, tk::kw_null,
|
||||
tk::assign, tk::equals, tk::negate, tk::noteq, tk::less, tk::lesseq, tk::more,
|
||||
tk::moreeq, tk::plus, tk::minus, tk::star, tk::slash, tk::modulo, tk::logand,
|
||||
tk::logor, tk::bitand, tk::bitor, tk::bitxor, tk::bitnot, tk::lshift, tk::rshift,
|
||||
tk::pluseq, tk::minuseq, tk::stareq, tk::slasheq, tk::moduloeq, tk::bitandeq,
|
||||
tk::bitoreq, tk::bitxoreq, tk::lshifteq, tk::rshifteq, tk::increment, tk::decrement,
|
||||
tk::cascade, tk::cascadeeq
|
||||
] { made[each as u64] |= tt::text as u32; }
|
||||
|
||||
for each in [tk::name, tk::scope, tk::kw_mut, tk::bitand, tk::star, tk::kw_not] {
|
||||
made[each as u64] |= tt::piece as u32;
|
||||
}
|
||||
|
||||
for each in [tk::more, tk::rshift, tk::moreeq, tk::rshifteq] { made[each as u64] |= tt::angle as u32; }
|
||||
return made;
|
||||
}
|
||||
|
||||
const def make_token_powers(): parser::bp[tk::count as u64] {
|
||||
var made: parser::bp[tk::count as u64];
|
||||
for each in [
|
||||
tk::assign, tk::pluseq, tk::minuseq, tk::stareq, tk::slasheq, tk::moduloeq,
|
||||
tk::bitandeq, tk::bitoreq, tk::bitxoreq, tk::lshifteq, tk::rshifteq
|
||||
] { made[each as u64] = parser::bp::assign; }
|
||||
|
||||
made[tk::kw_else as u64] = parser::bp::fallback;
|
||||
made[tk::quest as u64] = parser::bp::ternary;
|
||||
made[tk::cascade as u64] = parser::bp::range;
|
||||
made[tk::cascadeeq as u64] = parser::bp::range;
|
||||
made[tk::logor as u64] = parser::bp::logor;
|
||||
made[tk::logand as u64] = parser::bp::logand;
|
||||
made[tk::bitor as u64] = parser::bp::bitor;
|
||||
made[tk::bitxor as u64] = parser::bp::bitxor;
|
||||
made[tk::bitand as u64] = parser::bp::bitand;
|
||||
for each in [tk::equals, tk::noteq] { made[each as u64] = parser::bp::equality; }
|
||||
for each in [tk::less, tk::lesseq, tk::more, tk::moreeq] { made[each as u64] = parser::bp::compare; }
|
||||
for each in [tk::lshift, tk::rshift] { made[each as u64] = parser::bp::shift; }
|
||||
for each in [tk::plus, tk::minus] { made[each as u64] = parser::bp::sum; }
|
||||
for each in [tk::star, tk::slash, tk::modulo] { made[each as u64] = parser::bp::product; }
|
||||
for each in [tk::kw_as, tk::kw_is] { made[each as u64] = parser::bp::cast; }
|
||||
for each in [tk::lparen, tk::lbracket, tk::dot, tk::increment, tk::decrement, tk::scope] {
|
||||
made[each as u64] = parser::bp::postfix;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
@@ -0,0 +1,382 @@
|
||||
#! @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();
|
||||
|
||||
var made: u32 = 0;
|
||||
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);
|
||||
made = this.make_node(kind, token, this.type_expr(), parser::bit(mutable, nf::mutable));
|
||||
} else {
|
||||
made = this.type_postfix();
|
||||
}
|
||||
|
||||
this.leave();
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A type followed by the lengths of fixed arrays of it, as `T[4][2]`.
|
||||
#! @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) {
|
||||
val token := this.index;
|
||||
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;
|
||||
}
|
||||
|
||||
# `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;
|
||||
}
|
||||
|
||||
#! 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.
|
||||
#! @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,
|
||||
else => false
|
||||
};
|
||||
return this.constant_arg(0) if value;
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
#! @file when.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the parsing of `when` blocks, which choose the declarations or
|
||||
#! statements a program has while compiling, and of the conditions they test.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! `when condition { ... }`, holding declarations at the top level of a file and
|
||||
#! statements within a function, followed by `else when` and `else`.
|
||||
#! @param this The parser.
|
||||
#! @param declarations Whether it holds declarations, at the top level of a
|
||||
#! file, rather than statements.
|
||||
#! @returns The `when_block` node.
|
||||
def parser::when_block(&mut this, declarations: bool): u32 {
|
||||
return this.error_here() if !this.enter();
|
||||
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
|
||||
val condition := this.condition();
|
||||
val then := declarations ? this.decl_block() : this.block();
|
||||
var other: u32 = 0;
|
||||
if this.accept(tk::kw_else) {
|
||||
other = this.check(tk::kw_when)
|
||||
? this.when_block(declarations)
|
||||
: declarations ? this.decl_block() : this.block();
|
||||
}
|
||||
|
||||
this.leave();
|
||||
return this.branch(nk::when_block, token, condition, then, other);
|
||||
}
|
||||
|
||||
#! The declarations of a `when` at the top level, as a `block`, which cannot
|
||||
#! import or begin a module.
|
||||
#! @param this The parser.
|
||||
#! @returns The `block` node.
|
||||
def parser::decl_block(&mut this): u32 {
|
||||
if !this.check(tk::lbrace) {
|
||||
this.fail(ec::token, "Expected `{` to begin the declarations.");
|
||||
return this.error_here();
|
||||
}
|
||||
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
|
||||
val mark := this.mark;
|
||||
while !this.check(tk::rbrace) && !this.check(tk::eof) {
|
||||
if this.check(tk::kw_imp) || this.check(tk::kw_mod) || this.check(tk::kw_extern) {
|
||||
this.fail(ec::decl,
|
||||
"Imports and modules cannot be within `when`; a whole section of a file can be declared `module path when condition;`.");
|
||||
} else {
|
||||
this.push(this.declaration());
|
||||
}
|
||||
|
||||
if this.panic {
|
||||
this.synchronize(parser::scope::declarations);
|
||||
}
|
||||
}
|
||||
|
||||
val declarations := this.make_run(mark);
|
||||
this.expect(tk::rbrace, "Expected `}` to close the declarations.");
|
||||
return this.make_node(nk::block, token, declarations);
|
||||
}
|
||||
|
||||
#! A condition on the target, where `&&` binds tighter than `||`.
|
||||
#! @param this The parser.
|
||||
#! @returns The condition's node.
|
||||
def parser::condition(&mut this): u32 {
|
||||
var left := this.condition_and();
|
||||
while this.check(tk::logor) {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
left = this.make_node(nk::binary, token, left, this.condition_and());
|
||||
}
|
||||
|
||||
return left;
|
||||
}
|
||||
|
||||
def parser::condition_and(&mut this): u32 {
|
||||
var left := this.condition_operand();
|
||||
while this.check(tk::logand) {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
left = this.make_node(nk::binary, token, left, this.condition_operand());
|
||||
}
|
||||
|
||||
return left;
|
||||
}
|
||||
|
||||
#! A target key compared with a value, as `os == linux`, a negation, or a
|
||||
#! condition in parentheses.
|
||||
#! @param this The parser.
|
||||
#! @returns The operand's node, or an `error` node.
|
||||
def parser::condition_operand(&mut this): u32 {
|
||||
return this.error_here() if !this.enter();
|
||||
|
||||
val token := this.index;
|
||||
var made: u32 = 0;
|
||||
if this.accept(tk::negate) {
|
||||
made = this.make_node(nk::unary, token, this.condition_operand());
|
||||
} else if this.accept(tk::lparen) {
|
||||
made = this.condition();
|
||||
this.expect(tk::rparen, "Expected `)` to close the condition.");
|
||||
} else if !this.check(tk::name) {
|
||||
this.fail(ec::ident, "Expected a target key: `os`, `arch`, or `backend`.");
|
||||
made = this.error_here();
|
||||
} else {
|
||||
made = this.comparison();
|
||||
}
|
||||
|
||||
this.leave();
|
||||
return made;
|
||||
}
|
||||
|
||||
#! `key == value` or `key != value`, from the key.
|
||||
#! @param this The parser.
|
||||
#! @returns The `binary` node.
|
||||
def parser::comparison(&mut this): u32 {
|
||||
val key := this.name_node("Expected a target key: `os`, `arch`, or `backend`.");
|
||||
if !this.check(tk::equals) && !this.check(tk::noteq) {
|
||||
this.fail(ec::token, "Expected `==` or `!=` after the target key.");
|
||||
return this.error_here();
|
||||
}
|
||||
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
val value := this.name_node("Expected the value the key is compared with, as `linux`.");
|
||||
return this.make_node(nk::binary, token, key, value);
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
#! @file printer.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the printer, which writes a syntax tree as text, the way the
|
||||
#! parser's tests say what tree they expect.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! Prints the tree under a node, which is how the parser's tests say what tree
|
||||
#! they expect, and how one is read while debugging.
|
||||
#!
|
||||
#! A node is printed as `(kind:text ...)`, its slots following in the order its
|
||||
#! shape lists them, and one whose slots all hold nothing, being absent nodes,
|
||||
#! empty runs, or no flags, is printed as `kind:text` alone. The text is that of
|
||||
#! its token where it says something, as a name, a literal, or an operator, and
|
||||
#! left out where it is punctuation or a keyword the kind already says. An
|
||||
#! absent node is `_`, a run is `[...]`, and flags are `{mutable,constant}`,
|
||||
#! printed only where any are set.
|
||||
#! @param this The syntax tree.
|
||||
#! @param at The node to print.
|
||||
#! @param source The source the tokens are of, for their text.
|
||||
#! @param names The names the tokens were lexed with, for the length of each
|
||||
#! name.
|
||||
#! @returns The tree printed.
|
||||
pub def syntax::print(&this, at: u32, source: &source, names: &names): string {
|
||||
var out := string::new(nothing {});
|
||||
this.print_into(at, source, names, &mut out);
|
||||
return out;
|
||||
}
|
||||
|
||||
def syntax::print_into(&this, at: u32, source: &source, names: &names, out: &mut string): void {
|
||||
if at == 0 {
|
||||
out.append("_");
|
||||
return;
|
||||
}
|
||||
|
||||
val held := this.node(at);
|
||||
val shape := held.shape;
|
||||
val bare := this.slot_empty(shape.left, held.left, shape.record)
|
||||
&& this.slot_empty(shape.right, held.right, shape.record);
|
||||
if !bare {
|
||||
out.append("(");
|
||||
}
|
||||
|
||||
out.append(kind_names[held.kind as u64]);
|
||||
val token := this.token(held.token, names);
|
||||
if token.kind.has(tt::text) {
|
||||
out.append(":");
|
||||
val text := source.make_lexeme(token.offset, token.length);
|
||||
# A parameter an accessor implies has the `get` or `set` for its token.
|
||||
val flags := held.kind == nk::param ? this.flags_at(at) : 0;
|
||||
if (flags & nf::implied as u32) != 0 {
|
||||
out.append(text == "set" && (flags & nf::mutable as u32) == 0 ? "value" : "this");
|
||||
} else {
|
||||
out.append(text);
|
||||
}
|
||||
}
|
||||
|
||||
return if bare;
|
||||
|
||||
this.print_slot(shape.left, held.left, shape.record, source, names, out);
|
||||
this.print_slot(shape.right, held.right, shape.record, source, names, out);
|
||||
out.append(")");
|
||||
}
|
||||
|
||||
def syntax::print_slot(
|
||||
&this,
|
||||
kind: slot,
|
||||
value: u32,
|
||||
record: span<slot>,
|
||||
source: &source,
|
||||
names: &names,
|
||||
out: &mut string
|
||||
): void {
|
||||
match kind {
|
||||
slot::node => {
|
||||
out.append(" ");
|
||||
this.print_into(value, source, names, out);
|
||||
}
|
||||
slot::run, slot::bounds => {
|
||||
return if kind == slot::bounds && this.run_length(value) == 0;
|
||||
out.append(" [");
|
||||
for i in 0..this.run_length(value) {
|
||||
if i != 0 {
|
||||
out.append(" ");
|
||||
}
|
||||
this.print_into(this.run_at(value, i as u32), source, names, out);
|
||||
}
|
||||
out.append("]");
|
||||
}
|
||||
slot::flags => {
|
||||
return if value == 0;
|
||||
out.append(" {");
|
||||
var first := true;
|
||||
for i in 0..flag_names.length {
|
||||
if (value & (1 << i as u32)) != 0 {
|
||||
if !first {
|
||||
out.append(",");
|
||||
}
|
||||
out.append(flag_names[i]);
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
out.append("}");
|
||||
}
|
||||
slot::extra => {
|
||||
for i in 0..record.length {
|
||||
this.print_slot(record[i], this.extras[value as u64 + i], no_record, source, names, out);
|
||||
}
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether the slot holds nothing where it holds `value`.
|
||||
#! @param this The syntax tree.
|
||||
#! @param kind What the slot holds.
|
||||
#! @param value The slot's value.
|
||||
#! @param record The shape of the node's record, where the slot holds one.
|
||||
#! @returns Whether it holds nothing.
|
||||
def syntax::slot_empty(&this, kind: slot, value: u32, record: span<slot>): bool {
|
||||
return match kind {
|
||||
slot::node, slot::flags => value == 0,
|
||||
slot::run, slot::bounds => this.run_length(value) == 0,
|
||||
slot::extra => this.record_empty(value, record),
|
||||
else => true
|
||||
};
|
||||
}
|
||||
|
||||
def syntax::record_empty(&this, at: u32, record: span<slot>): bool {
|
||||
for i in 0..record.length {
|
||||
return false if !this.slot_empty(record[i], this.extras[at as u64 + i], no_record);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! The names of the kinds of node, in the order `nk` declares them.
|
||||
const kind_names: strview[nk::count as u64] = [
|
||||
"error", "document", "block",
|
||||
"import_decl", "module_decl", "extern_import", "extern_module", "when_block", "function", "param", "variable",
|
||||
"field", "spread", "rename", "property", "accessor", "struct_decl", "union_decl",
|
||||
"trait_decl", "assoc_type", "enumeration", "enumerator", "alias", "attribute",
|
||||
"type_param", "const_param", "type_pattern", "array_pattern",
|
||||
"segment", "type_name", "type_ref", "type_ptr", "type_fixed", "type_func", "type_spread", "type_of",
|
||||
"if_stmt", "if_const", "while_stmt", "for_stmt", "match_stmt", "match_arm",
|
||||
"return_stmt", "break_stmt", "continue_stmt", "expr_stmt", "contract",
|
||||
"name", "path", "number", "character", "string", "istring", "boolean", "null_lit",
|
||||
"unary", "postfix", "reference", "binary", "assign", "ternary", "fallback", "call",
|
||||
"type_args", "index", "slice", "member", "member_of", "cast", "is_test",
|
||||
"construct", "field_init", "array", "lambda", "match_value", "range", "old_value",
|
||||
"undefined",
|
||||
];
|
||||
|
||||
#! The names of the bits of `nf`, from its lowest.
|
||||
const flag_names: span<strview> = [
|
||||
"exported", "mutable", "constant", "reference", "variadic", "packed",
|
||||
"negated", "computed", "function", "named", "inclusive", "implied",
|
||||
];
|
||||
@@ -0,0 +1,270 @@
|
||||
#! @file calling.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains what is being called at a position, for an editor to show while the
|
||||
#! arguments are written: every overload of what is called, and the parameter
|
||||
#! the position writes.
|
||||
|
||||
import std::containers;
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! An overload of what is being called.
|
||||
pub struct overload {
|
||||
pub var signature: string; #! How it is declared, as `hover` shows it.
|
||||
pub var documentation: string; #! Its documentation comment, or empty.
|
||||
pub var contract: string; #! The `expects` and `ensures` its body begins with, a line each, or empty.
|
||||
pub var arity: u32; #! How many parameters its signature declares.
|
||||
pub var variadic: bool; #! Whether its last parameter takes every argument after the others.
|
||||
}
|
||||
|
||||
#! What is being called at a position.
|
||||
pub struct calls {
|
||||
pub var overloads: vector<overload>; #! Each overload, the one the arguments written so far fit first.
|
||||
pub var parameter: u32; #! The parameter the position writes, counting the receiver of a method called through a value.
|
||||
}
|
||||
|
||||
#! The call whose parentheses are open at a position: the token naming what it
|
||||
#! calls, and the argument being written.
|
||||
struct open_call {
|
||||
var name: u32; #! The token naming what is called.
|
||||
var argument: u32; #! The argument being written, from 0.
|
||||
}
|
||||
|
||||
#! A bracket open before a position, as `open_calls` reads them.
|
||||
struct open_bracket {
|
||||
var closes: tk; #! The token that closes it.
|
||||
var call: bool; #! Whether it is a call's parentheses.
|
||||
var name: u32; #! The token naming what a call calls.
|
||||
var argument: u32; #! The argument of a call being written, from 0.
|
||||
}
|
||||
|
||||
#! What is being called at the offset of the file: the innermost call whose
|
||||
#! parentheses are open there, whose overloads are given, the one a call of the
|
||||
#! arguments written so far would choose first.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param offset The byte of its text.
|
||||
#! @returns What is called, or nothing where no call is open there.
|
||||
pub def checker::calls_at(&mut this, file: u32, offset: u32): maybe<calls> {
|
||||
var opens := this.open_calls(file, offset);
|
||||
return nothing {} if opens.length == 0;
|
||||
|
||||
# The innermost call whose callee is a function, or a value of a type with an
|
||||
# `invoke`, as a call of it is a call of that.
|
||||
val asked := this.begin_query(file);
|
||||
var member := false;
|
||||
var decl: u32 = 0;
|
||||
var argument: u32 = 0;
|
||||
var i := opens.length;
|
||||
while i > 0 && decl == 0 {
|
||||
i--;
|
||||
member = false;
|
||||
decl = this.called_decl(file, offset, &opens[i], &asked.walked, &asked.decls, &mut member);
|
||||
argument = opens[i].argument;
|
||||
}
|
||||
# A method called through a value is given its receiver, which its signature
|
||||
# names first, so the argument written is the one after it.
|
||||
if member && decl != 0 && this.decls.has(decl, df::method) {
|
||||
argument++;
|
||||
}
|
||||
return nothing {} if decl == 0 || this.decls.kinds.p[decl] != dk::function;
|
||||
|
||||
var made := calls { overloads = vector::<overload>::new(), parameter = argument };
|
||||
var walk := this.decls.walk_overloads(this.first_overload(decl), 32);
|
||||
while true {
|
||||
val at := walk.next();
|
||||
break if at == 0;
|
||||
if !this.decls.has(at, df::failed) {
|
||||
this.resolve(at);
|
||||
val kind: u32 = this.decls.types.p[at];
|
||||
made.overloads.append(overload {
|
||||
signature = this.signature_of(at),
|
||||
documentation = this.documentation_of(this.decls.files.p[at], this.decls.nodes.p[at]),
|
||||
contract = this.contract_of(at),
|
||||
arity = kind != 0 ? this.types.part_count(kind) : 0,
|
||||
variadic = this.decls.has(at, df::variadic)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
# The overload the arguments written so far fit comes first.
|
||||
for i in 0..made.overloads.length {
|
||||
continue if made.overloads[i].arity <= argument && !made.overloads[i].variadic;
|
||||
var fitting := move(&mut made.overloads[i]);
|
||||
made.overloads.remove_at(i);
|
||||
made.overloads.insert_at(0, move(&mut fitting));
|
||||
break;
|
||||
}
|
||||
return move(&mut made);
|
||||
}
|
||||
|
||||
#! The first of the overloads of a function: the first member of its name of
|
||||
#! the type it is declared through, or the first declaration of its name of its
|
||||
#! module.
|
||||
#! @param this The checker.
|
||||
#! @param decl The function.
|
||||
#! @returns The first overload.
|
||||
def checker::first_overload(&this, decl: u32): u32 {
|
||||
val owner: u32 = this.decls.owners.p[decl];
|
||||
val first := owner != 0
|
||||
? this.first_member(decl)
|
||||
: this.modules.decl(this.decls.modules.p[decl], this.decls.names.p[decl]);
|
||||
return first != 0 ? first : decl;
|
||||
}
|
||||
|
||||
#! Finds the calls whose parentheses are open at the offset: the name each
|
||||
#! calls, and the argument being written. The tokens are read rather than the
|
||||
#! tree, since a call is rarely whole while its arguments are written.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param offset The byte of its text.
|
||||
#! @returns The calls, the innermost last.
|
||||
def checker::open_calls(&this, file: u32, offset: u32): vector<open_call> {
|
||||
val syntax := &this.units[file].syntax;
|
||||
var open := vector::<open_bracket>::new();
|
||||
var called: u32 = 0;
|
||||
var has_called := false;
|
||||
var scope := false;
|
||||
for at in 0..syntax.token_count {
|
||||
val token := at as u32;
|
||||
break if syntax.token_offsets[token] >= offset;
|
||||
val kind := syntax.token_kinds[token];
|
||||
break if kind == tk::eof;
|
||||
if kind == tk::lparen || kind == tk::lbracket || kind == tk::lbrace {
|
||||
open.append(open_bracket {
|
||||
closes = kind == tk::lparen ? tk::rparen : kind == tk::lbracket ? tk::rbracket : tk::rbrace,
|
||||
call = kind == tk::lparen && has_called, name = called
|
||||
});
|
||||
} else if kind == tk::less && scope {
|
||||
# Type arguments follow `::`, as `f::<u8>(x)`, and their commas are not the
|
||||
# call's, so they take a frame of their own.
|
||||
open.append(open_bracket { closes = tk::more });
|
||||
} else if kind == tk::rparen || kind == tk::rbracket || kind == tk::rbrace || kind == tk::more {
|
||||
if open.length != 0 && open.last().closes == kind {
|
||||
open.truncate();
|
||||
}
|
||||
} else if kind == tk::comma {
|
||||
if open.length != 0 && open.last().call {
|
||||
open.last().argument++;
|
||||
}
|
||||
}
|
||||
|
||||
# The name a `(` follows is the last one written before it.
|
||||
if kind == tk::name {
|
||||
called = token;
|
||||
has_called = true;
|
||||
} else if kind != tk::scope && kind != tk::less && kind != tk::more && kind != tk::dot {
|
||||
has_called = false;
|
||||
}
|
||||
scope = kind == tk::scope;
|
||||
}
|
||||
|
||||
# The calls still open, which the position is writing an argument of, the
|
||||
# innermost last.
|
||||
var made := vector::<open_call>::new();
|
||||
for &each in open {
|
||||
if each.call {
|
||||
made.append(open_call { name = each.name, argument = each.argument });
|
||||
}
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The function a call open at a position calls: what the node naming it
|
||||
#! refers to, and otherwise a function of the name the position can name.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param offset The byte of its text.
|
||||
#! @param open The call.
|
||||
#! @param walked The file's tree.
|
||||
#! @param decls The declarations of the file's nodes.
|
||||
#! @param member Where whether it is called through a value is written.
|
||||
#! @returns The function, or 0.
|
||||
def checker::called_decl(
|
||||
&mut this,
|
||||
file: u32,
|
||||
offset: u32,
|
||||
open: &open_call,
|
||||
walked: &tree_walk,
|
||||
decls: &dict<u32, u32>,
|
||||
member: &mut bool
|
||||
): u32 {
|
||||
for &node in walked.order {
|
||||
continue if this.token_of(node) != open.name;
|
||||
val kind := this.kind_of(node);
|
||||
continue if kind != nk::name && kind != nk::member && kind != nk::segment && kind != nk::path;
|
||||
member = kind == nk::member;
|
||||
val meant := this.meaning_of(node, walked, decls);
|
||||
if meant.decl != 0 && this.decls.kinds.p[meant.decl] == dk::function {
|
||||
return meant.decl;
|
||||
}
|
||||
if kind == nk::member {
|
||||
val found := this.member_meaning(this.type_at(this.left_of(node)), this.name_of(node));
|
||||
return found.decl if found.decl != 0 && this.decls.kinds.p[found.decl] == dk::function;
|
||||
}
|
||||
|
||||
# A value of a type with an `invoke` is called through it, which is given
|
||||
# the value as its receiver.
|
||||
val held := this.type_at(node);
|
||||
if held != 0 && held != bt::error {
|
||||
val found := this.find_member(this.reached(held), word::invoke);
|
||||
if found.decl != 0 && this.decls.kinds.p[found.decl] == dk::function {
|
||||
member = true;
|
||||
return found.decl;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
# A call being written rarely parses, so where the tree has no node for the
|
||||
# name, or the checker made nothing of the one it has, the name is looked up
|
||||
# as the checker would: a function of the module, of an import, or one built
|
||||
# in.
|
||||
this.at.home = this.home_at(file, offset);
|
||||
val found := this.lookup_global(this.units[file].syntax.token_names[open.name], 0);
|
||||
this.at.home = 0;
|
||||
return found;
|
||||
}
|
||||
|
||||
#! The type of the argument being written at the offset of the file, of the
|
||||
#! call whose parentheses are open there, or 0 where none is.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param offset The byte of its text.
|
||||
#! @param walked The file's tree.
|
||||
#! @param decls The declarations of the file's nodes.
|
||||
#! @returns The type, or 0.
|
||||
def checker::argument_type(&mut this, file: u32, offset: u32, walked: &tree_walk, decls: &dict<u32, u32>): u32 {
|
||||
var opens := this.open_calls(file, offset);
|
||||
return 0 if opens.length == 0;
|
||||
var member := false;
|
||||
val open := opens.last();
|
||||
val decl := this.called_decl(file, offset, open, walked, decls, &mut member);
|
||||
return 0 if decl == 0 || this.decls.kinds.p[decl] != dk::function;
|
||||
var argument := open.argument;
|
||||
if member && this.decls.has(decl, df::method) {
|
||||
argument++;
|
||||
}
|
||||
|
||||
# The first overload with a parameter for the argument, as the call is read
|
||||
# so far. Every argument after a variadic parameter's first is of it too.
|
||||
var walk := this.decls.walk_overloads(this.first_overload(decl), 32);
|
||||
while true {
|
||||
val at := walk.next();
|
||||
break if at == 0;
|
||||
this.resolve(at);
|
||||
val kind: u32 = this.decls.types.p[at];
|
||||
val count := kind != 0 ? this.types.part_count(kind) : 0;
|
||||
val variadic := this.decls.has(at, df::variadic);
|
||||
if argument < count {
|
||||
return this.types.part_at(kind, argument);
|
||||
}
|
||||
if variadic && count != 0 {
|
||||
return this.types.part_at(kind, count - 1);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,81 @@
|
||||
#! @file highlights.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the names of a file as what the checker made of each, for an editor
|
||||
#! to colour them by that rather than by how they are written.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! A name of a file, as what the checker made of it.
|
||||
pub struct highlight {
|
||||
pub var offset: u32; #! Where the name begins in the file's text.
|
||||
pub var length: u32; #! How many bytes it covers.
|
||||
pub var kind: symbol; #! What it is.
|
||||
pub var declared: bool; #! Whether this is where it is declared.
|
||||
pub var readonly: bool; #! Whether what it names is never written, as a `val` or a `const`.
|
||||
}
|
||||
|
||||
#! The names of the file the checker resolved, in the order they are written,
|
||||
#! each with what it is, so an editor colours the rest as it otherwise would. A
|
||||
#! file whose syntax has mistakes gives the names of what parsed.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @returns The names.
|
||||
pub def checker::highlights(&mut this, file: u32): vector<highlight> {
|
||||
var made := vector::<highlight>::new();
|
||||
val syntax := &this.units[file].syntax;
|
||||
val asked := this.begin_query(file);
|
||||
val walked := &asked.walked;
|
||||
for &node in walked.order {
|
||||
val token: u32 = syntax.node_tokens[node];
|
||||
# A contract's word, `old` within an `ensures`, and `undefined` as a
|
||||
# variable's value are the language's own words there, though names
|
||||
# everywhere else.
|
||||
val held := syntax.node_kinds[node];
|
||||
if held == nk::contract || held == nk::old_value || held == nk::undefined {
|
||||
made.append(highlight {
|
||||
offset = syntax.token_offsets[token], length = syntax.token_length(token, this.names), kind = symbol::keyword
|
||||
});
|
||||
continue;
|
||||
}
|
||||
continue if syntax.token_kinds[token] != tk::name;
|
||||
val meant := this.meaning_of(node, walked, &asked.decls);
|
||||
continue if !meant.found();
|
||||
var declared := meant.local == node && meant.file == file;
|
||||
if meant.decl != 0 {
|
||||
declared = this.decls.nodes.p[meant.decl] == node && this.decls.files.p[meant.decl] == file;
|
||||
}
|
||||
if meant.is_module {
|
||||
val outer: u32 = walked.parents[walked.parents[node]];
|
||||
declared = outer != 0 && (syntax.node_kinds[outer] == nk::module_decl || syntax.node_kinds[outer] == nk::extern_module)
|
||||
|| (walked.parents[node] != 0 && (syntax.node_kinds[walked.parents[node]] == nk::module_decl
|
||||
|| syntax.node_kinds[walked.parents[node]] == nk::extern_module));
|
||||
}
|
||||
# A type named where it is used is never written there.
|
||||
val kind := this.symbol_meant(&meant);
|
||||
val names_type := kind == symbol::struct_type || kind == symbol::trait_type || kind == symbol::enum_type
|
||||
|| kind == symbol::type_name || kind == symbol::type_param;
|
||||
made.append(highlight {
|
||||
offset = syntax.token_offsets[token],
|
||||
length = syntax.token_length(token, this.names),
|
||||
kind = kind,
|
||||
declared = declared,
|
||||
readonly = this.readonly_meant(&meant) || (names_type && !declared)
|
||||
});
|
||||
this.query_file(file);
|
||||
}
|
||||
|
||||
# A receiver is written before the name of what it declares, as `rect` is in
|
||||
# `def rect::area`, so the names are put in the order they are written, and a
|
||||
# name the walk reached twice is one.
|
||||
made.sort_by(def(a: &highlight, b: &highlight): bool { return a.offset < b.offset; });
|
||||
var kept := vector::<highlight>::new();
|
||||
for &each in made {
|
||||
continue if kept.length != 0 && kept.last().offset == each.offset;
|
||||
kept.append(each);
|
||||
}
|
||||
return kept;
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
#! @file hover.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains hovering: what an editor shows of the name at a position, which is
|
||||
#! how what it refers to is declared, with the types the checker gave it and
|
||||
#! the contract a function's body begins with, and its documentation.
|
||||
|
||||
import std::containers;
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! What hovering a name shows.
|
||||
pub struct hover {
|
||||
pub var signature: string; #! How what it refers to is declared, as `def str::trim(this: &str): str` or `val count: int`, after the attributes written on it, and of a function, a line for each `expects` and `ensures` its body begins with.
|
||||
pub var documentation: string; #! The documentation comment of what it refers to, without its `#!`, or empty.
|
||||
pub var offset: u32; #! Where the name begins in the file's text.
|
||||
pub var length: u32; #! How many bytes it covers.
|
||||
}
|
||||
|
||||
#! What hovering the name at the offset of the file shows: a variable,
|
||||
#! parameter, function, method, field, type, member of an enum, or module,
|
||||
#! used or declared there.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param offset The byte of its text.
|
||||
#! @returns What it shows, or nothing where no name is there, or checking left
|
||||
#! it unresolved.
|
||||
pub def checker::hover(&mut this, file: u32, offset: u32): maybe<hover> {
|
||||
val token := this.token_at(file, offset);
|
||||
return nothing {} if token as u64 >= this.units[file].syntax.token_count;
|
||||
|
||||
val asked := this.begin_query(file);
|
||||
var found := hover {
|
||||
signature = string::new(nothing {}),
|
||||
documentation = string::new(nothing {})
|
||||
};
|
||||
var shown := false;
|
||||
for &node in asked.walked.order {
|
||||
continue if this.token_of(node) != token;
|
||||
shown = this.shown_at(node, &asked.walked, &asked.decls, &mut found);
|
||||
break if shown;
|
||||
}
|
||||
return nothing {} if !shown;
|
||||
return move(&mut found);
|
||||
}
|
||||
|
||||
#! What hovering a node of the file being queried shows, or nothing where it
|
||||
#! names nothing the checker resolved.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param walked The file's tree.
|
||||
#! @param decls The declarations of the file's nodes.
|
||||
#! @param out Where what it shows is written.
|
||||
#! @returns Whether it shows anything.
|
||||
def checker::shown_at(&mut this, node: u32, walked: &tree_walk, decls: &dict<u32, u32>, out: &mut hover): bool {
|
||||
val file := this.at.file;
|
||||
val spot := this.spot_of(file, this.token_of(node));
|
||||
val meant := this.meaning_of(node, walked, decls);
|
||||
var signature := string::new(nothing {});
|
||||
var documentation := string::new(nothing {});
|
||||
|
||||
if meant.is_module {
|
||||
signature = this.module_signature(meant.named_module);
|
||||
} else if meant.decl != 0 {
|
||||
val decl := meant.decl;
|
||||
val home: u32 = this.decls.files.p[decl];
|
||||
val declared: u32 = this.decls.nodes.p[decl];
|
||||
if declared != 0 {
|
||||
this.attributes_text(home, declared, &mut signature);
|
||||
}
|
||||
var written := this.signature_seen(decl, node, walked.parents[node]);
|
||||
signature.append(written.view());
|
||||
val contract := this.contract_of(decl);
|
||||
if contract.length != 0 {
|
||||
signature.append("\n");
|
||||
signature.append(contract.view());
|
||||
}
|
||||
documentation = this.documentation_of(home, declared);
|
||||
this.query_file(file);
|
||||
} else if meant.local != 0 {
|
||||
signature = this.local_signature(meant.file, meant.local);
|
||||
documentation = this.documentation_of(meant.file, meant.local);
|
||||
} else if this.kind_of(node) == nk::member && this.type_at(node) != 0 && this.type_at(node) != bt::error {
|
||||
# What the compiler gives a value, as the length of a fixed array.
|
||||
signature.append("val ");
|
||||
signature.append(this.text_of(node));
|
||||
signature.append(": ");
|
||||
this.type_text(this.type_at(node), &mut signature);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
out.signature = move(&mut signature);
|
||||
out.documentation = move(&mut documentation);
|
||||
out.offset = spot.offset;
|
||||
out.length = spot.length;
|
||||
return true;
|
||||
}
|
||||
|
||||
#! The contract a function's body begins with, which is what callers are
|
||||
#! promised: each `expects` and `ensures` before its first other statement, as
|
||||
#! it is written, with its spaces and line breaks run together, a line each,
|
||||
#! as `expects(b != 0)`.
|
||||
#! @param this The checker.
|
||||
#! @param decl The function.
|
||||
#! @returns The lines, or empty text where it begins with none.
|
||||
pub def checker::contract_of(&mut this, decl: u32): string {
|
||||
var made := string::new(nothing {});
|
||||
return made if this.decls.kinds.p[decl] != dk::function || this.decls.has(decl, df::accessor);
|
||||
val file: u32 = this.decls.files.p[decl];
|
||||
val syntax := &this.units[file].syntax;
|
||||
val source := &this.units[file].source;
|
||||
val node: u32 = this.decls.nodes.p[decl];
|
||||
return made if node == 0 || syntax.node_kinds[node] != nk::function;
|
||||
val body := syntax.extras[syntax.node_lefts[node] as u64 + function_slot::body as u64];
|
||||
return made if body == 0 || syntax.node_kinds[body] != nk::block;
|
||||
|
||||
val run := syntax.node_lefts[body];
|
||||
for i in 0..syntax.run_length(run) {
|
||||
val each := syntax.run_at(run, i as u32);
|
||||
break if syntax.node_kinds[each] != nk::contract;
|
||||
val first: u32 = syntax.node_tokens[each];
|
||||
continue if syntax.token_names[first] == names::asserts_id;
|
||||
# What it was parsed from ends at its `;`, which is left out.
|
||||
var last: u32 = syntax.node_end(each);
|
||||
if last > first && syntax.token_kinds[last] == tk::semicolon {
|
||||
last--;
|
||||
}
|
||||
val begin: u64 = syntax.token_offsets[first];
|
||||
val end: u64 = syntax.token_offsets[last] + syntax.token_length(last, this.names);
|
||||
continue if end <= begin;
|
||||
if made.length != 0 {
|
||||
made.append("\n");
|
||||
}
|
||||
var spaced := false;
|
||||
for &byte in source.make_lexeme(begin, end - begin) {
|
||||
if byte == ' ' || byte == '\n' || byte == '\t' || byte == '\r' {
|
||||
spaced = true;
|
||||
continue;
|
||||
}
|
||||
if spaced && byte != ')' && made.length != 0 && made[made.length - 1] != '(' && made[made.length - 1] != '\n' {
|
||||
made.push(' ');
|
||||
}
|
||||
spaced = false;
|
||||
made.push(byte);
|
||||
}
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The instance a call of a node uses, where the node is what a call calls.
|
||||
#! @param this The checker.
|
||||
#! @param callee The node.
|
||||
#! @returns One more than the instance, or nothing.
|
||||
def checker::called_by(&mut this, callee: u32): maybe<u32> {
|
||||
# The call is found by its callee, which its node holds.
|
||||
val syntax := &this.syn();
|
||||
for at in 1..syntax.node_count {
|
||||
val node := at as u32;
|
||||
continue if syntax.node_kinds[node] != nk::call || this.left_of(node) != callee;
|
||||
if this.called.get(&this.result_key(node)) is some(found) {
|
||||
return found;
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! How a declaration is written where a node names it: a field reached through
|
||||
#! a value of a generic type, as `p.x` of a `box<int>`, is of the type the value
|
||||
#! gives it, and a method called through one is of the types it is given.
|
||||
#! @param this The checker.
|
||||
#! @param decl The declaration.
|
||||
#! @param node The node naming it, of the file being queried.
|
||||
#! @param parent The node holding it.
|
||||
#! @returns The signature.
|
||||
def checker::signature_seen(&mut this, decl: u32, node: u32, parent: u32): string {
|
||||
val kind := this.kind_of(node);
|
||||
val seen := this.type_at(node);
|
||||
|
||||
# A generic function a call uses is shown as the instance the call uses.
|
||||
if this.decls.kinds.p[decl] == dk::function && !this.decls.has(decl, df::accessor) {
|
||||
# The call is of the node, or of the path whose last segment it is.
|
||||
var made: u32 = 0;
|
||||
var callee := node;
|
||||
if parent != 0 && kind == nk::segment && (this.kind_of(parent) == nk::path || this.kind_of(parent) == nk::type_name) {
|
||||
callee = parent;
|
||||
}
|
||||
if this.called.get(&this.result_key(callee)) is some(found) {
|
||||
made = found;
|
||||
}
|
||||
if made == 0 && callee != node {
|
||||
if this.called.get(&this.result_key(node)) is some(found) {
|
||||
made = found;
|
||||
}
|
||||
}
|
||||
if made == 0 {
|
||||
if this.called_by(callee) is some(found) {
|
||||
made = found;
|
||||
}
|
||||
}
|
||||
if made != 0 && made <= this.instances.length as u32 && this.instances[made - 1].decl == decl {
|
||||
var out := string::new(nothing {});
|
||||
if this.decls.has(decl, df::exported) {
|
||||
out.append("pub ");
|
||||
}
|
||||
this.instance_text_of(decl, true, made, &mut out);
|
||||
return out;
|
||||
}
|
||||
}
|
||||
if (kind == nk::member || kind == nk::field_init) && seen != 0 && seen != bt::error
|
||||
&& this.decls.kinds.p[decl] == dk::field && this.decls.types.p[decl] != seen {
|
||||
var out := string::new(nothing {});
|
||||
if this.decls.has(decl, df::exported) {
|
||||
out.append("pub ");
|
||||
}
|
||||
out.append(this.decls.has(decl, df::mutable) ? "var " : "val ");
|
||||
out.append(this.decl_text(decl));
|
||||
out.append(": ");
|
||||
this.type_text(seen, &mut out);
|
||||
return out;
|
||||
}
|
||||
return this.signature_of(decl);
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
#! @file names.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains what the name at a position refers to, for an editor to go to where
|
||||
#! that is declared, and everywhere it is written, for an editor to find its
|
||||
#! references and rename it, with why some names cannot be renamed.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! What the name at a position refers to.
|
||||
pub struct referent {
|
||||
pub var at: spot; #! The name at the position.
|
||||
pub var declaration: spot; #! Where what it refers to is declared, where `declared` says it is.
|
||||
pub var declared: bool; #! Whether it has a declaration to go to, which a built-in type has not.
|
||||
pub var refusal: strview; #! Why it cannot be renamed, as that it is built into the language, or empty where it can.
|
||||
pub var local: bool; #! Whether it is a local, a parameter, a type parameter, or a name a pattern binds, which is only written within the declaration holding it.
|
||||
pub var member: bool; #! Whether it is a member of a type, as a field, method, property, member of an enum, or associated variable, which is written after `.` or `::` wherever it is not declared.
|
||||
}
|
||||
|
||||
#! What the name at the offset of the file refers to, used or declared there. A
|
||||
#! name the offset is just past is the one asked about, as an editor puts the
|
||||
#! cursor after the name it asks about.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param offset The byte of its text.
|
||||
#! @returns What it refers to, or nothing where no name the checker resolved is
|
||||
#! there.
|
||||
pub def checker::name_at(&mut this, file: u32, offset: u32): maybe<referent> {
|
||||
var meant := checker::meant {};
|
||||
val node := this.seek_name(file, offset, &mut meant);
|
||||
return nothing {} if node == 0;
|
||||
|
||||
var made := referent {
|
||||
at = this.spot_of(file, this.units[file].syntax.node_tokens[node]),
|
||||
refusal = ""
|
||||
};
|
||||
|
||||
var declared := spot {};
|
||||
made.declared = this.declared_at(&meant, &mut declared);
|
||||
made.declaration = declared;
|
||||
made.refusal = this.refusal_of(&meant);
|
||||
made.local = meant.local != 0 || (meant.decl != 0 && this.decls.kinds.p[meant.decl] == dk::type_param);
|
||||
made.member = meant.decl != 0 && this.decls.owners.p[meant.decl] != 0
|
||||
&& this.decls.kinds.p[meant.decl] != dk::type_param;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Finds the node naming something at the offset of the file, or at the byte
|
||||
#! before it.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param offset The byte of its text.
|
||||
#! @param meant Where what it refers to is written.
|
||||
#! @returns The node, or 0.
|
||||
def checker::seek_name(&mut this, file: u32, offset: u32, meant: &mut checker::meant): u32 {
|
||||
val syntax := &this.units[file].syntax;
|
||||
val asked := this.begin_query(file);
|
||||
var found: u32 = 0;
|
||||
for back in 0..2 {
|
||||
break if found != 0 || back as u32 > offset;
|
||||
val token := this.token_at(file, offset - back as u32);
|
||||
continue if token as u64 >= syntax.token_count || syntax.token_kinds[token] != tk::name;
|
||||
for &node in asked.walked.order {
|
||||
continue if this.token_of(node) != token;
|
||||
val each := this.meaning_of(node, &asked.walked, &asked.decls);
|
||||
if each.found() {
|
||||
meant = each;
|
||||
found = node;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
#! Where what a name refers to is declared: the name of its declaration, of the
|
||||
#! node declaring a local, or of the first module declaration naming a module.
|
||||
#! @param this The checker.
|
||||
#! @param meant What the name refers to.
|
||||
#! @param out Where it is written.
|
||||
#! @returns Whether it has a declaration to go to.
|
||||
def checker::declared_at(&mut this, meant: &checker::meant, out: &mut spot): bool {
|
||||
if meant.local != 0 {
|
||||
out = this.spot_of(meant.file, this.units[meant.file].syntax.node_tokens[meant.local]);
|
||||
return true;
|
||||
}
|
||||
if meant.is_module {
|
||||
return this.module_declared(meant.named_module, out);
|
||||
}
|
||||
val decl := meant.decl;
|
||||
return false if decl == 0 || this.decls.kinds.p[decl] == dk::builtin;
|
||||
val file: u32 = this.decls.files.p[decl];
|
||||
val node: u32 = this.decls.nodes.p[decl];
|
||||
return false if node == 0;
|
||||
val syntax := &this.units[file].syntax;
|
||||
val token: u32 = syntax.node_tokens[node];
|
||||
return false if syntax.token_names[token] != this.decls.names.p[decl];
|
||||
out = this.spot_of(file, token);
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Where a module is declared: the last segment of the first `module` naming it,
|
||||
#! in the order the files were given.
|
||||
#! @param this The checker.
|
||||
#! @param id The module.
|
||||
#! @param out Where it is written.
|
||||
#! @returns Whether a file declares it.
|
||||
def checker::module_declared(&mut this, id: u32, out: &mut spot): bool {
|
||||
for file in 0..this.units.length {
|
||||
val syntax := &this.units[file].syntax;
|
||||
val decls := syntax.node_lefts[this.units[file].root];
|
||||
for &node in syntax.run_view(decls) {
|
||||
continue if syntax.node_kinds[node] != nk::module_decl && syntax.node_kinds[node] != nk::extern_module;
|
||||
val path: u32 = syntax.node_lefts[node];
|
||||
continue if this.module_named(file as u32, path, 0xFFFFFFFF) != id;
|
||||
val run: u32 = syntax.node_lefts[path];
|
||||
val last := run == 0 ? path : syntax.run_at(run, syntax.run_length(run) - 1);
|
||||
out = this.spot_of(file as u32, syntax.node_tokens[last]);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Why renaming what a name refers to would lose it, or empty text where it
|
||||
#! would not: what is built in, a module, `this`, and what the compiler finds by
|
||||
#! its name.
|
||||
#! @param this The checker.
|
||||
#! @param meant What the name refers to.
|
||||
#! @returns Why it cannot be renamed, or empty text.
|
||||
def checker::refusal_of(&mut this, meant: &checker::meant): strview {
|
||||
if meant.is_module {
|
||||
return "A module is named by every file that declares or imports it, which renaming does not change.";
|
||||
}
|
||||
if meant.local != 0 {
|
||||
val name := this.local_text(meant.file, meant.local);
|
||||
if name == "this" {
|
||||
return "`this` is what every method calls its receiver.";
|
||||
}
|
||||
val syntax := &this.units[meant.file].syntax;
|
||||
if syntax.node_kinds[meant.local] == nk::param && (syntax.flags_at(meant.local) & nf::implied as u32) != 0 {
|
||||
return "`value` is what every `set` calls what it is given.";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
val decl := meant.decl;
|
||||
return "" if decl == 0;
|
||||
if this.decls.kinds.p[decl] == dk::builtin || this.decls.nodes.p[decl] == 0 {
|
||||
return "It is built into the language.";
|
||||
}
|
||||
if this.decls.kinds.p[decl] == dk::type_param && this.decls.names.p[decl] == names::self_id {
|
||||
return "`self` is what implements the trait it is written within.";
|
||||
}
|
||||
if this.decls.kinds.p[decl] == dk::function && this.decls.has(decl, df::intrinsic) {
|
||||
return "An `@intrinsic` function is bound to what implements it by its name.";
|
||||
}
|
||||
if this.decls.kinds.p[decl] == dk::function && this.decls.has(decl, df::foreign) && !this.has_body(decl) {
|
||||
return "A function without a body in an `extern module` is the C function of its name.";
|
||||
}
|
||||
if (this.decls.kinds.p[decl] == dk::struct_type || this.decls.kinds.p[decl] == dk::union_type) && this.decls.has(decl, df::foreign) {
|
||||
return this.decls.kinds.p[decl] == dk::union_type
|
||||
? "A union of an `extern module` is C's: every field begins where it does, and nothing says which it holds."
|
||||
: "A struct of an `extern module` is laid out as C lays it out.";
|
||||
}
|
||||
return this.compiler_names(decl);
|
||||
}
|
||||
|
||||
#! Why renaming a declaration would lose it to the compiler, which finds some by
|
||||
#! their names: the declarations of std it knows, as the types it makes values
|
||||
#! of and the traits whose methods it calls, the methods those traits ask for,
|
||||
#! the methods its arithmetic operators call, where a program begins, and the
|
||||
#! runtime an executable calls into.
|
||||
#! @param this The checker.
|
||||
#! @param decl The declaration.
|
||||
#! @returns Why it cannot be renamed, or empty text.
|
||||
def checker::compiler_names(&mut this, decl: u32): strview {
|
||||
for &each in this.known {
|
||||
if each.value == decl && decl != 0 {
|
||||
return match this.decls.kinds.p[decl] {
|
||||
dk::trait_type => "The compiler finds it by its name, as a trait whose methods it calls or whose meaning it decides.",
|
||||
dk::struct_type, dk::union_type, dk::enum_type, dk::alias_type => "The compiler finds it by its name, as a type it makes values of.",
|
||||
else => "The compiler finds it by its name."
|
||||
};
|
||||
}
|
||||
}
|
||||
if this.in_runtime(decl) && this.decls.kinds.p[decl] != dk::field {
|
||||
return "The compiler calls into `runtime` by name.";
|
||||
}
|
||||
if this.decls.kinds.p[decl] == dk::function && this.decls.owners.p[decl] == 0 && this.decls.modules.p[decl] == 0
|
||||
&& this.decls.names.p[decl] == word::main {
|
||||
return "A program begins at the function named `main`.";
|
||||
}
|
||||
|
||||
# A method the compiler calls for every type implementing one of its traits.
|
||||
if this.decls.kinds.p[decl] == dk::function && this.decls.owners.p[decl] != 0 {
|
||||
var traits := this.traits_asking(decl);
|
||||
for &trait_decl in traits {
|
||||
for &each in this.known {
|
||||
if each.value == trait_decl {
|
||||
return "The compiler calls it by its name, for every type implementing the trait asking for it.";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# A method an operator calls, which a type has the operator by declaring: `add`
|
||||
# for `+`, and the rest, taking the other operand, and `negate` for `-x` and
|
||||
# `bit_not` for `~x`.
|
||||
if this.decls.kinds.p[decl] == dk::function && this.decls.has(decl, df::method) {
|
||||
val name: u32 = this.decls.names.p[decl];
|
||||
val taken := this.types.part_count(this.decls.types.p[decl]);
|
||||
if name == word::negate && taken == 1 {
|
||||
return "The compiler calls it by its name, as the method `-x` is.";
|
||||
}
|
||||
if name == word::bit_not && taken == 1 {
|
||||
return "The compiler calls it by its name, as the method `~x` is.";
|
||||
}
|
||||
if taken == 2 && (name == word::add || name == word::sub || name == word::mul
|
||||
|| name == word::div || name == word::rem || name == word::bit_and
|
||||
|| name == word::bit_or || name == word::bit_xor || name == word::shift_left
|
||||
|| name == word::shift_right) {
|
||||
return "The compiler calls it by its name, as the method an operator is, as `+` is `add`.";
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
#! Whether a declaration is of the module `runtime`, which only an executable
|
||||
#! holds.
|
||||
#! @param this The checker.
|
||||
#! @param decl The declaration.
|
||||
#! @returns Whether it is.
|
||||
def checker::in_runtime(&this, decl: u32): bool {
|
||||
val home: u32 = this.decls.modules.p[decl];
|
||||
return home != 0 && this.modules.parents[home] == 0 && this.names.text(this.modules.names[home]) == "runtime";
|
||||
}
|
||||
|
||||
#! The traits that ask for a method: its own type's, where that is a trait, and
|
||||
#! those its type implements, or those compose, with a member of its name.
|
||||
#! @param this The checker.
|
||||
#! @param method The method.
|
||||
#! @returns The traits' declarations.
|
||||
def checker::traits_asking(&mut this, method: u32): vector<u32> {
|
||||
var made := vector::<u32>::new();
|
||||
val owner: u32 = this.decls.owners.p[method];
|
||||
return made if owner == 0;
|
||||
if this.decls.kinds.p[owner] == dk::trait_type {
|
||||
made.append(owner);
|
||||
}
|
||||
this.add_asking(owner, this.decls.names.p[method], &mut made, 0);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Adds the traits a type implements, or a trait composes, and those they
|
||||
#! compose, that have a member of the name.
|
||||
#! @param this The checker.
|
||||
#! @param decl The type or trait.
|
||||
#! @param name The ID of the name.
|
||||
#! @param into The traits found so far.
|
||||
#! @param depth How deeply composition has been followed.
|
||||
def checker::add_asking(&mut this, decl: u32, name: u32, into: &mut vector<u32>, depth: u32): void {
|
||||
return if depth > 16;
|
||||
val kind: dk = this.decls.kinds.p[decl];
|
||||
return if kind != dk::struct_type && kind != dk::union_type && kind != dk::trait_type;
|
||||
val run := this.composed_of(decl);
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val trait_decl := this.types.first_of(this.decls.list_at(run, i as u32));
|
||||
continue if trait_decl == 0 || this.decls.kinds.p[trait_decl] != dk::trait_type;
|
||||
if this.decls.member(trait_decl, name) != 0 {
|
||||
var known := false;
|
||||
for &each in into {
|
||||
known = known || each == trait_decl;
|
||||
}
|
||||
if !known {
|
||||
into.append(trait_decl);
|
||||
}
|
||||
}
|
||||
this.add_asking(trait_decl, name, into, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether a trait is another, or composes it.
|
||||
#! @param this The checker.
|
||||
#! @param trait_decl The trait.
|
||||
#! @param target The trait it may compose.
|
||||
#! @param depth How deeply composition has been followed.
|
||||
#! @returns Whether it does.
|
||||
def checker::trait_composes(&mut this, trait_decl: u32, target: u32, depth: u32): bool {
|
||||
return true if trait_decl == target;
|
||||
return false if depth > 16 || this.decls.kinds.p[trait_decl] != dk::trait_type;
|
||||
val run := this.composed_of(trait_decl);
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
return true if this.trait_composes(this.types.first_of(this.decls.list_at(run, i as u32)), target, depth + 1);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Everywhere the name at the offset of the file refers to is written, its
|
||||
#! declaration among them, in every file of the program, ordered by file and
|
||||
#! then by where in it they are. Each place is written with the very text of
|
||||
#! the name, so an editor renames it by replacing each.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param offset The byte of its text.
|
||||
#! @returns The places, which are none where no name the checker resolved is
|
||||
#! there.
|
||||
pub def checker::references(&mut this, file: u32, offset: u32): vector<spot> {
|
||||
var found := vector::<spot>::new();
|
||||
var strays := vector::<spot>::new();
|
||||
this.refer_all(file, offset, &mut found, &mut strays);
|
||||
return found;
|
||||
}
|
||||
|
||||
#! The places the name at the offset of the file is written but the checker left
|
||||
#! unresolved, as in a branch of `when` for another target, which may refer to
|
||||
#! the same thing. A local is sought only within the declaration holding it.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param offset The byte of its text.
|
||||
#! @returns The places, ordered as `references` orders them.
|
||||
pub def checker::unresolved(&mut this, file: u32, offset: u32): vector<spot> {
|
||||
var found := vector::<spot>::new();
|
||||
var strays := vector::<spot>::new();
|
||||
this.refer_all(file, offset, &mut found, &mut strays);
|
||||
return strays;
|
||||
}
|
||||
|
||||
#! Everywhere what the name at a place refers to is written, and where its text
|
||||
#! is written but unresolved, as `references` and `unresolved` give them.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param offset The byte of its text.
|
||||
#! @param found Where the places it is written are put.
|
||||
#! @param strays Where the places it is written unresolved are put.
|
||||
pub def checker::refer_all(&mut this, file: u32, offset: u32, found: &mut vector<spot>, strays: &mut vector<spot>): void {
|
||||
var meant := checker::meant {};
|
||||
val named := this.seek_name(file, offset, &mut meant);
|
||||
return if named == 0;
|
||||
var declared := spot {};
|
||||
return if !this.declared_at(&meant, &mut declared);
|
||||
|
||||
val name: u32 = this.units[declared.file].syntax.token_names[this.token_at(declared.file, declared.offset)];
|
||||
var sought := vector::<checker::meant>::new();
|
||||
sought.append(meant);
|
||||
this.widen(&meant, &mut sought);
|
||||
|
||||
# The top-level declaration holding a local, which alone may name it.
|
||||
var home_top: u32 = 0;
|
||||
if meant.local != 0 {
|
||||
home_top = this.top_holding(meant.file, meant.local);
|
||||
}
|
||||
|
||||
for each in 0..this.units.length {
|
||||
val at := each as u32;
|
||||
continue if meant.local != 0 && at != meant.file;
|
||||
val syntax := &this.units[at].syntax;
|
||||
val asked := this.begin_query(at);
|
||||
val walked := &asked.walked;
|
||||
for &node in walked.order {
|
||||
val token: u32 = syntax.node_tokens[node];
|
||||
continue if syntax.token_names[token] != name || syntax.token_kinds[token] != tk::name;
|
||||
continue if home_top != 0 && this.top_of(walked, node) != home_top;
|
||||
val held := this.meaning_of(node, walked, &asked.decls);
|
||||
var hit := false;
|
||||
for &want in sought {
|
||||
hit = hit || held.same(&want);
|
||||
}
|
||||
if hit {
|
||||
this.add_place(found, this.spot_of(at, token));
|
||||
if syntax.node_kinds[node] == nk::type_param || syntax.node_kinds[node] == nk::const_param {
|
||||
this.refer_bounds(at, node, found);
|
||||
}
|
||||
} else if !held.found() {
|
||||
val kind := syntax.node_kinds[node];
|
||||
val unnamed_type := (kind == nk::type_name && syntax.node_lefts[node] == 0) || kind == nk::segment;
|
||||
if kind == nk::name || kind == nk::member || unnamed_type
|
||||
|| (kind == nk::field_init && (syntax.flags_at(node) & nf::named as u32) != 0) {
|
||||
this.add_place(strays, this.spot_of(at, token));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
this.sort_places(found);
|
||||
this.sort_places(strays);
|
||||
}
|
||||
|
||||
#! Adds a place, once.
|
||||
#! @param this The checker.
|
||||
#! @param into The places.
|
||||
#! @param place The place.
|
||||
def checker::add_place(&this, into: &mut vector<spot>, place: spot): void {
|
||||
for &each in into {
|
||||
return if each.file == place.file && each.offset == place.offset;
|
||||
}
|
||||
into.append(place);
|
||||
}
|
||||
|
||||
#! Orders places by the path of their file, then where in it they are, so the
|
||||
#! places of a name come in the same order however the files were given.
|
||||
#! @param this The checker.
|
||||
#! @param places The places.
|
||||
def checker::sort_places(&this, places: &mut vector<spot>): void {
|
||||
places.sort_by(def(a: &spot, b: &spot): bool { return this.place_before(a, b); });
|
||||
}
|
||||
|
||||
#! Whether one place comes before another.
|
||||
#! @param this The checker.
|
||||
#! @param a The one place.
|
||||
#! @param b The other.
|
||||
#! @returns Whether `a` comes first.
|
||||
def checker::place_before(&this, a: &spot, b: &spot): bool {
|
||||
if a.file != b.file {
|
||||
return this.units[a.file].source.path.compare(this.units[b.file].source.path) < 0;
|
||||
}
|
||||
return a.offset < b.offset;
|
||||
}
|
||||
|
||||
#! The top-level declaration holding a node of a file.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param node The node.
|
||||
#! @returns The top-level declaration's node.
|
||||
def checker::top_holding(&this, file: u32, node: u32): u32 {
|
||||
val walked := this.tree_of(file);
|
||||
return this.top_of(&walked, node);
|
||||
}
|
||||
|
||||
#! The top-level node holding a node, which is the node itself where the
|
||||
#! document holds it.
|
||||
#! @param this The checker.
|
||||
#! @param walked The file's tree.
|
||||
#! @param node The node.
|
||||
#! @returns The top-level node.
|
||||
def checker::top_of(&this, walked: &tree_walk, node: u32): u32 {
|
||||
var at := node;
|
||||
var steps := 0;
|
||||
while steps < 4096 {
|
||||
val parent: u32 = walked.parents[at];
|
||||
return at if parent == 0 || walked.parents[parent] == 0;
|
||||
at = parent;
|
||||
steps++;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
#! A `where` clause names the type parameters it bounds, as `T` of
|
||||
#! `where T: show`, though no node holds the name there, since the bounds are
|
||||
#! given to the parameter. So the tokens after the parameter are read up to the
|
||||
#! body, or the `;` ending the declaration, for each name that follows `where`
|
||||
#! or `,` and is followed by `:`.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param param The `type_param` node.
|
||||
#! @param into Where the places are put.
|
||||
def checker::refer_bounds(&this, file: u32, param: u32, into: &mut vector<spot>): void {
|
||||
val syntax := &this.units[file].syntax;
|
||||
val name: u32 = syntax.token_names[syntax.node_tokens[param]];
|
||||
var depth := 0;
|
||||
var clause := false;
|
||||
var at: u32 = syntax.node_tokens[param] + 1;
|
||||
while at as u64 + 1 < syntax.token_count {
|
||||
val kind := syntax.token_kinds[at];
|
||||
if kind == tk::lparen || kind == tk::lbracket || kind == tk::less {
|
||||
depth++;
|
||||
} else if (kind == tk::rparen || kind == tk::rbracket || kind == tk::more) && depth > 0 {
|
||||
depth--;
|
||||
}
|
||||
break if depth == 0 && (kind == tk::lbrace || kind == tk::semicolon);
|
||||
if depth == 0 && kind == tk::kw_where {
|
||||
clause = true;
|
||||
} else if clause && kind == tk::name && syntax.token_names[at] == name && syntax.token_kinds[at + 1] == tk::colon {
|
||||
val prior := syntax.token_kinds[at - 1];
|
||||
if prior == tk::kw_where || prior == tk::comma {
|
||||
this.add_place(into, this.spot_of(file, at));
|
||||
}
|
||||
}
|
||||
at++;
|
||||
}
|
||||
}
|
||||
|
||||
#! A method a trait asks for is one name with each method implementing it, since
|
||||
#! a type implements a trait by the names of its methods: renaming one alone
|
||||
#! would leave a type no longer implementing a trait it declares. So a trait's
|
||||
#! method is sought with the method of the name of every type declaring the
|
||||
#! trait, directly or through one composing it, and a method of a type with the
|
||||
#! members of the traits its type declares that ask for it, and so with theirs.
|
||||
#! @param this The checker.
|
||||
#! @param meant What the name refers to.
|
||||
#! @param sought What is sought, which the rest are added to.
|
||||
def checker::widen(&mut this, meant: &checker::meant, sought: &mut vector<checker::meant>): void {
|
||||
val decl := meant.decl;
|
||||
return if decl == 0 || this.decls.kinds.p[decl] != dk::function || this.decls.owners.p[decl] == 0;
|
||||
var traits := this.traits_asking(decl);
|
||||
return if traits.length == 0;
|
||||
|
||||
val name: u32 = this.decls.names.p[decl];
|
||||
this.add_family(this.decls.owners.p[decl], name, sought);
|
||||
for &trait_decl in traits {
|
||||
this.add_family(trait_decl, name, sought);
|
||||
for id in 1..this.decls.count {
|
||||
val type_decl := id as u32;
|
||||
val kind: dk = this.decls.kinds.p[type_decl];
|
||||
continue if kind != dk::struct_type && kind != dk::union_type && kind != dk::trait_type;
|
||||
val run := this.composed_of(type_decl);
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val named := this.types.first_of(this.decls.list_at(run, i as u32));
|
||||
if this.trait_composes(named, trait_decl, 0) {
|
||||
this.add_family(type_decl, name, sought);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Adds each member of the name a type has, which overloads of a trait's method
|
||||
#! are renamed together, as `at(&this)` and `at(&mut this)`.
|
||||
#! @param this The checker.
|
||||
#! @param owner The type.
|
||||
#! @param name The ID of the name.
|
||||
#! @param sought What is sought.
|
||||
def checker::add_family(&mut this, owner: u32, name: u32, sought: &mut vector<checker::meant>): void {
|
||||
var walk := this.decls.walk_overloads(this.decls.member(owner, name), 256);
|
||||
while true {
|
||||
val at := walk.next();
|
||||
break if at == 0;
|
||||
val each := checker::meant { decl = this.standing_for(at) };
|
||||
var known := false;
|
||||
for &held in sought {
|
||||
known = known || held.same(&each);
|
||||
}
|
||||
if !known {
|
||||
sought.append(each);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
#! @file programs.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains what says which program a file belongs to. A file declaring `main`
|
||||
#! begins a program, which holds it and every file declaring none, so an
|
||||
#! editor whose workspace holds several, as a program and the program testing
|
||||
#! it, checks one of them at a time.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! Whether a parsed file declares `main` outside any module, beginning a
|
||||
#! program. A `main` in any branch of a `when` counts, whatever the target, and
|
||||
#! one after a `module` is that module's and does not. A file whose syntax has
|
||||
#! mistakes counts by what parsed.
|
||||
#! @param this The file's syntax.
|
||||
#! @param root Its `document` node.
|
||||
#! @param main The ID of the name `main`.
|
||||
#! @returns Whether it does.
|
||||
pub def syntax::declares_main(&this, root: u32, main: u32): bool {
|
||||
var found := false;
|
||||
this.main_within(this.node_lefts[root], main, &mut found);
|
||||
return found;
|
||||
}
|
||||
|
||||
#! Whether a run of top-level declarations declares `main` before a `module`.
|
||||
#! @param this The file's syntax.
|
||||
#! @param run The run.
|
||||
#! @param main The ID of the name `main`.
|
||||
#! @param found Where whether one does is written.
|
||||
#! @returns Whether a `module` ended the run, so nothing after it counts.
|
||||
def syntax::main_within(&this, run: u32, main: u32, found: &mut bool): bool {
|
||||
for &node in this.run_view(run) {
|
||||
match this.node_kinds[node] {
|
||||
nk::module_decl, nk::extern_module => return true;
|
||||
nk::function => {
|
||||
if this.token_names[this.node_tokens[node]] == main && this.record_at(node, function_slot::receiver) == 0 {
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
nk::when_block => {
|
||||
# Each branch is a block of declarations, or another `when`.
|
||||
var branch := this.record_at(node, if_slot::then);
|
||||
var other := this.record_at(node, if_slot::other);
|
||||
var steps := 0;
|
||||
while steps < 64 {
|
||||
steps++;
|
||||
if branch != 0 && this.node_kinds[branch] == nk::block {
|
||||
return true if this.main_within(this.node_lefts[branch], main, found);
|
||||
}
|
||||
break if other == 0;
|
||||
if this.node_kinds[other] == nk::when_block {
|
||||
branch = this.record_at(other, if_slot::then);
|
||||
other = this.record_at(other, if_slot::other);
|
||||
} else {
|
||||
branch = other;
|
||||
other = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Whether any note made of a file is a mistake of its syntax, which the lexer
|
||||
#! or the parser made, so what the checker says of it would mislead.
|
||||
#! @param this The note.
|
||||
#! @returns Whether it is.
|
||||
pub val note::is_syntax: bool {
|
||||
get {
|
||||
return match this.code {
|
||||
ec::syntax, ec::token, ec::expr, ec::ident, ec::kind, ec::decl, ec::escape, ec::char, ec::block => true,
|
||||
else => false
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,829 @@
|
||||
#! @file signatures.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains how an editor is shown what a name is: the signature it is declared
|
||||
#! with, with the types the checker gave it, as `def str::trim(this: &str): str`
|
||||
#! or `val count: int`, and the documentation comment written for it.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! The most members a type's signature lists.
|
||||
const checker::listed: u32 = 48;
|
||||
|
||||
#! How a declaration is written, with the types the checker gave it, as
|
||||
#! `pub def vec2::length(this: &vec2): float`. A struct, union, trait, or enum
|
||||
#! lists its members.
|
||||
#! @param this The checker.
|
||||
#! @param decl The declaration.
|
||||
#! @returns The signature.
|
||||
pub def checker::signature_of(&mut this, decl: u32): string {
|
||||
var out := string::new(nothing {});
|
||||
this.resolve(decl);
|
||||
val kind: dk = this.decls.kinds.p[decl];
|
||||
|
||||
# What another module reaches is written as it was declared, `pub` and all.
|
||||
if this.decls.has(decl, df::exported) && kind != dk::enum_member && kind != dk::type_param && kind != dk::builtin {
|
||||
out.append("pub ");
|
||||
}
|
||||
|
||||
match kind {
|
||||
dk::function => {
|
||||
if this.decls.has(decl, df::accessor) {
|
||||
this.property_text(this.decls.owners.p[decl], &mut out);
|
||||
} else {
|
||||
this.function_text(decl, true, &mut out);
|
||||
}
|
||||
}
|
||||
dk::property => this.property_text(decl, &mut out);
|
||||
dk::field => this.field_text(decl, this.decls.names.p[decl], &mut out);
|
||||
dk::enum_member => {
|
||||
this.owner_prefix(decl, &mut out);
|
||||
out.append(this.decl_text(decl));
|
||||
out.append(" = ");
|
||||
this.value_text(decl, &mut out);
|
||||
}
|
||||
dk::variable, dk::attribute => {
|
||||
out.append(this.decls.has(decl, df::constant) ? "const " : this.decls.has(decl, df::mutable) ? "var " : "val ");
|
||||
this.owner_prefix(decl, &mut out);
|
||||
out.append(this.decl_text(decl));
|
||||
out.append(": ");
|
||||
this.type_text(this.decls.types.p[decl], &mut out);
|
||||
}
|
||||
dk::struct_type, dk::union_type => this.aggregate_text(decl, &mut out);
|
||||
dk::trait_type => this.trait_text(decl, &mut out);
|
||||
dk::enum_type => this.enum_text(decl, &mut out);
|
||||
dk::alias_type => {
|
||||
val syntax := &this.units[this.decls.files.p[decl]].syntax;
|
||||
val node: u32 = this.decls.nodes.p[decl];
|
||||
out.append("type ");
|
||||
this.type_name_text(decl, &mut out);
|
||||
this.generics_text(this.decls.files.p[decl], syntax.record_at(node, alias_slot::type_params), &mut out);
|
||||
out.append(" = ");
|
||||
this.type_text(this.decls.targets.p[decl], &mut out);
|
||||
this.where_text(this.decls.files.p[decl], syntax.record_at(node, alias_slot::type_params), &mut out);
|
||||
}
|
||||
dk::type_param => this.type_param_text(decl, &mut out);
|
||||
dk::assoc_type => {
|
||||
out.append("type ");
|
||||
out.append(this.decl_text(decl));
|
||||
val bounds: u32 = this.decls.children.p[decl];
|
||||
for i in 0..this.decls.list_length(bounds) {
|
||||
out.append(i == 0 ? ": " : " + ");
|
||||
this.type_text(this.decls.list_at(bounds, i as u32), &mut out);
|
||||
}
|
||||
}
|
||||
dk::builtin => {
|
||||
# A built-in type is written as notes spell it, as `int` for `i64`.
|
||||
out.append("type ");
|
||||
this.type_text(this.decls.types.p[decl], &mut out);
|
||||
}
|
||||
else => {
|
||||
out.append("type ");
|
||||
out.append(this.decl_text(decl));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
#! The name a local is known by, as its declaration writes it, or of a parameter
|
||||
#! an accessor implies, whose token is the `get` or `set`, `this` or `value`.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param node The node declaring it.
|
||||
#! @returns The name.
|
||||
pub def checker::local_text(&mut this, file: u32, node: u32): strview {
|
||||
val syntax := &this.units[file].syntax;
|
||||
val text := this.token_text(file, syntax.node_tokens[node]);
|
||||
return text if syntax.node_kinds[node] != nk::param || (syntax.flags_at(node) & nf::implied as u32) == 0;
|
||||
return text == "set" && (syntax.flags_at(node) & nf::mutable as u32) == 0 ? "value" : "this";
|
||||
}
|
||||
|
||||
#! How a local is written, with the type the checker gave it, as `val n: int`,
|
||||
#! or `n: int` for a parameter.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param node The node declaring it.
|
||||
#! @returns The signature.
|
||||
pub def checker::local_signature(&mut this, file: u32, node: u32): string {
|
||||
var out := string::new(nothing {});
|
||||
val syntax := &this.units[file].syntax;
|
||||
val saved := this.at;
|
||||
this.use_table(this.units[file].table);
|
||||
var kind := this.type_at(node);
|
||||
val kind_of := syntax.node_kinds[node];
|
||||
val name := this.local_text(file, node);
|
||||
|
||||
if kind_of == nk::param {
|
||||
val flags := syntax.flags_at(node);
|
||||
# A parameter of a function without a body is no local, so its type is the
|
||||
# function's.
|
||||
if !this.has_flag(node, rf::local) {
|
||||
kind = this.param_type(file, node);
|
||||
}
|
||||
out.append(name);
|
||||
out.append(": ");
|
||||
if (flags & nf::variadic as u32) != 0 && this.types.kind_of(kind) == ty::named && this.types.part_count(kind) == 1 {
|
||||
this.type_text(this.types.part_at(kind, 0), &mut out);
|
||||
out.append("...");
|
||||
} else {
|
||||
this.type_text(kind, &mut out);
|
||||
}
|
||||
this.at = saved;
|
||||
return out;
|
||||
}
|
||||
|
||||
val flags := kind_of == nk::variable ? syntax.flags_at(node) : 0;
|
||||
if (flags & nf::constant as u32) != 0 {
|
||||
out.append("const ");
|
||||
} else {
|
||||
out.append(this.has_flag(node, rf::mutable) || (flags & nf::mutable as u32) != 0 ? "var " : "val ");
|
||||
}
|
||||
out.append(name);
|
||||
out.append(": ");
|
||||
this.type_text(kind, &mut out);
|
||||
this.at = saved;
|
||||
return out;
|
||||
}
|
||||
|
||||
#! The type of a parameter of a function, as its function's type gives it.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param node The `param` node.
|
||||
#! @returns Its type, or the error type.
|
||||
def checker::param_type(&mut this, file: u32, node: u32): u32 {
|
||||
# Resolving a function may make more declarations of the file, but nothing is
|
||||
# read of those it lists once one is resolved.
|
||||
for &id in this.decls.by_file.of(file) {
|
||||
continue if this.decls.kinds.p[id] != dk::function;
|
||||
val syntax := &this.units[file].syntax;
|
||||
val owner: u32 = this.decls.nodes.p[id];
|
||||
val run := this.decls.has(id, df::accessor) ? syntax.node_lefts[owner] : syntax.record_at(owner, function_slot::params);
|
||||
for i in 0..syntax.run_length(run) {
|
||||
continue if syntax.run_at(run, i as u32) != node;
|
||||
this.resolve(id);
|
||||
val kind: u32 = this.decls.types.p[id];
|
||||
return i < this.types.part_count(kind) ? this.types.part_at(kind, i as u32) : bt::error;
|
||||
}
|
||||
}
|
||||
return bt::error;
|
||||
}
|
||||
|
||||
#! How a module is written, as `module std::io`.
|
||||
#! @param this The checker.
|
||||
#! @param id The module.
|
||||
#! @returns The signature.
|
||||
pub def checker::module_signature(&this, id: u32): string {
|
||||
var out := string::from("module ", nothing {});
|
||||
this.module_text(id, &mut out);
|
||||
return out;
|
||||
}
|
||||
|
||||
#! Writes the path of a module, as `std::io`.
|
||||
#! @param this The checker.
|
||||
#! @param id The module.
|
||||
#! @param out Where it is written.
|
||||
pub def checker::module_text(&this, id: u32, out: &mut string): void {
|
||||
return if id == 0;
|
||||
val parent: u32 = this.modules.parents[id];
|
||||
if parent != 0 {
|
||||
this.module_text(parent, out);
|
||||
out.append("::");
|
||||
}
|
||||
out.append(this.names.text(this.modules.names[id]));
|
||||
}
|
||||
|
||||
#! Writes a type as notes spell it, as `&mut list<int>`.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param out Where it is written.
|
||||
def checker::type_text(&this, kind: u32, out: &mut string): void {
|
||||
if kind == 0 {
|
||||
out.append("?");
|
||||
return;
|
||||
}
|
||||
val described := this.describe(kind);
|
||||
out.append(described.view());
|
||||
}
|
||||
|
||||
#! Writes the type a member is declared through, as `rect::` of `rect::area`.
|
||||
#! @param this The checker.
|
||||
#! @param decl The member.
|
||||
#! @param out Where it is written.
|
||||
def checker::owner_prefix(&this, decl: u32, out: &mut string): void {
|
||||
val owner: u32 = this.decls.owners.p[decl];
|
||||
return if owner == 0;
|
||||
out.append(this.decl_text(owner));
|
||||
out.append("::");
|
||||
}
|
||||
|
||||
#! Writes the value of a member of an enum.
|
||||
#! @param this The checker.
|
||||
#! @param decl The member.
|
||||
#! @param out Where it is written.
|
||||
def checker::value_text(&this, decl: u32, out: &mut string): void {
|
||||
var held := constant {};
|
||||
if !this.decl_value(decl, &mut held) {
|
||||
out.append("?");
|
||||
return;
|
||||
}
|
||||
if held.negative {
|
||||
out.append("-");
|
||||
}
|
||||
val text := $"{held.magnitude}";
|
||||
out.append(text.view());
|
||||
}
|
||||
|
||||
#! Writes a function as it is declared: `def`, its name, after the type it is
|
||||
#! declared through where `owner` says, its own type parameters, its
|
||||
#! parameters with the types the checker gave them, and what it gives.
|
||||
#! @param this The checker.
|
||||
#! @param decl The function.
|
||||
#! @param owner Whether the type it is declared through is written.
|
||||
#! @param out Where it is written.
|
||||
def checker::function_text(&mut this, decl: u32, owner: bool, out: &mut string): void {
|
||||
this.instance_text_of(decl, owner, 0, out);
|
||||
}
|
||||
|
||||
#! Writes a function as `function_text` does, or where it is given an instance
|
||||
#! of it, as the instance is: its type arguments in place of its own type
|
||||
#! parameters, and its parameters and result of the types they give, as
|
||||
#! `def max<int>(a: int, b: int): int`.
|
||||
#! @param this The checker.
|
||||
#! @param decl The function.
|
||||
#! @param owner Whether the type it is declared through is written.
|
||||
#! @param made One more than the instance, or 0.
|
||||
#! @param out Where it is written.
|
||||
def checker::instance_text_of(&mut this, decl: u32, owner: bool, made: u32, out: &mut string): void {
|
||||
val file: u32 = this.decls.files.p[decl];
|
||||
val syntax := &this.units[file].syntax;
|
||||
val node: u32 = this.decls.nodes.p[decl];
|
||||
if this.decls.has(decl, df::optional) {
|
||||
out.append("@optional ");
|
||||
}
|
||||
if this.decls.has(decl, df::intrinsic) {
|
||||
out.append("@intrinsic ");
|
||||
} else if this.decls.has(decl, df::constant) {
|
||||
out.append("const ");
|
||||
}
|
||||
out.append("def ");
|
||||
if owner {
|
||||
this.owner_prefix(decl, out);
|
||||
}
|
||||
out.append(this.decl_text(decl));
|
||||
var kind: u32 = this.decls.types.p[decl];
|
||||
if made != 0 {
|
||||
# The arguments of its own type parameters, which follow those of the type
|
||||
# it is declared through, written as notes write them.
|
||||
val held: instance = this.instances[made - 1];
|
||||
kind = held.kind;
|
||||
val own := this.own_param_count(decl);
|
||||
val count := this.types.part_count(held.args);
|
||||
if own != 0 && own <= count {
|
||||
val parts := this.types.parts_view(held.args);
|
||||
out.append("<");
|
||||
this.describe_args(span::<u32>::over(parts.data + (count - own), own as u64), out);
|
||||
out.append(">");
|
||||
}
|
||||
} else {
|
||||
this.generics_text(file, syntax.record_at(node, function_slot::type_params), out);
|
||||
}
|
||||
|
||||
out.append("(");
|
||||
val params := syntax.record_at(node, function_slot::params);
|
||||
val count := syntax.run_length(params);
|
||||
for i in 0..count {
|
||||
if i != 0 {
|
||||
out.append(", ");
|
||||
}
|
||||
val param := syntax.run_at(params, i as u32);
|
||||
out.append(this.token_text(file, syntax.node_tokens[param]));
|
||||
out.append(": ");
|
||||
val held: u32 = kind != 0 && i < this.types.part_count(kind) ? this.types.part_at(kind, i as u32) : 0;
|
||||
this.type_text(held, out);
|
||||
# A pack's type is already written as spread, as `Ts...`.
|
||||
if i as u32 + 1 == count && this.decls.has(decl, df::variadic) && held != 0 && !this.types.is_open_pack(held) {
|
||||
out.append("...");
|
||||
}
|
||||
}
|
||||
out.append("): ");
|
||||
this.type_text(kind != 0 ? this.types.first_of(kind) : 0, out);
|
||||
if made == 0 {
|
||||
this.where_text(file, syntax.record_at(node, function_slot::type_params), out);
|
||||
}
|
||||
}
|
||||
|
||||
#! Writes a property as it is declared rather than as either of its accessors:
|
||||
#! `val` where it only reads, `var` where it also writes, and its type.
|
||||
#! @param this The checker.
|
||||
#! @param property The property.
|
||||
#! @param out Where it is written.
|
||||
def checker::property_text(&mut this, property: u32, out: &mut string): void {
|
||||
this.resolve(property);
|
||||
var intrinsic := this.decls.has(property, df::intrinsic);
|
||||
val run: u32 = this.decls.children.p[property];
|
||||
for &each in this.decls.list_view(run) {
|
||||
intrinsic = intrinsic || this.decls.has(each, df::intrinsic);
|
||||
}
|
||||
if intrinsic {
|
||||
out.append("@intrinsic ");
|
||||
}
|
||||
out.append(this.property_setter(property) != 0 ? "var " : "val ");
|
||||
this.owner_prefix(property, out);
|
||||
out.append(this.decl_text(property));
|
||||
out.append(": ");
|
||||
this.type_text(this.decls.types.p[property], out);
|
||||
}
|
||||
|
||||
#! Writes a field as it is declared, by the name it is reached by, as `var x: int`
|
||||
#! or `val base: ...pair`.
|
||||
#! @param this The checker.
|
||||
#! @param field The field.
|
||||
#! @param name The ID of the name it is reached by.
|
||||
#! @param out Where it is written.
|
||||
def checker::field_text(&mut this, field: u32, name: u32, out: &mut string): void {
|
||||
this.resolve(field);
|
||||
out.append(this.decls.has(field, df::mutable) ? "var " : "val ");
|
||||
out.append(this.names.text(name));
|
||||
out.append(": ");
|
||||
if this.is_spread(field) {
|
||||
out.append("...");
|
||||
}
|
||||
this.type_text(this.decls.types.p[field], out);
|
||||
}
|
||||
|
||||
#! Writes the name a type is declared with, after the type it is declared
|
||||
#! through as that is written, as `list<T>::iter`.
|
||||
#! @param this The checker.
|
||||
#! @param decl The type.
|
||||
#! @param out Where it is written.
|
||||
def checker::type_name_text(&this, decl: u32, out: &mut string): void {
|
||||
val file: u32 = this.decls.files.p[decl];
|
||||
val node: u32 = this.decls.nodes.p[decl];
|
||||
val syntax := &this.units[file].syntax;
|
||||
val receiver := node == 0 ? 0 : syntax.record_at(node, decl_slot::receiver);
|
||||
if receiver != 0 {
|
||||
val run: u32 = syntax.node_lefts[receiver];
|
||||
val count := run == 0 ? 1 : syntax.run_length(run);
|
||||
for i in 0..count {
|
||||
val segment := run == 0 ? receiver : syntax.run_at(run, i as u32);
|
||||
out.append(this.token_text(file, syntax.node_tokens[segment]));
|
||||
this.generics_text(file, run == 0 ? 0 : syntax.node_lefts[segment], out);
|
||||
out.append("::");
|
||||
}
|
||||
}
|
||||
out.append(this.decl_text(decl));
|
||||
}
|
||||
|
||||
#! Writes the names of a run of type parameters, as `<K, V>`, or nothing where
|
||||
#! the run is empty.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param run The run of `type_param` nodes.
|
||||
#! @param out Where it is written.
|
||||
def checker::generics_text(&this, file: u32, run: u32, out: &mut string): void {
|
||||
val syntax := &this.units[file].syntax;
|
||||
return if run == 0 || syntax.run_length(run) == 0;
|
||||
out.append("<");
|
||||
for i in 0..syntax.run_length(run) {
|
||||
if i != 0 {
|
||||
out.append(", ");
|
||||
}
|
||||
# A pattern parameter is written whole, as `def(Ts...): R` or `L[N]`.
|
||||
val param := syntax.run_at(run, i as u32);
|
||||
if syntax.node_kinds[param] == nk::type_pattern || syntax.node_kinds[param] == nk::array_pattern {
|
||||
var held := this.written(file, param);
|
||||
out.append(held.view());
|
||||
} else {
|
||||
out.append(this.token_text(file, syntax.node_tokens[param]));
|
||||
}
|
||||
}
|
||||
out.append(">");
|
||||
}
|
||||
|
||||
#! Writes the `where` clause bounding a run of type parameters, as
|
||||
#! ` where T: show + equatable`, or nothing where none is bounded.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param run The run of `type_param` nodes.
|
||||
#! @param out Where it is written.
|
||||
def checker::where_text(&this, file: u32, run: u32, out: &mut string): void {
|
||||
val syntax := &this.units[file].syntax;
|
||||
return if run == 0;
|
||||
var first := true;
|
||||
for &each in syntax.run_view(run) {
|
||||
var param := each;
|
||||
continue if syntax.node_kinds[param] == nk::type_pattern;
|
||||
# An array pattern's element is bounded as a type parameter is.
|
||||
if syntax.node_kinds[param] == nk::array_pattern {
|
||||
param = syntax.node_lefts[param];
|
||||
}
|
||||
val bounds: u32 = syntax.node_lefts[param];
|
||||
continue if bounds == 0 || syntax.run_length(bounds) == 0;
|
||||
out.append(first ? " where " : ", ");
|
||||
this.param_text(file, param, out);
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
|
||||
#! Writes a type parameter as it is declared, with its bounds, as
|
||||
#! `T: show + equatable`, `Ts...`, or `N: u64`.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param param The `type_param` or `const_param` node.
|
||||
#! @param out Where it is written.
|
||||
def checker::param_text(&this, file: u32, param: u32, out: &mut string): void {
|
||||
val syntax := &this.units[file].syntax;
|
||||
out.append(this.token_text(file, syntax.node_tokens[param]));
|
||||
if syntax.node_kinds[param] == nk::type_param && (syntax.node_rights[param] & nf::packed as u32) != 0 {
|
||||
out.append("...");
|
||||
}
|
||||
var joined := ": ";
|
||||
if syntax.node_kinds[param] == nk::const_param && syntax.node_rights[param] != 0 {
|
||||
out.append(": ");
|
||||
var held := this.written(file, syntax.node_rights[param]);
|
||||
out.append(held.view());
|
||||
joined = " + ";
|
||||
} else if syntax.node_kinds[param] == nk::const_param {
|
||||
# The length an array pattern names, as `N` of `L[N]`.
|
||||
out.append(": u64");
|
||||
joined = " + ";
|
||||
}
|
||||
val bounds: u32 = syntax.node_lefts[param];
|
||||
for i in 0..(bounds == 0 ? 0 : syntax.run_length(bounds)) {
|
||||
out.append(i == 0 ? joined : " + ");
|
||||
var held := this.written(file, syntax.run_at(bounds, i as u32));
|
||||
out.append(held.view());
|
||||
}
|
||||
}
|
||||
|
||||
#! Writes a type parameter, as `type parameter T: show`, or a constant one, as
|
||||
#! `constant parameter N: u64`.
|
||||
#! @param this The checker.
|
||||
#! @param decl The type parameter.
|
||||
#! @param out Where it is written.
|
||||
def checker::type_param_text(&this, decl: u32, out: &mut string): void {
|
||||
val file: u32 = this.decls.files.p[decl];
|
||||
val node: u32 = this.decls.nodes.p[decl];
|
||||
val syntax := &this.units[file].syntax;
|
||||
out.append(this.decls.has(decl, df::valued) ? "constant parameter " : "type parameter ");
|
||||
if node != 0 && (syntax.node_kinds[node] == nk::type_param || syntax.node_kinds[node] == nk::const_param) {
|
||||
this.param_text(file, node, out);
|
||||
} else {
|
||||
out.append(this.decl_text(decl));
|
||||
}
|
||||
}
|
||||
|
||||
#! Writes the traits a type implements, or a trait composes, as they are
|
||||
#! written, as `: show, equatable`.
|
||||
#! @param this The checker.
|
||||
#! @param decl The type.
|
||||
#! @param out Where it is written.
|
||||
def checker::traits_text(&this, decl: u32, out: &mut string): void {
|
||||
val file: u32 = this.decls.files.p[decl];
|
||||
val node: u32 = this.decls.nodes.p[decl];
|
||||
val syntax := &this.units[file].syntax;
|
||||
val run := node == 0 ? 0 : syntax.record_at(node, aggregate_slot::traits);
|
||||
for i in 0..(run == 0 ? 0 : syntax.run_length(run)) {
|
||||
out.append(i == 0 ? ": " : ", ");
|
||||
var held := this.written(file, syntax.run_at(run, i as u32));
|
||||
out.append(held.view());
|
||||
}
|
||||
}
|
||||
|
||||
#! Writes a struct or union with its fields.
|
||||
#! @param this The checker.
|
||||
#! @param decl The type.
|
||||
#! @param out Where it is written.
|
||||
def checker::aggregate_text(&mut this, decl: u32, out: &mut string): void {
|
||||
val file: u32 = this.decls.files.p[decl];
|
||||
val node: u32 = this.decls.nodes.p[decl];
|
||||
val syntax := &this.units[file].syntax;
|
||||
val union_type := this.decls.kinds.p[decl] == dk::union_type;
|
||||
out.append(union_type ? "union " : "struct ");
|
||||
this.type_name_text(decl, out);
|
||||
this.generics_text(file, syntax.record_at(node, aggregate_slot::type_params), out);
|
||||
this.traits_text(decl, out);
|
||||
this.where_text(file, syntax.record_at(node, aggregate_slot::type_params), out);
|
||||
|
||||
out.append(" {");
|
||||
var listed: u32 = 0;
|
||||
val run: u32 = this.decls.children.p[decl];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val field := this.decls.list_at(run, i as u32);
|
||||
continue if this.decls.kinds.p[field] != dk::field;
|
||||
break if listed == checker::listed;
|
||||
out.append("\n ");
|
||||
if this.decls.has(field, df::exported) {
|
||||
out.append("pub ");
|
||||
}
|
||||
this.field_text(field, this.decls.names.p[field], out);
|
||||
out.append(";");
|
||||
listed++;
|
||||
}
|
||||
out.append(listed != 0 ? "\n}" : "}");
|
||||
}
|
||||
|
||||
#! Writes a trait with the methods it asks for.
|
||||
#! @param this The checker.
|
||||
#! @param decl The trait.
|
||||
#! @param out Where it is written.
|
||||
def checker::trait_text(&mut this, decl: u32, out: &mut string): void {
|
||||
out.append("trait ");
|
||||
this.type_name_text(decl, out);
|
||||
val file: u32 = this.decls.files.p[decl];
|
||||
val node: u32 = this.decls.nodes.p[decl];
|
||||
this.generics_text(file, this.units[file].syntax.record_at(node, aggregate_slot::type_params), out);
|
||||
this.traits_text(decl, out);
|
||||
|
||||
out.append(" {");
|
||||
var listed: u32 = 0;
|
||||
val run: u32 = this.decls.children.p[decl];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val member := this.decls.list_at(run, i as u32);
|
||||
continue if this.decls.kinds.p[member] != dk::function;
|
||||
break if listed == checker::listed;
|
||||
this.resolve(member);
|
||||
out.append("\n ");
|
||||
this.function_text(member, false, out);
|
||||
out.append(";");
|
||||
listed++;
|
||||
}
|
||||
out.append(listed != 0 ? "\n}" : "}");
|
||||
}
|
||||
|
||||
#! Writes an enum with its members and their values.
|
||||
#! @param this The checker.
|
||||
#! @param decl The enum.
|
||||
#! @param out Where it is written.
|
||||
def checker::enum_text(&mut this, decl: u32, out: &mut string): void {
|
||||
out.append("enum ");
|
||||
this.type_name_text(decl, out);
|
||||
out.append(": ");
|
||||
this.type_text(this.decls.targets.p[decl], out);
|
||||
|
||||
out.append(" {");
|
||||
var listed: u32 = 0;
|
||||
val run: u32 = this.decls.children.p[decl];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
val member := this.decls.list_at(run, i as u32);
|
||||
continue if this.decls.kinds.p[member] != dk::enum_member;
|
||||
break if listed == checker::listed;
|
||||
this.resolve(member);
|
||||
out.append("\n ");
|
||||
out.append(this.decl_text(member));
|
||||
out.append(" = ");
|
||||
this.value_text(member, out);
|
||||
out.append(",");
|
||||
listed++;
|
||||
}
|
||||
out.append(listed != 0 ? "\n}" : "}");
|
||||
}
|
||||
|
||||
#! Writes the attributes written on a declaration, each on a line of its own as
|
||||
#! it is written, as `@test`.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param node The declaration's node.
|
||||
#! @param out Where they are written.
|
||||
def checker::attributes_text(&this, file: u32, node: u32, out: &mut string): void {
|
||||
val syntax := &this.units[file].syntax;
|
||||
val run := match syntax.node_kinds[node] {
|
||||
nk::function, nk::variable, nk::field, nk::property, nk::struct_decl, nk::union_decl,
|
||||
nk::trait_decl, nk::assoc_type, nk::enumeration, nk::alias => syntax.record_at(node, decl_slot::attributes),
|
||||
nk::enumerator => syntax.node_lefts[node],
|
||||
else => 0
|
||||
};
|
||||
for i in 0..(run == 0 ? 0 : syntax.run_length(run)) {
|
||||
var held := this.written(file, syntax.run_at(run, i as u32));
|
||||
out.append(held.view());
|
||||
out.append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
#! The documentation comment of a declaration: the `#!` lines written on lines
|
||||
#! of their own right above it, and a `#!` after it on its own line, without
|
||||
#! their markers. A parameter or type parameter is described by its line of
|
||||
#! its declaration's comment, `@param` or `@tparam`.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param node The node declaring it.
|
||||
#! @param walked The file's tree, where it is at hand, which says what holds a
|
||||
#! parameter.
|
||||
#! @returns The comment, or empty text.
|
||||
pub def checker::documentation_of(&this, file: u32, node: u32): string {
|
||||
var made := string::new(nothing {});
|
||||
return made if node == 0;
|
||||
val syntax := &this.units[file].syntax;
|
||||
val kind := syntax.node_kinds[node];
|
||||
if kind == nk::param || kind == nk::type_param || kind == nk::const_param {
|
||||
val owner := this.owner_of_param(file, node);
|
||||
return made if owner == 0;
|
||||
var whole := this.documentation_of(file, owner);
|
||||
return this.tagged(whole.view(), kind == nk::param ? "param" : "tparam", this.token_text(file, syntax.node_tokens[node]));
|
||||
}
|
||||
|
||||
val text := this.units[file].source.make_lexeme(0, this.units[file].source.length);
|
||||
val start: u32 = syntax.token_offsets[syntax.start_of(node)];
|
||||
var line := start;
|
||||
while line > 0 && text[(line - 1) as u64] != '\n' {
|
||||
line--;
|
||||
}
|
||||
|
||||
# The comment above a line is of the declaration it begins, as `def str::trim`,
|
||||
# and not of the names declared after it on the line.
|
||||
var leading := true;
|
||||
for at in line..start {
|
||||
val byte: u8 = text[at as u64];
|
||||
leading = leading && (byte == ' ' || byte == '\t' || byte == ':' || byte == '<' || byte == '>' || byte == ','
|
||||
|| byte == '&' || byte == '_' || (byte >= 'a' && byte <= 'z') || (byte >= 'A' && byte <= 'Z') || (byte >= '0' && byte <= '9'));
|
||||
}
|
||||
|
||||
var lines := vector::<strview>::new();
|
||||
var above := line;
|
||||
while leading && above > 0 && lines.length < 64 {
|
||||
var previous := above - 1;
|
||||
while previous > 0 && text[(previous - 1) as u64] != '\n' {
|
||||
previous--;
|
||||
}
|
||||
var at := previous;
|
||||
while at < above && (text[at as u64] == ' ' || text[at as u64] == '\t') {
|
||||
at++;
|
||||
}
|
||||
break if above - at < 3 || text[at as u64] != '#' || text[(at + 1) as u64] != '!' || text[(at + 2) as u64] == '<';
|
||||
lines.append(this.comment_text(text, at + 2));
|
||||
above = previous;
|
||||
}
|
||||
var i := lines.length;
|
||||
while i > 0 {
|
||||
i--;
|
||||
made.append(lines[i]);
|
||||
made.append("\n");
|
||||
}
|
||||
|
||||
# A `#!` after the declaration on its own line, outside any string there.
|
||||
var quote: u8 = 0;
|
||||
var at: u32 = syntax.token_offsets[syntax.node_tokens[node]] + syntax.token_length(syntax.node_tokens[node], this.names);
|
||||
while (at as u64) < text.length && text[at as u64] != '\n' {
|
||||
val byte: u8 = text[at as u64];
|
||||
if quote != 0 {
|
||||
if byte == '\\' {
|
||||
at++;
|
||||
} else if byte == quote {
|
||||
quote = 0;
|
||||
}
|
||||
} else if byte == '"' || byte == '\'' {
|
||||
quote = byte;
|
||||
} else if byte == '#' {
|
||||
if at as u64 + 1 < text.length && text[(at + 1) as u64] == '!' {
|
||||
val after := at as u64 + 2 < text.length && text[(at + 2) as u64] == '<' ? at + 3 : at + 2;
|
||||
made.append(this.comment_text(text, after));
|
||||
made.append("\n");
|
||||
}
|
||||
break;
|
||||
}
|
||||
at++;
|
||||
}
|
||||
|
||||
while made.length != 0 && made[made.length - 1] == '\n' {
|
||||
made = string::from(made.substr(0, made.length - 1), nothing {});
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The text of a comment from after its marker to the end of its line, with one
|
||||
#! space after the marker and the spacing ending the line left out.
|
||||
#! @param this The checker.
|
||||
#! @param text The file's text.
|
||||
#! @param from Where the text after the marker begins.
|
||||
#! @returns The text.
|
||||
def checker::comment_text(&this, text: strview, from: u32): strview {
|
||||
var start := from as u64;
|
||||
var stop := start;
|
||||
while stop < text.length && text[stop] != '\n' {
|
||||
stop++;
|
||||
}
|
||||
if start < stop && text[start] == ' ' {
|
||||
start++;
|
||||
}
|
||||
while stop > start && (text[stop - 1] == '\r' || text[stop - 1] == ' ') {
|
||||
stop--;
|
||||
}
|
||||
return text.substr(start, stop - start);
|
||||
}
|
||||
|
||||
#! What a documentation comment says of one of its parameters: the text after
|
||||
#! `@param name`, or `@tparam name`, through the lines continuing it.
|
||||
#! @param this The checker.
|
||||
#! @param text The comment.
|
||||
#! @param tag `param` or `tparam`.
|
||||
#! @param name The parameter's name.
|
||||
#! @returns The text, or empty text.
|
||||
def checker::tagged(&this, text: strview, tag: strview, name: strview): string {
|
||||
var made := string::new(nothing {});
|
||||
var within := false;
|
||||
var line: u64 = 0;
|
||||
while line < text.length {
|
||||
var stop := line;
|
||||
while stop < text.length && text[stop] != '\n' {
|
||||
stop++;
|
||||
}
|
||||
var at := line;
|
||||
while at < stop && (text[at] == ' ' || text[at] == '\t') {
|
||||
at++;
|
||||
}
|
||||
if at < stop && (text[at] == '@' || text[at] == '\\') {
|
||||
within = false;
|
||||
if stop - at > tag.length && text.substr(at + 1, tag.length) == tag {
|
||||
at += 1 + tag.length;
|
||||
if at < stop && text[at] == '[' {
|
||||
while at < stop && text[at] != ']' {
|
||||
at++;
|
||||
}
|
||||
at++;
|
||||
}
|
||||
while at < stop && (text[at] == ' ' || text[at] == '\t') {
|
||||
at++;
|
||||
}
|
||||
val word := at;
|
||||
while at < stop && is_word_byte(text[at]) {
|
||||
at++;
|
||||
}
|
||||
if text.substr(word, at - word) == name {
|
||||
while at < stop && (text[at] == ' ' || text[at] == '\t') {
|
||||
at++;
|
||||
}
|
||||
made.append(text.substr(at, stop - at));
|
||||
within = true;
|
||||
}
|
||||
}
|
||||
} else if within && at < stop {
|
||||
made.append(" ");
|
||||
made.append(text.substr(at, stop - at));
|
||||
}
|
||||
line = stop + 1;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The node of the declaration a parameter or type parameter belongs to, whose
|
||||
#! documentation describes it, or 0.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param node The `param`, `type_param`, or `const_param` node.
|
||||
#! @returns The declaration's node, or 0.
|
||||
def checker::owner_of_param(&this, file: u32, node: u32): u32 {
|
||||
val syntax := &this.units[file].syntax;
|
||||
for &id in this.decls.by_file.of(file) {
|
||||
val owner: u32 = this.decls.nodes.p[id];
|
||||
continue if owner == 0;
|
||||
match syntax.node_kinds[owner] {
|
||||
nk::function => {
|
||||
return owner if this.run_holds(syntax, syntax.record_at(owner, function_slot::params), node)
|
||||
|| this.run_holds(syntax, syntax.record_at(owner, function_slot::type_params), node)
|
||||
|| this.receiver_holds(syntax, syntax.record_at(owner, function_slot::receiver), node);
|
||||
}
|
||||
nk::struct_decl, nk::union_decl, nk::trait_decl, nk::alias => {
|
||||
return owner if this.run_holds(syntax, syntax.record_at(owner, decl_slot::type_params), node);
|
||||
}
|
||||
nk::variable, nk::property => {
|
||||
return owner if this.receiver_holds(syntax, syntax.record_at(owner, decl_slot::receiver), node);
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! Whether a run of a syntax holds a node.
|
||||
#! @param this The checker.
|
||||
#! @param syntax The syntax.
|
||||
#! @param run The run.
|
||||
#! @param node The node.
|
||||
#! @returns Whether it does.
|
||||
def checker::run_holds(&this, syntax: &syntax, run: u32, node: u32): bool {
|
||||
return false if run == 0;
|
||||
for &each in syntax.run_view(run) {
|
||||
return true if each == node;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Whether the last segment of a receiver declares a type parameter, as `T` of
|
||||
#! `def box<T>::get`.
|
||||
#! @param this The checker.
|
||||
#! @param syntax The syntax.
|
||||
#! @param receiver The receiver's `type_name` node, or 0.
|
||||
#! @param node The type parameter's node.
|
||||
#! @returns Whether it does.
|
||||
def checker::receiver_holds(&this, syntax: &syntax, receiver: u32, node: u32): bool {
|
||||
return false if receiver == 0;
|
||||
val run: u32 = syntax.node_lefts[receiver];
|
||||
return false if run == 0;
|
||||
for &each in syntax.run_view(run) {
|
||||
return true if this.run_holds(syntax, syntax.node_lefts[each], node);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,628 @@
|
||||
#! @file symbols.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains what the queries an editor asks of a checked program share: what a
|
||||
#! name is, as `symbol` says, where one is written, as a `spot`, the walk of a
|
||||
#! file that finds what holds each node, and what the name a node writes
|
||||
#! refers to.
|
||||
#!
|
||||
#! The queries read what checking recorded of each node, as the declaration a
|
||||
#! name refers to and the type of each expression, together with the tables the
|
||||
#! check built. They ask the checker nothing that reports, so a query never
|
||||
#! adds a note.
|
||||
|
||||
import std::containers;
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! What a name is, as an editor offers it to complete and colours it.
|
||||
pub enum symbol : u8 {
|
||||
keyword, #! A keyword, as `def`.
|
||||
namespace, #! A module.
|
||||
function, #! A function, or a function declared through a type.
|
||||
method, #! A method, which takes `this`.
|
||||
variable, #! A variable, or a local.
|
||||
constant, #! A constant, or a variable that is never written, declared outside any function.
|
||||
parameter, #! A parameter.
|
||||
field, #! A field, or a property.
|
||||
struct_type, #! A struct or union.
|
||||
trait_type, #! A trait.
|
||||
enum_type, #! An enum.
|
||||
enum_member, #! A member of an enum.
|
||||
type_name, #! Any other type, as a built-in one or an alias.
|
||||
type_param, #! A type parameter.
|
||||
}
|
||||
|
||||
#! Where a name is written: its file, and the bytes of its text it covers.
|
||||
pub struct spot {
|
||||
pub var file: u32; #! The index of the file.
|
||||
pub var offset: u32; #! Where the name begins in the file's text.
|
||||
pub var length: u32; #! How many bytes it covers.
|
||||
}
|
||||
|
||||
#! What a name refers to: a declaration, a local, or a module.
|
||||
struct checker::meant {
|
||||
var decl: u32; #! The declaration, or 0.
|
||||
var file: u32; #! The file of the local.
|
||||
var local: u32; #! The node declaring the local, as a `variable` or `param`, or 0.
|
||||
var named_module: u32; #! The module, where `is_module` says it is one.
|
||||
var is_module: bool; #! Whether it is a module.
|
||||
}
|
||||
|
||||
#! Whether a name refers to anything.
|
||||
#! @param this What it refers to.
|
||||
#! @returns Whether it does.
|
||||
def checker::meant::found(&this): bool {
|
||||
return this.decl != 0 || this.local != 0 || this.is_module;
|
||||
}
|
||||
|
||||
#! Whether two names refer to the same thing.
|
||||
#! @param this What one refers to.
|
||||
#! @param other What the other refers to.
|
||||
#! @returns Whether they do.
|
||||
def checker::meant::same(&this, other: &checker::meant): bool {
|
||||
return this.decl == other.decl && this.local == other.local && this.file == other.file
|
||||
&& this.is_module == other.is_module && this.named_module == other.named_module;
|
||||
}
|
||||
|
||||
#! The nodes of a file a walk from its `document` meets, each before the nodes
|
||||
#! it holds, and the node holding each. The nodes a reparse left behind are no
|
||||
#! longer in the tree, and the walk never meets them.
|
||||
struct tree_walk {
|
||||
var order: vector<u32>; #! The nodes, in the order the walk meets them.
|
||||
var parents: vector<u32>; #! The node holding each, by its index, or 0.
|
||||
}
|
||||
|
||||
#! The tree of the file, walked from its `document`.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @returns The tree.
|
||||
def checker::tree_of(&this, file: u32): tree_walk {
|
||||
val syntax := &this.units[file].syntax;
|
||||
var made := tree_walk { order = vector::<u32>::new(), parents = vector::<u32>::new() };
|
||||
made.parents.resize(syntax.node_count);
|
||||
var todo := vector::<u32>::new();
|
||||
var held := vector::<u32>::new();
|
||||
todo.append(this.units[file].root);
|
||||
while todo.length != 0 {
|
||||
val at: u32 = todo.last();
|
||||
todo.truncate();
|
||||
made.order.append(at);
|
||||
held.clear();
|
||||
syntax.children(at, &mut held);
|
||||
var i := held.length;
|
||||
while i > 0 {
|
||||
i--;
|
||||
val child: u32 = held[i];
|
||||
continue if child as u64 >= syntax.node_count || made.parents[child] != 0;
|
||||
made.parents[child] = at;
|
||||
todo.append(child);
|
||||
}
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The token of the file whose text holds the offset, or the count of its
|
||||
#! tokens where none does, as between two.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param offset The byte of its text.
|
||||
#! @returns The token.
|
||||
def checker::token_at(&this, file: u32, offset: u32): u32 {
|
||||
val syntax := &this.units[file].syntax;
|
||||
val count := syntax.token_count as u32;
|
||||
# The token before the first beginning past the offset is the one that may
|
||||
# hold it.
|
||||
val after := syntax.token_offsets.view().upper_bound(&offset) as u32;
|
||||
return count if after == 0;
|
||||
val token := after - 1;
|
||||
val start: u32 = syntax.token_offsets[token];
|
||||
return token if offset < start + syntax.token_length(token, this.names);
|
||||
return count;
|
||||
}
|
||||
|
||||
#! Where the token is written.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param token The token.
|
||||
#! @returns Its spot.
|
||||
def checker::spot_of(&this, file: u32, token: u32): spot {
|
||||
val syntax := &this.units[file].syntax;
|
||||
return spot { file = file, offset = syntax.token_offsets[token], length = syntax.token_length(token, this.names) };
|
||||
}
|
||||
|
||||
#! The text of a token of a file.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param token The token.
|
||||
#! @returns The text, which views the file's source.
|
||||
def checker::token_text(&this, file: u32, token: u32): strview {
|
||||
val syntax := &this.units[file].syntax;
|
||||
return this.units[file].source.make_lexeme(syntax.token_offsets[token], syntax.token_length(token, this.names));
|
||||
}
|
||||
|
||||
#! The text a node of a file is written as, from its first token through its
|
||||
#! last, with each run of spacing made one space, as `std::list<T>`.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param node The node.
|
||||
#! @returns The text.
|
||||
def checker::written(&this, file: u32, node: u32): string {
|
||||
val syntax := &this.units[file].syntax;
|
||||
var made := string::new(nothing {});
|
||||
return made if node == 0;
|
||||
val first: u32 = syntax.node_tokens[node];
|
||||
var last: u32 = syntax.node_end(node);
|
||||
last = last < first ? first : last;
|
||||
val start: u32 = syntax.token_offsets[first];
|
||||
val end: u32 = syntax.token_offsets[last] + syntax.token_length(last, this.names);
|
||||
val text := this.units[file].source.make_lexeme(start, end - start);
|
||||
var spaced := false;
|
||||
for i in 0..text.length {
|
||||
val byte: u8 = text[i];
|
||||
if byte == ' ' || byte == '\t' || byte == '\n' || byte == '\r' {
|
||||
spaced = true;
|
||||
continue;
|
||||
}
|
||||
if spaced && made.length != 0 {
|
||||
made.push(' ');
|
||||
}
|
||||
spaced = false;
|
||||
made.push(byte);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A slot of a node's record, in whichever slot its shape keeps the record.
|
||||
#! @param this The syntax tree.
|
||||
#! @param node The node.
|
||||
#! @param index The slot's position in the record.
|
||||
#! @returns The slot, or 0 where the node has no record.
|
||||
def syntax::record_at(&this, node: u32, index: u32): u32 {
|
||||
val kind := this.node_kinds[node];
|
||||
val at: u32 = kind.shape.left == slot::extra ? this.node_lefts[node] : this.node_rights[node];
|
||||
return this.extras[at as u64 + index as u64];
|
||||
}
|
||||
|
||||
#! The flags of a node, wherever its shape keeps them.
|
||||
#! @param this The syntax tree.
|
||||
#! @param node The node.
|
||||
#! @returns The flags, as `nf` says, or 0.
|
||||
def syntax::flags_at(&this, node: u32): u32 {
|
||||
val shape := this.node_kinds[node].shape;
|
||||
return this.node_rights[node] if shape.right == slot::flags;
|
||||
return this.node_lefts[node] if shape.left == slot::flags;
|
||||
for i in 0..shape.record.length {
|
||||
return this.record_at(node, i as u32) if shape.record[i] == slot::flags;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! A query of a file under way: where checking was before it began, the walk
|
||||
#! of the file's tree, and the declarations of the file's nodes. It closes
|
||||
#! where its scope ends, however the query returns, which puts back where
|
||||
#! checking was.
|
||||
struct checker::query : owning {
|
||||
var checker: &mut checker; #! The checker queried.
|
||||
var saved: checker::frame; #! Where checking was, which closing puts back.
|
||||
var walked: tree_walk; #! The file's tree.
|
||||
var decls: dict<u32, u32>; #! The declarations each node of the file declares, by the node.
|
||||
var open: bool; #! Whether it is yet to close.
|
||||
}
|
||||
|
||||
#! Begins a query of the file: its results are what is read, nothing the
|
||||
#! checker works out depends on the query, and nothing it reports is noted,
|
||||
#! until the query closes.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @returns The query, holding the file's tree and the declarations of its
|
||||
#! nodes.
|
||||
def checker::begin_query(&mut this, file: u32): checker::query {
|
||||
val saved := this.at;
|
||||
this.use_table(this.units[file].table);
|
||||
this.at.decl = 0;
|
||||
this.at.instance = 0;
|
||||
this.at.scope = 0;
|
||||
this.at.home = 0;
|
||||
this.mute++;
|
||||
this.owned_names = true;
|
||||
return checker::query {
|
||||
checker = this,
|
||||
saved = saved,
|
||||
walked = this.tree_of(file),
|
||||
decls = this.decls_in(file),
|
||||
open = true
|
||||
};
|
||||
}
|
||||
|
||||
#! Ends the query, putting back where checking was, once.
|
||||
#! @param this The query.
|
||||
def checker::query::close(&mut this): void {
|
||||
return if !this.open;
|
||||
this.open = false;
|
||||
this.checker.mute--;
|
||||
this.checker.owned_names = this.checker.mute != 0 && this.checker.owned_names;
|
||||
this.checker.at = this.saved;
|
||||
close(&mut this.walked);
|
||||
close(&mut this.decls);
|
||||
}
|
||||
|
||||
#! Moves the query to another file, whose results are read from then on.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
def checker::query_file(&mut this, file: u32): void {
|
||||
this.use_table(this.units[file].table);
|
||||
this.at.decl = 0;
|
||||
this.at.instance = 0;
|
||||
}
|
||||
|
||||
#! The module the declarations a file makes before the offset are in: that of
|
||||
#! the last `module` before it, or the program's own.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param offset The byte of its text.
|
||||
#! @returns The module.
|
||||
def checker::home_at(&mut this, file: u32, offset: u32): u32 {
|
||||
val syntax := &this.units[file].syntax;
|
||||
val decls := syntax.node_lefts[this.units[file].root];
|
||||
var home: u32 = 0;
|
||||
for &node in syntax.run_view(decls) {
|
||||
break if syntax.token_offsets[syntax.node_tokens[node]] > offset;
|
||||
continue if syntax.node_kinds[node] != nk::module_decl && syntax.node_kinds[node] != nk::extern_module;
|
||||
val found := this.module_named(file, syntax.node_lefts[node], 0xFFFFFFFF);
|
||||
if found != 0 {
|
||||
home = found;
|
||||
}
|
||||
}
|
||||
return home;
|
||||
}
|
||||
|
||||
#! The module a `path` of a file names from the program's own, through its
|
||||
#! segment at `last`, or 0 where it names none.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param path The `path` node.
|
||||
#! @param last The position of the last segment read, or more for all.
|
||||
#! @returns The module, or 0.
|
||||
def checker::module_named(&this, file: u32, path: u32, last: u32): u32 {
|
||||
val syntax := &this.units[file].syntax;
|
||||
val run: u32 = syntax.node_lefts[path];
|
||||
if run == 0 {
|
||||
return this.modules.find(0, syntax.token_names[syntax.node_tokens[path]]);
|
||||
}
|
||||
var at: u32 = 0;
|
||||
for i in 0..syntax.run_length(run) {
|
||||
break if i as u32 > last;
|
||||
val segment := syntax.run_at(run, i as u32);
|
||||
at = this.modules.find(at, syntax.token_names[syntax.node_tokens[segment]]);
|
||||
return 0 if at == 0;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
#! The declarations each node of a file declares, by the node.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @returns The declarations, by their nodes.
|
||||
def checker::decls_in(&this, file: u32): dict<u32, u32> {
|
||||
var made := dict::<u32, u32>::new();
|
||||
for &id in this.decls.by_file.of(file) {
|
||||
continue if this.decls.kinds.p[id] == dk::none || this.decls.kinds.p[id] == dk::builtin;
|
||||
made.insert(this.decls.nodes.p[id], id);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! What a declaration a name refers to stands for: a property for its accessors,
|
||||
#! which are renamed and shown as one.
|
||||
#! @param this The checker.
|
||||
#! @param decl The declaration.
|
||||
#! @returns What it stands for.
|
||||
def checker::standing_for(&this, decl: u32): u32 {
|
||||
if decl != 0 && this.decls.kinds.p[decl] == dk::function && this.decls.has(decl, df::accessor) {
|
||||
return this.decls.owners.p[decl];
|
||||
}
|
||||
return decl;
|
||||
}
|
||||
|
||||
#! What a reference a node records refers to.
|
||||
#! @param this The checker.
|
||||
#! @param ref The reference, as `ref_at` gives it.
|
||||
#! @returns What it refers to.
|
||||
def checker::meant_by(&this, ref: u32): checker::meant {
|
||||
return checker::meant {} if ref == 0;
|
||||
if (ref & ref_local) != 0 {
|
||||
return checker::meant { file = this.at.file, local = ref & ref_mask };
|
||||
}
|
||||
if (ref & ref_type) != 0 {
|
||||
# A pack whose types are not known is of the pack parameter it is.
|
||||
val kind := ref & ref_mask;
|
||||
val decl := this.type_decl(kind);
|
||||
if decl == 0 && this.types.kind_of(kind) == ty::pack && this.types.part_count(kind) == 0 {
|
||||
return checker::meant { decl = this.types.first_of(kind) };
|
||||
}
|
||||
return checker::meant { decl = decl };
|
||||
}
|
||||
return checker::meant {} if ref >= this.decls.count as u32;
|
||||
return checker::meant { decl = this.standing_for(ref) };
|
||||
}
|
||||
|
||||
#! What the name a node of the file being queried writes refers to, or nothing
|
||||
#! where it writes none, or one checking left unresolved.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @param walked The file's tree.
|
||||
#! @param decls The declarations of the file's nodes.
|
||||
#! @returns What it refers to.
|
||||
def checker::meaning_of(&mut this, node: u32, walked: &tree_walk, decls: &dict<u32, u32>): checker::meant {
|
||||
val parent: u32 = walked.parents[node];
|
||||
match this.kind_of(node) {
|
||||
nk::name => {
|
||||
val ref := this.ref_at(node);
|
||||
return this.meant_by(ref) if ref != 0;
|
||||
|
||||
# A name a pattern binds, or a loop or `else` names, declares it.
|
||||
if this.has_flag(node, rf::local) {
|
||||
return checker::meant { file = this.at.file, local = node };
|
||||
}
|
||||
|
||||
# A field a pattern names, as `number` of `number(n)`, which the pattern's
|
||||
# call refers to.
|
||||
if parent != 0 && this.kind_of(parent) == nk::call && this.left_of(parent) == node {
|
||||
val held := this.ref_at(parent);
|
||||
if held != 0 && (held & (ref_local | ref_type)) == 0 && held < this.decls.count as u32
|
||||
&& this.decls.kinds.p[held] == dk::field {
|
||||
return checker::meant { decl = held };
|
||||
}
|
||||
}
|
||||
return checker::meant {};
|
||||
}
|
||||
nk::segment => return this.segment_meaning(parent, node, walked, decls);
|
||||
nk::type_name, nk::path => {
|
||||
# A name of one segment is its own segment, and one of more is its
|
||||
# segments', which the walk meets after it.
|
||||
return checker::meant {} if this.left_of(node) != 0;
|
||||
return this.segment_meaning(node, node, walked, decls);
|
||||
}
|
||||
nk::member, nk::member_of => {
|
||||
val ref := this.ref_at(node);
|
||||
return this.meant_by(ref) if ref != 0;
|
||||
return checker::meant {} if this.kind_of(node) == nk::member_of;
|
||||
return this.member_meaning(this.type_at(this.left_of(node)), this.name_of(node));
|
||||
}
|
||||
nk::field_init => {
|
||||
return checker::meant {} if !this.node_has(node, nf::named);
|
||||
return this.meant_by(this.ref_at(node));
|
||||
}
|
||||
nk::rename => {
|
||||
# The name a spread renames is a field of the struct spread.
|
||||
return checker::meant {} if parent == 0 || this.kind_of(parent) != nk::spread;
|
||||
val spread := this.type_name_meaning(this.left_of(parent));
|
||||
return checker::meant {} if spread.decl == 0;
|
||||
return this.member_meaning(this.decls.types.p[spread.decl], this.name_of(node));
|
||||
}
|
||||
nk::function, nk::struct_decl, nk::union_decl, nk::trait_decl, nk::alias, nk::enumeration,
|
||||
nk::enumerator, nk::field, nk::property, nk::assoc_type, nk::type_param, nk::const_param => {
|
||||
if decls.get(&node) is some(found) {
|
||||
return checker::meant { decl = this.standing_for(found) };
|
||||
}
|
||||
return checker::meant {};
|
||||
}
|
||||
nk::variable => {
|
||||
if decls.get(&node) is some(found) {
|
||||
return checker::meant { decl = found };
|
||||
}
|
||||
return checker::meant { file = this.at.file, local = node } if this.has_flag(node, rf::local);
|
||||
return checker::meant {};
|
||||
}
|
||||
nk::param => {
|
||||
# A parameter an accessor implies has no name of its own written, and its
|
||||
# token is the `get` or `set`.
|
||||
return checker::meant {} if this.node_has(node, nf::implied);
|
||||
# A parameter of a function without a body is no local, but is still
|
||||
# the function's.
|
||||
return checker::meant { file = this.at.file, local = node };
|
||||
}
|
||||
else => return checker::meant {};
|
||||
}
|
||||
return checker::meant {};
|
||||
}
|
||||
|
||||
#! What a segment of a `type_name`, `path`, `import`, or `module` names: the
|
||||
#! last what the whole names, and those before it the modules and types it is
|
||||
#! within.
|
||||
#! @param this The checker.
|
||||
#! @param holder The `type_name` or `path` node holding the segment.
|
||||
#! @param segment The segment, which is the holder itself where it has one.
|
||||
#! @param walked The file's tree.
|
||||
#! @param decls The declarations of the file's nodes.
|
||||
#! @returns What it names.
|
||||
def checker::segment_meaning(&mut this, holder: u32, segment: u32, walked: &tree_walk, decls: &dict<u32, u32>): checker::meant {
|
||||
return checker::meant {} if holder == 0;
|
||||
val ref := this.ref_at(segment);
|
||||
if ref != 0 {
|
||||
return this.meant_by(ref);
|
||||
}
|
||||
|
||||
# The position of the segment in the holder.
|
||||
val run := this.left_of(holder);
|
||||
var index: u32 = 0;
|
||||
for i in 0..(run == 0 ? 0 : this.run_length(run)) {
|
||||
if this.run_at(run, i as u32) == segment {
|
||||
index = i as u32;
|
||||
}
|
||||
}
|
||||
val last := run == 0 || index + 1 == this.run_length(run);
|
||||
|
||||
# A path an `import` or `module` names is of modules alone.
|
||||
val outer: u32 = walked.parents[holder];
|
||||
if outer != 0 && (this.kind_of(outer) == nk::import_decl || this.kind_of(outer) == nk::module_decl
|
||||
|| this.kind_of(outer) == nk::extern_module) {
|
||||
val found := this.module_named(this.at.file, holder, index);
|
||||
return checker::meant { named_module = found, is_module = true } if found != 0;
|
||||
return checker::meant {};
|
||||
}
|
||||
|
||||
# The type a declaration is made through, as `rect` of `def rect::area`, is
|
||||
# what it is a member of, and a segment before the last, what that is
|
||||
# declared through in turn.
|
||||
if outer != 0 && this.is_receiving(outer) && this.record(outer, decl_slot::receiver) == holder {
|
||||
if decls.get(&outer) is some(found) {
|
||||
var at: u32 = this.decls.owners.p[found];
|
||||
if this.decls.kinds.p[at] == dk::property {
|
||||
at = this.decls.owners.p[at];
|
||||
}
|
||||
val count := run == 0 ? 1 : this.run_length(run);
|
||||
var steps := count - 1 - index;
|
||||
while steps > 0 && at != 0 {
|
||||
at = this.decls.owners.p[at];
|
||||
steps--;
|
||||
}
|
||||
return checker::meant { decl = at } if at != 0;
|
||||
}
|
||||
}
|
||||
|
||||
# A whole path refers to what its node says, and its last segment with it.
|
||||
if last && segment != holder {
|
||||
val whole := this.ref_at(holder);
|
||||
if whole != 0 {
|
||||
return this.meant_by(whole);
|
||||
}
|
||||
}
|
||||
|
||||
# After `is`, a name that is no type is the field of the union tested, which
|
||||
# the test refers to.
|
||||
if outer != 0 && this.kind_of(outer) == nk::is_test && this.record(outer, is_slot::target) == holder && index == 0 {
|
||||
val held := this.ref_at(outer);
|
||||
if held != 0 && (held & (ref_local | ref_type)) == 0 && held < this.decls.count as u32 {
|
||||
return checker::meant { decl = held };
|
||||
}
|
||||
}
|
||||
|
||||
# A segment naming no declaration may name a module, from where the file is.
|
||||
if !last || run != 0 {
|
||||
val name := this.name_of(segment);
|
||||
var home := this.home_at(this.at.file, this.units[this.at.file].syntax.token_offsets[this.token_of(segment)]);
|
||||
if index == 0 {
|
||||
val saved := this.at.home;
|
||||
this.at.home = home;
|
||||
val found := this.lookup_module(name);
|
||||
this.at.home = saved;
|
||||
return checker::meant { named_module = found, is_module = true } if found != 0;
|
||||
return checker::meant {};
|
||||
}
|
||||
val before := this.segment_meaning(holder, this.run_at(run, index - 1), walked, decls);
|
||||
if before.is_module {
|
||||
val found := this.modules.find(before.named_module, name);
|
||||
return checker::meant { named_module = found, is_module = true } if found != 0;
|
||||
}
|
||||
}
|
||||
return checker::meant {};
|
||||
}
|
||||
|
||||
#! What a `type_name` names, as its last segment refers to it.
|
||||
#! @param this The checker.
|
||||
#! @param node The `type_name` node.
|
||||
#! @returns What it names.
|
||||
def checker::type_name_meaning(&mut this, node: u32): checker::meant {
|
||||
return checker::meant {} if node == 0 || this.kind_of(node) != nk::type_name;
|
||||
val run := this.left_of(node);
|
||||
val last := run == 0 ? node : this.run_at(run, this.run_length(run) - 1);
|
||||
return this.meant_by(this.ref_at(last));
|
||||
}
|
||||
|
||||
#! Whether a node declares what may be made through a type, as `rect` of
|
||||
#! `def rect::area`, which its record's second slot names.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns Whether it does.
|
||||
def checker::is_receiving(&this, node: u32): bool {
|
||||
return match this.kind_of(node) {
|
||||
nk::function, nk::variable, nk::property, nk::struct_decl, nk::union_decl, nk::trait_decl,
|
||||
nk::enumeration, nk::alias => true,
|
||||
else => false
|
||||
};
|
||||
}
|
||||
|
||||
#! The member of a type a name reaches after `.`, as a field, a property, or a
|
||||
#! method, or nothing where the type has none of the name.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type of the value.
|
||||
#! @param name The ID of the name.
|
||||
#! @returns What the name refers to.
|
||||
def checker::member_meaning(&mut this, kind: u32, name: u32): checker::meant {
|
||||
return checker::meant {} if kind == 0 || kind == bt::error;
|
||||
val found := this.find_member(this.reached(kind), name);
|
||||
return checker::meant {} if found.decl == 0;
|
||||
return checker::meant { decl = this.standing_for(found.decl) };
|
||||
}
|
||||
|
||||
#! What a declaration is, as `symbol` says.
|
||||
#! @param this The checker.
|
||||
#! @param decl The declaration.
|
||||
#! @returns What it is.
|
||||
def checker::symbol_of(&mut this, decl: u32): symbol {
|
||||
val kind: dk = this.decls.kinds.p[decl];
|
||||
if kind == dk::function {
|
||||
# A property is read and written by its name alone, so it is offered and
|
||||
# coloured as a field is rather than as the methods its accessors are.
|
||||
return symbol::field if this.decls.has(decl, df::accessor);
|
||||
return this.decls.owners.p[decl] != 0 && this.decls.has(decl, df::method) ? symbol::method : symbol::function;
|
||||
}
|
||||
if kind == dk::type_param {
|
||||
return this.decls.has(decl, df::valued) ? symbol::constant : symbol::type_param;
|
||||
}
|
||||
if kind == dk::variable {
|
||||
return this.decls.has(decl, df::mutable) ? symbol::variable : symbol::constant;
|
||||
}
|
||||
return match kind {
|
||||
dk::property => symbol::field,
|
||||
dk::field => symbol::field,
|
||||
dk::attribute => symbol::constant,
|
||||
dk::enum_member => symbol::enum_member,
|
||||
dk::struct_type, dk::union_type => symbol::struct_type,
|
||||
dk::trait_type => symbol::trait_type,
|
||||
dk::enum_type => symbol::enum_type,
|
||||
else => symbol::type_name
|
||||
};
|
||||
}
|
||||
|
||||
#! What a name refers to is, as `symbol` says.
|
||||
#! @param this The checker.
|
||||
#! @param meant What it refers to.
|
||||
#! @returns What it is.
|
||||
def checker::symbol_meant(&mut this, meant: &checker::meant): symbol {
|
||||
return symbol::namespace if meant.is_module;
|
||||
return this.symbol_of(meant.decl) if meant.decl != 0;
|
||||
val kind := this.units[meant.file].syntax.node_kinds[meant.local];
|
||||
return kind == nk::param ? symbol::parameter : symbol::variable;
|
||||
}
|
||||
|
||||
#! Whether what a name refers to is never written, as a `val`, a `const`, or a
|
||||
#! member of an enum.
|
||||
#! @param this The checker.
|
||||
#! @param meant What it refers to.
|
||||
#! @returns Whether it is.
|
||||
def checker::readonly_meant(&mut this, meant: &checker::meant): bool {
|
||||
return true if meant.is_module;
|
||||
if meant.decl != 0 {
|
||||
return match this.decls.kinds.p[meant.decl] {
|
||||
dk::variable, dk::field, dk::attribute => !this.decls.has(meant.decl, df::mutable),
|
||||
dk::enum_member => true,
|
||||
dk::property => this.property_setter(meant.decl) == 0,
|
||||
dk::type_param => true,
|
||||
else => false
|
||||
};
|
||||
}
|
||||
|
||||
# A parameter is a binding the body writes, so it is not marked read-only.
|
||||
val syntax := &this.units[meant.file].syntax;
|
||||
return false if syntax.node_kinds[meant.local] == nk::param;
|
||||
val saved := this.at;
|
||||
this.use_table(this.units[meant.file].table);
|
||||
val writes := this.has_flag(meant.local, rf::mutable);
|
||||
this.at = saved;
|
||||
return !writes;
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
#! @file reading.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains how the files of a program are read: each lexed, then parsed, as
|
||||
#! many at once as there are threads asked for. Each thread reading files lexes
|
||||
#! them with names of its own, which it keeps from file to file. The names a
|
||||
#! file uses join the program's in the order the file first uses them, and the
|
||||
#! files' in the order of the files, each once those of the files before it
|
||||
#! have, so every word is given the ID it would have were the files read one
|
||||
#! after another, and what is read is the same however many threads read it.
|
||||
#! What reading notes is heard as it is noted, on the thread noting it, rather
|
||||
#! than kept.
|
||||
|
||||
import std::thread;
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! What hears what reading files notes, as it is noted.
|
||||
pub struct listener {
|
||||
pub var noted: def(&mut note): void; #! Hears each note as it is made, on the thread reading its file, which it may move.
|
||||
pub var read: def(u32): void; #! Hears that the file of the index was read whole, after which nothing more is noted of reading it.
|
||||
}
|
||||
|
||||
#! Lexes and parses some of the files of a program, those from one index up to
|
||||
#! another, as many at once as there are threads asked for, each taking the
|
||||
#! next file none has taken. A program read by reference reads its files so, a
|
||||
#! round at a time, each round's after those before it.
|
||||
#! @param sources The source of each file, which stays where it is, as what
|
||||
#! is read refers to it.
|
||||
#! @param syntaxes Where each file is read into: one, empty, for each source.
|
||||
#! @param roots Where the `document` node of each file is written.
|
||||
#! @param names The program's names, which the words of each file join.
|
||||
#! @param threads How many threads read files, the one calling among them;
|
||||
#! where it is one, none starts, and the files are read one
|
||||
#! after another, with the program's names.
|
||||
#! @param heard What hears what reading notes.
|
||||
#! @param from The index of the first file read, whose names join the
|
||||
#! program's after those of every file before it.
|
||||
#! @param to The index past the last.
|
||||
pub def read_files(
|
||||
sources: &vector<source>,
|
||||
syntaxes: &mut vector<syntax>,
|
||||
roots: &mut vector<u32>,
|
||||
names: &mut names,
|
||||
threads: u32,
|
||||
heard: &listener,
|
||||
from: u64,
|
||||
to: u64
|
||||
): void {
|
||||
return if to <= from;
|
||||
val count := to - from;
|
||||
if roots.length < to {
|
||||
roots.resize(to);
|
||||
}
|
||||
var helpers: u64 = threads <= 1 || count <= 1 ? 0 : (threads - 1) as u64;
|
||||
if helpers > count - 1 {
|
||||
helpers = count - 1;
|
||||
}
|
||||
# The lexer and parser are given a vector to keep notes in, which stays
|
||||
# empty, as they hear each note instead.
|
||||
if helpers == 0 {
|
||||
var kept := vector::<note>::new();
|
||||
for j in from..to {
|
||||
var lexing := lexer::new(sources.at(j), names, &mut kept, j as u32);
|
||||
lexing.sink.heard = heard.noted;
|
||||
lexing.tokenize_all(syntaxes.at(j));
|
||||
roots[j] = parse_heard(syntaxes.at(j), names, j as u32, heard);
|
||||
heard.read(j as u32);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
# The names of each file join the program's in its turn: `turn` holds the
|
||||
# index of the file whose names join next.
|
||||
var next := atomic::<u64>::new(from);
|
||||
var turn := thread::mutex::<u64>::new(from);
|
||||
var turned := thread::condition::new();
|
||||
val reader := def(): void {
|
||||
var kept := vector::<note>::new();
|
||||
# The names this thread lexes with; of each, one more than the index of the
|
||||
# last file seen to use it, and its ID in the program's names, there; and
|
||||
# the names the file being read uses, in the order it first uses them.
|
||||
var own := names::new();
|
||||
var seen := vector::<u64>::new();
|
||||
var ids := vector::<u32>::new();
|
||||
var used := vector::<u32>::new();
|
||||
while true {
|
||||
val j := next.fetch_add(1);
|
||||
return if j >= to;
|
||||
var lexing := lexer::new(sources.at(j), &mut own, &mut kept, j as u32);
|
||||
lexing.sink.heard = heard.noted;
|
||||
lexing.tokenize_all(syntaxes.at(j));
|
||||
|
||||
# The file is parsed with the names it was lexed with, before its turn to
|
||||
# join them to the program's, which other threads write meanwhile. The
|
||||
# parser knows its words by the IDs every table gives them, and the tree
|
||||
# holds no ID of its own.
|
||||
roots[j] = parse_heard(syntaxes.at(j), &own, j as u32, heard);
|
||||
|
||||
# Every word lexed is a token, so the order the file first uses each name
|
||||
# in is that of its tokens.
|
||||
seen.resize(own.count);
|
||||
ids.resize(own.count);
|
||||
used.clear();
|
||||
for &id in syntaxes.at(j).token_names {
|
||||
if seen[id as u64] != j + 1 {
|
||||
seen[id as u64] = j + 1;
|
||||
used.append(id);
|
||||
}
|
||||
}
|
||||
join_names(&mut turn, &mut turned, j, names, &own, used.view(), &mut ids);
|
||||
syntaxes.at(j).rename(ids.view());
|
||||
heard.read(j as u32);
|
||||
}
|
||||
};
|
||||
var started := vector::<thread::handle<void>>::new();
|
||||
for _ in 0..helpers {
|
||||
var made := thread::spawn(reader) else (_) { break; };
|
||||
started.append(move(&mut made));
|
||||
}
|
||||
reader();
|
||||
for &mut handle in started {
|
||||
handle.join();
|
||||
}
|
||||
}
|
||||
|
||||
#! Parses a file lexed, the notes heard as they are made.
|
||||
#! @param syntax The file's tokens, which its nodes join.
|
||||
#! @param names The names the file was lexed with.
|
||||
#! @param file The index of the file.
|
||||
#! @param heard What hears the notes.
|
||||
#! @returns The file's `document` node.
|
||||
def parse_heard(syntax: &mut syntax, names: &names, file: u32, heard: &listener): u32 {
|
||||
var kept := vector::<note>::new();
|
||||
var parsing := parser::new(syntax, names, &mut kept, file);
|
||||
parsing.sink.heard = heard.noted;
|
||||
return parsing.parse();
|
||||
}
|
||||
|
||||
#! Waits for a file's turn, which comes once the names of the files before it
|
||||
#! have joined the program's, then adds those it uses.
|
||||
#! @param turn The index of the file whose names join next.
|
||||
#! @param turned What is notified where the turn passes.
|
||||
#! @param file The index of the file.
|
||||
#! @param names The program's names.
|
||||
#! @param own The names the file was lexed with.
|
||||
#! @param used Those the file uses, in the order it first uses them.
|
||||
#! @param ids Where the ID in the program's names of each it uses is
|
||||
#! written, by its ID in its own.
|
||||
def join_names(
|
||||
turn: &mut thread::mutex<u64>,
|
||||
turned: &mut thread::condition,
|
||||
file: u64,
|
||||
names: &mut names,
|
||||
own: &names,
|
||||
used: span<u32>,
|
||||
ids: &mut vector<u32>
|
||||
): void {
|
||||
var held := turn.lock();
|
||||
while held.value() != file {
|
||||
turned.wait(&mut held);
|
||||
}
|
||||
for &id in used {
|
||||
ids[id as u64] = names.intern(&own.text(id));
|
||||
}
|
||||
held.value() = file + 1;
|
||||
turned.notify_all();
|
||||
}
|
||||
@@ -0,0 +1,455 @@
|
||||
#! @file shapes.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the shapes of the nodes, which say what the slots and records of
|
||||
#! each kind of node hold, so the tree can be walked and printed without knowing
|
||||
#! each kind, and the positions of the slots of each record, by name.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
#! Describes the shape of any given syntax node within the language.
|
||||
#!
|
||||
#! All nodes have a distinct `left` and `right`, but they may mean something
|
||||
#! different. They can point to another node by index, an extra piece of data
|
||||
#! by index, a run of nodes whose indices are proceeding the length in the
|
||||
#! extras vector, or simply the flags associated with the node.
|
||||
#!
|
||||
#! When the slot, `left` or `right`, is populated by `slot::extra` then the
|
||||
#! record variable is guaranteed to be populated, as this will describe the
|
||||
#! full structure of the node. For example, a function node has many additional
|
||||
#! features to it: receiver, generics, params, return type, body, attributes.
|
||||
#! All of those cannot be described in simply the `left` and `right` slots. It
|
||||
#! can be described in `right` if `slot::extra` indicates that `record` further
|
||||
#! describes it shape and the record tells you how many additional pieces there
|
||||
#! are and what they represent.
|
||||
pub struct shape {
|
||||
#! What a node's first slot holds.
|
||||
val left: slot;
|
||||
#! What its second slot holds.
|
||||
val right: slot;
|
||||
#! What its record holds, slot by slot, where a slot holds one.
|
||||
val record: span<slot>;
|
||||
}
|
||||
|
||||
#! Describes what a left hand or right hand side of a node contains.
|
||||
#!
|
||||
#! This works in conjunction with the `shape` structure to describe the exact
|
||||
#! layout of a given node for the purposes of traversing the abstract syntax
|
||||
#! tree of the language.
|
||||
pub enum slot : u8 {
|
||||
none, #! Unused.
|
||||
node, #! An index into `nodes`.
|
||||
extra, #! An index into `extras` of one node.
|
||||
run, #! An index into `extras` where a count is followed by that many nodes.
|
||||
flags, #! Bits the kind defines, as `mut` or `const`.
|
||||
bounds #! A run, which only shows where it holds nodes: those a trait's method bounds beside its own.
|
||||
}
|
||||
|
||||
|
||||
#! The slots the records of declarations share, by their positions, as `record`
|
||||
#! takes them: each begins with its attributes, then its receiver, where it can
|
||||
#! be declared through a type, then its type parameters, where it takes them. So
|
||||
#! what reads one of these of any declaration reads the same slot.
|
||||
pub enum decl_slot : u32 {
|
||||
attributes, #! Attributes, of every declaration's record.
|
||||
receiver, #! Receiver, of all but a type a trait asks for.
|
||||
type_params, #! Type parameters, of a function's, a struct's, union's, or trait's, and an alias's.
|
||||
}
|
||||
|
||||
#! Describes how the extras of an `if` statement is laid out.
|
||||
#!
|
||||
#! An if statement is described by a `left` containing the condition, and
|
||||
#! `right` containing the `then` and `else` branch of the statement. Thus, this
|
||||
#! record describes two nodes slots.
|
||||
pub const if_record: span<slot> = [
|
||||
slot::node, #! Then body, a `block`.
|
||||
slot::node #! Else body, a `block` or `no_record`.
|
||||
];
|
||||
|
||||
#! The slots of the record of an `if`, a `when`, `if const`, or `?:`, by their
|
||||
#! positions, as `record` takes them.
|
||||
pub enum if_slot : u32 {
|
||||
then, #! What is taken where the condition holds.
|
||||
other, #! What is taken where it does not, or 0.
|
||||
}
|
||||
|
||||
#! Describes how the extras of a function are laid out.
|
||||
#!
|
||||
#! `left` is this record and `right` its flags. The receiver is the type a
|
||||
#! method or nested function is declared through, as `box<T>` of `box<T>::get`,
|
||||
#! and the result and body are 0 where they are left out: a lambda's result, or
|
||||
#! the body of a function ending at its signature.
|
||||
pub const function_record: span<slot> = [
|
||||
slot::run, #! Attributes.
|
||||
slot::node, #! Receiver, a `type_name`.
|
||||
slot::run, #! Type parameters, each a `type_param`.
|
||||
slot::run, #! Parameters, each a `param`.
|
||||
slot::node, #! Result type.
|
||||
slot::node, #! Body, a `block`.
|
||||
slot::bounds, #! Bounds a trait's method puts on the trait's type parameters and `self`, each a `type_param`.
|
||||
];
|
||||
|
||||
#! The slots of a function's record, by their positions, as `record` takes them.
|
||||
pub enum function_slot : u32 {
|
||||
attributes, #! Attributes.
|
||||
receiver, #! Receiver.
|
||||
type_params, #! Type parameters.
|
||||
params, #! Parameters.
|
||||
result, #! Result type.
|
||||
body, #! Body.
|
||||
outer, #! Bounds on the trait's type parameters and `self`.
|
||||
}
|
||||
|
||||
#! Describes how the extras of a parameter are laid out: `left` is its type,
|
||||
#! which a lambda may leave out, and `right` this record.
|
||||
pub const param_record: span<slot> = [
|
||||
slot::node, #! Default value.
|
||||
slot::flags, #! `variadic`, and `mutable` for `&mut this`.
|
||||
];
|
||||
|
||||
#! The slots of a parameter's record, by their positions, as `record` takes
|
||||
#! them.
|
||||
pub enum parameter_slot : u32 {
|
||||
value, #! Default value.
|
||||
flags, #! Flags.
|
||||
}
|
||||
|
||||
#! Describes how the extras of a variable, constant, or field are laid out:
|
||||
#! `left` is this record and `right` its flags. A spread field's type is a
|
||||
#! `spread`.
|
||||
pub const variable_record: span<slot> = [
|
||||
slot::run, #! Attributes.
|
||||
slot::node, #! Receiver, a `type_name`, as `rect` of `val rect::unit`.
|
||||
slot::node, #! Type.
|
||||
slot::node, #! Value.
|
||||
];
|
||||
|
||||
#! The slots of the record of a variable, constant, or field, by their
|
||||
#! positions, as `record` takes them.
|
||||
pub enum variable_slot : u32 {
|
||||
attributes, #! Attributes.
|
||||
receiver, #! Receiver.
|
||||
type_expr, #! Type.
|
||||
value, #! Value.
|
||||
}
|
||||
|
||||
#! Describes how the extras of a property are laid out: `left` is this record
|
||||
#! and `right` the run of its accessors.
|
||||
pub const property_record: span<slot> = [
|
||||
slot::run, #! Attributes.
|
||||
slot::node, #! Receiver, a `type_name`.
|
||||
slot::node, #! Type.
|
||||
slot::flags, #! `mutable` for `var`, and `exported`.
|
||||
];
|
||||
|
||||
#! The slots of a property's record, by their positions, as `record` takes them.
|
||||
pub enum property_slot : u32 {
|
||||
attributes, #! Attributes.
|
||||
receiver, #! Receiver.
|
||||
type_expr, #! Type.
|
||||
flags, #! Flags.
|
||||
}
|
||||
|
||||
#! Describes how the extras of an accessor are laid out: `left` is the run of
|
||||
#! its parameters, `&this` first, and `right` this record. Its token says `get`
|
||||
#! or `set`.
|
||||
pub const accessor_record: span<slot> = [
|
||||
slot::node, #! Body, 0 where it ends at its signature.
|
||||
slot::flags, #! `exported`, where the accessor is `pub` of its own.
|
||||
];
|
||||
|
||||
#! The slots of an accessor's record, by their positions, as `record` takes
|
||||
#! them.
|
||||
pub enum accessor_slot : u32 {
|
||||
body, #! Body.
|
||||
flags, #! Flags.
|
||||
}
|
||||
|
||||
#! Describes how the extras of a struct, union, or trait are laid out: `left` is
|
||||
#! this record and `right` the run of its members. Which it is, is its kind.
|
||||
pub const aggregate_record: span<slot> = [
|
||||
slot::run, #! Attributes.
|
||||
slot::node, #! Receiver, a `type_name`.
|
||||
slot::run, #! Type parameters, each a `type_param`.
|
||||
slot::run, #! Traits it implements, or composes, each a `type_name`.
|
||||
slot::flags, #! `exported`.
|
||||
];
|
||||
|
||||
#! The slots of the record of a struct, union, or trait, by their positions, as
|
||||
#! `record` takes them.
|
||||
pub enum aggregate_slot : u32 {
|
||||
attributes, #! Attributes.
|
||||
receiver, #! Receiver.
|
||||
type_params, #! Type parameters.
|
||||
traits, #! Traits it implements, or composes.
|
||||
flags, #! Flags.
|
||||
}
|
||||
|
||||
#! Describes how the extras of a type a trait asks for are laid out: `left` is
|
||||
#! this record and `right` the type standing in where the implementer gives
|
||||
#! none.
|
||||
pub const assoc_record: span<slot> = [
|
||||
slot::run, #! Attributes.
|
||||
slot::run, #! Bounds, each a `type_name`.
|
||||
slot::flags, #! `packed`, of a pack, as `type params...;`.
|
||||
];
|
||||
|
||||
#! The slots of the record of a type a trait asks for, by their positions, as
|
||||
#! `record` takes them.
|
||||
pub enum assoc_slot : u32 {
|
||||
attributes, #! Attributes.
|
||||
bounds, #! Bounds.
|
||||
flags, #! Flags.
|
||||
}
|
||||
|
||||
#! Describes how the extras of an enum are laid out: `left` is this record and
|
||||
#! `right` the run of its members.
|
||||
pub const enumeration_record: span<slot> = [
|
||||
slot::run, #! Attributes.
|
||||
slot::node, #! Receiver, a `type_name`.
|
||||
slot::node, #! The integer type holding it.
|
||||
slot::flags, #! `exported`.
|
||||
];
|
||||
|
||||
#! The slots of an enum's record, by their positions, as `record` takes them.
|
||||
pub enum enumeration_slot : u32 {
|
||||
attributes, #! Attributes.
|
||||
receiver, #! Receiver.
|
||||
integer, #! The integer type holding it.
|
||||
flags, #! Flags.
|
||||
}
|
||||
|
||||
#! Describes how the extras of a type alias are laid out: `left` is this record
|
||||
#! and `right` the aliased type.
|
||||
pub const alias_record: span<slot> = [
|
||||
slot::run, #! Attributes.
|
||||
slot::node, #! Receiver, a `type_name`.
|
||||
slot::run, #! Type parameters, each a `type_param`.
|
||||
slot::flags, #! `exported`.
|
||||
];
|
||||
|
||||
#! The slots of a type alias's record, by their positions, as `record` takes
|
||||
#! them.
|
||||
pub enum alias_slot : u32 {
|
||||
attributes, #! Attributes.
|
||||
receiver, #! Receiver.
|
||||
type_params, #! Type parameters.
|
||||
flags, #! Flags.
|
||||
}
|
||||
|
||||
#! Describes how the extras of a `for` loop are laid out: `left` is this record
|
||||
#! and `right` the body.
|
||||
pub const for_record: span<slot> = [
|
||||
slot::node, #! The index, a `name`, as `i` of `for i, x in xs`.
|
||||
slot::node, #! The variable, a `name`.
|
||||
slot::node, #! What is iterated, or where a range begins.
|
||||
slot::node, #! Where a range ends, as `n` of `0..n`.
|
||||
slot::flags, #! `reference` for `&x`, with `mutable` for `&mut x`, `constant`, and `inclusive` for `0..=n`.
|
||||
];
|
||||
|
||||
#! The slots of a `for` loop's record, by their positions, as `record` takes
|
||||
#! them.
|
||||
pub enum for_slot : u32 {
|
||||
index, #! The index.
|
||||
variable, #! The variable.
|
||||
iterated, #! What is iterated, or where a range begins.
|
||||
end, #! Where a range ends.
|
||||
flags, #! Flags.
|
||||
}
|
||||
|
||||
#! Describes how the extras of an `else` fallback are laid out: `left` is the
|
||||
#! result or maybe it takes from, and `right` this record.
|
||||
pub const fallback_record: span<slot> = [
|
||||
slot::node, #! The error it names, a `name`, as `e` of `else (e)`.
|
||||
slot::node, #! What stands in: a `block` that leaves, or an expression.
|
||||
];
|
||||
|
||||
#! The slots of the record of an `else` fallback, by their positions, as
|
||||
#! `record` takes them.
|
||||
pub enum fallback_slot : u32 {
|
||||
error, #! The error it names.
|
||||
other, #! What stands in.
|
||||
}
|
||||
|
||||
#! Describes how the extras of a slice are laid out: `left` is what is sliced,
|
||||
#! and `right` this record, either of whose bounds may be left out, as in
|
||||
#! `xs[a:]`.
|
||||
pub const slice_record: span<slot> = [
|
||||
slot::node, #! Start.
|
||||
slot::node, #! Count.
|
||||
];
|
||||
|
||||
#! The slots of a slice's record, by their positions, as `record` takes them.
|
||||
pub enum slice_slot : u32 {
|
||||
start, #! Start.
|
||||
count, #! Count.
|
||||
}
|
||||
|
||||
#! Describes how the extras of an `is` test are laid out: `left` is the value
|
||||
#! tested, and `right` this record.
|
||||
pub const is_record: span<slot> = [
|
||||
slot::node, #! The field or trait, a `type_name`, or what names a field, as `d` of `x is (d)`.
|
||||
slot::node, #! The value the field holds, a `name`, or a `reference` to one.
|
||||
slot::flags, #! `negated` for `is not`, and `computed` for `x is (d)`.
|
||||
];
|
||||
|
||||
#! The slots of the record of an `is` test, by their positions, as `record`
|
||||
#! takes them.
|
||||
pub enum is_slot : u32 {
|
||||
target, #! The field or trait.
|
||||
binding, #! The value the field holds.
|
||||
flags, #! Flags.
|
||||
}
|
||||
|
||||
#! Describes how the extras of a contract are laid out: `left` is its
|
||||
#! condition, and `right` this record, which is none where it says nothing but
|
||||
#! its condition. Its token is the word saying which it is.
|
||||
pub const contract_record: span<slot> = [
|
||||
slot::node, #! The name an `ensures` gives what the function returns, a `name`.
|
||||
slot::node, #! What it says failed, in place of the condition as written.
|
||||
];
|
||||
|
||||
#! The slots of the record of a contract, by their positions, as `record` takes
|
||||
#! them.
|
||||
pub enum contract_slot : u32 {
|
||||
bound, #! The name given what is returned.
|
||||
text, #! What it says failed.
|
||||
}
|
||||
|
||||
#! Which contract a `contract` node is, as its token says.
|
||||
pub enum clause : u8 {
|
||||
expects, #! What a function needs of what it is given, checked where it is written.
|
||||
asserts, #! What must hold as the work goes on, checked where it is written.
|
||||
ensures, #! What holds where the block it is written in is left, checked there.
|
||||
}
|
||||
|
||||
#! Describes how the extras of a lambda are laid out: `left` is the run of its
|
||||
#! parameters, and `right` this record.
|
||||
pub const lambda_record: span<slot> = [
|
||||
slot::node, #! Result type, 0 where it is left out.
|
||||
slot::node, #! Body: a `block`, or the expression after `=>`.
|
||||
];
|
||||
|
||||
#! The slots of a lambda's record, by their positions, as `record` takes them.
|
||||
pub enum lambda_slot : u32 {
|
||||
result, #! Result type.
|
||||
body, #! Body.
|
||||
}
|
||||
|
||||
#! No record, for the kinds whose slots hold everything they have.
|
||||
pub const no_record: span<slot> = [];
|
||||
|
||||
|
||||
#! The shape of each kind of node, in the order `nk` declares them.
|
||||
#!
|
||||
#! Index 0 stands for "absent" in both vectors: node 0 is an `error` node
|
||||
#! holding nothing, a run at 0 is empty, and a record at 0 holds nothing in each
|
||||
#! of its slots, which the zeros `extras` begins with make true. So a slot left
|
||||
#! out holds 0 whatever it is, and a record of nothing takes no room.
|
||||
#!
|
||||
#! A `type_name` of one segment without type arguments, as `u8`, holds no run,
|
||||
#! its token being the name, and likewise a `path` of one segment.
|
||||
#!
|
||||
#! Where a node's token alone says what it is, as a `name` or a `number`, both
|
||||
#! of its slots are unused. An operator's token is the operator.
|
||||
pub const shapes: shape[nk::count as u64] = [
|
||||
# Structure
|
||||
shape { left = slot::run, right = slot::none, record = no_record }, # error: what it did parse
|
||||
shape { left = slot::run, right = slot::none, record = no_record }, # document: declarations
|
||||
shape { left = slot::run, right = slot::none, record = no_record }, # block: statements
|
||||
|
||||
# Declarations
|
||||
shape { left = slot::node, right = slot::none, record = no_record }, # import_decl: `path`
|
||||
shape { left = slot::node, right = slot::node, record = no_record }, # module_decl: `path`, `when` condition
|
||||
shape { left = slot::node, right = slot::node, record = no_record }, # extern_import: `string`, `when` condition
|
||||
shape { left = slot::node, right = slot::node, record = no_record }, # extern_module: `path`, `when` condition
|
||||
shape { left = slot::node, right = slot::extra, record = if_record }, # when_block: condition, [then, else]
|
||||
shape { left = slot::extra, right = slot::flags, record = function_record }, # function
|
||||
shape { left = slot::node, right = slot::extra, record = param_record }, # param: type, [default, flags]
|
||||
shape { left = slot::extra, right = slot::flags, record = variable_record }, # variable
|
||||
shape { left = slot::extra, right = slot::flags, record = variable_record }, # field
|
||||
shape { left = slot::node, right = slot::run, record = no_record }, # spread: `type_name`, renames
|
||||
shape { left = slot::node, right = slot::none, record = no_record }, # rename: new `name`; token is the old
|
||||
shape { left = slot::extra, right = slot::run, record = property_record }, # property: [...], accessors
|
||||
shape { left = slot::run, right = slot::extra, record = accessor_record }, # accessor: params, [body, flags]
|
||||
shape { left = slot::extra, right = slot::run, record = aggregate_record }, # struct_decl: [...], fields
|
||||
shape { left = slot::extra, right = slot::run, record = aggregate_record }, # union_decl: [...], fields
|
||||
shape { left = slot::extra, right = slot::run, record = aggregate_record }, # trait_decl: [...], members
|
||||
shape { left = slot::extra, right = slot::node, record = assoc_record }, # assoc_type: [...], default
|
||||
shape { left = slot::extra, right = slot::run, record = enumeration_record }, # enumeration: [...], members
|
||||
shape { left = slot::run, right = slot::node, record = no_record }, # enumerator: attributes, value
|
||||
shape { left = slot::extra, right = slot::node, record = alias_record }, # alias: [...], aliased type
|
||||
shape { left = slot::node, right = slot::run, record = no_record }, # attribute: `type_name`, field inits
|
||||
shape { left = slot::run, right = slot::flags, record = no_record }, # type_param: bounds, `packed`
|
||||
shape { left = slot::run, right = slot::node, record = no_record }, # const_param: bounds, type
|
||||
shape { left = slot::run, right = slot::node, record = no_record }, # type_pattern: parameters' type parameters, result's
|
||||
shape { left = slot::node, right = slot::node, record = no_record }, # array_pattern: element's type parameter, length's
|
||||
|
||||
# Types
|
||||
shape { left = slot::run, right = slot::none, record = no_record }, # segment: type arguments or parameters
|
||||
shape { left = slot::run, right = slot::none, record = no_record }, # type_name: segments
|
||||
shape { left = slot::node, right = slot::flags, record = no_record }, # type_ref: referent, `mutable`
|
||||
shape { left = slot::node, right = slot::flags, record = no_record }, # type_ptr: pointee, `mutable`
|
||||
shape { left = slot::node, right = slot::node, record = no_record }, # type_fixed: element, length
|
||||
shape { left = slot::run, right = slot::node, record = no_record }, # type_func: parameter types, result
|
||||
shape { left = slot::node, right = slot::none, record = no_record }, # type_spread: the type spread
|
||||
shape { left = slot::node, right = slot::none, record = no_record }, # type_of: declaration
|
||||
|
||||
# Statements
|
||||
shape { left = slot::node, right = slot::extra, record = if_record }, # if_stmt: condition, [then, else]
|
||||
shape { left = slot::node, right = slot::extra, record = if_record }, # if_const: condition, [then, else]
|
||||
shape { left = slot::node, right = slot::node, record = no_record }, # while_stmt: condition, body
|
||||
shape { left = slot::extra, right = slot::node, record = for_record }, # for_stmt: [...], body
|
||||
shape { left = slot::node, right = slot::run, record = no_record }, # match_stmt: subject, arms
|
||||
shape { left = slot::run, right = slot::node, record = no_record }, # arm: patterns (empty for `else`), body
|
||||
shape { left = slot::node, right = slot::none, record = no_record }, # return_stmt: value
|
||||
shape { left = slot::none, right = slot::none, record = no_record }, # break_stmt
|
||||
shape { left = slot::none, right = slot::none, record = no_record }, # continue_stmt
|
||||
shape { left = slot::node, right = slot::none, record = no_record }, # expr_stmt: expression
|
||||
shape { left = slot::node, right = slot::extra, record = contract_record }, # contract: condition, [name, text]; token is the word
|
||||
|
||||
# Expressions
|
||||
shape { left = slot::none, right = slot::none, record = no_record }, # name
|
||||
shape { left = slot::run, right = slot::none, record = no_record }, # path: segments
|
||||
shape { left = slot::none, right = slot::none, record = no_record }, # number
|
||||
shape { left = slot::none, right = slot::none, record = no_record }, # character
|
||||
shape { left = slot::none, right = slot::none, record = no_record }, # string
|
||||
shape { left = slot::run, right = slot::none, record = no_record }, # istring: text pieces and holes
|
||||
shape { left = slot::none, right = slot::none, record = no_record }, # boolean
|
||||
shape { left = slot::none, right = slot::none, record = no_record }, # null_lit
|
||||
shape { left = slot::node, right = slot::none, record = no_record }, # unary: operand; also `*p` and `...xs`
|
||||
shape { left = slot::node, right = slot::none, record = no_record }, # postfix: operand of `++` or `--`
|
||||
shape { left = slot::node, right = slot::flags, record = no_record }, # reference: operand, `mutable`
|
||||
shape { left = slot::node, right = slot::node, record = no_record }, # binary: left, right
|
||||
shape { left = slot::node, right = slot::node, record = no_record }, # assign: target, value
|
||||
shape { left = slot::node, right = slot::extra, record = if_record }, # ternary: condition, [then, else]
|
||||
shape { left = slot::node, right = slot::extra, record = fallback_record }, # fallback: value, [error, fallback]
|
||||
shape { left = slot::node, right = slot::run, record = no_record }, # call: callee, arguments
|
||||
shape { left = slot::node, right = slot::run, record = no_record }, # type_args: callee, types, as `value_of(d)::<i64>`
|
||||
shape { left = slot::node, right = slot::node, record = no_record }, # index: object, index
|
||||
shape { left = slot::node, right = slot::extra, record = slice_record }, # slice: object, [start, count]
|
||||
shape { left = slot::node, right = slot::run, record = no_record }, # member: object, type arguments
|
||||
shape { left = slot::node, right = slot::node, record = no_record }, # member_of: object, declaration, as `x.(d)`
|
||||
shape { left = slot::node, right = slot::node, record = no_record }, # cast: value, type
|
||||
shape { left = slot::node, right = slot::extra, record = is_record }, # is_test: value, [target, binding, flags]
|
||||
shape { left = slot::node, right = slot::run, record = no_record }, # construct: `type_name`, field inits
|
||||
shape { left = slot::node, right = slot::flags, record = no_record }, # field_init: value, `named`; token is the field where named
|
||||
shape { left = slot::run, right = slot::none, record = no_record }, # array: elements
|
||||
shape { left = slot::run, right = slot::extra, record = lambda_record }, # lambda: params, [result, body]
|
||||
shape { left = slot::node, right = slot::run, record = no_record }, # match_value: subject, arms
|
||||
shape { left = slot::node, right = slot::node, record = no_record }, # range: start, end; token is `..` or `..=`
|
||||
shape { left = slot::node, right = slot::none, record = no_record }, # old_value: the expression, within an `ensures`
|
||||
shape { left = slot::none, right = slot::none, record = no_record }, # undefined
|
||||
];
|
||||
|
||||
#! The shape of the node, which says what its `left` and `right` hold.
|
||||
#! @param this The node.
|
||||
#! @returns The shape.
|
||||
pub val node::shape: shape { get => shapes[this.kind as u64]; }
|
||||
|
||||
#! The shape of nodes of the kind.
|
||||
#! @param this The kind of node.
|
||||
#! @returns The shape.
|
||||
pub val nk::shape: shape { get => shapes[this as u64]; }
|
||||
@@ -0,0 +1,227 @@
|
||||
#! @file source.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the source type, which is the text of a file and where its lines
|
||||
#! begin, read from disk or given from memory, along with the classes of bytes
|
||||
#! the lexer reads the text by.
|
||||
|
||||
import std::io;
|
||||
import core::swar;
|
||||
module sakura::analyzer;
|
||||
|
||||
#! Represents the source information for a file.
|
||||
#!
|
||||
#! The source keeps the path to the file, the loaded text of the file, and a
|
||||
#! `lines` vector to indicate where lines start within the source text, which
|
||||
#! it finds itself as it is made, so the text is never changed after. Each line
|
||||
#! break Windows writes, CR LF, is kept as the LF alone, as other systems write
|
||||
#! one, so the lexer, the lines, and a literal spanning lines read the same
|
||||
#! text whichever system wrote the file.
|
||||
pub struct source {
|
||||
pub var path: strview; #! The path the file is reported as.
|
||||
var text: string; #! The file's text.
|
||||
pub var lines: lines; #! Where each line of the text begins.
|
||||
}
|
||||
|
||||
#! Provides the length of the source text.
|
||||
#! @param this The source object to get the length of its text.
|
||||
#! @returns The length of the source text.
|
||||
pub val source::length: u64 {
|
||||
get => this.text.length;
|
||||
}
|
||||
|
||||
#! Creates a new source object by opening the file it points to and reading it.
|
||||
#! @param path The path to the source file to open.
|
||||
#! @returns The source object containing the file contents read.
|
||||
pub def source::open(path: strview): source {
|
||||
var result := source {
|
||||
path = path,
|
||||
text = without_mark(source::read(path)),
|
||||
lines = lines::new(nothing {})
|
||||
};
|
||||
result.finish();
|
||||
return result;
|
||||
}
|
||||
|
||||
# Reads the whole of the file at a path, giving empty text where it cannot be.
|
||||
def source::read(text: strview): string {
|
||||
val at := path::parse(text) else (_) { return string::new(nothing {}); };
|
||||
return read_file(at, nothing {}) else string::new(nothing {});
|
||||
}
|
||||
|
||||
# Finds the lines of the text, which finds whether it holds a CR, so only text
|
||||
# holding one is read again, made without its CR LFs, and its lines found again.
|
||||
def source::finish(&mut this): void {
|
||||
return if !this.find_lines();
|
||||
val held := this.text.length;
|
||||
this.text = without_returns(move(&mut this.text));
|
||||
if this.text.length != held {
|
||||
this.lines.clear();
|
||||
_ = this.find_lines();
|
||||
}
|
||||
}
|
||||
|
||||
# The text without the byte order mark some editors begin a file of UTF-8 with,
|
||||
# which is no part of the language, or the text itself where it has none.
|
||||
def without_mark(text: string): string {
|
||||
val bytes := text.view();
|
||||
return text if bytes.length < 3 || bytes[0] != 0xEF || bytes[1] != 0xBB || bytes[2] != 0xBF;
|
||||
return string::from(bytes[3:], nothing {});
|
||||
}
|
||||
|
||||
# The text with each CR LF line break made the LF alone, or the text itself
|
||||
# where it has none.
|
||||
def without_returns(text: string): string {
|
||||
val bytes := text.view();
|
||||
var found := false;
|
||||
for i in 1..bytes.length {
|
||||
if bytes[i] == '\n' && bytes[i - 1] == '\r' {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return text if !found;
|
||||
|
||||
var made := string::new(nothing {});
|
||||
made.reserve(bytes.length);
|
||||
for i in 0..bytes.length {
|
||||
if bytes[i] != '\r' || i + 1 == bytes.length || bytes[i + 1] != '\n' {
|
||||
made.push(bytes[i]);
|
||||
}
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Finds where each line of the text begins: at its start, and past each line
|
||||
#! break, and whether the text holds a CR, which a CR LF line break begins
|
||||
#! with.
|
||||
#! @param this The source file.
|
||||
#! @returns Whether the text holds a CR.
|
||||
def source::find_lines(&mut this): bool {
|
||||
val text := this.text.view().data;
|
||||
val size := this.text.length;
|
||||
this.lines.reserve(size / 24 + 2);
|
||||
this.lines.append(0);
|
||||
|
||||
# Where vectors are held in registers, sixteen bytes at a time: the bits of
|
||||
# the bytes that are `\n`, each found from the lowest. Then eight at a time,
|
||||
# as words, each `\n` found from the first of the mask of them. The bytes
|
||||
# that are `\r` are gathered as they go.
|
||||
var at: u64 = 0;
|
||||
var returns := false;
|
||||
if lanes_held() {
|
||||
val newline := u8x16::splat('\n');
|
||||
val back := u8x16::splat('\r');
|
||||
var held: u32 = 0;
|
||||
while at + 16 <= size {
|
||||
val chunk: u8x16 = *((text + at) as *u8x16);
|
||||
var marks := chunk.equal(&newline).bits();
|
||||
while marks != 0 {
|
||||
this.lines.append((at + trailing_zeros(marks) as u64 + 1) as u32);
|
||||
marks = marks & (marks - 1);
|
||||
}
|
||||
held |= chunk.equal(&back).bits();
|
||||
at += 16;
|
||||
}
|
||||
returns = held != 0;
|
||||
}
|
||||
while at + 8 <= size {
|
||||
val word := swar::load(text + at);
|
||||
var marks := word.equal('\n');
|
||||
while marks.any() {
|
||||
this.lines.append((at + marks.first() + 1) as u32);
|
||||
marks = marks.rest();
|
||||
}
|
||||
returns = returns || word.equal('\r').any();
|
||||
at += 8;
|
||||
}
|
||||
for k in at..size {
|
||||
if text[k] == '\n' {
|
||||
this.lines.append((k + 1) as u32);
|
||||
}
|
||||
returns = returns || text[k] == '\r';
|
||||
}
|
||||
return returns;
|
||||
}
|
||||
|
||||
#! Creates a lexeme from the given start location in the source and the count.
|
||||
#! @param this The source object to create a lexeme from.
|
||||
#! @param start The starting index within the source to create the lexeme.
|
||||
#! @param count The number of characters for the lexeme to be created.
|
||||
#! @returns A strview of the lexeme requested from the source.
|
||||
pub def source::make_lexeme(&this, start: u64, count: u64): strview {
|
||||
return this.text.view().substr(start, count);
|
||||
}
|
||||
|
||||
#! The classes a byte may be of, as bits of `char_classes`.
|
||||
enum cc : u8 {
|
||||
space = 0x01, #! Spacing between tokens: ` `, and `\t` through `\r`.
|
||||
start = 0x02, #! What a word begins with: a letter or `_`.
|
||||
word = 0x04, #! What a word goes on with: a letter, a digit, or `_`.
|
||||
digit = 0x08, #! What a number begins with.
|
||||
}
|
||||
|
||||
#! The classes of each byte, as bits of `cc`, worked out while compiling, so the
|
||||
#! lexer asks what a byte is with one load.
|
||||
const char_classes: u8[256] = make_char_classes();
|
||||
|
||||
#! Whether a byte goes on a name: a letter, a digit, or `_`.
|
||||
#! @param byte The byte.
|
||||
#! @returns Whether it does.
|
||||
pub def is_word_byte(byte: u8): bool {
|
||||
return (char_classes[byte as u64] & cc::word as u8) != 0;
|
||||
}
|
||||
|
||||
const def make_char_classes(): u8[256] {
|
||||
var made: u8[256];
|
||||
for each in 0..256 {
|
||||
val byte := each as u8;
|
||||
if byte == ' ' || (byte >= '\t' && byte <= '\r') {
|
||||
made[each] |= cc::space as u8;
|
||||
}
|
||||
if (byte >= 'a' && byte <= 'z') || (byte >= 'A' && byte <= 'Z') || byte == '_' {
|
||||
made[each] |= cc::start as u8 | cc::word as u8;
|
||||
}
|
||||
if byte >= '0' && byte <= '9' {
|
||||
made[each] |= cc::digit as u8 | cc::word as u8;
|
||||
}
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# A set of character boolean checks that are specific to sakura.
|
||||
|
||||
val u8::is_cmnt: bool { get => this == '#'; }
|
||||
val u8::is_dot: bool { get => this == '.'; }
|
||||
val u8::is_zero: bool { get => this == '0'; }
|
||||
val u8::is_squote: bool { get => this == '\''; }
|
||||
val u8::is_dquote: bool { get => this == '\"'; }
|
||||
val u8::is_format: bool { get => this == '$'; }
|
||||
val u8::is_escape: bool { get => this == '\\'; }
|
||||
val u8::is_lbrace: bool { get => this == '{'; }
|
||||
val u8::is_rbrace: bool { get => this == '}'; }
|
||||
val u8::is_brace: bool { get => this.is_lbrace || this.is_rbrace; }
|
||||
val u8::is_blank: bool { get => this == ' ' || this == '\t'; }
|
||||
|
||||
#! Whether the byte continues a character of more than one byte, which UTF-8
|
||||
#! writes as `10xxxxxx`.
|
||||
#! @param this The byte.
|
||||
#! @returns Whether it does.
|
||||
val u8::is_continuation: bool { get => (this & 0xC0) == 0x80; }
|
||||
|
||||
#! Creates a source object of text held in memory rather than read from a file,
|
||||
#! as an editor's unsaved buffer or a test's program.
|
||||
#! @param path The path to report the text as.
|
||||
#! @param text The text.
|
||||
#! @returns The source object holding a copy of the text.
|
||||
pub def source::from(path: strview, text: strview): source {
|
||||
var result := source {
|
||||
path = path,
|
||||
text = without_mark(string::from(text, nothing {})),
|
||||
lines = lines::new(nothing {})
|
||||
};
|
||||
result.finish();
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
#! @file syntax.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the syntax type, which keeps the tokens, nodes, and extras of a
|
||||
#! parsed file, its comments, and the documentation and starts of its
|
||||
#! declarations.
|
||||
|
||||
import std::containers;
|
||||
module sakura::analyzer;
|
||||
|
||||
#! Represents a parsed syntax for a given file.
|
||||
#!
|
||||
#! As the lexer reads the source code, it stores the tokens into this
|
||||
#! structure, then as the parser builds new nodes, it stores those into this
|
||||
#! structure too.
|
||||
#!
|
||||
#! Nodes and tokens are each kept as one vector per field, indexed alike, so a
|
||||
#! pass reading one field, as the kind of every node, reads only that, and no
|
||||
#! padding sits between fields. `node` and `token` are values gathered from
|
||||
#! them, for reading one whole.
|
||||
#!
|
||||
#! What a token's kind or name says is not kept again: how many bytes a keyword
|
||||
#! or a punctuator covers is its kind's, as `token_widths` says, and a name's is
|
||||
#! its text's. Only the lengths of the rest, the literals, a few of every
|
||||
#! hundred tokens, are kept, as `token_length` reads them.
|
||||
pub struct syntax {
|
||||
# Nodes, by index.
|
||||
pub var node_kinds: vector<nk>; #! The kind of each node.
|
||||
pub var node_tokens: vector<u32>; #! The token each says what it is by.
|
||||
var node_lefts: vector<u32>; #! The first slot of each, which its kind's shape says the meaning of.
|
||||
var node_rights: vector<u32>; #! The second slot of each.
|
||||
var node_spans: vector<u8>; #! How many tokens past its own each was parsed through, or `syntax::wide`, where `wide_spans` holds how many.
|
||||
|
||||
# How many tokens past its own each node spanning more than a byte counts was
|
||||
# parsed through, a few of every thousand, as a document or a function body.
|
||||
var wide_spans: keymap; #! How many, by the node.
|
||||
|
||||
# What nodes hold beyond their two slots: records and runs.
|
||||
var extras: vector<u32>; #! The records and runs, each where a slot says it begins.
|
||||
|
||||
# Tokens, by index.
|
||||
var token_kinds: vector<tk>; #! The kind of each token.
|
||||
pub var token_offsets: vector<u32>; #! The byte of the text each begins at.
|
||||
var token_names: vector<u32>; #! The ID of the name each is, or 0 where it is no word.
|
||||
|
||||
# The tokens whose kind and name do not say how many bytes they cover, the
|
||||
# literals, in order, and how many each covers.
|
||||
var literal_tokens: vector<u32>; #! Each literal token, in increasing order.
|
||||
var literal_lengths: vector<u32>; #! How many bytes each covers.
|
||||
|
||||
# The documentation comments, `#!` lines, in order, and where each
|
||||
# declaration begins, its attributes and `pub` included, which says which of
|
||||
# them document it.
|
||||
var docs: vector<doc>; #! The documentation comments.
|
||||
var starts: keymap; #! The token each declaration begins at, by its node.
|
||||
|
||||
# The other comments, in order, which are no part of the tree but are kept for
|
||||
# the tools that write the text back out, as a formatter.
|
||||
var comments: vector<comment>; #! The other comments.
|
||||
|
||||
# How many nodes and extras the last whole parse left. A reparse leaves the
|
||||
# nodes it replaced behind, unreachable, and these say when they are enough
|
||||
# to parse whole again and let go of them.
|
||||
var whole_nodes: u64; #! The node count the last whole parse left.
|
||||
var whole_extras: u64; #! The extras count the last whole parse left.
|
||||
|
||||
# How many times a reparse parsed the file whole again, which makes every
|
||||
# node anew, so what was kept of the old ones by their indexes is no longer of
|
||||
# them.
|
||||
pub var parses: u32; #! How many times the file was parsed whole again.
|
||||
}
|
||||
|
||||
#! A line of documentation, `#!` and what follows it on its line.
|
||||
pub struct doc {
|
||||
var offset: u32; #! The byte of the text it begins at.
|
||||
var length: u32; #! How many bytes it covers.
|
||||
var token: u32; #! The token it is written before.
|
||||
}
|
||||
|
||||
#! A comment that is not documentation, `#` and what follows it on its line.
|
||||
pub struct comment {
|
||||
var offset: u32; #! The byte of the text it begins at.
|
||||
var length: u32; #! How many bytes it covers.
|
||||
var token: u32; #! The token after it.
|
||||
}
|
||||
|
||||
#! The documentation of a declaration: `count` lines from `first` of `docs`.
|
||||
pub struct doc_range {
|
||||
var first: u32; #! The first line, in `docs`.
|
||||
var count: u32; #! How many lines.
|
||||
}
|
||||
|
||||
#! How many entries at the start of `extras` are 0, which stand for both an
|
||||
#! empty run and a record whose slots are all absent, as large as the largest
|
||||
#! record.
|
||||
pub const syntax::zeros: u32 = 6;
|
||||
|
||||
#! Creates a new instance of a syntax object.
|
||||
#! @returns The instantiated syntax.
|
||||
pub def syntax::new(): syntax {
|
||||
var made := syntax {
|
||||
node_kinds = vector::<nk>::new(),
|
||||
node_tokens = vector::<u32>::new(),
|
||||
node_lefts = vector::<u32>::new(),
|
||||
node_rights = vector::<u32>::new(),
|
||||
node_spans = vector::<u8>::new(),
|
||||
wide_spans = keymap::new(),
|
||||
extras = vector::<u32>::new(),
|
||||
token_kinds = vector::<tk>::new(),
|
||||
token_offsets = vector::<u32>::new(),
|
||||
token_names = vector::<u32>::new(),
|
||||
literal_tokens = vector::<u32>::new(),
|
||||
literal_lengths = vector::<u32>::new(),
|
||||
docs = vector::<doc>::new(),
|
||||
starts = keymap::new(),
|
||||
comments = vector::<comment>::new()
|
||||
};
|
||||
|
||||
made.reset();
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Lets go of every node and extra, leaving only what stands for absent: node 0,
|
||||
#! an `error` node holding nothing, and the zeros at the start of `extras`.
|
||||
#! @param this The syntax tree.
|
||||
pub def syntax::reset(&mut this): void {
|
||||
this.node_kinds.clear();
|
||||
this.node_tokens.clear();
|
||||
this.node_lefts.clear();
|
||||
this.node_rights.clear();
|
||||
this.node_spans.clear();
|
||||
this.wide_spans.clear();
|
||||
this.extras.clear();
|
||||
this.starts.clear();
|
||||
|
||||
this.add_node(nk::error, 0, 0, 0, 0);
|
||||
this.extras.resize(syntax::zeros as u64);
|
||||
}
|
||||
|
||||
#! How many nodes there are, node 0 included.
|
||||
#! @param this The syntax tree.
|
||||
#! @returns The count.
|
||||
pub val syntax::node_count: u64 { get => this.node_kinds.length; }
|
||||
|
||||
#! How many tokens there are, the `eof` ending them included.
|
||||
#! @param this The syntax tree.
|
||||
#! @returns The count.
|
||||
pub val syntax::token_count: u64 { get => this.token_kinds.length; }
|
||||
|
||||
#! Appends a node.
|
||||
#! @param this The syntax tree.
|
||||
#! @param kind Its kind.
|
||||
#! @param token The token it says what it is by.
|
||||
#! @param left Its first slot.
|
||||
#! @param right Its second slot.
|
||||
#! @param end The last token of what it was parsed from.
|
||||
#! @returns Its index.
|
||||
pub def syntax::add_node(&mut this, kind: nk, token: u32, left: u32, right: u32, end: u32): u32 {
|
||||
this.node_kinds.append(kind);
|
||||
this.node_tokens.append(token);
|
||||
this.node_lefts.append(left);
|
||||
this.node_rights.append(right);
|
||||
this.node_spans.append(0);
|
||||
val at := (this.node_kinds.length - 1) as u32;
|
||||
this.set_node_end(at, end);
|
||||
return at;
|
||||
}
|
||||
|
||||
#! A node's span, in a byte, that says `wide_spans` holds it.
|
||||
pub const syntax::wide: u8 = 255;
|
||||
|
||||
#! The last token of what the node was parsed from.
|
||||
#! @param this The syntax tree.
|
||||
#! @param at The node's index.
|
||||
#! @returns The token.
|
||||
pub def syntax::node_end(&this, at: u32): u32 {
|
||||
val span := this.node_spans[at];
|
||||
return this.node_tokens[at] + (span != syntax::wide ? span as u32 : this.wide_spans.get_or(&(at as u64), 0));
|
||||
}
|
||||
|
||||
#! Says the last token of what the node was parsed from, which its token is
|
||||
#! set before.
|
||||
#! @param this The syntax tree.
|
||||
#! @param at The node's index.
|
||||
#! @param end The token.
|
||||
pub def syntax::set_node_end(&mut this, at: u32, end: u32): void {
|
||||
# Held as a count past its token, which wraps where it ends before it, so
|
||||
# adding the count back gives the end.
|
||||
val span := end - this.node_tokens[at];
|
||||
if span < syntax::wide as u32 {
|
||||
if this.node_spans[at] == syntax::wide {
|
||||
this.wide_spans.remove(&(at as u64));
|
||||
}
|
||||
this.node_spans[at] = span as u8;
|
||||
return;
|
||||
}
|
||||
this.node_spans[at] = syntax::wide;
|
||||
this.wide_spans.set(at as u64, span);
|
||||
}
|
||||
|
||||
#! The node at the index, gathered from its fields.
|
||||
#! @param this The syntax tree.
|
||||
#! @param at The node's index.
|
||||
#! @returns The node.
|
||||
pub def syntax::node(&this, at: u32): node {
|
||||
return node {
|
||||
kind = this.node_kinds[at],
|
||||
token = this.node_tokens[at],
|
||||
left = this.node_lefts[at],
|
||||
right = this.node_rights[at],
|
||||
end = this.node_end(at)
|
||||
};
|
||||
}
|
||||
|
||||
#! Appends a token of the kind, spanning `length` bytes from `offset`, which is
|
||||
#! the word of the ID `name`, or 0 where it is no word.
|
||||
#! @param this The syntax tree.
|
||||
#! @param kind Its kind.
|
||||
#! @param offset The byte of the text it begins at.
|
||||
#! @param length How many bytes it covers.
|
||||
#! @param name The ID of the word it is, or 0.
|
||||
pub def syntax::add_token(&mut this, kind: tk, offset: u32, length: u32, name: u32): void {
|
||||
if kind != tk::name && kind.width == 0 && length != 0 {
|
||||
this.literal_tokens.append(this.token_kinds.length as u32);
|
||||
this.literal_lengths.append(length);
|
||||
}
|
||||
this.token_kinds.append(kind);
|
||||
this.token_offsets.append(offset);
|
||||
this.token_names.append(name);
|
||||
}
|
||||
|
||||
#! How many bytes the token covers: as many as its kind says, or its name's
|
||||
#! text, or as were kept of a literal.
|
||||
#! @param this The syntax tree.
|
||||
#! @param at The token's index.
|
||||
#! @param names The names the file was lexed with, or joined.
|
||||
#! @returns How many.
|
||||
pub def syntax::token_length(&this, at: u32, names: &names): u32 {
|
||||
val kind := this.token_kinds[at];
|
||||
val width := kind.width;
|
||||
return width if width != 0;
|
||||
return names.text(this.token_names[at]).length as u32 if kind == tk::name;
|
||||
return this.literal_length(at);
|
||||
}
|
||||
|
||||
#! How many bytes a literal token covers, or 0 for a token not kept as one, as
|
||||
#! `eof`.
|
||||
#! @param this The syntax tree.
|
||||
#! @param at The token's index.
|
||||
#! @returns How many.
|
||||
def syntax::literal_length(&this, at: u32): u32 {
|
||||
val found := this.literal_tokens.view().lower_bound(&at);
|
||||
return found < this.literal_tokens.length && this.literal_tokens[found] == at ? this.literal_lengths[found] : 0;
|
||||
}
|
||||
|
||||
#! Gives each token the ID of its name in another table of names, as where a
|
||||
#! file lexed with names of its own joins those of the program.
|
||||
#! @param this The syntax tree.
|
||||
#! @param ids The ID in the other table of each name, by its ID in the one
|
||||
#! the file was lexed with.
|
||||
pub def syntax::rename(&mut this, ids: span<u32>): void {
|
||||
for i in 0..this.token_names.length {
|
||||
this.token_names[i] = ids[this.token_names[i] as u64];
|
||||
}
|
||||
}
|
||||
|
||||
#! The token at the index, gathered from its fields.
|
||||
#! @param this The syntax tree.
|
||||
#! @param at The token's index.
|
||||
#! @param names The names the file was lexed with, or joined, which give a
|
||||
#! name's length.
|
||||
#! @returns The token.
|
||||
pub def syntax::token(&this, at: u32, names: &names): token {
|
||||
return token {
|
||||
kind = this.token_kinds[at],
|
||||
offset = this.token_offsets[at],
|
||||
length = this.token_length(at, names),
|
||||
name = this.token_names[at]
|
||||
};
|
||||
}
|
||||
|
||||
#! Makes room for the tokens lexing text of so many bytes makes, which are
|
||||
#! seldom more than one for every four bytes, so lexing seldom moves them; the
|
||||
#! room left is let go of once lexing ends, as `fit_tokens` does.
|
||||
#! @param this The syntax tree.
|
||||
#! @param bytes How many bytes the text holds.
|
||||
pub def syntax::reserve_for_text(&mut this, bytes: u32): void {
|
||||
val tokens := this.token_count + bytes as u64 / 4 + 16;
|
||||
this.token_kinds.reserve(tokens);
|
||||
this.token_offsets.reserve(tokens);
|
||||
this.token_names.reserve(tokens);
|
||||
}
|
||||
|
||||
#! Makes room for the nodes and extras parsing the tokens makes, which are
|
||||
#! seldom more than three quarters of the tokens, so parsing seldom moves them;
|
||||
#! the room left is let go of once parsing ends, as `fit_nodes` does.
|
||||
#! @param this The syntax tree.
|
||||
pub def syntax::reserve_for_tokens(&mut this): void {
|
||||
val tokens := this.token_count;
|
||||
val nodes := this.node_count + tokens * 3 / 4 + 16;
|
||||
this.node_kinds.reserve(nodes);
|
||||
this.node_tokens.reserve(nodes);
|
||||
this.node_lefts.reserve(nodes);
|
||||
this.node_rights.reserve(nodes);
|
||||
this.node_spans.reserve(nodes);
|
||||
this.extras.reserve(this.extras.length + tokens * 3 / 4 + 16);
|
||||
}
|
||||
|
||||
#! Lets go of the room the tokens were given beyond those lexed, which is
|
||||
#! about a third of it.
|
||||
#! @param this The syntax tree.
|
||||
pub def syntax::fit_tokens(&mut this): void {
|
||||
fitted(&mut this.token_kinds);
|
||||
fitted(&mut this.token_offsets);
|
||||
fitted(&mut this.token_names);
|
||||
fitted(&mut this.literal_tokens);
|
||||
fitted(&mut this.literal_lengths);
|
||||
}
|
||||
|
||||
#! Lets go of the room the nodes and extras were given beyond those parsed.
|
||||
#! @param this The syntax tree.
|
||||
pub def syntax::fit_nodes(&mut this): void {
|
||||
fitted(&mut this.node_kinds);
|
||||
fitted(&mut this.node_tokens);
|
||||
fitted(&mut this.node_lefts);
|
||||
fitted(&mut this.node_rights);
|
||||
fitted(&mut this.node_spans);
|
||||
fitted(&mut this.extras);
|
||||
}
|
||||
|
||||
# Moves the items into a block of their own size, where the one they are in
|
||||
# has room for more than an eighth as many again.
|
||||
def fitted<T>(items: &mut vector<T>): void {
|
||||
return if items.capacity - items.length <= items.length / 8 + 16;
|
||||
var made := vector::<T>::new();
|
||||
made.reserve(items.length);
|
||||
made.extend(items.view());
|
||||
items = move(&mut made);
|
||||
}
|
||||
|
||||
#! The token a declaration begins at, its attributes and `pub` included, or its
|
||||
#! own token where it was not recorded.
|
||||
#! @param this The syntax tree.
|
||||
#! @param at The declaration's node.
|
||||
#! @returns The token.
|
||||
pub def syntax::start_of(&this, at: u32): u32 {
|
||||
return this.starts.get_or(&(at as u64), this.node_tokens[at]);
|
||||
}
|
||||
|
||||
#! The documentation comments written before a declaration.
|
||||
#! @param this The syntax tree.
|
||||
#! @param at The declaration's node.
|
||||
#! @returns The lines, which are none where it has no documentation.
|
||||
pub def syntax::docs_of(&this, at: u32): doc_range {
|
||||
val start := this.starts.get(&(at as u64)) else { return doc_range {}; };
|
||||
val low := this.docs.view().partition_point(def(each: &doc): bool { return each.token < start; });
|
||||
|
||||
var count: u32 = 0;
|
||||
while low + (count as u64) < this.docs.length && this.docs[low + count as u64].token == start {
|
||||
count++;
|
||||
}
|
||||
return doc_range { first = low as u32, count = count };
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
#! @file token.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the token type, which is a kind of token and the text it was read
|
||||
#! from, and `tk`, the kinds of token.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
#! Defines a source code token.
|
||||
#!
|
||||
#! A token is the kind and location of a piece of text within some source code. The
|
||||
#! type is used in the parser to identify constructs and build them into an
|
||||
#! abstract syntax tree. The offset of the token points to the index within the
|
||||
#! source code that token resides. The offset can be used with the
|
||||
#! `source::lines` vector to identify a place within the source code that the
|
||||
#! token resides.
|
||||
pub struct token {
|
||||
var offset: u32; #! Where it begins in the source text.
|
||||
var length: u32; #! How many bytes of the source text it spans.
|
||||
var name: u32; #! The ID of the word it is, or 0 where it is no word.
|
||||
var kind: tk; #! Its kind.
|
||||
}
|
||||
|
||||
#! The kinds of token.
|
||||
#!
|
||||
#! They are grouped by what they are: the keywords, then the literals, the
|
||||
#! pieces of an interpolated string, and the punctuators. `true`, `false`, and
|
||||
#! `null` are keywords that are also literals, and they are the last keywords,
|
||||
#! so `kw_beg` to `kw_end` spans every keyword.
|
||||
#!
|
||||
#! `eof` marks the end of the source, and `bad_number` and `bad_quote` are what
|
||||
#! the lexer gives for a number or a quote it could not make sense of, so it
|
||||
#! goes on and the parser reports them where they are. The lexer almost never
|
||||
#! fails otherwise.
|
||||
pub enum tk : u8 {
|
||||
# Keywords
|
||||
kw_imp, kw_mod, kw_extern, kw_pub, kw_const, kw_var, kw_val, kw_def,
|
||||
kw_mut, kw_ret, kw_if, kw_else, kw_for, kw_in, kw_while, kw_break,
|
||||
kw_cont, kw_type, kw_enum, kw_struct, kw_union, kw_trait, kw_as, kw_is,
|
||||
kw_not, kw_match, kw_when, kw_where, kw_true, kw_false, kw_null,
|
||||
|
||||
# Literals
|
||||
name, unknown, signed, unsigned, float, char, string, istring,
|
||||
|
||||
# Pieces of an interpolated string with holes, between which come the tokens of
|
||||
# each hole: `$"text{`, then `}text{` between two holes, then `}text"`.
|
||||
istring_beg, istring_mid, istring_end,
|
||||
|
||||
# Punctuators
|
||||
lparen, rparen, lbrace, rbrace, lbracket, rbracket, semicolon, comma,
|
||||
dot, cascade, spread, colon, quest, attr, assign, arrow,
|
||||
equals, negate, noteq, less, lesseq, more, moreeq, plus,
|
||||
minus, star, slash, modulo, logand, logor, bitand, bitor,
|
||||
bitxor, bitnot, lshift, rshift, scope, pluseq, minuseq, stareq,
|
||||
slasheq, moduloeq, logandeq, logoreq, bitandeq, bitoreq, bitxoreq, bitnoteq,
|
||||
lshifteq, rshifteq, increment, decrement, cascadeeq,
|
||||
|
||||
# End of file marker.
|
||||
#! The end of the source.
|
||||
eof,
|
||||
|
||||
# Error tokens.
|
||||
#! A number written wrongly.
|
||||
bad_number,
|
||||
#! A string or character with no closing quote.
|
||||
bad_quote,
|
||||
|
||||
# Not a kind: how many there are, which sizes the tables indexed by kind.
|
||||
#! How many kinds there are, which sizes the tables indexed by kind; not a
|
||||
#! kind itself.
|
||||
count,
|
||||
|
||||
# Ranges.
|
||||
#! The first keyword.
|
||||
kw_beg = tk::kw_imp,
|
||||
#! The last keyword.
|
||||
kw_end = tk::kw_null,
|
||||
}
|
||||
|
||||
#! How many bytes a token of the kind covers, where its kind says: those of a
|
||||
#! keyword or a punctuator, or 0 for a kind of any length, as a name or a
|
||||
#! literal.
|
||||
#! @param this The kind of token.
|
||||
#! @returns How many.
|
||||
pub val tk::width: u32 { get => token_widths[this as u64] as u32; }
|
||||
|
||||
#! How many bytes a token of each kind covers, where its kind says, worked out
|
||||
#! while compiling: a keyword's word, and a punctuator's bytes.
|
||||
const token_widths: u8[tk::count as u64] = make_token_widths();
|
||||
|
||||
const def make_token_widths(): u8[tk::count as u64] {
|
||||
var made: u8[tk::count as u64];
|
||||
for &each in _keywords { made[each.kind as u64] = each.text.length as u8; }
|
||||
for each in [
|
||||
tk::lparen, tk::rparen, tk::lbrace, tk::rbrace, tk::lbracket, tk::rbracket, tk::semicolon,
|
||||
tk::comma, tk::dot, tk::colon, tk::quest, tk::attr, tk::assign, tk::negate,
|
||||
tk::less, tk::more, tk::plus, tk::minus, tk::star, tk::slash, tk::modulo,
|
||||
tk::bitand, tk::bitor, tk::bitxor, tk::bitnot
|
||||
] { made[each as u64] = 1; }
|
||||
for each in [
|
||||
tk::cascade, tk::scope, tk::arrow, tk::equals, tk::noteq, tk::lesseq,
|
||||
tk::moreeq, tk::logand, tk::logor, tk::lshift, tk::rshift, tk::pluseq,
|
||||
tk::minuseq, tk::stareq, tk::slasheq, tk::moduloeq, tk::bitandeq, tk::bitoreq,
|
||||
tk::bitxoreq, tk::bitnoteq, tk::increment, tk::decrement
|
||||
] { made[each as u64] = 2; }
|
||||
for each in [tk::spread, tk::cascadeeq, tk::logandeq, tk::logoreq, tk::lshifteq, tk::rshifteq] {
|
||||
made[each as u64] = 3;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Whether the token compares, as `==` or `<` do.
|
||||
#! @param this The token.
|
||||
#! @returns Whether it does.
|
||||
pub def tk::compares(&this): bool {
|
||||
return this == tk::equals || this == tk::noteq || this == tk::less
|
||||
|| this == tk::lesseq || this == tk::more || this == tk::moreeq;
|
||||
}
|
||||
|
||||
#! The operator a compound assignment applies, as `+` of `+=`, or the token.
|
||||
#! @param this The token.
|
||||
#! @returns The operator.
|
||||
pub def tk::applied(&this): tk {
|
||||
return match this {
|
||||
tk::pluseq => tk::plus,
|
||||
tk::minuseq => tk::minus,
|
||||
tk::stareq => tk::star,
|
||||
tk::slasheq => tk::slash,
|
||||
tk::moduloeq => tk::modulo,
|
||||
tk::bitandeq => tk::bitand,
|
||||
tk::bitoreq => tk::bitor,
|
||||
tk::bitxoreq => tk::bitxor,
|
||||
tk::lshifteq => tk::lshift,
|
||||
tk::rshifteq => tk::rshift,
|
||||
else => this
|
||||
};
|
||||
}
|
||||
|
||||
# Match based token kind extensions.
|
||||
# Given the current token kind and the next character, produces the next token
|
||||
# kind. This assists the lexer in matching greedily. `>>`, `>=`, and `>>=` are
|
||||
# matched as well, though they may close type arguments instead, so the lexer
|
||||
# follows each with tokens of what is left of it, as `lexer` says.
|
||||
def tk::from(&this, char: u8): tk {
|
||||
return match char {
|
||||
# Single
|
||||
'(' => tk::lparen,
|
||||
')' => tk::rparen,
|
||||
'{' => tk::lbrace,
|
||||
'}' => tk::rbrace,
|
||||
'[' => tk::lbracket,
|
||||
']' => tk::rbracket,
|
||||
';' => tk::semicolon,
|
||||
',' => tk::comma,
|
||||
'?' => tk::quest,
|
||||
'@' => tk::attr,
|
||||
|
||||
# Multi
|
||||
'.' => tk::dot,
|
||||
':' => tk::colon,
|
||||
'=' => tk::assign,
|
||||
'!' => tk::negate,
|
||||
'<' => tk::less,
|
||||
'>' => tk::more,
|
||||
'+' => tk::plus,
|
||||
'-' => tk::minus,
|
||||
'*' => tk::star,
|
||||
'/' => tk::slash,
|
||||
'%' => tk::modulo,
|
||||
'&' => tk::bitand,
|
||||
'|' => tk::bitor,
|
||||
'^' => tk::bitxor,
|
||||
'~' => tk::bitnot,
|
||||
else => tk::unknown
|
||||
} if this == tk::unknown;
|
||||
|
||||
return match this {
|
||||
# Doubles
|
||||
tk::dot => match char {
|
||||
'.' => tk::cascade,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::colon => match char {
|
||||
':' => tk::scope,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::assign => match char {
|
||||
'=' => tk::equals,
|
||||
'>' => tk::arrow,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::negate => match char {
|
||||
'=' => tk::noteq,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::less => match char {
|
||||
'=' => tk::lesseq,
|
||||
'<' => tk::lshift,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::more => match char {
|
||||
'=' => tk::moreeq,
|
||||
'>' => tk::rshift,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::plus => match char {
|
||||
'=' => tk::pluseq,
|
||||
'+' => tk::increment,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::minus => match char {
|
||||
'=' => tk::minuseq,
|
||||
'-' => tk::decrement,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::star => match char {
|
||||
'=' => tk::stareq,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::slash => match char {
|
||||
'=' => tk::slasheq,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::modulo => match char {
|
||||
'=' => tk::moduloeq,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::bitand => match char {
|
||||
'=' => tk::bitandeq,
|
||||
'&' => tk::logand,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::bitor => match char {
|
||||
'=' => tk::bitoreq,
|
||||
'|' => tk::logor,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::bitxor => match char {
|
||||
'=' => tk::bitxoreq,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::bitnot => match char {
|
||||
'=' => tk::bitnoteq,
|
||||
else => tk::unknown
|
||||
},
|
||||
|
||||
# Triples
|
||||
tk::cascade => match char {
|
||||
'.' => tk::spread,
|
||||
'=' => tk::cascadeeq,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::lshift => match char {
|
||||
'=' => tk::lshifteq,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::rshift => match char {
|
||||
'=' => tk::rshifteq,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::logand => match char {
|
||||
'=' => tk::logandeq,
|
||||
else => tk::unknown
|
||||
},
|
||||
tk::logor => match char {
|
||||
'=' => tk::logoreq,
|
||||
else => tk::unknown
|
||||
},
|
||||
else => tk::unknown
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
#! @file walker.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the walker, which finds the nodes a node holds through its shape,
|
||||
#! so every pass can walk the tree without knowing each kind of node.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! Appends the nodes a node holds to `into`, in the order its shape lists its
|
||||
#! slots: the node of each `node` slot that is not absent, every node of each
|
||||
#! `run`, and those of its record, likewise.
|
||||
#!
|
||||
#! This is how every pass walks the tree without knowing each kind of node, as
|
||||
#! the shapes say what each kind holds.
|
||||
#! @param this The syntax tree.
|
||||
#! @param at The node.
|
||||
#! @param into Where the nodes are appended.
|
||||
pub def syntax::children(&this, at: u32, into: &mut vector<u32>): void {
|
||||
return if at == 0;
|
||||
|
||||
# Only the slots are read, rather than the whole node, whose end is worked
|
||||
# out apart.
|
||||
val shape := this.node_kinds[at].shape;
|
||||
this.slot_children(shape.left, this.node_lefts[at], shape.record, into);
|
||||
this.slot_children(shape.right, this.node_rights[at], shape.record, into);
|
||||
}
|
||||
|
||||
#! The nodes the slot holds, where it holds `value`.
|
||||
#! @param this The syntax tree.
|
||||
#! @param kind What the slot holds.
|
||||
#! @param value The slot's value.
|
||||
#! @param record The shape of the node's record, where the slot holds one.
|
||||
#! @param into Where the nodes are appended.
|
||||
def syntax::slot_children(
|
||||
&this,
|
||||
kind: slot,
|
||||
value: u32,
|
||||
record: span<slot>,
|
||||
into: &mut vector<u32>
|
||||
): void {
|
||||
match kind {
|
||||
slot::node => {
|
||||
if value != 0 {
|
||||
into.append(value);
|
||||
}
|
||||
}
|
||||
slot::run, slot::bounds => {
|
||||
into.extend(this.run_view(value));
|
||||
}
|
||||
slot::extra => {
|
||||
for i in 0..record.length {
|
||||
val inner := this.extras[value as u64 + i];
|
||||
this.slot_children(record[i], inner, no_record, into);
|
||||
}
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
}
|
||||
|
||||
#! How many nodes the run at `extras[run]` holds.
|
||||
#! @param this The syntax tree.
|
||||
#! @param run Where the run begins.
|
||||
#! @returns How many nodes it holds.
|
||||
pub def syntax::run_length(&this, run: u32): u32 {
|
||||
return this.extras[run];
|
||||
}
|
||||
|
||||
#! The node at the index of the run at `extras[run]`.
|
||||
#! @param this The syntax tree.
|
||||
#! @param run Where the run begins.
|
||||
#! @param index The position, below its length.
|
||||
#! @returns The node.
|
||||
pub def syntax::run_at(&this, run: u32, index: u32): u32 {
|
||||
return this.extras[run as u64 + 1 + index as u64];
|
||||
}
|
||||
|
||||
#! The nodes of the run at `extras[run]`, where they are.
|
||||
#! @param this The syntax tree.
|
||||
#! @param run Where the run begins.
|
||||
#! @returns The nodes, a view only good until the syntax grows, as by parsing.
|
||||
pub def syntax::run_view(&this, run: u32): span<u32> {
|
||||
return span::<u32>::over(this.extras.view().data + run as u64 + 1, this.extras[run] as u64);
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
name: sakurac
|
||||
gpid: malunal
|
||||
semv: 1.0.0
|
||||
|
||||
options:
|
||||
level: 2
|
||||
debug: false
|
||||
|
||||
requires:
|
||||
- https://git.malunal.studio/sakura/std@v1.0.0
|
||||
- https://git.malunal.studio/sakura/binary@v1.0.0
|
||||
|
||||
targets:
|
||||
- name: sakurac
|
||||
type: program
|
||||
level: ${level}
|
||||
petal: ${debug}
|
||||
deps:
|
||||
- binary.elf
|
||||
- binary.dwarf
|
||||
- binary.pe
|
||||
- binary.pdb
|
||||
- binary.amd64
|
||||
- sakura.analyzer
|
||||
- sakura.compiler
|
||||
- sakura.machine
|
||||
- sakura.native
|
||||
- sakura.server
|
||||
- std.args
|
||||
- std.io
|
||||
- std.json
|
||||
- std.process
|
||||
- std.thread
|
||||
srcs:
|
||||
- entry.sakura
|
||||
|
||||
# The compiler's parts, each a library of its own in the folder of its name.
|
||||
- name: sakura.analyzer
|
||||
type: library
|
||||
root: ./analyzer
|
||||
deps: [std.containers, std.io, std.thread]
|
||||
|
||||
- name: sakura.compiler
|
||||
type: library
|
||||
root: ./compiler
|
||||
deps: [std.allocators, std.containers, std.thread, sakura.analyzer]
|
||||
|
||||
- name: sakura.machine
|
||||
type: library
|
||||
root: ./machine
|
||||
deps: [std.containers, std.io, std.thread, std.time, sakura.analyzer, sakura.compiler]
|
||||
|
||||
- name: sakura.native
|
||||
type: library
|
||||
root: ./native
|
||||
deps:
|
||||
- std.containers
|
||||
- std.io
|
||||
- std.thread
|
||||
- sakura.analyzer
|
||||
- sakura.compiler
|
||||
- binary.amd64
|
||||
- binary.elf
|
||||
- binary.dwarf
|
||||
- binary.pe
|
||||
- binary.pdb
|
||||
|
||||
- name: sakura.server
|
||||
type: library
|
||||
root: ./server
|
||||
deps: [std.io, std.json, std.net, std.process, std.serial, sakura.analyzer, sakura.machine]
|
||||
|
||||
tests:
|
||||
- name: sakurac.tests
|
||||
type: program
|
||||
deps: [sakura.analyzer, std.io, std.process, std.testing]
|
||||
srcs: [tests/main.sakura, tests/libraries.sakura]
|
||||
|
||||
# Each part's tests, in the folder of its name. Those of the native backend
|
||||
# evaluate constants on the machine, as `sakurac build` does, and find `core`,
|
||||
# `system`, and `runtime` as the language server does.
|
||||
- name: sakura.analyzer.tests
|
||||
type: program
|
||||
deps: [sakura.analyzer, std.testing]
|
||||
srcs: [tests/main.sakura, tests/analyzer/*.sakura]
|
||||
|
||||
- name: sakura.compiler.tests
|
||||
type: program
|
||||
deps: [sakura.analyzer, sakura.compiler, std.containers, std.io, std.testing]
|
||||
srcs: [tests/main.sakura, tests/compiler/*.sakura]
|
||||
|
||||
- name: sakura.machine.tests
|
||||
type: program
|
||||
deps: [sakura.analyzer, sakura.compiler, sakura.machine, std.io, std.testing]
|
||||
srcs: [tests/main.sakura, tests/machine/*.sakura]
|
||||
|
||||
# The machine's tests again, built and run as an executable, where the machine
|
||||
# compiles the functions it runs to the processor's code, as on Windows.
|
||||
- name: sakura.machine.native
|
||||
type: program
|
||||
runs: native
|
||||
deps: [sakura.analyzer, sakura.compiler, sakura.machine, std.io, std.testing]
|
||||
srcs: [tests/main.sakura, tests/machine/*.sakura]
|
||||
|
||||
- name: sakura.native.tests
|
||||
type: program
|
||||
deps:
|
||||
- sakura.analyzer
|
||||
- sakura.compiler
|
||||
- sakura.machine
|
||||
- sakura.server
|
||||
- binary.amd64
|
||||
- binary.elf
|
||||
- sakura.native
|
||||
- std.io
|
||||
- std.process
|
||||
- std.testing
|
||||
srcs: [tests/main.sakura, tests/native/*.sakura]
|
||||
|
||||
- name: sakura.server.tests
|
||||
type: program
|
||||
deps: [sakura.analyzer, sakura.server, std.io, std.testing]
|
||||
srcs: [tests/main.sakura, tests/server/*.sakura]
|
||||
|
||||
# The tests of `core` and `system`, which ship with the compiler, built and run
|
||||
# as executables.
|
||||
- name: sakurac.core
|
||||
type: program
|
||||
runs: native
|
||||
deps: [std.containers, std.io, std.math, std.process, std.serial, std.testing, std.thread]
|
||||
srcs: [tests/core/*.sakura]
|
||||
|
||||
# The corpus, each program run by the compiler just built, over the standard
|
||||
# library's repository beside this one.
|
||||
|
||||
- name: sakurac.corpus
|
||||
type: program
|
||||
checks: false
|
||||
srcs: [tools/corpus.sakura]
|
||||
deps: [std.io, std.process]
|
||||
args: ["${bin}/sakurac", run, --lib, std=../std]
|
||||
|
||||
- name: sakurac.checked
|
||||
type: program
|
||||
checks: false
|
||||
srcs: [tools/corpus.sakura]
|
||||
deps: [std.io, std.process]
|
||||
args: [--dir, tests/checked, "${bin}/sakurac", run, --lib, std=../std]
|
||||
|
||||
- name: sakurac.memory
|
||||
type: program
|
||||
checks: false
|
||||
srcs: [tools/corpus.sakura]
|
||||
deps: [std.io, std.process]
|
||||
args: [--dir, tests/memory, "${bin}/sakurac", run, --lib, std=../std, --checks]
|
||||
|
||||
exports:
|
||||
- sakura.analyzer
|
||||
- sakura.compiler
|
||||
- sakura.machine
|
||||
- sakura.native
|
||||
- sakura.server
|
||||
|
||||
install:
|
||||
- !include ./core
|
||||
- !include ./system
|
||||
- !include ./runtime
|
||||
|
||||
package:
|
||||
lic: MIT
|
||||
desc: The Sakura programming language compiler.
|
||||
auth: John Christman <sorakatadzuma@gmail.com>
|
||||
url: https://git.malunal.studio/sakura/sakurac
|
||||
@@ -0,0 +1,136 @@
|
||||
# sakura::compiler
|
||||
|
||||
`sakura::compiler` is the middle of the Sakura compiler. It lowers a program
|
||||
that `sakura::analyzer` has checked to intermediate code: values each assigned
|
||||
once, in blocks that take parameters where control flow joins. It optimizes
|
||||
that code, and assembles each function into the code `sakura::machine` runs.
|
||||
The compiler's back end builds executables from the same intermediate code.
|
||||
|
||||
## Using it
|
||||
|
||||
Require this repository, which exports each of the compiler's libraries, and name this
|
||||
one among a target's `deps` with the analyzer, which it reads itself:
|
||||
|
||||
```yaml
|
||||
requires:
|
||||
- https://git.malunal.studio/sakura/std@v1.0.0
|
||||
- https://git.malunal.studio/sakura/sakurac@v1.0.0
|
||||
|
||||
targets:
|
||||
- name: app
|
||||
type: program
|
||||
deps: [sakura.analyzer, sakura.compiler, std.io]
|
||||
```
|
||||
|
||||
A program is lowered from the checker that checked it, as `sakura::analyzer`'s
|
||||
README checks one:
|
||||
|
||||
```sakura
|
||||
import std::io;
|
||||
import sakura::analyzer;
|
||||
import sakura::compiler;
|
||||
|
||||
# Checks a file importing nothing, with `core`, whose folder is given, then
|
||||
# lowers it, optimizes it at a level, and prints the code of the function of a
|
||||
# name. Gives whether it could.
|
||||
def lower(path: strview, core: strview, level: u32, name: strview): bool {
|
||||
var paths := vector::<string>::new();
|
||||
paths.append(string::from(path, nothing {}));
|
||||
paths.append(string::from(builtin_path, nothing {}));
|
||||
every_file(core, &mut paths);
|
||||
|
||||
var names := names::new();
|
||||
var notes := vector::<note>::new();
|
||||
var sources := vector::<source>::new();
|
||||
var syntaxes := vector::<syntax>::new();
|
||||
var roots := vector::<u32>::new();
|
||||
sources.reserve(paths.length);
|
||||
syntaxes.reserve(paths.length);
|
||||
for i in 0..paths.length {
|
||||
val at := paths[i].view();
|
||||
sources.append(at == builtin_path ? source::from(at, builtin_text) : source::open(at));
|
||||
syntaxes.append(syntax::new());
|
||||
var lexing := lexer::new(sources.at(i), &mut names, &mut notes, i as u32);
|
||||
lexing.tokenize_all(syntaxes.at(i));
|
||||
var parsing := parser::new(syntaxes.at(i), &names, &mut notes, i as u32);
|
||||
roots.append(parsing.parse());
|
||||
}
|
||||
var checker := checker::new(&mut names, &mut notes);
|
||||
for i in 0..paths.length {
|
||||
checker.add(sources.at(i), syntaxes.at(i), roots.at(i));
|
||||
}
|
||||
checker.check();
|
||||
return false if notes.length != 0;
|
||||
|
||||
var lowered := lowerer::new(&mut checker, lowering { verify = true, level = level });
|
||||
lowered.compile();
|
||||
for &each in lowered.problems {
|
||||
println(each);
|
||||
}
|
||||
return false if lowered.problems.length != 0;
|
||||
lowered.drop_unreached_functions();
|
||||
for &function in lowered.program.functions {
|
||||
if function.lowered && function.name.view() == name {
|
||||
print(function.body.print());
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
For `def square(x: i32): i32 { return x * x; }` at level 0, it prints:
|
||||
|
||||
```
|
||||
b0(v0: i64):
|
||||
v1 = mul v0, v0
|
||||
v2 = wrap v1, 32, signed
|
||||
ret v2
|
||||
```
|
||||
|
||||
The values of constants are computed by running code on `sakura::machine`.
|
||||
Its `evaluate` gives the `outcomes`, which are set as the lowerer's `evaluated`
|
||||
before `compile`.
|
||||
|
||||
## What it holds
|
||||
|
||||
- **Lowering**: `lowerer` lowers each function once something that runs names
|
||||
it, by `lowering`'s options. `emitter/` has a file for each part of the
|
||||
language.
|
||||
- `layouts` lays out types as C lays out the same fields.
|
||||
- `dispatch` holds the vtables of traits.
|
||||
- `globals` gives the globals their values before `main` runs.
|
||||
- `escapes` and `flows` find where each reference may go, so a local whose
|
||||
address is kept lives in a cell of the frame.
|
||||
- **Intermediate code** (`intermediate/`): `code`, a function's blocks,
|
||||
instructions and cells. `builder` makes it in one pass. `verifier` checks it
|
||||
is well formed. `printer` writes it as text.
|
||||
- **Optimizing** (`optimizer/`):
|
||||
- `-O1` simplifies, cleans up control flow, numbers values, and removes dead
|
||||
code.
|
||||
- `-O2` also inlines and promotes cells to values.
|
||||
- Below `-O2`, calls of `@inline` functions are inlined all the same, and at
|
||||
`-O0` that is all that changes.
|
||||
- At `-O1` and above, a function asking which vector instructions the
|
||||
processor has, or counting a word's bits, gets a version for x86-64-v3's,
|
||||
and an executable's stores filling 16 bytes of a struct are merged into one
|
||||
of a vector once the rest is done.
|
||||
- Each pass leaves the code well formed.
|
||||
- **The machine's code**: `bytecode` assembles each function into the words
|
||||
`sakura::machine` runs.
|
||||
- **Constants**: the program that computes the constants and the `if const`
|
||||
conditions the checker left undecided.
|
||||
- **Threads**: `workers` shares functions among threads, which optimize and
|
||||
assemble them into the same bytes however many there are.
|
||||
|
||||
## Testing
|
||||
|
||||
From the repository's root, `blossom test` runs them as `sakura.compiler.tests`, or:
|
||||
|
||||
```sh
|
||||
sakurac run --lib sakura::analyzer=analyzer --lib sakura::compiler=compiler \
|
||||
tests/main.sakura tests/compiler/*.sakura
|
||||
```
|
||||
|
||||
The tests are declared within the module. Most check and lower a small program
|
||||
and compare its printed code with what is expected, after the verifier has
|
||||
found nothing wrong with it.
|
||||
@@ -0,0 +1,71 @@
|
||||
#! @file atomics.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the operations of atomics, as `core::atomic` and both compilers number
|
||||
#! them, and the orders they take, as `core::order` does.
|
||||
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
# The operations an `atomic` instruction works, its `aux`. Each takes the address
|
||||
# first, but a fence, which takes none, and its orders last.
|
||||
pub const atomic_load: u32 = 0; #! (address, order): what the address holds.
|
||||
pub const atomic_store: u32 = 1; #! (address, value, order): writes the value, giving nothing.
|
||||
pub const atomic_exchange: u32 = 2; #! (address, value, order): writes the value, giving what was there.
|
||||
pub const atomic_compare_exchange: u32 = 3; #! (address, expected, desired, success, failure): writes `desired` where it holds `expected`, giving what was there.
|
||||
pub const atomic_add: u32 = 4; #! (address, operand, order): adds, wrapping, giving what was there.
|
||||
pub const atomic_sub: u32 = 5; #! Subtracts, wrapping.
|
||||
pub const atomic_and: u32 = 6; #! Keeps the bits both have.
|
||||
pub const atomic_or: u32 = 7; #! Keeps the bits either has.
|
||||
pub const atomic_xor: u32 = 8; #! Keeps the bits one has.
|
||||
pub const atomic_min: u32 = 9; #! Keeps the less, compared as the access is, signed or unsigned.
|
||||
pub const atomic_max: u32 = 10; #! Keeps the greater.
|
||||
pub const atomic_fence: u32 = 11; #! (order): orders the reads and writes around it, giving nothing.
|
||||
|
||||
#! Set in an `atomic` instruction's `imm`, beside its access, where the integer
|
||||
#! is unsigned, which the access alone does not say of 64 bits.
|
||||
pub const atomic_unsigned: u64 = 0x100;
|
||||
|
||||
#! The access an `atomic` instruction reads and writes as.
|
||||
#! @param imm Its `imm`.
|
||||
#! @returns The access.
|
||||
pub def atomic_access(imm: u64): access {
|
||||
return (imm & 0xFF) as access;
|
||||
}
|
||||
|
||||
#! Whether an `atomic` instruction compares as signed integers do.
|
||||
#! @param imm Its `imm`.
|
||||
#! @returns Whether it does.
|
||||
pub def atomic_signed(imm: u64): bool {
|
||||
val how := atomic_access(imm);
|
||||
return (imm & atomic_unsigned) == 0 && (how == access::i8 || how == access::i16 || how == access::i32 || how == access::i64);
|
||||
}
|
||||
|
||||
# The orders, as `core::order` numbers them.
|
||||
pub const order_relaxed: u64 = 0;
|
||||
pub const order_acquire: u64 = 1;
|
||||
pub const order_release: u64 = 2;
|
||||
pub const order_acq_rel: u64 = 3;
|
||||
pub const order_seq_cst: u64 = 4;
|
||||
|
||||
#! The name of each atomic operation, as the printed code writes it.
|
||||
pub const atomic_names: strview[12] = [
|
||||
"load", "store", "exchange", "compare_exchange", "add", "sub", "and", "or", "xor", "min", "max", "fence"
|
||||
];
|
||||
|
||||
#! Whether an atomic operation gives what the address held.
|
||||
#! @param operation The operation.
|
||||
#! @returns Whether it does.
|
||||
pub def atomic_gives(operation: u32): bool {
|
||||
return operation != atomic_store && operation != atomic_fence;
|
||||
}
|
||||
|
||||
#! Whether an atomic operation is one of those `core::atomic`'s integers alone
|
||||
#! have, which read, combine, and write.
|
||||
#! @param operation The operation.
|
||||
#! @returns Whether it is.
|
||||
pub def atomic_combines(operation: u32): bool {
|
||||
return operation >= atomic_add && operation <= atomic_max;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,475 @@
|
||||
#! @file compiler.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the compiler, which lowers a checked program to a program of
|
||||
#! intermediate code: `main`, the code initializing the globals, and every
|
||||
#! function they reach, each lowered once something that runs names it. What
|
||||
#! each node means comes from the checker's tables: a function's nodes from
|
||||
#! its file's result table, and those of an instance of a generic from the
|
||||
#! instance's. What lowering does with each part of the language is split
|
||||
#! across the files of the `emitter` directory, as the checker's are.
|
||||
|
||||
import std::containers;
|
||||
import sakura::analyzer;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! How the code is lowered.
|
||||
pub struct lowering {
|
||||
pub var keep_locals: bool; #! Whether every named local is kept in a cell of its own, as debugging information wants.
|
||||
pub var describe: bool; #! Whether the variables of optimized code are noted for debugging information, which changes nothing of the code.
|
||||
pub var verify: bool; #! Whether each function is verified once lowered.
|
||||
pub var everything: bool; #! Whether every function that is no generic's template is lowered, not only those `main` reaches.
|
||||
pub var evaluating: bool; #! Whether the program evaluates constants while compiling, rather than running.
|
||||
pub var checks: bool; #! Whether what each reference and pointer reaches is checked as the program runs, as `run --checks` asks.
|
||||
pub var level: u32; #! How much the code is optimized: 0 not at all, 1 within each function, 2 inlining too.
|
||||
pub var inline_limit: u32; #! The most instructions a function inlined may have, but for its constants, or 0 for `inline_limit`.
|
||||
pub var threads: u32; #! How many threads optimize and assemble functions at once, the compiler's own among them; 0 or 1 for it alone.
|
||||
}
|
||||
|
||||
#! The compiler.
|
||||
pub struct lowerer {
|
||||
pub var checker: &mut checker; #! The checker, whose tables say what the program means.
|
||||
pub var program: program; #! What is made.
|
||||
var options: lowering; #! How the code is lowered.
|
||||
|
||||
var layout_ids: dict<u32, u32>; #! The layout of each type.
|
||||
var laying: u32; #! How many layouts are being made, one within another.
|
||||
var referents: vector<u32>; #! References and pointers laid out, each with the type it reaches, which is laid out once the outermost is.
|
||||
var signature_ids: dict<u32, u32>; #! The signature of each function type.
|
||||
var function_ids: dict<u64, u32>; #! The function of each declaration and instance, by `pair_key(decl, instance)`, the instance one more than its index.
|
||||
var builtin_ids: dict<u64, u32>; #! The function giving each built-in type each method, by `pair_key(type, name)`.
|
||||
var lambda_ids: dict<u64, u32>; #! The function of each anonymous function, by `pair_key(table, node)`.
|
||||
var adapter_ids: dict<u64, u32>; #! The adapter of each function named as a value of another function type, by `pair_key(table, node)`.
|
||||
var global_ids: dict<u32, u64>; #! Where each global is among the globals, by its declaration.
|
||||
var begun_globals: hashset<u32>; #! The globals whose initializers are lowered, or being lowered.
|
||||
var vtable_ids: dict<u64, u32>; #! The vtable of each type for each trait's type, by `pair_key(type, trait)`.
|
||||
var retrait_ids: dict<u64, u32>; #! The map of each conversion between traits' types, by `pair_key(from, to)`.
|
||||
var linked_ids: dict<u32, u32>; #! The C function each foreign declaration calls.
|
||||
var texts: interner<string>; #! Each text a datum holds.
|
||||
var text_data: vector<u32>; #! The datum holding each text, by its ID in `texts`.
|
||||
var dispatches: dict<u32, u32>; #! The run of the methods of each trait in the order its vtables hold them, in `lists`.
|
||||
var lists: runs<u32>; #! The runs `dispatches` names.
|
||||
var queue: vector<u32>; #! The functions waiting to be lowered.
|
||||
pub var problems: vector<string>; #! What lowering could not lower, which a program the checker passes never has.
|
||||
var summaries: dict<u64, keeping>; #! What each function does with what it is given, by `pair_key(decl, instance)`, once found for good.
|
||||
var pending: vector<pending_scan>; #! The functions whose summaries are being found, in the order they were reached.
|
||||
var pending_ids: dict<u64, u32>; #! The place of each in `pending`, by its key.
|
||||
var reader_of: vector<u32>; #! Of each link of a pending function's readers, the reader, by its place.
|
||||
var reader_next: vector<u32>; #! Of each link, one more than the next link of the same function, or 0.
|
||||
var read_pairs: hashset<u64>; #! The pending functions each reader read, by `pair_key(read, reader)`.
|
||||
var scanning: u32; #! The pending function whose scan is being made, or `no_scan`.
|
||||
pub var dispatch: u32; #! The function safe points call, `system::dispatch`, or `no_function` where the program handles no signal.
|
||||
pub var evaluations: vector<evaluation>; #! Of a program evaluating constants, what it evaluates.
|
||||
pub var evaluation_ids: dict<u64, u32>; #! The evaluation of each constant, condition, or text, by its key.
|
||||
pub var evaluated: outcomes; #! What evaluating worked out, which the program holds as data.
|
||||
var constant_data: dict<u64, u32>; #! The datum holding each constant evaluated, by its key.
|
||||
}
|
||||
|
||||
#! Provides read only access to how much the code is optimized: 0 not at all,
|
||||
#! 1 within each function, 2 inlining too.
|
||||
#! @param this The compiler.
|
||||
#! @returns How much.
|
||||
pub val lowerer::level: u32 {
|
||||
get => this.options.level;
|
||||
}
|
||||
|
||||
#! Makes a compiler of a program the checker has checked.
|
||||
#! @param checker The checker.
|
||||
#! @param options How the code is lowered.
|
||||
#! @returns The compiler.
|
||||
pub def lowerer::new(checker: &mut checker, options: lowering): lowerer {
|
||||
return lowerer {
|
||||
checker = checker,
|
||||
program = program::new(),
|
||||
options = options,
|
||||
layout_ids = dict::<u32, u32>::new(),
|
||||
referents = vector::<u32>::new(),
|
||||
signature_ids = dict::<u32, u32>::new(),
|
||||
function_ids = dict::<u64, u32>::new(),
|
||||
builtin_ids = dict::<u64, u32>::new(),
|
||||
lambda_ids = dict::<u64, u32>::new(),
|
||||
adapter_ids = dict::<u64, u32>::new(),
|
||||
global_ids = dict::<u32, u64>::new(),
|
||||
begun_globals = hashset::<u32>::new(),
|
||||
vtable_ids = dict::<u64, u32>::new(),
|
||||
retrait_ids = dict::<u64, u32>::new(),
|
||||
linked_ids = dict::<u32, u32>::new(),
|
||||
texts = interner::<string>::new(),
|
||||
text_data = vector::<u32>::new(),
|
||||
dispatches = dict::<u32, u32>::new(),
|
||||
lists = runs::<u32>::new(),
|
||||
queue = vector::<u32>::new(),
|
||||
problems = vector::<string>::new(),
|
||||
summaries = dict::<u64, keeping>::new(),
|
||||
pending = vector::<pending_scan>::new(),
|
||||
pending_ids = dict::<u64, u32>::new(),
|
||||
reader_of = vector::<u32>::new(),
|
||||
reader_next = vector::<u32>::new(),
|
||||
read_pairs = hashset::<u64>::new(),
|
||||
scanning = no_scan,
|
||||
dispatch = no_function,
|
||||
evaluations = vector::<evaluation>::new(),
|
||||
evaluation_ids = dict::<u64, u32>::new(),
|
||||
evaluated = outcomes::new(),
|
||||
constant_data = dict::<u64, u32>::new()
|
||||
};
|
||||
}
|
||||
|
||||
#! Lowers the program: the code initializing the globals, `main`, and every
|
||||
#! function they reach, then fills the vtables' maps between traits.
|
||||
#! @param this The compiler.
|
||||
#! @returns Whether everything was lowered, with nothing it could not lower.
|
||||
pub def lowerer::compile(&mut this): bool {
|
||||
# A program evaluating constants computes them, and runs nothing else.
|
||||
if this.options.evaluating {
|
||||
this.lower_evaluations();
|
||||
this.drain();
|
||||
this.fill_retraits();
|
||||
this.drain();
|
||||
return this.problems.length == 0;
|
||||
}
|
||||
|
||||
val main := this.checker.modules.decl(0, word::main);
|
||||
if main != 0 && this.checker.decls.kinds.p[main] == dk::function {
|
||||
this.program.main = this.function_of(main, 0);
|
||||
}
|
||||
|
||||
this.find_dispatch();
|
||||
val point := mark_scratch();
|
||||
this.program.init = this.lower_globals();
|
||||
release_scratch(point);
|
||||
if this.options.everything {
|
||||
this.want_everything();
|
||||
}
|
||||
this.drain();
|
||||
this.fill_retraits();
|
||||
this.drain();
|
||||
this.optimize();
|
||||
return this.problems.length == 0;
|
||||
}
|
||||
|
||||
#! Lowers the functions waiting, and those they reach in turn, each freeing
|
||||
#! the scratch memory it took as it ends.
|
||||
#! @param this The compiler.
|
||||
pub def lowerer::drain(&mut this): void {
|
||||
var at: u64 = 0;
|
||||
while at < this.queue.length {
|
||||
val point := mark_scratch();
|
||||
this.lower_function(this.queue[at]);
|
||||
release_scratch(point);
|
||||
at++;
|
||||
}
|
||||
this.queue.clear();
|
||||
}
|
||||
|
||||
#! Notes what lowering could not lower.
|
||||
#! @param this The compiler.
|
||||
#! @param file The file it is in.
|
||||
#! @param node Its node.
|
||||
#! @param what What it is, said in words.
|
||||
pub def lowerer::problem(&mut this, file: u32, node: u32, what: strview): void {
|
||||
val held := &this.checker.units[file].source;
|
||||
val at := held.lines.place_of(this.node_offset(file, node));
|
||||
this.problems.append($"{held.path}:{at.line}:{at.column}: {what}");
|
||||
}
|
||||
|
||||
#! The type of a function, or of an instance of it.
|
||||
#! @param this The compiler.
|
||||
#! @param decl The function's declaration.
|
||||
#! @param instance One more than the instance, or 0.
|
||||
#! @returns The type.
|
||||
pub def lowerer::type_of_function(&this, decl: u32, instance: u32): u32 {
|
||||
return instance != 0 ? this.checker.instances[instance - 1].kind : this.checker.decls.types.p[decl];
|
||||
}
|
||||
|
||||
#! The table of nodes a function's body was checked in: its instance's, whose
|
||||
#! instances are checked where they were not yet, or its file's, where it is no
|
||||
#! instance or the instance's body was never checked.
|
||||
#! @param this The compiler.
|
||||
#! @param decl The function's declaration.
|
||||
#! @param instance One more than the instance, or 0.
|
||||
#! @returns The table.
|
||||
pub def lowerer::body_table(&mut this, decl: u32, instance: u32): u32 {
|
||||
if instance != 0 {
|
||||
if this.checker.instances[instance - 1].table == 0 {
|
||||
this.check_instances();
|
||||
}
|
||||
val held: u32 = this.checker.instances[instance - 1].table;
|
||||
return held - 1 if held != 0;
|
||||
}
|
||||
return this.checker.units[this.checker.decls.files.p[decl]].table;
|
||||
}
|
||||
|
||||
#! The function a declaration is lowered to, given the instance of a generic it
|
||||
#! is, made and waiting to be lowered where it is new.
|
||||
#! @param this The compiler.
|
||||
#! @param decl The function's declaration.
|
||||
#! @param instance One more than the instance of the checker it is, or 0.
|
||||
#! @returns The function's index.
|
||||
pub def lowerer::function_of(&mut this, decl: u32, instance: u32): u32 {
|
||||
val key := pair_key(decl, instance);
|
||||
if this.function_ids.get(&key) is some(got) {
|
||||
return got;
|
||||
}
|
||||
|
||||
this.checker.resolve(decl);
|
||||
val kind := this.type_of_function(decl, instance);
|
||||
val index := this.add_function(this.function_name(decl, instance), this.signature_of(this.call_type(this.function_type(decl, kind))));
|
||||
this.function_ids.set(key, index);
|
||||
val node: u32 = this.checker.decls.nodes.p[decl];
|
||||
val file: u32 = this.checker.decls.files.p[decl];
|
||||
this.program.functions[index].decl = decl;
|
||||
this.program.functions[index].instance = instance;
|
||||
this.program.functions[index].file = file;
|
||||
this.program.functions[index].offset = this.node_offset(file, node);
|
||||
this.program.functions[index].callback = this.checker.decls.has(decl, df::callback);
|
||||
this.program.functions[index].inline = this.checker.decls.has(decl, df::inline);
|
||||
val name: u32 = this.checker.decls.names.p[decl];
|
||||
this.program.functions[index].stepping = this.checker.decls.has(decl, df::method)
|
||||
&& (name == word::next || name == word::next_back || name == word::invoke);
|
||||
this.want(index);
|
||||
return index;
|
||||
}
|
||||
|
||||
#! The function type a function is lowered with: its own, where a trait's
|
||||
#! default method takes `this` as a reference to the trait rather than to
|
||||
#! `self`, which only what implements it knows. A default compiled for each
|
||||
#! type takes its own type, as its type says.
|
||||
#! @param this The compiler.
|
||||
#! @param decl The function's declaration.
|
||||
#! @param kind Its function type, given its type arguments.
|
||||
#! @returns The function type.
|
||||
pub def lowerer::function_type(&mut this, decl: u32, kind: u32): u32 {
|
||||
val holder: u32 = this.checker.decls.owners.p[decl];
|
||||
val owner: u32 = holder != 0 && this.checker.decls.kinds.p[holder] == dk::property
|
||||
? this.checker.decls.owners.p[holder]
|
||||
: holder;
|
||||
return kind if owner == 0 || this.checker.decls.kinds.p[owner] != dk::trait_type
|
||||
|| !this.checker.decls.has(decl, df::method) || this.checker.typed_default(decl);
|
||||
|
||||
# An instance of a generic trait's default already takes the trait, given
|
||||
# its arguments.
|
||||
var params := this.checker.types.parts_of(kind);
|
||||
return kind if params.length == 0;
|
||||
val taken := this.checker.unalias(this.checker.types.first_of(params[0]));
|
||||
return kind if this.checker.named_kind(taken) == dk::trait_type;
|
||||
val writes := this.checker.decls.has(decl, df::mut_this);
|
||||
params[0] = this.checker.types.reference(this.checker.decls.types.p[owner], writes);
|
||||
return this.checker.types.function(params.view(), this.checker.types.first_of(kind), this.checker.types.second_of(kind) != 0);
|
||||
}
|
||||
|
||||
#! Adds a function of the program, lowered later.
|
||||
#! @param this The compiler.
|
||||
#! @param name Its name, as a trace writes it.
|
||||
#! @param signature How it is called.
|
||||
#! @returns Its index.
|
||||
pub def lowerer::add_function(&mut this, name: string, signature: u32): u32 {
|
||||
this.program.functions.append(function {
|
||||
name = move(&mut name),
|
||||
signature = signature,
|
||||
body = code::new(),
|
||||
compiled = bytecode::new(),
|
||||
order = vector::<u32>::new(),
|
||||
named = vector::<u32>::new()
|
||||
});
|
||||
return (this.program.functions.length - 1) as u32;
|
||||
}
|
||||
|
||||
#! Notes that a function's code names another as a value, each once.
|
||||
#! @param this The compiler.
|
||||
#! @param function The function naming it.
|
||||
#! @param named The function named.
|
||||
pub def lowerer::names(&mut this, function: u32, named: u32): void {
|
||||
for &each in this.program.functions[function].named.view() {
|
||||
return if each == named;
|
||||
}
|
||||
this.program.functions[function].named.append(named);
|
||||
}
|
||||
|
||||
#! Marks a function as named by code that runs, so it is lowered.
|
||||
#! @param this The compiler.
|
||||
#! @param index The function.
|
||||
pub def lowerer::want(&mut this, index: u32): void {
|
||||
return if this.program.functions[index].queued;
|
||||
this.program.functions[index].queued = true;
|
||||
this.queue.append(index);
|
||||
}
|
||||
|
||||
#! The name of a function as a trace writes it, as the C compiler names it: a
|
||||
#! method's names its type, as `vec2::normalize`, and an instance of a generic
|
||||
#! names its type arguments, as `max<i64>` and `list<i64>::push`.
|
||||
#! @param this The compiler.
|
||||
#! @param decl The function's declaration.
|
||||
#! @param instance One more than the instance of a generic it is, or 0.
|
||||
#! @returns The name.
|
||||
pub def lowerer::function_name(&mut this, decl: u32, instance: u32): string {
|
||||
var holder: u32 = this.checker.decls.owners.p[decl];
|
||||
if holder != 0 && this.checker.decls.kinds.p[holder] == dk::property {
|
||||
holder = this.checker.decls.owners.p[holder];
|
||||
}
|
||||
|
||||
# The type arguments of an instance are its owner's, then its own.
|
||||
val args := instance != 0 ? this.checker.types.parts_view(this.checker.instances[instance - 1].args) : span::<u32>::empty();
|
||||
val own := this.checker.own_param_count(decl) as u64;
|
||||
val outer := args.length > own ? args.length - own : 0;
|
||||
|
||||
var made := string::new(nothing {});
|
||||
if holder != 0 {
|
||||
made.append(this.checker.names.text(this.checker.decls.names.p[holder]));
|
||||
if outer != 0 {
|
||||
this.type_args(args, 0, outer, &mut made);
|
||||
}
|
||||
made.append("::");
|
||||
}
|
||||
made.append(this.checker.names.text(this.checker.decls.names.p[decl]));
|
||||
if own != 0 && args.length > outer {
|
||||
this.type_args(args, outer, args.length, &mut made);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Writes type arguments as a name shows them, `<i64, bool>`, a pack's types as
|
||||
#! the arguments they are, and an empty pack as none, as the checker writes them.
|
||||
#! @param this The compiler.
|
||||
#! @param args The type arguments.
|
||||
#! @param from The first written.
|
||||
#! @param to The one past the last written.
|
||||
#! @param out Where they are written.
|
||||
def lowerer::type_args(&this, args: span<u32>, from: u64, to: u64, out: &mut string): void {
|
||||
out.append("<");
|
||||
this.checker.describe_args(span::<u32>::over(args.data + from, to - from), out);
|
||||
out.append(">");
|
||||
}
|
||||
|
||||
#! The byte of a file a node begins at.
|
||||
#! @param this The compiler.
|
||||
#! @param file The file.
|
||||
#! @param node The node.
|
||||
#! @returns The byte.
|
||||
pub def lowerer::node_offset(&this, file: u32, node: u32): u32 {
|
||||
val syntax := &this.checker.units[file].syntax;
|
||||
return syntax.token_offsets[syntax.node_tokens[node]];
|
||||
}
|
||||
|
||||
#! Lowers a function waiting to be lowered.
|
||||
#! @param this The compiler.
|
||||
#! @param index The function.
|
||||
def lowerer::lower_function(&mut this, index: u32): void {
|
||||
return if this.program.functions[index].lowered;
|
||||
this.program.functions[index].lowered = true;
|
||||
|
||||
var made := emitter::new(this, index);
|
||||
made.lower();
|
||||
made.finish();
|
||||
}
|
||||
|
||||
#! The datum holding text, made where it is new: its bytes, followed by a zero
|
||||
#! the length does not count.
|
||||
#! @param this The compiler.
|
||||
#! @param text The text.
|
||||
#! @returns The datum's index.
|
||||
pub def lowerer::text_datum(&mut this, text: strview): u32 {
|
||||
# A text new to `texts` is given the next ID, which has no datum yet.
|
||||
val id := this.texts.intern_view(text);
|
||||
if id < this.text_data.length {
|
||||
return this.text_data[id];
|
||||
}
|
||||
|
||||
var bytes := vector::<u8>::new();
|
||||
bytes.extend(text);
|
||||
bytes.append(0);
|
||||
val index := this.program.data.length as u32;
|
||||
this.program.data.append(datum {
|
||||
bytes = move(&mut bytes),
|
||||
align = 1,
|
||||
relocations = vector::<relocation>::new()
|
||||
});
|
||||
this.text_data.append(index);
|
||||
return index;
|
||||
}
|
||||
|
||||
#! Places a global after those placed before it, where it is not yet placed.
|
||||
#! @param this The compiler.
|
||||
#! @param decl The global's declaration.
|
||||
#! @returns Where it is among the globals.
|
||||
pub def lowerer::global_of(&mut this, decl: u32): u64 {
|
||||
if this.global_ids.get(&decl) is some(got) {
|
||||
return got;
|
||||
}
|
||||
|
||||
this.checker.resolve(decl);
|
||||
val held := this.shape_of(this.checker.decls.types.p[decl]);
|
||||
this.program.globals = round_up(this.program.globals, held.align);
|
||||
val offset := this.program.globals;
|
||||
this.global_ids.set(decl, offset);
|
||||
this.program.globals += held.size;
|
||||
|
||||
# Evaluating, a byte between globals keeps an address just past one from being
|
||||
# where the next begins, so an empty view at the end of a constant's array is
|
||||
# still that constant's.
|
||||
if this.options.evaluating {
|
||||
this.program.globals += 1;
|
||||
}
|
||||
return offset;
|
||||
}
|
||||
|
||||
#! Places a global no declaration names after those placed before it, as what
|
||||
#! a global refers to that was made for it is.
|
||||
#! @param this The compiler.
|
||||
#! @param kind Its type.
|
||||
#! @returns Where it is among the globals.
|
||||
pub def lowerer::unnamed_global(&mut this, kind: u32): u64 {
|
||||
val held := this.shape_of(kind);
|
||||
this.program.globals = round_up(this.program.globals, held.align);
|
||||
val offset := this.program.globals;
|
||||
this.program.globals += held.size == 0 ? 1 : held.size;
|
||||
return offset;
|
||||
}
|
||||
|
||||
#! Asks for every function that is no generic's template, and has a body, as a
|
||||
#! library's tests want, rather than only those `main` reaches.
|
||||
#! @param this The lowerer.
|
||||
def lowerer::want_everything(&mut this): void {
|
||||
for id in 1..this.checker.decls.count {
|
||||
val decl := id as u32;
|
||||
continue if this.checker.decls.kinds.p[decl] != dk::function || this.checker.decls.has(decl, df::generic);
|
||||
continue if this.checker.decls.has(decl, df::intrinsic) || this.checker.decls.has(decl, df::failed);
|
||||
continue if !this.checker.has_body(decl) || this.trait_of_method(decl) != 0;
|
||||
this.function_of(decl, 0);
|
||||
}
|
||||
}
|
||||
|
||||
#! Gives the program safe points where it handles a signal, which is where
|
||||
#! anything calls `system::handle`: each calls `system::dispatch`, which runs
|
||||
#! the handlers of the signals that have come.
|
||||
#! @param this The lowerer.
|
||||
def lowerer::find_dispatch(&mut this): void {
|
||||
val sys := this.checker.modules.find(0, word::system);
|
||||
return if sys == 0;
|
||||
val handle := this.checker.modules.decl(sys, this.checker.names.intern(&"handle"));
|
||||
val dispatch := this.checker.modules.decl(sys, this.checker.names.intern(&"dispatch"));
|
||||
return if handle == 0 || dispatch == 0 || this.checker.decls.kinds.p[dispatch] != dk::function;
|
||||
|
||||
return if !this.checker.is_depended(handle);
|
||||
this.dispatch = this.function_of(dispatch, 0);
|
||||
}
|
||||
|
||||
#! Whether a declaration is `core`'s, std's, or `system`'s, whose code has no
|
||||
#! safe points.
|
||||
#! @param this The lowerer.
|
||||
#! @param decl The declaration.
|
||||
#! @returns Whether it is.
|
||||
pub def lowerer::in_std(&this, decl: u32): bool {
|
||||
var at: u32 = this.checker.decls.modules.p[decl];
|
||||
var steps := 0;
|
||||
while at != 0 && this.checker.modules.parents[at] != 0 && steps < 64 {
|
||||
at = this.checker.modules.parents[at];
|
||||
steps++;
|
||||
}
|
||||
return at != 0 && (this.checker.modules.names[at] == word::std
|
||||
|| this.checker.modules.names[at] == word::core
|
||||
|| this.checker.modules.names[at] == word::system);
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
#! @file constants.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the values computed while compiling: the constants, the
|
||||
#! conditions of the `if const` statements the checker left undecided, and the
|
||||
#! text of each `compile_error` it was given text it could not read.
|
||||
#!
|
||||
#! A program evaluating them is lowered first, with a function of its own for
|
||||
#! each, which computes the value into a global. Reading a constant stops that
|
||||
#! program unless the constant is evaluated, so the machine evaluates the one it
|
||||
#! needs first; and it stops reading what only a running program has, such as
|
||||
#! a variable given its value once it runs.
|
||||
#!
|
||||
#! The value each computes is kept as bytes laid out as its type, with the
|
||||
#! memory it points into, each address within them noted rather than written,
|
||||
#! since the memory it was computed in is the compiler's. The program then
|
||||
#! holds each as data, whose addresses are written where it is placed: a
|
||||
#! constant is read where its data is, and a condition decides its branch.
|
||||
|
||||
import sakura::analyzer;
|
||||
import std::containers;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! What stands for no block, where an address a value holds names a function.
|
||||
pub const no_block: u32 = 0xFFFFFFFF;
|
||||
|
||||
#! What stands for a block, where an address a value holds points into another
|
||||
#! constant's value, which `decl`, or `table` and `node`, name as for a function.
|
||||
pub const in_constant: u32 = 0xFFFFFFFE;
|
||||
|
||||
#! Where a value computed while compiling holds an address: of memory it points
|
||||
#! into, kept as a block, of another constant's value, or of a function, as a
|
||||
#! function value holds it.
|
||||
pub struct kept_address {
|
||||
pub var at: u64; #! The byte of the value or block the address is written at.
|
||||
pub var block: u32; #! The block it points into, `in_constant`, or `no_block` for a function.
|
||||
pub var addend: u64; #! How far into the block or the constant's value it points.
|
||||
pub var decl: u32; #! The function's or the global constant's declaration, or 0 for an anonymous function or a local constant.
|
||||
pub var instance: u32; #! One more than the instance of a generic it is, or 0.
|
||||
pub var table: u32; #! Of an anonymous function or a local constant, the result table of its nodes.
|
||||
pub var node: u32; #! Of an anonymous function, its `lambda` node, and of a local constant, its `variable` node.
|
||||
pub var file: u32; #! Of an anonymous function, its file.
|
||||
}
|
||||
|
||||
#! Memory a value computed while compiling points into.
|
||||
pub struct kept_block {
|
||||
pub var bytes: vector<u8>; #! What it holds.
|
||||
pub var addresses: vector<kept_address>; #! Where it holds addresses.
|
||||
}
|
||||
|
||||
#! A value computed while compiling: its bytes, laid out as its type is, and
|
||||
#! the memory it reaches.
|
||||
pub struct evaluated {
|
||||
pub var bytes: vector<u8>; #! The value.
|
||||
pub var addresses: vector<kept_address>; #! Where it holds addresses.
|
||||
pub var blocks: vector<kept_block>; #! The memory it points into, which addresses name by index.
|
||||
}
|
||||
|
||||
#! What evaluating worked out, by the key of each constant, condition, or text.
|
||||
pub struct outcomes {
|
||||
pub var values: dict<u64, evaluated>; #! The value of each constant.
|
||||
pub var decisions: dict<u64, bool>; #! Whether the condition of each `if const` holds.
|
||||
pub var texts: dict<u64, string>; #! What each `compile_error` evaluating reports says.
|
||||
}
|
||||
|
||||
#! Makes outcomes holding nothing.
|
||||
#! @returns The outcomes.
|
||||
pub def outcomes::new(): outcomes {
|
||||
return outcomes {
|
||||
values = dict::<u64, evaluated>::new(),
|
||||
decisions = dict::<u64, bool>::new(),
|
||||
texts = dict::<u64, string>::new()
|
||||
};
|
||||
}
|
||||
|
||||
#! The key of a global constant.
|
||||
#! @param decl Its declaration.
|
||||
#! @returns The key.
|
||||
pub def decl_key(decl: u32): u64 {
|
||||
return decl as u64;
|
||||
}
|
||||
|
||||
#! The key of a local constant, the condition of an `if const`, or the text of
|
||||
#! a `compile_error`: the result table it was checked in, and its node.
|
||||
#! @param table The table.
|
||||
#! @param node The `variable`, `if_const`, or `call` node.
|
||||
#! @returns The key.
|
||||
pub def node_key(table: u32, node: u32): u64 {
|
||||
return (1u << 63) | pair_key(table, node);
|
||||
}
|
||||
|
||||
#! A value computed while compiling, in the program evaluating them.
|
||||
pub struct evaluation {
|
||||
pub var key: u64; #! Its key.
|
||||
pub var decl: u32; #! The global constant, or 0.
|
||||
pub var table: u32; #! The result table a local constant, condition, or text was checked in.
|
||||
pub var node: u32; #! Its `variable`, `if_const`, or `call` node.
|
||||
pub var condition: bool; #! Whether it is the condition of an `if const`.
|
||||
pub var text: bool; #! Whether it is the text of a `compile_error`, its first argument.
|
||||
pub var kind: u32; #! The type of its value.
|
||||
pub var offset: u64; #! The global holding its value.
|
||||
pub var function: u32; #! The function computing it.
|
||||
}
|
||||
|
||||
#! Lowers the program evaluating what the checker left to evaluating: every
|
||||
#! global constant whose value is not a number it worked out, and the local
|
||||
#! constants, conditions of `if const`, and text of `compile_error` it noted.
|
||||
#! @param this The compiler.
|
||||
pub def lowerer::lower_evaluations(&mut this): void {
|
||||
for id in 1..this.checker.decls.count {
|
||||
val decl := id as u32;
|
||||
continue if !this.needs_evaluation(decl);
|
||||
this.evaluation_of(decl_key(decl), decl, 0, 0, false);
|
||||
}
|
||||
for i in 0..this.checker.to_evaluate.length {
|
||||
val each: u64 = this.checker.to_evaluate[i];
|
||||
val table := pair_high(each);
|
||||
val node := pair_low(each);
|
||||
val syntax := &this.checker.units[this.checker.tables.p[table].file].syntax;
|
||||
val condition := syntax.node_kinds[node] == nk::if_const;
|
||||
this.evaluation_of(node_key(table, node), 0, table, node, condition);
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether a declaration is a global constant whose value is evaluated: one the
|
||||
#! checker did not work out as a number, or one of a struct, a union, or an
|
||||
#! array.
|
||||
#! @param this The compiler.
|
||||
#! @param decl The declaration.
|
||||
#! @returns Whether it is.
|
||||
pub def lowerer::needs_evaluation(&mut this, decl: u32): bool {
|
||||
return false if this.checker.decls.kinds.p[decl] != dk::variable || !this.checker.decls.has(decl, df::constant);
|
||||
return false if this.checker.decls.has(decl, df::failed) || this.checker.decls.nodes.p[decl] == 0;
|
||||
val owner: u32 = this.checker.decls.owners.p[decl];
|
||||
return false if owner != 0 && this.checker.own_param_count(owner) != 0;
|
||||
|
||||
val saved := this.checker.at;
|
||||
this.checker.use_table(this.checker.units[this.checker.decls.files.p[decl]].table);
|
||||
val value := this.checker.record(this.checker.decls.nodes.p[decl], variable_slot::value);
|
||||
val known := value != 0 && this.checker.is_known(value) && this.is_scalar_type(this.checker.decls.types.p[decl]);
|
||||
this.checker.at = saved;
|
||||
return value != 0 && !known;
|
||||
}
|
||||
|
||||
#! Whether values of a type are one word, as a number, `bool`, enum, or pointer.
|
||||
#! @param this The compiler.
|
||||
#! @param kind The type.
|
||||
#! @returns Whether they are.
|
||||
pub def lowerer::is_scalar_type(&mut this, kind: u32): bool {
|
||||
return false if kind == bt::error || kind == bt::void_type || kind == 0;
|
||||
val plain := this.layout_type(kind);
|
||||
return this.checker.types.is_numeric(plain) || this.checker.types.is_boolean(plain)
|
||||
|| this.checker.named_kind(plain) == dk::enum_type || this.checker.types.kind_of(plain) == ty::pointer;
|
||||
}
|
||||
|
||||
#! The evaluation computing a constant, condition, or text, made where it is
|
||||
#! new: a global holding its value, and a function computing it there.
|
||||
#! @param this The compiler.
|
||||
#! @param key Its key.
|
||||
#! @param decl The global constant, or 0.
|
||||
#! @param table The result table of a local constant, condition, or text.
|
||||
#! @param node Its node: of text, the `compile_error` call.
|
||||
#! @param condition Whether it is the condition of an `if const`.
|
||||
#! @returns Its index.
|
||||
pub def lowerer::evaluation_of(&mut this, key: u64, decl: u32, table: u32, node: u32, condition: bool): u32 {
|
||||
if this.evaluation_ids.get(&key) is some(got) {
|
||||
return got;
|
||||
}
|
||||
|
||||
val saved := this.checker.at;
|
||||
var kind: u32 = bt::boolean;
|
||||
var offset: u64 = 0;
|
||||
var text := false;
|
||||
var name := string::new(nothing {});
|
||||
if decl != 0 {
|
||||
this.checker.resolve(decl);
|
||||
kind = this.checker.decls.types.p[decl];
|
||||
offset = this.global_of(decl);
|
||||
name.append(this.checker.names.text(this.checker.decls.names.p[decl]));
|
||||
} else {
|
||||
this.checker.use_table(table);
|
||||
text = !condition && this.checker.kind_of(node) == nk::call;
|
||||
if text {
|
||||
# Text is evaluated as the type it is given as, as a `string` that owns
|
||||
# its bytes, rather than the view `compile_error` takes of them.
|
||||
kind = this.checker.type_at(this.checker.run_at(this.checker.right_of(node), 0));
|
||||
name.append("<compile_error>");
|
||||
} else if !condition {
|
||||
kind = this.checker.type_at(node);
|
||||
name.append(this.checker.names.text(this.checker.name_of(node)));
|
||||
} else {
|
||||
name.append("<if const>");
|
||||
}
|
||||
val held := this.shape_of(kind);
|
||||
this.program.globals = round_up(this.program.globals, held.align);
|
||||
offset = this.program.globals;
|
||||
this.program.globals += (held.size == 0 ? word_size : held.size) + 1;
|
||||
}
|
||||
this.checker.at = saved;
|
||||
|
||||
val void_type := this.checker.types.function(span::<u32>::empty(), bt::void_type, false);
|
||||
val function := this.add_function(move(&mut name), this.signature_of(void_type));
|
||||
val index := this.evaluations.length as u32;
|
||||
this.evaluations.append(evaluation {
|
||||
key = key,
|
||||
decl = decl,
|
||||
table = table,
|
||||
node = node,
|
||||
condition = condition,
|
||||
text = text,
|
||||
kind = kind,
|
||||
offset = offset,
|
||||
function = function
|
||||
});
|
||||
this.evaluation_ids.set(key, index);
|
||||
this.program.functions[function].evaluation = index + 1;
|
||||
this.want(function);
|
||||
return index;
|
||||
}
|
||||
|
||||
#! Lowers the function computing an evaluation's value into its global.
|
||||
#! @param this The emitter.
|
||||
#! @param index The evaluation.
|
||||
pub def emitter::lower_evaluation(&mut this, index: u32): void {
|
||||
val held: evaluation = this.c.evaluations[index];
|
||||
var value: u32 = 0;
|
||||
if held.decl != 0 {
|
||||
this.table = this.c.checker.units[this.c.checker.decls.files.p[held.decl]].table;
|
||||
this.use_own_table();
|
||||
value = this.c.checker.record(this.c.checker.decls.nodes.p[held.decl], variable_slot::value);
|
||||
this.at_node(this.c.checker.decls.nodes.p[held.decl]);
|
||||
} else {
|
||||
this.table = held.table;
|
||||
this.use_own_table();
|
||||
if held.condition {
|
||||
value = this.c.checker.left_of(held.node);
|
||||
} else if held.text {
|
||||
value = this.c.checker.run_at(this.c.checker.right_of(held.node), 0);
|
||||
} else {
|
||||
value = this.c.checker.record(held.node, variable_slot::value);
|
||||
}
|
||||
this.at_node(held.node);
|
||||
}
|
||||
this.result = bt::void_type;
|
||||
this.plan_storage(value);
|
||||
|
||||
val mark := this.begin_statement();
|
||||
val address := this.build.value(op::global, span::<u32>::empty(), vt::word, 0, held.offset);
|
||||
val place := location { kind = held.kind, address = address };
|
||||
val made := this.value_as(value, held.kind);
|
||||
this.adopt(&made);
|
||||
this.store(&place, &made);
|
||||
this.end_statement(mark);
|
||||
this.build.ret(span::<u32>::empty());
|
||||
}
|
||||
|
||||
#! The data holding a value computed while compiling, made where it is new:
|
||||
#! the memory it points into first, then the value, each address within them
|
||||
#! written where the data is placed, and each function as it is numbered here.
|
||||
#! @param this The compiler.
|
||||
#! @param key The constant's key.
|
||||
#! @param kind Its type.
|
||||
#! @returns The datum, or `no_block` where nothing was evaluated for it.
|
||||
pub def lowerer::evaluated_datum(&mut this, key: u64, kind: u32): u32 {
|
||||
if this.constant_data.get(&key) is some(got) {
|
||||
return got;
|
||||
}
|
||||
return no_block if !this.evaluated.values.contains(&key);
|
||||
|
||||
# Each block is placed before any is written, since one may point into another.
|
||||
val count := this.evaluated.values[key].blocks.length;
|
||||
val first := this.program.data.length as u32;
|
||||
for _ in 0..count {
|
||||
this.program.data.append(datum { bytes = vector::<u8>::new(), align = 16, relocations = vector::<relocation>::new() });
|
||||
}
|
||||
for b in 0..count {
|
||||
var bytes := vector::<u8>::copy_of(&this.evaluated.values[key].blocks[b].bytes);
|
||||
var moved := vector::<relocation>::new();
|
||||
var addresses := vector::<kept_address>::copy_of(&this.evaluated.values[key].blocks[b].addresses);
|
||||
this.place_addresses(&mut bytes, &mut moved, addresses.view(), first);
|
||||
bytes.append(0);
|
||||
this.program.data[first as u64 + b].bytes = move(&mut bytes);
|
||||
this.program.data[first as u64 + b].relocations = move(&mut moved);
|
||||
}
|
||||
|
||||
var bytes := vector::<u8>::copy_of(&this.evaluated.values[key].bytes);
|
||||
var moved := vector::<relocation>::new();
|
||||
var addresses := vector::<kept_address>::copy_of(&this.evaluated.values[key].addresses);
|
||||
this.place_addresses(&mut bytes, &mut moved, addresses.view(), first);
|
||||
bytes.append(0);
|
||||
val shape := this.shape_of(kind);
|
||||
val index := this.program.data.length as u32;
|
||||
this.program.data.append(datum {
|
||||
bytes = move(&mut bytes),
|
||||
align = shape.align < word_size ? word_size : shape.align,
|
||||
relocations = move(&mut moved)
|
||||
});
|
||||
this.constant_data.set(key, index);
|
||||
return index;
|
||||
}
|
||||
|
||||
#! Writes the addresses a value computed while compiling holds: each of a
|
||||
#! block as a relocation into the data the block became, each into another
|
||||
#! constant as one into the data that constant's value is, and each function
|
||||
#! as its index here plus one.
|
||||
#! @param this The compiler.
|
||||
#! @param bytes The bytes holding them.
|
||||
#! @param moved Where the relocations are written.
|
||||
#! @param addresses The addresses.
|
||||
#! @param first The datum the first block became.
|
||||
def lowerer::place_addresses(&mut this, bytes: &mut vector<u8>, moved: &mut vector<relocation>, addresses: span<kept_address>, first: u32): void {
|
||||
for &each in addresses {
|
||||
if each.block == in_constant {
|
||||
# The constant was evaluated before the one pointing into it, so its data
|
||||
# never waits on this.
|
||||
moved.append(relocation { at = each.at, target = this.constant_datum(each.decl, each.table, each.node), addend = each.addend });
|
||||
continue;
|
||||
}
|
||||
if each.block != no_block {
|
||||
moved.append(relocation { at = each.at, target = first + each.block, addend = each.addend });
|
||||
continue;
|
||||
}
|
||||
var function: u32 = 0;
|
||||
if each.decl != 0 {
|
||||
function = this.function_of(each.decl, each.instance);
|
||||
} else {
|
||||
val saved := this.checker.at;
|
||||
this.checker.use_table(each.table);
|
||||
val kind := this.checker.type_at(each.node);
|
||||
this.checker.at = saved;
|
||||
function = this.lambda_of(each.table, each.node, each.file, kind, false);
|
||||
}
|
||||
this.program.functions[function].taken = true;
|
||||
val word := function as u64 + 1;
|
||||
write_number(bytes, each.at, word_size, word);
|
||||
}
|
||||
}
|
||||
|
||||
#! The data holding another constant's value, which an address a value holds
|
||||
#! points into, made where it is new.
|
||||
#! @param this The compiler.
|
||||
#! @param decl The global constant, or 0 for a local one.
|
||||
#! @param table Of a local constant, the result table it was checked in.
|
||||
#! @param node Of a local constant, its `variable` node.
|
||||
#! @returns The datum.
|
||||
def lowerer::constant_datum(&mut this, decl: u32, table: u32, node: u32): u32 {
|
||||
if decl != 0 {
|
||||
return this.evaluated_datum(decl_key(decl), this.checker.decls.types.p[decl]);
|
||||
}
|
||||
val saved := this.checker.at;
|
||||
this.checker.use_table(table);
|
||||
val kind := this.checker.type_at(node);
|
||||
this.checker.at = saved;
|
||||
return this.evaluated_datum(node_key(table, node), kind);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
#! @file conventions.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains what the machine and the native backend both know of how calls
|
||||
#! cross to C: how many words of a frame a value passed to a function of the
|
||||
#! program takes, and which aggregates Microsoft's ABI passes by value. The
|
||||
#! machine calls C through code of its own on Windows, and the native backend
|
||||
#! writes the code of each call, so both cross by these rules.
|
||||
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! How many words of a frame a value of a layout takes as an argument of a
|
||||
#! function of the program: the address of one held in memory, or its words.
|
||||
#! @param shape The layout.
|
||||
#! @returns How many.
|
||||
pub def argument_words(shape: &layout): u64 {
|
||||
return in_memory(shape) ? 1 : word_count(shape) as u64;
|
||||
}
|
||||
|
||||
#! Whether Microsoft's ABI passes an aggregate of a size by value, as an integer
|
||||
#! of as many bytes, which it does for one of 1, 2, 4, or 8 bytes. It passes any
|
||||
#! other by the address of a copy, and returns it through memory whose address
|
||||
#! the caller passes.
|
||||
#! @param size The aggregate's bytes.
|
||||
#! @returns Whether it does.
|
||||
pub def micro_by_value(size: u64): bool {
|
||||
return size == 1 || size == 2 || size == 4 || size == 8;
|
||||
}
|
||||
@@ -0,0 +1,427 @@
|
||||
#! @file dispatch.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains how calls reach the functions they call: the instance of a method
|
||||
#! a value of a generic type is given, the order a trait's vtables hold its
|
||||
#! methods in, each type's vtable for each trait it is referred to through, the
|
||||
#! maps a reference to one trait becomes one to another by, and the C functions
|
||||
#! the program calls by name.
|
||||
|
||||
import sakura::analyzer;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! What a method called on a value of a type reaches: a function of the
|
||||
#! program, or a trait's method, called through a vtable.
|
||||
pub struct target {
|
||||
var function: u32; #! The function called directly, or `no_function`.
|
||||
var holder: u32; #! The trait whose vtable is called through, or 0.
|
||||
var kind: u32; #! The method's function type, given the type's arguments.
|
||||
}
|
||||
|
||||
#! What a method called on a value of a type reaches: the instance of a generic
|
||||
#! type's method, given the type's arguments, a function of its own, or a
|
||||
#! trait's method, which a value of a type parameter or a reference to a trait
|
||||
#! calls through a vtable.
|
||||
#! @param this The compiler.
|
||||
#! @param decl The method's declaration.
|
||||
#! @param owner The type it is called on, read through its references.
|
||||
#! @returns What it reaches.
|
||||
pub def lowerer::method_target(&mut this, decl: u32, owner: u32): target {
|
||||
this.checker.resolve(decl);
|
||||
var holder: u32 = this.checker.decls.owners.p[decl];
|
||||
if holder != 0 && this.checker.decls.kinds.p[holder] == dk::property {
|
||||
holder = this.checker.decls.owners.p[holder];
|
||||
}
|
||||
val plain := this.checker.unalias(owner);
|
||||
if this.checker.trait_asks(decl) {
|
||||
val kind := this.checker.trait_method_type(decl, plain);
|
||||
val dynamic := this.checker.named_kind(plain) == dk::trait_type || this.checker.types.kind_of(plain) == ty::param;
|
||||
if dynamic || !this.checker.has_body(decl) {
|
||||
return target { function = no_function, holder = holder, kind = kind };
|
||||
}
|
||||
val own := span::<u32>::empty();
|
||||
return target { function = this.default_of(decl, this.checker.implemented(plain, holder), plain, own), kind = kind };
|
||||
}
|
||||
|
||||
if !this.checker.decls.has(decl, df::generic) {
|
||||
return target { function = this.function_of(decl, 0), kind = this.checker.decls.types.p[decl] };
|
||||
}
|
||||
|
||||
# A generic type's method is the instance its arguments give.
|
||||
var args := vector::<u32>::new();
|
||||
if this.checker.types.kind_of(plain) == ty::named {
|
||||
for i in 0..this.checker.types.part_count(plain) {
|
||||
args.append(this.checker.types.part_at(plain, i as u32));
|
||||
}
|
||||
}
|
||||
val instance := this.checker.instance_of(decl, args.view(), 0);
|
||||
if instance == 0 {
|
||||
return target { function = this.function_of(decl, 0), kind = this.checker.method_type(decl, plain) };
|
||||
}
|
||||
return target {
|
||||
function = this.function_of(decl, instance),
|
||||
kind = this.checker.instances[instance - 1].kind
|
||||
};
|
||||
}
|
||||
|
||||
#! Checks the bodies of the instances asked for since the checker last did,
|
||||
#! which lowering asks for where it calls a method the checker only looked up,
|
||||
#! as a loop's `next` or a value's `close`.
|
||||
#! @param this The compiler.
|
||||
pub def lowerer::check_instances(&mut this): void {
|
||||
val notes := this.checker.notes_made;
|
||||
this.checker.check_wanted();
|
||||
if this.checker.notes_made != notes {
|
||||
this.problems.append("Checking an instance lowering asked for made notes.");
|
||||
}
|
||||
}
|
||||
|
||||
#! The methods of a trait in the order its vtables hold them: what it takes on
|
||||
#! from the traits it composes, in order, and then what it declares itself, the
|
||||
#! accessors of a property among them. A member taken on is numbered by each
|
||||
#! trait taking it in its own order.
|
||||
#! @param this The compiler.
|
||||
#! @param holder The trait's declaration.
|
||||
#! @returns The run of the methods in `lists`.
|
||||
pub def lowerer::dispatch_of(&mut this, holder: u32): u32 {
|
||||
if this.dispatches.get(&holder) is some(got) {
|
||||
return got;
|
||||
}
|
||||
|
||||
var methods := vector::<u32>::new();
|
||||
this.collect_dispatch(holder, &mut methods, 0);
|
||||
val run := this.lists.add(methods.view());
|
||||
this.dispatches.set(holder, run);
|
||||
return run;
|
||||
}
|
||||
|
||||
#! Collects the methods a trait's vtables hold, those of the traits it composes
|
||||
#! first, each once.
|
||||
#! @param this The compiler.
|
||||
#! @param holder The trait's declaration.
|
||||
#! @param methods Where they are collected.
|
||||
#! @param depth How deeply composition has been followed.
|
||||
def lowerer::collect_dispatch(&mut this, holder: u32, methods: &mut vector<u32>, depth: u32): void {
|
||||
return if depth > 16;
|
||||
val composed := this.checker.composed_of(holder);
|
||||
for i in 0..this.checker.decls.list_length(composed) {
|
||||
val inner := this.checker.types.first_of(this.checker.decls.list_at(composed, i as u32));
|
||||
this.collect_dispatch(inner, methods, depth + 1);
|
||||
}
|
||||
|
||||
val run: u32 = this.checker.decls.children.p[holder];
|
||||
for i in 0..this.checker.decls.list_length(run) {
|
||||
val member := this.checker.decls.list_at(run, i as u32);
|
||||
match this.checker.decls.kinds.p[member] {
|
||||
dk::function => this.add_method(member, methods);
|
||||
dk::property => {
|
||||
val accessors: u32 = this.checker.decls.children.p[member];
|
||||
for j in 0..this.checker.decls.list_length(accessors) {
|
||||
this.add_method(this.checker.decls.list_at(accessors, j as u32), methods);
|
||||
}
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Adds a method to those a vtable holds, where it is not there already.
|
||||
#! @param this The compiler.
|
||||
#! @param method The method's declaration.
|
||||
#! @param methods The methods so far.
|
||||
def lowerer::add_method(&mut this, method: u32, methods: &mut vector<u32>): void {
|
||||
return if methods.view().contains(&method);
|
||||
methods.append(method);
|
||||
}
|
||||
|
||||
#! The slot of a method among those a trait's vtables hold.
|
||||
#! @param this The compiler.
|
||||
#! @param holder The trait's declaration.
|
||||
#! @param method The method's declaration.
|
||||
#! @returns The slot.
|
||||
pub def lowerer::dispatch_index(&mut this, holder: u32, method: u32): u32 {
|
||||
val run := this.dispatch_of(holder);
|
||||
if this.lists.view(run).index_of(&method) is some(slot) {
|
||||
return slot as u32;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! The signature a call through a trait's vtable passes arguments by: the
|
||||
#! method's, taking `this` as a reference to the trait, and giving the type the
|
||||
#! call gives, which a generic trait's method gives in terms of the trait's
|
||||
#! arguments.
|
||||
#! @param this The compiler.
|
||||
#! @param method The method's declaration.
|
||||
#! @param holder The trait referred to.
|
||||
#! @param result The type the call gives.
|
||||
#! @returns The signature's index.
|
||||
pub def lowerer::trait_signature(&mut this, method: u32, holder: u32, result: u32, trait_kind: u32 = 0): u32 {
|
||||
this.checker.resolve(method);
|
||||
# A trait's method in terms of the arguments of the trait referred to, as a
|
||||
# pack it takes is the parameters of its types.
|
||||
val kind: u32 = trait_kind != 0
|
||||
? this.checker.requirement_type(method, this.checker.bound_for(trait_kind, this.trait_of_method(method)), trait_kind)
|
||||
: this.checker.decls.types.p[method];
|
||||
var params := this.checker.types.parts_of(kind);
|
||||
if params.length != 0 {
|
||||
params[0] = this.checker.types.reference(this.checker.decls.types.p[holder], this.checker.decls.has(method, df::mut_this));
|
||||
}
|
||||
val made := this.checker.types.function(params.view(), result, this.checker.types.second_of(kind) != 0);
|
||||
return this.signature_of(this.call_type(made));
|
||||
}
|
||||
|
||||
#! The vtable of a type for a trait it implements, made where it is new, which
|
||||
#! names the function giving each of the trait's methods, or the trait's default
|
||||
#! where the type gives none.
|
||||
#! @param this The compiler.
|
||||
#! @param kind The type referred to.
|
||||
#! @param trait_kind The trait's type, given its arguments.
|
||||
#! @returns The vtable's index.
|
||||
pub def lowerer::vtable_of(&mut this, kind: u32, trait_kind: u32): u32 {
|
||||
# An alias's methods come before those of what it stands for, so its vtable
|
||||
# is its own.
|
||||
val plain := this.checker.unalias(kind);
|
||||
val key := pair_key(kind, trait_kind);
|
||||
if this.vtable_ids.get(&key) is some(got) {
|
||||
return got;
|
||||
}
|
||||
|
||||
# Placed before its slots are filled, which may make more vtables.
|
||||
val holder := this.checker.types.first_of(trait_kind);
|
||||
val index := this.program.vtables.length as u32;
|
||||
this.program.vtables.append(vtable {
|
||||
type_id = kind,
|
||||
trait_id = trait_kind,
|
||||
layout = this.layout_of(plain),
|
||||
functions = vector::<u32>::new(),
|
||||
owners = vector::<u32>::new()
|
||||
});
|
||||
this.vtable_ids.set(key, index);
|
||||
|
||||
# Read by place, since making the vtables its slots name may add runs.
|
||||
val run := this.dispatch_of(holder);
|
||||
for i in 0..this.lists.length(run) {
|
||||
val method: u32 = this.lists.at(run, i);
|
||||
var function := no_function;
|
||||
var owner := index;
|
||||
val found := this.implementation(kind, method, trait_kind);
|
||||
if found != 0 && this.trait_of_method(found) == 0 {
|
||||
function = this.method_target(found, kind).function;
|
||||
} else if this.checker.has_body(method) {
|
||||
# The default addresses the slots of the trait declaring it.
|
||||
val declarer := this.trait_of_method(method);
|
||||
val declaring := this.checker.bound_for(trait_kind, declarer);
|
||||
function = this.default_of(method, declaring, plain, span::<u32>::empty());
|
||||
if declarer != holder {
|
||||
owner = this.vtable_of(kind, declaring);
|
||||
}
|
||||
} else if found != 0 && this.checker.has_body(found) {
|
||||
function = this.default_of(found, this.checker.bound_for(trait_kind, this.trait_of_method(found)), plain, span::<u32>::empty());
|
||||
} else if found == 0 {
|
||||
# A built-in type's method is a function the compiler makes.
|
||||
function = this.builtin_function(plain, this.checker.decls.names.p[method]);
|
||||
}
|
||||
this.program.vtables[index].functions.append(function);
|
||||
this.program.vtables[index].owners.append(owner);
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
#! The function a trait's default method is, for the trait given its
|
||||
#! arguments: an instance of it where the trait is generic, so its body is
|
||||
#! lowered with the types the arguments give, or for the type taking it, where
|
||||
#! the trait is only a bound.
|
||||
#! @param this The compiler.
|
||||
#! @param method The default's declaration.
|
||||
#! @param trait_kind The trait declaring it, given its arguments.
|
||||
#! @param self_kind The type taking it.
|
||||
#! @param own The default's own type arguments.
|
||||
#! @returns The function's index.
|
||||
pub def lowerer::default_of(&mut this, method: u32, trait_kind: u32, self_kind: u32, own: span<u32>): u32 {
|
||||
return this.function_of(method, this.checker.default_instance(method, trait_kind, self_kind, own));
|
||||
}
|
||||
|
||||
#! The trait a method is a member of, directly or as a property's accessor, or
|
||||
#! 0.
|
||||
#! @param this The compiler.
|
||||
#! @param method The method's declaration.
|
||||
#! @returns The trait's declaration, or 0.
|
||||
pub def lowerer::trait_of_method(&this, method: u32): u32 {
|
||||
var owner: u32 = this.checker.decls.owners.p[method];
|
||||
if owner != 0 && this.checker.decls.kinds.p[owner] == dk::property {
|
||||
owner = this.checker.decls.owners.p[owner];
|
||||
}
|
||||
return this.checker.trait_asks(method) ? owner : 0;
|
||||
}
|
||||
|
||||
#! The method of a type implementing a trait's: of its overloads, the one taking
|
||||
#! what the trait's does, or the trait's default where the type has none.
|
||||
#! @param this The compiler.
|
||||
#! @param kind The type.
|
||||
#! @param method The trait's method.
|
||||
#! @returns The type's method, or 0.
|
||||
def lowerer::implementation(&mut this, kind: u32, method: u32, trait_kind: u32): u32 {
|
||||
# A property's accessor is found through the property of its name.
|
||||
var name: u32 = this.checker.decls.names.p[method];
|
||||
val setter := this.checker.decls.has(method, df::setter);
|
||||
val accessor := this.checker.decls.has(method, df::accessor);
|
||||
val found := this.checker.find_member(kind, name);
|
||||
return 0 if found.decl == 0;
|
||||
|
||||
if accessor {
|
||||
return 0 if this.checker.decls.kinds.p[found.decl] != dk::property;
|
||||
val run: u32 = this.checker.decls.children.p[found.decl];
|
||||
for i in 0..this.checker.decls.list_length(run) {
|
||||
val each := this.checker.decls.list_at(run, i as u32);
|
||||
return each if this.checker.decls.has(each, df::setter) == setter;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
# Of overloads, the one with the method's shape, in terms of the trait's
|
||||
# arguments, as a pack it takes is the parameters of its types: as many
|
||||
# parameters, and `&mut this` where it takes it, or else `&this`, which meets
|
||||
# it too.
|
||||
this.checker.resolve(method);
|
||||
val asked := this.checker.requirement_type(method, this.checker.bound_for(trait_kind, this.trait_of_method(method)), kind);
|
||||
val wanted := this.checker.types.part_count(asked);
|
||||
var first: u32 = 0;
|
||||
var counted: u32 = 0;
|
||||
var walk := this.checker.decls.walk_overloads(found.decl);
|
||||
while true {
|
||||
val at := walk.next();
|
||||
break if at == 0;
|
||||
if this.checker.decls.kinds.p[at] == dk::function && this.checker.decls.has(at, df::method) {
|
||||
this.checker.resolve(at);
|
||||
val count := this.checker.types.part_count(this.checker.decls.types.p[at]);
|
||||
if first == 0 {
|
||||
first = at;
|
||||
}
|
||||
if count == wanted && counted == 0 {
|
||||
counted = at;
|
||||
}
|
||||
if count == wanted && this.checker.decls.has(at, df::mut_this) == this.checker.decls.has(method, df::mut_this) {
|
||||
return at;
|
||||
}
|
||||
}
|
||||
}
|
||||
return counted != 0 ? counted : first;
|
||||
}
|
||||
|
||||
#! The map a reference to one trait becomes one to another by, made where it is
|
||||
#! new, and filled once every vtable is made.
|
||||
#! @param this The compiler.
|
||||
#! @param from The trait's type converted from.
|
||||
#! @param to The trait's type converted to.
|
||||
#! @returns The map's index.
|
||||
pub def lowerer::retrait_of(&mut this, from: u32, to: u32): u32 {
|
||||
val key := pair_key(from, to);
|
||||
if this.retrait_ids.get(&key) is some(got) {
|
||||
return got;
|
||||
}
|
||||
val index := this.program.retraits.length as u32;
|
||||
this.program.retraits.append(retrait { from = from, to = to, vtables = vector::<u32>::new() });
|
||||
this.retrait_ids.set(key, index);
|
||||
return index;
|
||||
}
|
||||
|
||||
#! Fills each map between traits with the vtable each vtable of its trait
|
||||
#! becomes, once the code is lowered. Making a vtable of a trait converted to
|
||||
#! may make more, so every map is settled before any is filled.
|
||||
#! @param this The compiler.
|
||||
pub def lowerer::fill_retraits(&mut this): void {
|
||||
return if this.program.retraits.length == 0;
|
||||
var done: u64 = 0;
|
||||
while done < this.program.vtables.length {
|
||||
val count := this.program.vtables.length;
|
||||
for v in done..count {
|
||||
for i in 0..this.program.retraits.length {
|
||||
val from: u32 = this.program.retraits[i].from;
|
||||
val to: u32 = this.program.retraits[i].to;
|
||||
if this.program.vtables[v].trait_id == from {
|
||||
this.vtable_of(this.program.vtables[v].type_id, to);
|
||||
}
|
||||
}
|
||||
}
|
||||
done = count;
|
||||
}
|
||||
|
||||
for i in 0..this.program.retraits.length {
|
||||
var map := vector::<u32>::new();
|
||||
for v in 0..this.program.vtables.length {
|
||||
val held_trait: u32 = this.program.vtables[v].trait_id;
|
||||
if held_trait == this.program.retraits[i].from {
|
||||
map.append(this.vtable_of(this.program.vtables[v].type_id, this.program.retraits[i].to));
|
||||
} else {
|
||||
map.append(0);
|
||||
}
|
||||
}
|
||||
this.program.retraits[i].vtables = move(&mut map);
|
||||
}
|
||||
}
|
||||
|
||||
#! The C function a declaration of an `extern module` without a body calls,
|
||||
#! among those the program links, found by its name in its file's libraries.
|
||||
#! @param this The compiler.
|
||||
#! @param decl The declaration.
|
||||
#! @returns The C function's index.
|
||||
pub def lowerer::linked_of(&mut this, decl: u32): u32 {
|
||||
if this.linked_ids.get(&decl) is some(got) {
|
||||
return got;
|
||||
}
|
||||
val index := this.program.linked.length as u32;
|
||||
var libraries := this.libraries_of(decl);
|
||||
var first := libraries.length != 0 ? string::copy_of(&libraries[0]) : string::new(nothing {});
|
||||
this.program.linked.append(linked {
|
||||
name = this.checker.decls.names.p[decl],
|
||||
library = move(&mut first),
|
||||
libraries = move(&mut libraries),
|
||||
decl = decl
|
||||
});
|
||||
this.linked_ids.set(decl, index);
|
||||
return index;
|
||||
}
|
||||
|
||||
#! The libraries a C function may be found in: those its file's `extern import`s
|
||||
#! name for the target, or none for one the running program has.
|
||||
#! @param this The lowerer.
|
||||
#! @param decl The function's declaration.
|
||||
#! @returns The libraries.
|
||||
def lowerer::libraries_of(&mut this, decl: u32): vector<string> {
|
||||
var libraries := vector::<string>::new();
|
||||
val file: u32 = this.checker.decls.files.p[decl];
|
||||
val saved := this.checker.at;
|
||||
this.checker.use_table(this.checker.units[file].table);
|
||||
for &each in this.checker.libraries {
|
||||
continue if (each >> 32) as u32 != file;
|
||||
val written := this.checker.text_of(this.checker.left_of(each as u32));
|
||||
var text := string::new(nothing {});
|
||||
this.checker.decode_text(written.substr(1, written.length < 2 ? 0 : written.length - 2), &mut text);
|
||||
libraries.append(move(&mut text));
|
||||
}
|
||||
|
||||
this.checker.at = saved;
|
||||
return libraries;
|
||||
}
|
||||
|
||||
#! The function type as the code of a function takes its parameters: a variadic
|
||||
#! one's last as a view of what it is given.
|
||||
#! @param this The compiler.
|
||||
#! @param kind The function type.
|
||||
#! @returns The type.
|
||||
pub def lowerer::call_type(&mut this, kind: u32): u32 {
|
||||
val plain := this.checker.unalias(kind);
|
||||
val count := this.checker.types.part_count(plain);
|
||||
return plain if this.checker.types.kind_of(plain) != ty::function || this.checker.types.second_of(plain) == 0 || count == 0;
|
||||
|
||||
var params := this.checker.types.parts_of(plain);
|
||||
val last: u32 = params.last();
|
||||
if this.checker.types.kind_of(last) != ty::pack {
|
||||
params.last() = this.checker.span_of(last);
|
||||
}
|
||||
return this.checker.types.function(params.view(), this.checker.types.first_of(plain), false);
|
||||
}
|
||||
@@ -0,0 +1,699 @@
|
||||
#! @file emitter.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the emitter, which lowers one function's body to intermediate code:
|
||||
#! where each local is held, the scopes that close them, the values a
|
||||
#! statement makes that close and no place owns yet, and the cells of the
|
||||
#! frame what is held in memory lives in. What it does with each part of the
|
||||
#! language is split across the files of the `emitter` directory.
|
||||
|
||||
import sakura::analyzer;
|
||||
import std::containers;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! A value as lowering holds it: the words it is, or the address of the memory
|
||||
#! holding it, which a struct, union, or fixed array is held in.
|
||||
pub struct operand {
|
||||
var kind: u32; #! Its type.
|
||||
var count: u32; #! How many words it is, where it is held as words.
|
||||
var words: u32[2]; #! Its words.
|
||||
var address: u32; #! The address of its memory, where it is held there, or 0.
|
||||
}
|
||||
|
||||
#! Where a value is: in variables of the builder, or in memory.
|
||||
pub struct location {
|
||||
var kind: u32; #! The type of what is there.
|
||||
var held: bool; #! Whether it is in variables rather than memory.
|
||||
var vars: u32[2]; #! The variable of each word, where it is in variables.
|
||||
var address: u32; #! The address its memory is reached from.
|
||||
var offset: u64; #! How many bytes past the address it is.
|
||||
var framed: bool; #! Whether the memory is in the frame, which a reference to it refers to while the frame lasts.
|
||||
}
|
||||
|
||||
#! How a local is held.
|
||||
pub enum held_as : u8 {
|
||||
words, #! As the values of variables, where it is a word or a few.
|
||||
cell, #! In a cell of the frame, where it is in memory or referred to.
|
||||
}
|
||||
|
||||
#! A local the emitter knows: a variable, a parameter, or a name a test or a
|
||||
#! loop gives.
|
||||
pub struct local_info {
|
||||
var node: u32; #! The node declaring it.
|
||||
var place: location; #! Where it is.
|
||||
var closes: bool; #! Whether it is closed where its scope ends.
|
||||
var pack: u32; #! Of a pack, the first of its values in `packs`, and `count` how many.
|
||||
var count: u32; #! Of a pack, how many values it holds.
|
||||
var record: u32; #! One more than its variable among the code's, or 0.
|
||||
var checks: bool; #! Whether it is an `ensures`, which is checked where its scope ends rather than closed.
|
||||
}
|
||||
|
||||
#! A value a statement made that closes and no place owns, which the statement
|
||||
#! closes where it ends, where the flag says it was made.
|
||||
pub struct kept_value {
|
||||
var address: u32; #! The address of its memory.
|
||||
var cell: u32; #! One more than the cell holding it, whose address is taken again where it closes, or 0.
|
||||
var kind: u32; #! Its type.
|
||||
var flag: u32; #! The variable saying whether it was made, 1, or not, 0.
|
||||
}
|
||||
|
||||
#! A loop being lowered, which `break` and `continue` leave.
|
||||
pub struct loop_info {
|
||||
var exit: u32; #! The block `break` goes to.
|
||||
var next: u32; #! The block `continue` goes to.
|
||||
var locals: u64; #! How many locals there were before its body, which a jump out of it closes past.
|
||||
var kept: u64; #! How many kept values there were before its body, which a jump out of it closes past.
|
||||
}
|
||||
|
||||
#! The call whose defaults are being made, which a default asks where it is,
|
||||
#! or the text of what it was given.
|
||||
pub struct default_site {
|
||||
var node: u32; #! The call, or 0 where no default is being made.
|
||||
var file: u32; #! The file the call is in.
|
||||
var table: u32; #! The result table its nodes' results are in.
|
||||
var args: u32; #! The run of the arguments it writes.
|
||||
var params: u32; #! The run of the parameters of the function it calls.
|
||||
var skip: u32; #! How many parameters come before the first argument, as `this`.
|
||||
}
|
||||
|
||||
#! The emitter.
|
||||
pub struct emitter {
|
||||
var c: &mut lowerer; #! The compiler.
|
||||
var build: builder; #! What builds the code.
|
||||
var function: u32; #! The function being lowered.
|
||||
var table: u32; #! The result table its nodes' results are in.
|
||||
var result: u32; #! The type its `return` gives.
|
||||
var locals: vector<local_info>;#! The locals in scope, the innermost last.
|
||||
var local_ids: scoped_dict<u64, u32>; #! One more than the local each node declares, by its file and node, a change for each local in scope.
|
||||
var packs: vector<location>; #! The values packs hold.
|
||||
var kept: vector<kept_value>;#! The values made that close, which no place owns yet.
|
||||
var loops: vector<loop_info>; #! The loops around what is lowered, the innermost last.
|
||||
var storage: dict<u32, held_as>;#! How each local is held, by the node declaring it, where it is not in variables.
|
||||
var free: vector<u32>; #! The temporary cells free to be taken again.
|
||||
var lanes_cells: vector<bool>; #! Whether each cell is a temporary holding a vector, which only another vector takes again, so the cell is promoted to a vector, not words.
|
||||
var taken: vector<u32>; #! The temporary cells taken by the statements being lowered.
|
||||
var held: vector<u32>; #! The temporary cells holding kept values, freed once the values are closed or taken.
|
||||
var named: dict<u32, u64>; #! Of each variable of the builder holding a word of a named local, the local's variable among the code's, then which word, as `variable << 8 | word`.
|
||||
var defaulting: default_site; #! The call whose defaults are being made.
|
||||
var returned: operand; #! What a `return` gives, while the `ensures` it leaves are checked.
|
||||
var returning: bool; #! Whether a `return` giving a value is closing what it leaves.
|
||||
}
|
||||
|
||||
#! Makes an emitter of a function.
|
||||
#! @param c The compiler.
|
||||
#! @param function The function.
|
||||
#! @returns The emitter, whose builder takes the function's parameters.
|
||||
pub def emitter::new(c: &mut lowerer, function: u32): emitter {
|
||||
val signature: u32 = c.program.functions[function].signature;
|
||||
var params := c.param_types(signature);
|
||||
val result := c.layout_at(c.program.signatures[signature].result);
|
||||
# A closure is given its environment, a reference to what it captures.
|
||||
if c.program.functions[function].closure {
|
||||
params.append(vt::word);
|
||||
}
|
||||
|
||||
var made := emitter {
|
||||
c = c,
|
||||
build = builder::new(params.view()),
|
||||
function = function,
|
||||
locals = vector::<local_info>::new(scratch()),
|
||||
local_ids = scoped_dict::<u64, u32>::new(scratch()),
|
||||
packs = vector::<location>::new(scratch()),
|
||||
kept = vector::<kept_value>::new(scratch()),
|
||||
loops = vector::<loop_info>::new(scratch()),
|
||||
storage = dict::<u32, held_as>::new(scratch()),
|
||||
free = vector::<u32>::new(scratch()),
|
||||
lanes_cells = vector::<bool>::new(scratch()),
|
||||
taken = vector::<u32>::new(scratch()),
|
||||
held = vector::<u32>::new(scratch()),
|
||||
named = dict::<u32, u64>::new(scratch())
|
||||
};
|
||||
if !in_memory(&result) {
|
||||
for _ in 0..word_count(&result) {
|
||||
made.build.code.results.append(word_type(&result));
|
||||
}
|
||||
} else {
|
||||
made.build.code.returned = result.size as u32;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Finishes the code lowered and gives it to the function, verifying it where
|
||||
#! the options ask.
|
||||
#! @param this The emitter.
|
||||
pub def emitter::finish(&mut this): void {
|
||||
var body := this.build.finish();
|
||||
body.vectors = !this.c.options.evaluating && this.c.checker.names.text(this.c.checker.target.backend) == "native";
|
||||
if this.c.options.verify {
|
||||
val verdict := body.verify();
|
||||
for &each in verdict.problems {
|
||||
this.c.problems.append($"{this.c.program.functions[this.function].name}: {each}");
|
||||
}
|
||||
}
|
||||
this.c.program.functions[this.function].body = move(&mut body);
|
||||
}
|
||||
|
||||
#! Makes the function's result table the one the checker reads results from.
|
||||
#! @param this The emitter.
|
||||
pub def emitter::use_own_table(&mut this): void {
|
||||
this.c.checker.use_table(this.table);
|
||||
}
|
||||
|
||||
#! Notes what lowering could not lower, at a node.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node.
|
||||
#! @param what What it is, said in words.
|
||||
pub def emitter::problem(&mut this, node: u32, what: strview): void {
|
||||
if node == 0 {
|
||||
this.c.problems.append($"{this.c.program.functions[this.function].name}: {what}");
|
||||
return;
|
||||
}
|
||||
this.c.problem(this.c.checker.at.file, node, what);
|
||||
}
|
||||
|
||||
#! Says where in the source the instructions added next are from.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node they are lowered from.
|
||||
pub def emitter::at_node(&mut this, node: u32): void {
|
||||
return if node == 0;
|
||||
this.build.pos = this.place_at(node);
|
||||
}
|
||||
|
||||
#! Where in the source a node is, as instructions and variables say: one more
|
||||
#! than its file above its byte.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node.
|
||||
#! @returns Where.
|
||||
def emitter::place_at(&this, node: u32): u64 {
|
||||
val file := this.c.checker.at.file;
|
||||
return pair_key(file + 1, this.c.node_offset(file, node));
|
||||
}
|
||||
|
||||
# Operands.
|
||||
|
||||
#! A value of no words, as `void` is.
|
||||
#! @param kind The type.
|
||||
#! @returns The operand.
|
||||
pub def operand::none(kind: u32): operand {
|
||||
return operand { kind = kind };
|
||||
}
|
||||
|
||||
#! A value of one word.
|
||||
#! @param kind The type.
|
||||
#! @param word The word.
|
||||
#! @returns The operand.
|
||||
pub def operand::one(kind: u32, word: u32): operand {
|
||||
var made := operand { kind = kind, count = 1 };
|
||||
made.words[0] = word;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A value of two words, as a reference to a trait or a function is.
|
||||
#! @param kind The type.
|
||||
#! @param a The first word.
|
||||
#! @param b The second.
|
||||
#! @returns The operand.
|
||||
pub def operand::two(kind: u32, a: u32, b: u32): operand {
|
||||
var made := operand { kind = kind, count = 2 };
|
||||
made.words[0] = a;
|
||||
made.words[1] = b;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A value held in memory.
|
||||
#! @param kind The type.
|
||||
#! @param address The address of its memory.
|
||||
#! @returns The operand.
|
||||
pub def operand::at(kind: u32, address: u32): operand {
|
||||
return operand { kind = kind, address = address };
|
||||
}
|
||||
|
||||
#! The values of the code an operand gives where it is passed: its words, or
|
||||
#! the address of its memory.
|
||||
#! @param this The operand.
|
||||
#! @param into Where they are appended.
|
||||
pub def operand::args(&this, into: &mut vector<u32>): void {
|
||||
if this.address != 0 {
|
||||
into.append(this.address);
|
||||
return;
|
||||
}
|
||||
for i in 0..this.count {
|
||||
into.append(this.words[i]);
|
||||
}
|
||||
}
|
||||
|
||||
# Cells.
|
||||
|
||||
#! A temporary cell of a size, which the statement taking it holds until it
|
||||
#! ends: one taken before and freed since where one fits.
|
||||
#! @param this The emitter.
|
||||
#! @param size How many bytes it holds.
|
||||
#! @param align What its address is a multiple of.
|
||||
#! @returns The cell.
|
||||
pub def emitter::temporary(&mut this, size: u64, align: u64): u32 {
|
||||
return this.temporary_for(size, align, false);
|
||||
}
|
||||
|
||||
#! A temporary cell, as `temporary` gives, holding a vector or not: a cell is
|
||||
#! taken again only for what it held before, a vector or not.
|
||||
#! @param this The emitter.
|
||||
#! @param size How many bytes it holds.
|
||||
#! @param align What its address is a multiple of.
|
||||
#! @param lanes Whether it holds a vector.
|
||||
#! @returns The cell.
|
||||
def emitter::temporary_for(&mut this, size: u64, align: u64, lanes: bool): u32 {
|
||||
val wanted := round_up(size == 0 ? word_size : size, word_size) as u32;
|
||||
val aligned := (align < word_size ? word_size : align) as u32;
|
||||
for i in 0..this.free.length {
|
||||
val cell: u32 = this.free[i];
|
||||
val held: cell = this.build.code.cells[cell];
|
||||
val vector := (cell as u64) < this.lanes_cells.length && this.lanes_cells[cell];
|
||||
if held.size == wanted && held.align >= aligned && vector == lanes {
|
||||
this.free.remove_at(i);
|
||||
this.taken.append(cell);
|
||||
return cell;
|
||||
}
|
||||
}
|
||||
val made := this.build.code.add_cell(wanted, aligned, ck::temporary, 0);
|
||||
if lanes {
|
||||
this.lanes_cells.resize(made as u64 + 1);
|
||||
this.lanes_cells[made] = true;
|
||||
}
|
||||
this.taken.append(made);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A temporary cell holding a value of a type, and its address.
|
||||
#! @param this The emitter.
|
||||
#! @param kind The type.
|
||||
#! @returns The address of the cell.
|
||||
pub def emitter::temporary_of(&mut this, kind: u32): u32 {
|
||||
val held := this.c.shape_of(kind);
|
||||
return this.build.cell_address(this.temporary_for(held.size, held.align, this.c.checker.is_lanes_type(kind)));
|
||||
}
|
||||
|
||||
#! How many temporary cells the statements being lowered have taken, which
|
||||
#! `release` frees those taken since.
|
||||
#! @param this The emitter.
|
||||
#! @returns The mark.
|
||||
pub def emitter::cell_mark(&this): u64 {
|
||||
return this.taken.length;
|
||||
}
|
||||
|
||||
#! Frees the temporary cells taken since a mark, to be taken again.
|
||||
#! @param this The emitter.
|
||||
#! @param mark How many were taken before.
|
||||
pub def emitter::release(&mut this, mark: u64): void {
|
||||
while this.taken.length > mark {
|
||||
val cell: u32 = this.taken.last();
|
||||
this.taken.truncate();
|
||||
# A cell holding a value the statement still closes is held until it does.
|
||||
var kept := false;
|
||||
for &each in this.kept {
|
||||
kept = kept || each.cell == cell + 1;
|
||||
}
|
||||
if kept {
|
||||
this.held.append(cell);
|
||||
} else {
|
||||
this.free.append(cell);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Frees the cell a kept value was held in, once it is closed or a place took
|
||||
#! it, where the statement's cells were released before.
|
||||
#! @param this The emitter.
|
||||
#! @param cell One more than the cell, or 0.
|
||||
def emitter::unhold(&mut this, cell: u32): void {
|
||||
return if cell == 0;
|
||||
for i in 0..this.held.length {
|
||||
if this.held[i] == cell - 1 {
|
||||
this.held.remove_at(i);
|
||||
this.free.append(cell - 1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# Locals.
|
||||
|
||||
#! The local a node of the file being read declares, or none. A local is
|
||||
#! known by its file as well as its node, since the defaults of a call name the
|
||||
#! parameters of a function of another file, whose nodes are counted apart, as
|
||||
#! the arguments written for them name the caller's locals.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node.
|
||||
#! @returns One more than the local's index, or 0.
|
||||
pub def emitter::local_of(&this, node: u32): u32 {
|
||||
return this.local_ids.get_or(&pair_key(this.c.checker.at.file, node), 0);
|
||||
}
|
||||
|
||||
#! Declares a local where it is.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node declaring it.
|
||||
#! @param place Where it is.
|
||||
#! @param closes Whether it is closed where its scope ends.
|
||||
#! @returns The local's index.
|
||||
pub def emitter::declare(&mut this, node: u32, place: location, closes: bool): u32 {
|
||||
val index := this.locals.length as u32;
|
||||
this.locals.append(local_info {
|
||||
node = node,
|
||||
place = place,
|
||||
closes = closes,
|
||||
record = this.describe(node, &place)
|
||||
});
|
||||
this.local_ids.set(pair_key(this.c.checker.at.file, node), index + 1);
|
||||
return index;
|
||||
}
|
||||
|
||||
#! Notes a local as a variable debugging information shows, where it is named
|
||||
#! and held in memory: in a cell, or the copy of a parameter given as memory.
|
||||
#! Where locals are kept for debugging information, one in an object of the
|
||||
#! heap is too, whose address a cell is given to hold.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node declaring it.
|
||||
#! @param place Where it is.
|
||||
#! @returns One more than the variable among the code's, or 0.
|
||||
def emitter::describe(&mut this, node: u32, place: &location): u32 {
|
||||
return 0 if node == 0 || place.held || place.address == 0 || place.offset != 0;
|
||||
val name := this.c.checker.param_name(node);
|
||||
return 0 if name == 0;
|
||||
val at := this.place_at(node);
|
||||
val param := this.c.checker.kind_of(node) == nk::param;
|
||||
val held: origin = this.build.code.origins[place.address];
|
||||
var cell: u32 = 0;
|
||||
var given: u32 = 0;
|
||||
if held.param {
|
||||
return 0 if held.from != 0 || !place.framed;
|
||||
given = held.index + 1;
|
||||
} else if this.build.code.insts[held.from].kind == op::cell {
|
||||
cell = this.build.code.insts[held.from].aux + 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
# Optimized code notes them only for debugging information.
|
||||
return 0 if !this.c.options.keep_locals && !this.c.options.describe;
|
||||
this.build.code.variables.append(variable_info {
|
||||
name = name, at = at, kind = place.kind, cell = cell, given = given, param = param,
|
||||
first = this.build.code.insts.length as u32
|
||||
});
|
||||
return this.build.code.variables.length as u32;
|
||||
}
|
||||
|
||||
#! Notes a local held in values as a variable debugging information shows,
|
||||
#! where it is named: one in variables of the builder, which each value they
|
||||
#! are given binds.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node declaring it.
|
||||
#! @param place Where it is.
|
||||
#! @param words How many words it is.
|
||||
def emitter::describe_held(&mut this, node: u32, place: &location, words: u64): void {
|
||||
return if !this.c.options.describe;
|
||||
val name := this.c.checker.param_name(node);
|
||||
return if name == 0;
|
||||
val at := this.place_at(node);
|
||||
val param := this.c.checker.kind_of(node) == nk::param;
|
||||
val index := this.build.code.variables.length as u32;
|
||||
this.build.code.variables.append(variable_info {
|
||||
name = name, at = at, kind = place.kind, param = param, held = true
|
||||
});
|
||||
for i in 0..words {
|
||||
this.named.set(place.vars[i], (index as u64 << 8) | i);
|
||||
}
|
||||
}
|
||||
|
||||
#! Binds a named local to a value given a variable of the builder holding one
|
||||
#! of its words, where it is one.
|
||||
#! @param this The emitter.
|
||||
#! @param held The variable of the builder.
|
||||
#! @param value The value.
|
||||
pub def emitter::bind(&mut this, held: u32, value: u32): void {
|
||||
if this.named.get(&held) is some(found) {
|
||||
this.bind_word((found >> 8) as u32, (found & 0xFF) as u32, value);
|
||||
}
|
||||
}
|
||||
|
||||
#! Binds a word of a variable held in values to a value, where the code being
|
||||
#! built is.
|
||||
#! @param this The emitter.
|
||||
#! @param variable The variable, among the code's.
|
||||
#! @param word Which of its words.
|
||||
#! @param value The value.
|
||||
def emitter::bind_word(&mut this, variable: u32, word: u32, value: u32): void {
|
||||
val block := this.build.at;
|
||||
this.build.code.bindings.append(binding {
|
||||
variable = variable, word = word, value = value, after = this.build.code.blocks[block].last, block = block
|
||||
});
|
||||
}
|
||||
|
||||
#! Makes a place for a local of a type declared by a node, held as the storage
|
||||
#! worked out for it says: in variables, or a cell.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node declaring it.
|
||||
#! @param kind Its type.
|
||||
#! @param cells The kind of cell it takes where it takes one: `undefined` for
|
||||
#! one the frame leaves as it is.
|
||||
#! @returns Where it is.
|
||||
pub def emitter::new_place(&mut this, node: u32, kind: u32, cells: ck = ck::local): location {
|
||||
val held := this.c.shape_of(kind);
|
||||
var how := this.storage.get_or(&node, held_as::words);
|
||||
if in_memory(&held) && how == held_as::words {
|
||||
how = held_as::cell;
|
||||
}
|
||||
if this.c.options.keep_locals && how == held_as::words && word_count(&held) != 0 {
|
||||
how = held_as::cell;
|
||||
}
|
||||
|
||||
match how {
|
||||
held_as::cell => {
|
||||
val name := this.c.checker.name_of(node);
|
||||
val made := this.build.code.add_cell(round_up(held.size == 0 ? word_size : held.size, word_size) as u32,
|
||||
held.align < word_size ? word_size as u32 : held.align as u32, cells, name);
|
||||
return location { kind = kind, address = this.build.cell_address(made), framed = true };
|
||||
}
|
||||
else => {
|
||||
var place := location { kind = kind, held = true };
|
||||
for i in 0..word_count(&held) {
|
||||
place.vars[i] = this.build.variable(word_type(&held));
|
||||
}
|
||||
if !this.c.options.keep_locals {
|
||||
this.describe_held(node, &place, word_count(&held));
|
||||
}
|
||||
return place;
|
||||
}
|
||||
}
|
||||
return location { kind = kind };
|
||||
}
|
||||
|
||||
#! How many locals are in scope, which `end_scope` closes those declared since.
|
||||
#! @param this The emitter.
|
||||
#! @returns The mark.
|
||||
pub def emitter::scope_mark(&this): u64 {
|
||||
return this.locals.length;
|
||||
}
|
||||
|
||||
#! Closes the locals declared since a mark, in the reverse of the order they
|
||||
#! were declared, but the one given back by name, and ends their scope.
|
||||
#! @param this The emitter.
|
||||
#! @param mark How many were in scope before.
|
||||
#! @param given The node of a local given back by name, which is not closed, or
|
||||
#! 0.
|
||||
pub def emitter::end_scope(&mut this, mark: u64, given: u32): void {
|
||||
this.close_locals(mark, given);
|
||||
this.forget_locals(mark);
|
||||
}
|
||||
|
||||
#! Ends the scope of the locals declared since a mark, without closing them.
|
||||
#! @param this The emitter.
|
||||
#! @param mark How many were in scope before.
|
||||
pub def emitter::forget_locals(&mut this, mark: u64): void {
|
||||
# Each local set the node declaring it once, so taking back the changes
|
||||
# since the mark gives each node the local it named before.
|
||||
while this.locals.length > mark {
|
||||
val record: u32 = this.locals.last().record;
|
||||
if record != 0 {
|
||||
this.build.code.variables[record as u64 - 1].end = this.build.code.insts.length as u32;
|
||||
}
|
||||
this.locals.truncate();
|
||||
}
|
||||
this.local_ids.rewind(mark);
|
||||
}
|
||||
|
||||
#! Closes the locals declared since a mark that close, in the reverse of the
|
||||
#! order they were declared, so each is closed while everything it was built
|
||||
#! from still stands, but the one given back by name.
|
||||
#! @param this The emitter.
|
||||
#! @param mark How many were in scope before.
|
||||
#! @param given The node of a local given back by name, or 0.
|
||||
pub def emitter::close_locals(&mut this, mark: u64, given: u32): void {
|
||||
var at := this.locals.length;
|
||||
while at > mark {
|
||||
at--;
|
||||
val held: local_info = this.locals[at];
|
||||
continue if !held.closes || held.node == given;
|
||||
if held.checks {
|
||||
this.check_ensures(held.node);
|
||||
continue;
|
||||
}
|
||||
# A pack closes each of its values, the last first.
|
||||
if held.count != 0 {
|
||||
var k := held.count;
|
||||
while k > 0 {
|
||||
k--;
|
||||
val each: location = this.packs[held.pack as u64 + k as u64];
|
||||
this.close(&each);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
this.close(&held.place);
|
||||
}
|
||||
}
|
||||
|
||||
# Kept values.
|
||||
|
||||
#! Keeps a value a statement made that closes, which no place owns yet, so the
|
||||
#! statement closes it where it ends unless a place takes it first.
|
||||
#! @param this The emitter.
|
||||
#! @param value The value, held in memory.
|
||||
pub def emitter::keep(&mut this, value: &operand): void {
|
||||
return if value.address == 0 || !this.c.checker.closes(value.kind);
|
||||
for &each in this.kept {
|
||||
return if each.address == value.address;
|
||||
}
|
||||
val flag := this.build.variable(vt::word);
|
||||
this.build.assign(flag, this.build.word(1));
|
||||
|
||||
# It may be made down one branch of the statement, and closed where they join,
|
||||
# so the address of the cell holding it is taken again there.
|
||||
var cell: u32 = 0;
|
||||
val held: origin = this.build.code.origins[value.address];
|
||||
if !held.param && this.build.code.insts[held.from].kind == op::cell {
|
||||
cell = this.build.code.insts[held.from].aux + 1;
|
||||
}
|
||||
this.kept.append(kept_value { address = value.address, cell = cell, kind = value.kind, flag = flag });
|
||||
}
|
||||
|
||||
#! Says a place took a kept value, so the statement no longer closes it.
|
||||
#! @param this The emitter.
|
||||
#! @param value The value.
|
||||
pub def emitter::adopt(&mut this, value: &operand): void {
|
||||
return if value.address == 0;
|
||||
var at := this.kept.length;
|
||||
while at > 0 {
|
||||
at--;
|
||||
if this.kept[at].address == value.address {
|
||||
val cell: u32 = this.kept[at].cell;
|
||||
this.kept.remove_at(at);
|
||||
this.unhold(cell);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Closes the values kept since a mark, in the reverse of the order they were
|
||||
#! made, each where it was made on the way here, and forgets them.
|
||||
#! @param this The emitter.
|
||||
#! @param mark How many were kept before.
|
||||
pub def emitter::close_kept(&mut this, mark: u64): void {
|
||||
this.leave_kept(mark);
|
||||
while this.kept.length > mark {
|
||||
val cell: u32 = this.kept.last().cell;
|
||||
this.kept.truncate();
|
||||
this.unhold(cell);
|
||||
}
|
||||
}
|
||||
|
||||
#! Forgets the values kept since a mark without closing them, where the program
|
||||
#! stops before they would be.
|
||||
#! @param this The emitter.
|
||||
#! @param mark How many were kept before.
|
||||
pub def emitter::drop_kept(&mut this, mark: u64): void {
|
||||
while this.kept.length > mark {
|
||||
val cell: u32 = this.kept.last().cell;
|
||||
this.kept.truncate();
|
||||
this.unhold(cell);
|
||||
}
|
||||
}
|
||||
|
||||
#! Closes the values kept since a mark, each where it was made on the way here,
|
||||
#! without forgetting them, as a jump out of the statements keeping them does.
|
||||
#! @param this The emitter.
|
||||
#! @param mark How many were kept before.
|
||||
pub def emitter::leave_kept(&mut this, mark: u64): void {
|
||||
var at := this.kept.length;
|
||||
while at > mark {
|
||||
at--;
|
||||
val held: kept_value = this.kept[at];
|
||||
val made := this.build.read(held.flag);
|
||||
# Each close forgets it was made, so a jump in a later pass of a loop, taken
|
||||
# before it is made again, does not close it twice.
|
||||
if this.is_one(made) {
|
||||
val place := location { kind = held.kind, address = held.address, framed = true };
|
||||
this.close(&place);
|
||||
this.build.assign(held.flag, this.build.word(0));
|
||||
continue;
|
||||
}
|
||||
val closing := this.build.new_block();
|
||||
val after := this.build.new_block();
|
||||
this.build.branch(made, closing, after);
|
||||
this.build.seal(closing);
|
||||
this.build.switch_to(closing);
|
||||
val address := held.cell != 0 ? this.build.cell_address(held.cell - 1) : held.address;
|
||||
val place := location { kind = held.kind, address = address, framed = true };
|
||||
this.close(&place);
|
||||
this.build.assign(held.flag, this.build.word(0));
|
||||
this.build.jump(after);
|
||||
this.build.seal(after);
|
||||
this.build.switch_to(after);
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether a value is the word 1, made where it is known to be.
|
||||
#! @param this The emitter.
|
||||
#! @param value The value.
|
||||
#! @returns Whether it is.
|
||||
pub def emitter::is_one(&this, value: u32): bool {
|
||||
val held: origin = this.build.code.origins[value];
|
||||
return false if held.param;
|
||||
val made: inst = this.build.code.insts[held.from];
|
||||
return made.kind == op::iconst && made.imm == 1;
|
||||
}
|
||||
|
||||
# Statements.
|
||||
|
||||
#! What a statement holds while it is lowered, which it lets go of once it ends.
|
||||
pub struct statement_mark {
|
||||
var cells: u64; #! The temporary cells taken before it.
|
||||
var kept: u64; #! The values kept before it.
|
||||
}
|
||||
|
||||
#! Begins a statement.
|
||||
#! @param this The emitter.
|
||||
#! @returns What it holds, as `end_statement` takes it.
|
||||
pub def emitter::begin_statement(&this): statement_mark {
|
||||
return statement_mark { cells = this.taken.length, kept = this.kept.length };
|
||||
}
|
||||
|
||||
#! Ends a statement: closes what it kept, and frees the cells it took.
|
||||
#! @param this The emitter.
|
||||
#! @param mark What it held, as `begin_statement` gave it.
|
||||
pub def emitter::end_statement(&mut this, mark: statement_mark): void {
|
||||
this.close_kept(mark.kept);
|
||||
this.release(mark.cells);
|
||||
}
|
||||
|
||||
#! A safe point, where the handlers of the signals that have come run. Only a
|
||||
#! program handling a signal has them, and only in its own functions, at the
|
||||
#! start of each and of each pass of each loop, so a handler never finds a
|
||||
#! container of std in the middle of a change.
|
||||
#! @param this The emitter.
|
||||
pub def emitter::safepoint(&mut this): void {
|
||||
return if this.c.dispatch == no_function;
|
||||
val held := &this.c.program.functions[this.function];
|
||||
val decl: u32 = held.decl != 0 ? held.decl : held.outer;
|
||||
return if decl == 0 || held.builtin != 0 || this.c.in_std(decl);
|
||||
this.build.effect(op::safepoint, span::<u32>::empty(), this.c.dispatch, 0);
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
#! @file bodies.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the lowering of a function's body: where its parameters are, its
|
||||
#! statements, and how it returns, closing its parameters as it does.
|
||||
|
||||
import sakura::analyzer;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! Lowers the function the emitter is of.
|
||||
#! @param this The emitter.
|
||||
pub def emitter::lower(&mut this): void {
|
||||
val decl: u32 = this.c.program.functions[this.function].decl;
|
||||
val instance: u32 = this.c.program.functions[this.function].instance;
|
||||
val lambda: u32 = this.c.program.functions[this.function].node;
|
||||
if this.c.program.functions[this.function].adapted != 0 {
|
||||
this.lower_adapter();
|
||||
return;
|
||||
}
|
||||
if lambda != 0 {
|
||||
this.lower_lambda(lambda);
|
||||
return;
|
||||
}
|
||||
if this.c.program.functions[this.function].builtin != 0 {
|
||||
this.lower_builtin();
|
||||
return;
|
||||
}
|
||||
val evaluation: u32 = this.c.program.functions[this.function].evaluation;
|
||||
if evaluation != 0 {
|
||||
this.lower_evaluation(evaluation - 1);
|
||||
return;
|
||||
}
|
||||
if decl == 0 {
|
||||
this.build.unreachable();
|
||||
return;
|
||||
}
|
||||
|
||||
val table := this.c.body_table(decl, instance);
|
||||
if instance != 0 && this.c.checker.instances[instance - 1].table == 0 {
|
||||
this.c.checker.use_table(table);
|
||||
this.problem(this.c.checker.decls.nodes.p[decl], "The instance's body was never checked.");
|
||||
this.build.unreachable();
|
||||
return;
|
||||
}
|
||||
this.table = table;
|
||||
this.use_own_table();
|
||||
|
||||
val node: u32 = this.c.checker.decls.nodes.p[decl];
|
||||
val accessor := this.c.checker.decls.has(decl, df::accessor);
|
||||
val body := accessor ? this.c.checker.record(node, accessor_slot::body) : this.c.checker.record(node, function_slot::body);
|
||||
val params := accessor ? this.c.checker.left_of(node) : this.c.checker.record(node, function_slot::params);
|
||||
val kind := this.c.type_of_function(decl, instance);
|
||||
this.at_node(node);
|
||||
this.result = this.c.checker.types.first_of(kind);
|
||||
|
||||
this.plan_function(decl, params, kind, body);
|
||||
this.take_params(decl, params, kind);
|
||||
this.safepoint();
|
||||
this.lower_body(body);
|
||||
}
|
||||
|
||||
#! Lowers a body: a block, which ends returning nothing where control falls off
|
||||
#! its end, or an expression, whose value is returned.
|
||||
#! @param this The emitter.
|
||||
#! @param body The body's node.
|
||||
pub def emitter::lower_body(&mut this, body: u32): void {
|
||||
if this.c.checker.kind_of(body) != nk::block {
|
||||
val mark := this.begin_statement();
|
||||
this.at_node(body);
|
||||
if this.c.checker.types.kind_of(this.c.layout_type(this.result)) == ty::void_type {
|
||||
this.value(body);
|
||||
this.end_statement(mark);
|
||||
this.close_locals(0, 0);
|
||||
this.build.ret(span::<u32>::empty());
|
||||
return;
|
||||
}
|
||||
this.return_value(body, mark);
|
||||
return;
|
||||
}
|
||||
|
||||
this.lower_block(body);
|
||||
return if this.build.ended();
|
||||
|
||||
# Running off the end returns, which a function giving a value never does.
|
||||
if this.c.checker.types.kind_of(this.c.layout_type(this.result)) == ty::void_type {
|
||||
this.close_locals(0, 0);
|
||||
this.build.ret(span::<u32>::empty());
|
||||
return;
|
||||
}
|
||||
this.build.trap(fault::unreachable as u32);
|
||||
}
|
||||
|
||||
#! Takes the function's parameters where its code is given them: each as a
|
||||
#! local, held as its storage says, and a pack's as one local holding each.
|
||||
#! @param this The emitter.
|
||||
#! @param decl The function's declaration.
|
||||
#! @param params The run of its parameters' nodes.
|
||||
#! @param kind Its function type, given its type arguments.
|
||||
def emitter::take_params(&mut this, decl: u32, params: u32, kind: u32): void {
|
||||
val signature: u32 = this.c.program.functions[this.function].signature;
|
||||
val count := this.c.checker.run_length(params);
|
||||
var next: u32 = 0;
|
||||
|
||||
# A pack parameter takes every parameter from its own on, one value of each.
|
||||
val written: u32 = this.c.checker.decls.types.p[decl];
|
||||
val wcount := this.c.checker.types.part_count(written);
|
||||
val packed := this.c.checker.decls.has(decl, df::variadic) && wcount != 0
|
||||
&& this.c.checker.types.is_open_pack(this.c.checker.types.part_at(written, wcount - 1));
|
||||
val total := this.c.program.signatures[signature].params.length as u32;
|
||||
|
||||
for i in 0..count {
|
||||
val node := this.c.checker.run_at(params, i as u32);
|
||||
if packed && i as u32 + 1 == count {
|
||||
val first := this.packs.length as u32;
|
||||
for p in i as u32..total {
|
||||
val held := this.take_param(signature, p, &mut next);
|
||||
val place := this.param_place(0, held);
|
||||
this.packs.append(place);
|
||||
}
|
||||
val index := this.declare(node, location { kind = this.c.checker.type_at(node) }, true);
|
||||
this.locals[index].pack = first;
|
||||
this.locals[index].count = this.packs.length as u32 - first;
|
||||
continue;
|
||||
}
|
||||
break if i as u32 >= total;
|
||||
|
||||
val held := this.take_param(signature, i as u32, &mut next);
|
||||
val place := this.param_place(node, held);
|
||||
this.declare(node, place, this.c.checker.closes(held.kind));
|
||||
}
|
||||
}
|
||||
|
||||
#! A parameter as the code is given it: its words, or the address of the
|
||||
#! function's own copy of it.
|
||||
#! @param this The emitter.
|
||||
#! @param signature The function's signature.
|
||||
#! @param index The parameter's position.
|
||||
#! @param next The first of the code's parameters not yet taken, moved
|
||||
#! past those of this one.
|
||||
#! @returns The parameter's value.
|
||||
def emitter::take_param(&mut this, signature: u32, index: u32, next: &mut u32): operand {
|
||||
val layout_index: u32 = this.c.program.signatures[signature].params[index];
|
||||
val shape := this.c.layout_at(layout_index);
|
||||
val kind := shape.type_id;
|
||||
if in_memory(&shape) {
|
||||
val address := this.build.param(next);
|
||||
next++;
|
||||
return operand::at(kind, address);
|
||||
}
|
||||
|
||||
var made := operand { kind = kind, count = word_count(&shape) };
|
||||
for i in 0..made.count {
|
||||
made.words[i] = this.build.param(next);
|
||||
next++;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Where a parameter is held: in memory it was given, or its own copy, as its
|
||||
#! storage says where it is referred to.
|
||||
#! @param this The emitter.
|
||||
#! @param node The parameter's node, or 0 for a value of a pack.
|
||||
#! @param held Its value.
|
||||
#! @returns Where it is.
|
||||
def emitter::param_place(&mut this, node: u32, held: operand): location {
|
||||
if held.address != 0 {
|
||||
return location { kind = held.kind, address = held.address, framed = true };
|
||||
}
|
||||
|
||||
val place := node != 0 ? this.new_place(node, held.kind) : this.fresh_place(held.kind);
|
||||
this.store(&place, &held);
|
||||
return place;
|
||||
}
|
||||
|
||||
#! A place for a value of a type that no node declares, as each value of a
|
||||
#! pack: in variables, or a cell where it is in memory.
|
||||
#! @param this The emitter.
|
||||
#! @param kind The type.
|
||||
#! @returns Where it is.
|
||||
pub def emitter::fresh_place(&mut this, kind: u32): location {
|
||||
val held := this.c.shape_of(kind);
|
||||
if in_memory(&held) {
|
||||
val made := this.build.code.add_cell(round_up(held.size == 0 ? word_size : held.size, word_size) as u32,
|
||||
held.align < word_size ? word_size as u32 : held.align as u32, ck::local, 0);
|
||||
return location { kind = kind, address = this.build.cell_address(made), framed = true };
|
||||
}
|
||||
var place := location { kind = kind, held = true };
|
||||
for i in 0..word_count(&held) {
|
||||
place.vars[i] = this.build.variable(word_type(&held));
|
||||
}
|
||||
return place;
|
||||
}
|
||||
|
||||
#! Lowers `return value;`: the value is made, or the local it names handed
|
||||
#! over, everything the statements and scopes around it hold is closed, and the
|
||||
#! function returns.
|
||||
#! @param this The emitter.
|
||||
#! @param node The value's node.
|
||||
#! @param mark What the statement held before the value.
|
||||
pub def emitter::return_value(&mut this, node: u32, mark: statement_mark): void {
|
||||
var made := this.value_as(node, this.result);
|
||||
|
||||
# Returning a local by name hands it over, so it is not closed.
|
||||
var given: u32 = 0;
|
||||
if this.c.checker.kind_of(node) == nk::name {
|
||||
val ref := this.c.checker.ref_at(node);
|
||||
if (ref & ref_local) != 0 {
|
||||
given = ref & ref_mask;
|
||||
}
|
||||
}
|
||||
this.return_made(&mut made, given, mark);
|
||||
}
|
||||
|
||||
#! Ends the function returning a value made, closing what the statement made and
|
||||
#! what the function's locals hold, all but the local handed over.
|
||||
#! @param this The emitter.
|
||||
#! @param made The value returned.
|
||||
#! @param given The local the value is, handed over rather than closed, or 0.
|
||||
#! @param mark Where the statement began.
|
||||
pub def emitter::return_made(&mut this, made: &mut operand, given: u32, mark: statement_mark): void {
|
||||
this.adopt(made);
|
||||
|
||||
# What the statement made closes, and what the statements around it made too,
|
||||
# which they still close down the paths that do not return. The cells it took
|
||||
# are freed only once the closing is lowered, which might take them otherwise.
|
||||
var args := vector::<u32>::new();
|
||||
made.args(&mut args);
|
||||
this.close_kept(mark.kept);
|
||||
this.leave_kept(0);
|
||||
# An `ensures` naming what is returned reads it as the locals close.
|
||||
this.returned = made;
|
||||
this.returning = true;
|
||||
this.close_locals(0, given);
|
||||
this.returning = false;
|
||||
this.release(mark.cells);
|
||||
this.give_back(args.view());
|
||||
}
|
||||
|
||||
#! Ends the block returning what the function gives: its words, or the address
|
||||
#! of what it gives in memory, and nothing where that has no bytes, as a struct
|
||||
#! of no fields.
|
||||
#! @param this The emitter.
|
||||
#! @param args The words, or the address.
|
||||
pub def emitter::give_back(&mut this, args: span<u32>): void {
|
||||
if this.build.code.results.length == 0 && this.build.code.returned == 0 {
|
||||
this.build.ret(span::<u32>::empty());
|
||||
return;
|
||||
}
|
||||
this.build.ret(args);
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
#! @file builtins.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the methods the compiler gives the built-in types, which make
|
||||
#! numbers, `bool`, enums, and pointers `equatable`, `hashable`, `ordered`, and
|
||||
#! `numeric` as far as each allows: written where they are called, and made
|
||||
#! functions of their own where a vtable names them.
|
||||
|
||||
import sakura::analyzer;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! A call of a method the compiler gives a built-in type, on the value it is
|
||||
#! called on and the other operand.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `call` node.
|
||||
#! @returns What it gives.
|
||||
pub def emitter::builtin_call(&mut this, node: u32): operand {
|
||||
val callee := this.c.checker.left_of(node);
|
||||
val object := this.c.checker.left_of(callee);
|
||||
val name := this.c.checker.name_of(callee);
|
||||
|
||||
# `f.invoke(args)` calls the function, or the C function, the value is.
|
||||
if name == word::invoke {
|
||||
val made := this.value_of_type(object);
|
||||
val function := this.through_references(&made);
|
||||
var given := gathered { values = vector::<operand>::new() };
|
||||
this.gather(node, 0, 0, this.called_type(function.kind), 0, &mut given);
|
||||
return this.call_function_value(&function, &given);
|
||||
}
|
||||
|
||||
# A fixed array is compared and hashed element by element, where it is.
|
||||
val reached := this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(object)));
|
||||
if this.c.checker.types.kind_of(reached) == ty::fixed {
|
||||
val whole := this.object(object);
|
||||
val first := this.address_of(&whole);
|
||||
val result := this.c.checker.type_at(node);
|
||||
if name == word::hash {
|
||||
return operand::one(result, this.hash_elements(first, reached));
|
||||
}
|
||||
val run := this.c.checker.right_of(node);
|
||||
val other := this.object(this.c.checker.run_at(run, 0));
|
||||
return operand::one(result, this.equal_elements(first, this.address_of(&other), reached));
|
||||
}
|
||||
|
||||
val made := this.value_of_type(object);
|
||||
val subject := this.through_references(&made);
|
||||
var other := operand {};
|
||||
val run := this.c.checker.right_of(node);
|
||||
if this.c.checker.run_length(run) != 0 {
|
||||
val given := this.value_of_type(this.c.checker.run_at(run, 0));
|
||||
other = this.through_references(&given);
|
||||
other = this.convert(&other, subject.kind);
|
||||
}
|
||||
return this.builtin_method(name, &subject, &other, this.c.checker.type_at(node));
|
||||
}
|
||||
|
||||
#! What a method the compiler gives a built-in type gives: `equals` compares,
|
||||
#! `hash` gives the bits, as 0 for both zeros of a float, `compare` gives -1, 0,
|
||||
#! or 1, and the methods of `numeric` operate.
|
||||
#! @param this The emitter.
|
||||
#! @param name The ID of the method's name.
|
||||
#! @param a The value it is called on.
|
||||
#! @param b The other operand, where it takes one.
|
||||
#! @param result The type it gives.
|
||||
#! @returns What it gives.
|
||||
pub def emitter::builtin_method(&mut this, name: u32, a: &operand, b: &operand, result: u32): operand {
|
||||
val kind := a.kind;
|
||||
val floating := this.is_float(kind);
|
||||
val signed := this.is_signed(kind);
|
||||
if name == word::equals {
|
||||
return operand::one(result, this.build.binary(floating ? op::feq : op::eq, a.words[0], b.words[0]));
|
||||
}
|
||||
if name == word::compare {
|
||||
val less := floating ? op::flt : (signed ? op::lts : op::ltu);
|
||||
val below := this.build.binary(less, a.words[0], b.words[0]);
|
||||
val above := this.build.binary(less, b.words[0], a.words[0]);
|
||||
return operand::one(result, this.build.binary(op::sub, above, below));
|
||||
}
|
||||
if name == word::hash {
|
||||
if !floating {
|
||||
return operand::one(result, a.words[0]);
|
||||
}
|
||||
# Both zeros hash as 0, and anything else as its bits, an `f32`'s as one.
|
||||
val shape := this.c.shape_of(kind);
|
||||
val cell := this.temporary(word_size, word_size);
|
||||
val address := this.build.cell_address(cell);
|
||||
this.build.store(shape.bits <= 32 ? access::f32 : access::f64, address, 0, a.words[0]);
|
||||
val bits := this.build.load(shape.bits <= 32 ? access::u32 : access::i64, address, 0);
|
||||
val zero := this.build.binary(op::feq, a.words[0], this.build.real(0));
|
||||
val nonzero := this.build.binary(op::eq, zero, this.build.word(0));
|
||||
val mask := this.build.unary(op::neg, nonzero);
|
||||
return operand::one(result, this.build.binary(op::band, bits, mask));
|
||||
}
|
||||
if name == word::negate {
|
||||
val made := this.build.unary(floating ? op::fneg : op::neg, a.words[0]);
|
||||
return operand::one(result, this.normalize(made, kind));
|
||||
}
|
||||
if name == word::bit_not {
|
||||
return operand::one(result, this.normalize(this.build.unary(op::bnot, a.words[0]), kind));
|
||||
}
|
||||
|
||||
var chosen := op::add;
|
||||
if name == word::add {
|
||||
chosen = floating ? op::fadd : op::add;
|
||||
} else if name == word::sub {
|
||||
chosen = floating ? op::fsub : op::sub;
|
||||
} else if name == word::mul {
|
||||
chosen = floating ? op::fmul : op::mul;
|
||||
} else if name == word::div {
|
||||
chosen = floating ? op::fdiv : (signed ? op::divs : op::divu);
|
||||
} else if name == word::rem {
|
||||
chosen = floating ? op::frem : (signed ? op::rems : op::remu);
|
||||
} else if name == word::bit_and {
|
||||
chosen = op::band;
|
||||
} else if name == word::bit_or {
|
||||
chosen = op::bor;
|
||||
} else if name == word::bit_xor {
|
||||
chosen = op::bxor;
|
||||
} else if name == word::shift_left {
|
||||
chosen = op::shl;
|
||||
} else if name == word::shift_right {
|
||||
chosen = signed ? op::shrs : op::shru;
|
||||
}
|
||||
return operand::one(result, this.normalize(this.build.binary(chosen, a.words[0], b.words[0]), kind));
|
||||
}
|
||||
|
||||
#! The function giving a built-in type a method, as a vtable names it, made
|
||||
#! where it is new: it takes `this` and the other operand by reference, as the
|
||||
#! method's type says.
|
||||
#! @param this The compiler.
|
||||
#! @param kind The built-in type.
|
||||
#! @param name The ID of the method's name.
|
||||
#! @returns The function's index, or `no_function` where the type has no such
|
||||
#! method.
|
||||
pub def lowerer::builtin_function(&mut this, kind: u32, name: u32): u32 {
|
||||
val type_of := this.checker.builtin_method(kind, name);
|
||||
return no_function if type_of == 0;
|
||||
val key := pair_key(kind, name);
|
||||
if this.builtin_ids.get(&key) is some(got) {
|
||||
return got;
|
||||
}
|
||||
var text := string::from(this.checker.names.text(name), nothing {});
|
||||
val index := this.add_function(move(&mut text), this.signature_of(this.call_type(type_of)));
|
||||
this.builtin_ids.set(key, index);
|
||||
this.program.functions[index].builtin = name;
|
||||
this.program.functions[index].owner_type = kind;
|
||||
this.want(index);
|
||||
return index;
|
||||
}
|
||||
|
||||
#! Lowers a function giving a built-in type a method.
|
||||
#! @param this The emitter.
|
||||
pub def emitter::lower_builtin(&mut this): void {
|
||||
val name: u32 = this.c.program.functions[this.function].builtin;
|
||||
val kind: u32 = this.c.program.functions[this.function].owner_type;
|
||||
|
||||
# `invoke` calls the function, or the C function, its `this` refers to, with
|
||||
# the arguments it is given, as they are.
|
||||
if name == word::invoke {
|
||||
val signature: u32 = this.c.program.functions[this.function].signature;
|
||||
val total := this.c.program.signatures[signature].params.length as u32;
|
||||
var next: u32 = 0;
|
||||
val taken := this.take_param(signature, 0, &mut next);
|
||||
val place := location { kind = kind, address = taken.words[0] };
|
||||
val function := this.load(&place);
|
||||
var given := gathered { values = vector::<operand>::new() };
|
||||
for p in 1..total {
|
||||
given.values.append(this.take_param(signature, p as u32, &mut next));
|
||||
}
|
||||
val made := this.call_function_value(&function, &given);
|
||||
var args := vector::<u32>::new();
|
||||
made.args(&mut args);
|
||||
this.give_back(args.view());
|
||||
return;
|
||||
}
|
||||
if this.c.checker.types.kind_of(this.c.checker.unalias(kind)) == ty::fixed {
|
||||
val plain := this.c.checker.unalias(kind);
|
||||
var words: u32[1] = [0];
|
||||
if name == word::hash {
|
||||
words[0] = this.hash_elements(this.build.param(0), plain);
|
||||
} else {
|
||||
words[0] = this.equal_elements(this.build.param(0), this.build.param(2), plain);
|
||||
}
|
||||
this.build.ret(words[0:1]);
|
||||
return;
|
||||
}
|
||||
val first := location { kind = kind, address = this.build.param(0) };
|
||||
val a := this.load(&first);
|
||||
var b := operand {};
|
||||
if this.c.program.signatures[this.c.program.functions[this.function].signature].params.length > 1 {
|
||||
val second := location { kind = kind, address = this.build.param(2) };
|
||||
b = this.load(&second);
|
||||
}
|
||||
val result := this.c.checker.types.first_of(this.c.checker.builtin_method(kind, name));
|
||||
val made := this.builtin_method(name, &a, &b, result);
|
||||
var args := vector::<u32>::new();
|
||||
made.args(&mut args);
|
||||
this.give_back(args.view());
|
||||
}
|
||||
|
||||
#! Whether the elements of two fixed arrays are equal, one by one, as each
|
||||
#! says it is equal: a number by its value, and a struct by its `equals`.
|
||||
#! @param this The emitter.
|
||||
#! @param a The address of one array.
|
||||
#! @param b The address of the other.
|
||||
#! @param kind The arrays' type.
|
||||
#! @returns A word of 1 where they are, and 0 where not.
|
||||
pub def emitter::equal_elements(&mut this, a: u32, b: u32, kind: u32): u32 {
|
||||
val element := this.c.checker.types.first_of(kind);
|
||||
val count := this.c.checker.types.second_of(kind) as u64;
|
||||
val size := this.c.shape_of(element).size;
|
||||
val same := this.build.variable(vt::word);
|
||||
val index := this.build.variable(vt::word);
|
||||
this.build.assign(same, this.build.word(1));
|
||||
this.build.assign(index, this.build.word(0));
|
||||
|
||||
val head := this.build.new_block();
|
||||
val body := this.build.new_block();
|
||||
val differs := this.build.new_block();
|
||||
val next := this.build.new_block();
|
||||
val done := this.build.new_block();
|
||||
val at := this.count_up(index, count, head, body, done);
|
||||
val offset := this.scaled(at, size);
|
||||
val equal := this.element_equals(this.build.binary(op::add, a, offset), this.build.binary(op::add, b, offset), element);
|
||||
this.build.branch(equal, next, differs);
|
||||
this.build.seal(differs);
|
||||
this.build.switch_to(differs);
|
||||
this.build.assign(same, this.build.word(0));
|
||||
this.build.jump(done);
|
||||
this.build.seal(next);
|
||||
this.build.switch_to(next);
|
||||
this.count_on(index, head, done);
|
||||
return this.build.read(same);
|
||||
}
|
||||
|
||||
#! Whether two values of a type, at their addresses, are equal, as the type
|
||||
#! says it is.
|
||||
#! @param this The emitter.
|
||||
#! @param a The address of one.
|
||||
#! @param b The address of the other.
|
||||
#! @param kind The type.
|
||||
#! @returns A word of 1 where they are, and 0 where not.
|
||||
def emitter::element_equals(&mut this, a: u32, b: u32, kind: u32): u32 {
|
||||
val plain := this.c.checker.unalias(kind);
|
||||
if this.c.checker.types.kind_of(plain) == ty::fixed {
|
||||
return this.equal_elements(a, b, plain);
|
||||
}
|
||||
val first := location { kind = kind, address = a };
|
||||
val second := location { kind = kind, address = b };
|
||||
if this.c.checker.find_member(kind, word::equals).decl == 0 {
|
||||
val x := this.load(&first);
|
||||
val y := this.load(&second);
|
||||
return this.builtin_method(word::equals, &x, &y, bt::boolean).words[0];
|
||||
}
|
||||
val method := this.c.checker.find_member(kind, word::equals).decl;
|
||||
val reference := this.c.checker.types.reference(kind, false);
|
||||
val subject := this.reference_to(&first, reference);
|
||||
var others := vector::<operand>::new();
|
||||
others.append(this.reference_to(&second, reference));
|
||||
return this.method_call(method, kind, &subject, others.view()).words[0];
|
||||
}
|
||||
|
||||
#! The hash of a fixed array: of its length, then each element's in turn,
|
||||
#! mixed as the C compiler mixes them.
|
||||
#! @param this The emitter.
|
||||
#! @param a The array's address.
|
||||
#! @param kind Its type.
|
||||
#! @returns The hash.
|
||||
pub def emitter::hash_elements(&mut this, a: u32, kind: u32): u32 {
|
||||
val element := this.c.checker.types.first_of(kind);
|
||||
val count := this.c.checker.types.second_of(kind) as u64;
|
||||
val size := this.c.shape_of(element).size;
|
||||
val code := this.build.variable(vt::word);
|
||||
val index := this.build.variable(vt::word);
|
||||
this.build.assign(code, this.build.word(count));
|
||||
this.build.assign(index, this.build.word(0));
|
||||
|
||||
val head := this.build.new_block();
|
||||
val body := this.build.new_block();
|
||||
val done := this.build.new_block();
|
||||
val at := this.count_up(index, count, head, body, done);
|
||||
val each := this.element_hash(this.build.binary(op::add, a, this.scaled(at, size)), element);
|
||||
val mixed := this.build.binary(op::mul, this.build.binary(op::bxor, this.build.read(code), each), this.build.word(0x9E3779B97F4A7C15));
|
||||
this.build.assign(code, this.build.binary(op::bxor, mixed, this.build.binary(op::shru, mixed, this.build.word(29))));
|
||||
this.count_on(index, head, done);
|
||||
return this.build.read(code);
|
||||
}
|
||||
|
||||
#! The hash of a value of a type, at its address, as the type gives it.
|
||||
#! @param this The emitter.
|
||||
#! @param a The value's address.
|
||||
#! @param kind The type.
|
||||
#! @returns The hash.
|
||||
def emitter::element_hash(&mut this, a: u32, kind: u32): u32 {
|
||||
val plain := this.c.checker.unalias(kind);
|
||||
if this.c.checker.types.kind_of(plain) == ty::fixed {
|
||||
return this.hash_elements(a, plain);
|
||||
}
|
||||
val place := location { kind = kind, address = a };
|
||||
val method := this.c.checker.find_member(kind, word::hash).decl;
|
||||
if method == 0 {
|
||||
val x := this.load(&place);
|
||||
return this.builtin_method(word::hash, &x, &operand {}, bt::uint64).words[0];
|
||||
}
|
||||
val subject := this.reference_to(&place, this.c.checker.types.reference(kind, false));
|
||||
return this.method_call(method, kind, &subject, span::<operand>::empty()).words[0];
|
||||
}
|
||||
@@ -0,0 +1,702 @@
|
||||
#! @file calls.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the lowering of calls: of functions and the instances of generics,
|
||||
#! of methods given the value they are called on, of traits' methods through a
|
||||
#! vtable, of function values, and of C functions, with the arguments a call
|
||||
#! leaves to defaults, those a variadic parameter gathers, and those a pack
|
||||
#! spreads. Also contains the calls the compiler makes itself, for reading and
|
||||
#! writing a property and indexing what implements `indexable`, and the
|
||||
#! intrinsics, which are code of their own rather than calls.
|
||||
|
||||
import sakura::analyzer;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! The arguments of a call as lowering gathers them, each the value of a
|
||||
#! parameter, in order.
|
||||
pub struct gathered {
|
||||
var values: vector<operand>; #! The value given each parameter.
|
||||
}
|
||||
|
||||
#! The instance of a generic a node calls, as the checker recorded it.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node.
|
||||
#! @returns One more than the instance, or 0.
|
||||
pub def emitter::called(&mut this, node: u32): u32 {
|
||||
return this.c.called(node);
|
||||
}
|
||||
|
||||
#! Lowers a call.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `call` node.
|
||||
#! @returns What it gives.
|
||||
pub def emitter::call(&mut this, node: u32): operand {
|
||||
val callee := this.c.checker.left_of(node);
|
||||
var decl := this.c.checker.ref_at(node);
|
||||
# A value of no function type is called through its `invoke`, given the value
|
||||
# as `this`, which the callee is however it is reached, as `obj.f` of `obj.f(x)`.
|
||||
if this.c.checker.has_flag(node, rf::invokes) && decl != 0 {
|
||||
return this.call_decl(node, decl, callee);
|
||||
}
|
||||
# `x.(d)()` calls the method a description names, which the callee names.
|
||||
if decl == 0 && this.c.checker.kind_of(callee) == nk::member_of {
|
||||
decl = this.c.checker.ref_at(callee);
|
||||
}
|
||||
|
||||
# An intrinsic of reflection records what it reaches as the call's own, as
|
||||
# `value_of(d)` does the function `d` describes, so its callee says what it is.
|
||||
val named := this.c.checker.kind_of(callee) == nk::name || this.c.checker.kind_of(callee) == nk::path
|
||||
? this.c.checker.ref_at(callee) : 0;
|
||||
if named != 0 && (named & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[named] == dk::function
|
||||
&& this.c.checker.decls.has(named, df::intrinsic) {
|
||||
return this.intrinsic(node, named);
|
||||
}
|
||||
if decl != 0 && (decl & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[decl] == dk::function {
|
||||
if this.c.checker.decls.has(decl, df::intrinsic) {
|
||||
return this.intrinsic(node, decl);
|
||||
}
|
||||
var object: u32 = 0;
|
||||
val callee_kind := this.c.checker.kind_of(callee);
|
||||
if (callee_kind == nk::member || callee_kind == nk::member_of) && this.c.checker.decls.has(decl, df::method) {
|
||||
object = this.c.checker.left_of(callee);
|
||||
}
|
||||
return this.call_decl(node, decl, object);
|
||||
}
|
||||
|
||||
# A method the compiler gives a built-in type, as `equals` of a number, but
|
||||
# not a field holding a function.
|
||||
if this.c.checker.kind_of(callee) == nk::member && decl == 0 {
|
||||
val field := this.c.checker.ref_at(callee);
|
||||
val is_field := field != 0 && (field & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[field] == dk::field;
|
||||
if !is_field {
|
||||
return this.builtin_call(node);
|
||||
}
|
||||
}
|
||||
return this.call_value(node);
|
||||
}
|
||||
|
||||
#! Lowers a call of a declared function, given the value a method is called on.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `call` node.
|
||||
#! @param decl The function's declaration.
|
||||
#! @param object The node of the value a method is called on, or 0.
|
||||
#! @returns What it gives.
|
||||
def emitter::call_decl(&mut this, node: u32, decl: u32, object: u32): operand {
|
||||
val instance := this.called(node);
|
||||
val holder := this.c.trait_of_method(decl);
|
||||
var kind := this.c.type_of_function(decl, instance);
|
||||
if holder != 0 && object != 0 && instance == 0 {
|
||||
kind = this.c.checker.trait_method_type(decl, this.c.checker.reached(this.c.checker.type_at(object)));
|
||||
}
|
||||
|
||||
var given := gathered { values = vector::<operand>::new() };
|
||||
if object != 0 {
|
||||
given.values.append(this.receiver(object, this.c.checker.types.part_at(kind, 0), decl));
|
||||
}
|
||||
this.gather(node, decl, instance, kind, object != 0 ? 1 : 0, &mut given);
|
||||
return this.call_gathered(decl, instance, holder, kind, object, &given);
|
||||
}
|
||||
|
||||
#! Calls a declared function with its arguments gathered: through a vtable, as
|
||||
#! a trait's default, through its address where it is C's, or as it is.
|
||||
#! @param this The emitter.
|
||||
#! @param decl The function's declaration.
|
||||
#! @param instance One more than the instance called, or 0.
|
||||
#! @param holder The trait it is a member of, or 0.
|
||||
#! @param kind The function type called.
|
||||
#! @param object The node of the value a method is called on, or 0.
|
||||
#! @param given The arguments.
|
||||
#! @returns What it gives.
|
||||
pub def emitter::call_gathered(
|
||||
&mut this,
|
||||
decl: u32,
|
||||
instance: u32,
|
||||
holder: u32,
|
||||
kind: u32,
|
||||
object: u32,
|
||||
given: &gathered
|
||||
): operand {
|
||||
# A trait's method is called through the vtable of the value's trait
|
||||
# reference, but a default it writes a body for, called on a value of a type
|
||||
# that takes it, is that body: the type's own instance of it, which the
|
||||
# checker made where the call gives the default's type arguments, or one
|
||||
# given the value as a reference to the trait.
|
||||
if holder != 0 {
|
||||
val receiver_type := object != 0 ? this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(object))) : 0;
|
||||
val dynamic := object != 0 && (this.c.checker.named_kind(receiver_type) == dk::trait_type
|
||||
|| this.c.checker.types.kind_of(receiver_type) == ty::param);
|
||||
if dynamic || !this.c.checker.has_body(decl) {
|
||||
return this.call_trait(decl, holder, given, this.c.checker.types.first_of(kind));
|
||||
}
|
||||
if instance != 0 {
|
||||
return this.call_function(this.c.function_of(decl, instance), given, this.c.checker.types.first_of(kind));
|
||||
}
|
||||
val implemented := this.c.checker.implemented(receiver_type, this.c.checker.enclosing_trait(decl));
|
||||
val own := span::<u32>::empty();
|
||||
return this.call_function(this.c.default_of(decl, implemented, receiver_type, own), given, this.c.checker.types.first_of(kind));
|
||||
}
|
||||
|
||||
# A C function without a body is called through its address.
|
||||
if this.c.checker.decls.has(decl, df::foreign) && !this.c.checker.has_body(decl) {
|
||||
val address := this.build.value(op::c_address, span::<u32>::empty(), vt::word, this.c.linked_of(decl), 0);
|
||||
return this.call_address(address, this.c.call_type(kind), given, this.c.checker.types.first_of(kind));
|
||||
}
|
||||
return this.call_function(this.c.function_of(decl, instance), given, this.c.checker.types.first_of(kind));
|
||||
}
|
||||
|
||||
#! The reference a method's `this` takes to the value it is called on: the
|
||||
#! reference the value already is, read through to the one `this` takes, or one
|
||||
#! to the place it is, or to a copy of it where it is no place. A trait's
|
||||
#! default method takes it as a reference to the trait.
|
||||
#! @param this The emitter.
|
||||
#! @param object The node of the value.
|
||||
#! @param param The type of `this`.
|
||||
#! @param decl The method's declaration.
|
||||
#! @returns The reference.
|
||||
pub def emitter::receiver(&mut this, object: u32, param: u32, decl: u32): operand {
|
||||
var made := this.receiver_of(object, this.c.checker.decls.has(decl, df::mut_this));
|
||||
|
||||
# A default takes the value as a reference to its trait, unless it is compiled
|
||||
# for each type.
|
||||
val holder := this.c.trait_of_method(decl);
|
||||
if holder != 0 && made.count == 1 && !this.c.checker.typed_default(decl) {
|
||||
val given := this.c.checker.types.first_of(this.c.checker.unalias(made.kind));
|
||||
val referent := this.c.checker.unalias(given);
|
||||
if this.c.checker.named_kind(referent) != dk::trait_type {
|
||||
val implemented := this.c.checker.implemented(referent, this.c.checker.enclosing_trait(decl));
|
||||
val vtable := this.c.vtable_of(given, implemented);
|
||||
return operand::two(this.c.checker.types.reference(implemented, false),
|
||||
made.words[0], this.build.word(vtable as u64));
|
||||
}
|
||||
}
|
||||
return this.convert(&made, param);
|
||||
}
|
||||
|
||||
#! A reference to what a node gives, which a parameter taking a reference is
|
||||
#! given where the value given is no reference: one to its place, or to a copy
|
||||
#! of it the statement holds until it ends.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node.
|
||||
#! @param kind The reference's type.
|
||||
#! @returns The reference.
|
||||
pub def emitter::reference_arg(&mut this, node: u32, kind: u32): operand {
|
||||
if this.c.checker.is_place(node) {
|
||||
val place := this.place_of(node);
|
||||
return this.reference_to(&place, kind) if this.lends_as_is(place.kind, kind);
|
||||
}
|
||||
|
||||
# A value is referred to where the statement holds it, which closes it where
|
||||
# the statement ends. A value referred to as a trait it implements is held as
|
||||
# its own type.
|
||||
val referent := this.c.checker.types.first_of(this.c.checker.unalias(kind));
|
||||
var value := this.value_of_type(node);
|
||||
if this.c.checker.named_kind(this.c.checker.unalias(referent)) != dk::trait_type {
|
||||
value = this.convert(&value, referent);
|
||||
}
|
||||
val place := this.hold(&value);
|
||||
return this.reference_to(&place, kind);
|
||||
}
|
||||
|
||||
#! A reference to an operand an operator's method is given, which never keeps
|
||||
#! it: to the place it names, or to where the statement holds its value, which
|
||||
#! the statement closes where it ends.
|
||||
#! @param this The emitter.
|
||||
#! @param node The operand's node.
|
||||
#! @param kind The reference's type.
|
||||
#! @returns The reference.
|
||||
pub def emitter::lent_arg(&mut this, node: u32, kind: u32): operand {
|
||||
if this.c.checker.is_place(node) {
|
||||
val place := this.place_of(node);
|
||||
return this.reference_to(&place, kind) if this.lends_as_is(place.kind, kind);
|
||||
}
|
||||
val referent := this.c.checker.types.first_of(this.c.checker.unalias(kind));
|
||||
var value := this.value(node);
|
||||
value = this.convert(&value, referent);
|
||||
val place := this.hold(&value);
|
||||
if value.address == 0 {
|
||||
var held := operand::at(value.kind, place.address);
|
||||
this.keep(&held);
|
||||
}
|
||||
return this.reference_to(&place, kind);
|
||||
}
|
||||
|
||||
#! Whether a place is referred to as it is where a reference is wanted: one of
|
||||
#! its own type, of a trait it implements, of a reference it holds, or one
|
||||
#! written through. A place of another type is converted first, as a view where
|
||||
#! a `string` is wanted is copied into one, and the copy referred to.
|
||||
#! @param this The emitter.
|
||||
#! @param held The place's type.
|
||||
#! @param kind The reference's type.
|
||||
#! @returns Whether it is.
|
||||
def emitter::lends_as_is(&mut this, held: u32, kind: u32): bool {
|
||||
val wanted := this.c.checker.unalias(kind);
|
||||
return true if this.c.checker.types.kind_of(wanted) != ty::reference || this.c.checker.types.second_of(wanted) != 0;
|
||||
val referent := this.c.checker.unalias(this.c.checker.types.first_of(wanted));
|
||||
val own := this.c.checker.unalias(held);
|
||||
return referent == own || this.c.checker.named_kind(referent) == dk::trait_type
|
||||
|| this.c.checker.types.kind_of(own) == ty::reference;
|
||||
}
|
||||
|
||||
#! Gathers the arguments of a call: those written, each converted to its
|
||||
#! parameter or referred to where the parameter takes a reference, those a
|
||||
#! variadic parameter takes as a view of them, those a pack spreads, and the
|
||||
#! defaults of the parameters the call leaves out.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `call` node.
|
||||
#! @param decl The function's declaration.
|
||||
#! @param instance One more than the instance called, or 0.
|
||||
#! @param kind The function type called.
|
||||
#! @param skip How many parameters come before the first argument, as
|
||||
#! `this`.
|
||||
#! @param into Where the arguments are gathered, after any already there.
|
||||
pub def emitter::gather(
|
||||
&mut this,
|
||||
node: u32,
|
||||
decl: u32,
|
||||
instance: u32,
|
||||
kind: u32,
|
||||
skip: u32,
|
||||
into: &mut gathered
|
||||
): void {
|
||||
val run := this.c.checker.right_of(node);
|
||||
val count := this.c.checker.types.part_count(kind);
|
||||
val variadic := this.c.checker.types.second_of(kind) != 0;
|
||||
val stop: u32 = variadic ? count - 1 : count;
|
||||
var p := skip;
|
||||
var rest_given := false;
|
||||
|
||||
for i in 0..this.c.checker.run_length(run) {
|
||||
val arg := this.c.checker.run_at(run, i as u32);
|
||||
val packs := this.is_spread(arg)
|
||||
&& this.c.checker.types.kind_of(this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(this.c.checker.left_of(arg))))) == ty::pack;
|
||||
# A variadic function's pack ends in a view of the rest, which is the view a
|
||||
# variadic parameter takes as it is.
|
||||
val ends_in_rest := packs && this.c.checker.types.second_of(this.c.checker.reached(this.c.checker.type_at(this.c.checker.left_of(arg)))) != 0;
|
||||
break if p >= stop && variadic && !ends_in_rest;
|
||||
break if p >= count;
|
||||
|
||||
# `...args` spreads the values of a pack, one to a parameter.
|
||||
if packs {
|
||||
val pack := this.c.checker.left_of(arg);
|
||||
val ref := this.c.checker.ref_at(pack);
|
||||
val local := (ref & ref_local) != 0 ? this.local_of(ref & ref_mask) : 0;
|
||||
if local != 0 {
|
||||
val held: local_info = this.locals[local - 1];
|
||||
for j in 0..held.count {
|
||||
val place: location = this.packs[held.pack as u64 + j as u64];
|
||||
val value := this.load(&place);
|
||||
if ends_in_rest && variadic && j + 1 == held.count && p + 1 == count {
|
||||
into.values.append(value);
|
||||
p = count;
|
||||
rest_given = true;
|
||||
break;
|
||||
}
|
||||
# A value that closes is moved to the parameter taking it, as the
|
||||
# function then owns it: the pack is left empty, so it isn't closed
|
||||
# twice. The value was copied out of the pack's place as it was read.
|
||||
val param := this.c.checker.types.part_at(kind, p);
|
||||
if this.c.checker.closes(place.kind)
|
||||
&& this.c.checker.types.kind_of(this.c.checker.unalias(param)) != ty::reference {
|
||||
this.zero(&place);
|
||||
}
|
||||
into.values.append(this.convert(&value, param));
|
||||
p++;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
into.values.append(this.argument(arg, this.c.checker.types.part_at(kind, p)));
|
||||
p++;
|
||||
}
|
||||
|
||||
# A variadic parameter takes a view of the rest, which `...xs` gives as it is,
|
||||
# after the defaults of those before it the call leaves out.
|
||||
if variadic && !rest_given {
|
||||
if p < stop {
|
||||
this.defaults_of(decl, instance, kind, p, stop, into, node, skip);
|
||||
p = stop;
|
||||
}
|
||||
val element := this.c.checker.types.part_at(kind, count - 1);
|
||||
val view := this.c.checker.span_of(element);
|
||||
var rest := vector::<u32>::new();
|
||||
for i in (p - skip) as u64..this.c.checker.run_length(run) as u64 {
|
||||
rest.append(this.c.checker.run_at(run, i as u32));
|
||||
}
|
||||
if rest.length == 1 && this.is_spread(rest[0]) {
|
||||
into.values.append(this.spread_view(this.c.checker.left_of(rest[0]), view));
|
||||
} else {
|
||||
into.values.append(this.gathered_view(rest.view(), element, view));
|
||||
}
|
||||
p = count;
|
||||
}
|
||||
|
||||
# The parameters left out take their defaults, made where the function is.
|
||||
if p < count {
|
||||
this.defaults_of(decl, instance, kind, p, count, into, node, skip);
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether a node is `...xs`.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node.
|
||||
#! @returns Whether it is.
|
||||
pub def emitter::is_spread(&mut this, node: u32): bool {
|
||||
return this.c.checker.kind_of(node) == nk::unary && this.c.checker.token_kind(node) == tk::spread;
|
||||
}
|
||||
|
||||
#! An argument as its parameter takes it: converted to its type, or referred to
|
||||
#! where it takes a reference and the argument is none.
|
||||
#! @param this The emitter.
|
||||
#! @param node The argument's node.
|
||||
#! @param param The parameter's type.
|
||||
#! @returns The value.
|
||||
pub def emitter::argument(&mut this, node: u32, param: u32) : operand {
|
||||
if this.c.checker.has_flag(node, rf::borrowed) {
|
||||
val made := this.reference_arg(node, param);
|
||||
return this.convert(&made, param);
|
||||
}
|
||||
return this.value_as(node, param);
|
||||
}
|
||||
|
||||
#! A view of the arguments a variadic parameter gathers, held in an array the
|
||||
#! statement holds.
|
||||
#! @param this The emitter.
|
||||
#! @param args The arguments' nodes.
|
||||
#! @param element The type of each.
|
||||
#! @param view The view's type.
|
||||
#! @returns The view.
|
||||
def emitter::gathered_view(&mut this, args: span<u32>, element: u32, view: u32): operand {
|
||||
val address := this.temporary_of(view);
|
||||
if args.length == 0 {
|
||||
this.build.clear(address, 2 * word_size);
|
||||
return operand::at(view, address);
|
||||
}
|
||||
|
||||
val array := this.c.checker.types.fixed(element, args.length as u32);
|
||||
val held := this.c.shape_of(element);
|
||||
val first := this.temporary_of(array);
|
||||
for i in 0..args.length {
|
||||
val value := this.value_as(args[i], element);
|
||||
this.adopt(&value);
|
||||
val place := location { kind = element, address = first, offset = i as u64 * held.size, framed = true };
|
||||
this.store(&place, &value);
|
||||
}
|
||||
this.build.store(access::i64, address, 0, first);
|
||||
this.build.store(access::i64, address, word_size, this.build.word(args.length));
|
||||
# What the array holds closes where the statement ends, as an array literal's does.
|
||||
var whole := operand::at(array, first);
|
||||
this.keep(&whole);
|
||||
return operand::at(view, address);
|
||||
}
|
||||
|
||||
#! The view `...xs` gives a variadic parameter: a view as it is, or one of every
|
||||
#! element of a fixed array.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node of what is spread.
|
||||
#! @param view The view's type.
|
||||
#! @returns The view.
|
||||
def emitter::spread_view(&mut this, node: u32, view: u32): operand {
|
||||
val through := this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(node)));
|
||||
if this.c.checker.types.kind_of(through) == ty::fixed {
|
||||
val whole := this.object(node);
|
||||
val shape := this.c.shape_of(through);
|
||||
val address := this.temporary_of(view);
|
||||
this.build.store(access::i64, address, 0, this.address_of(&whole));
|
||||
this.build.store(access::i64, address, word_size, this.build.word(shape.count as u64));
|
||||
return operand::at(view, address);
|
||||
}
|
||||
val made := this.value(node);
|
||||
val read := this.through_references(&made);
|
||||
return this.convert(&read, view);
|
||||
}
|
||||
|
||||
#! The defaults of the parameters a call leaves out, each made where the
|
||||
#! function is declared, with the parameters before it named as the arguments
|
||||
#! the call gave them.
|
||||
#! @param this The emitter.
|
||||
#! @param decl The function's declaration.
|
||||
#! @param instance One more than the instance called, or 0.
|
||||
#! @param kind The function type called.
|
||||
#! @param from The first parameter left out.
|
||||
#! @param to One past the last.
|
||||
#! @param into The arguments gathered so far, which the defaults follow.
|
||||
def emitter::defaults_of(
|
||||
&mut this,
|
||||
decl: u32,
|
||||
instance: u32,
|
||||
kind: u32,
|
||||
from: u32,
|
||||
to: u32,
|
||||
into: &mut gathered,
|
||||
call: u32,
|
||||
skip: u32
|
||||
): void {
|
||||
# What a default asks of its call, as where it is or the text of an argument,
|
||||
# is of the call written, not of a call a default makes.
|
||||
val outer := this.defaulting;
|
||||
if outer.node == 0 {
|
||||
this.defaulting = default_site {
|
||||
node = call,
|
||||
file = this.c.checker.at.file,
|
||||
table = this.c.checker.at.table,
|
||||
args = this.c.checker.right_of(call),
|
||||
skip = skip
|
||||
};
|
||||
}
|
||||
val table := this.c.body_table(decl, instance);
|
||||
val saved := this.c.checker.at;
|
||||
this.c.checker.use_table(table);
|
||||
val node: u32 = this.c.checker.decls.nodes.p[decl];
|
||||
val params := this.c.checker.record(node, function_slot::params);
|
||||
val mark := this.scope_mark();
|
||||
if outer.node == 0 {
|
||||
this.defaulting.params = params;
|
||||
}
|
||||
|
||||
# The parameters given are named as what they were given.
|
||||
for i in 0..from {
|
||||
break if i as u64 >= into.values.length || i >= this.c.checker.run_length(params);
|
||||
val param := this.c.checker.run_at(params, i as u32);
|
||||
val place := this.hold(&into.values[i]);
|
||||
this.declare(param, place, false);
|
||||
}
|
||||
for i in from..to {
|
||||
break if i >= this.c.checker.run_length(params);
|
||||
val param := this.c.checker.run_at(params, i as u32);
|
||||
val value := this.c.checker.record(param, parameter_slot::value);
|
||||
val wanted := this.c.checker.types.part_at(kind, i as u32);
|
||||
if value == 0 {
|
||||
this.problem(param, "The parameter is left out and has no default.");
|
||||
into.values.append(this.zero_value(wanted));
|
||||
continue;
|
||||
}
|
||||
val made := this.value_as(value, wanted);
|
||||
into.values.append(made);
|
||||
val place := this.hold(&made);
|
||||
this.declare(param, place, false);
|
||||
}
|
||||
|
||||
this.forget_locals(mark);
|
||||
this.c.checker.at = saved;
|
||||
this.defaulting = outer;
|
||||
}
|
||||
|
||||
#! The argument a call wrote for a parameter a default names, where the default
|
||||
#! being made names one: the node, in the call's own table.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node naming the parameter, in the default.
|
||||
#! @returns The argument's node, or 0.
|
||||
pub def emitter::written_argument(&mut this, node: u32): u32 {
|
||||
return 0 if this.defaulting.node == 0 || this.c.checker.kind_of(node) != nk::name;
|
||||
val ref := this.c.checker.ref_at(node);
|
||||
return 0 if (ref & ref_local) == 0;
|
||||
val param := ref & ref_mask;
|
||||
val params := this.defaulting.params;
|
||||
for i in 0..this.c.checker.run_length(params) {
|
||||
continue if this.c.checker.run_at(params, i as u32) != param;
|
||||
return 0 if (i as u32) < this.defaulting.skip;
|
||||
val at := i as u32 - this.defaulting.skip;
|
||||
val saved := this.c.checker.at;
|
||||
this.c.checker.use_table(this.defaulting.table);
|
||||
val arg := at < this.c.checker.run_length(this.defaulting.args) ? this.c.checker.run_at(this.defaulting.args, at) : 0;
|
||||
this.c.checker.at = saved;
|
||||
return arg;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! Calls a function of the program with the arguments gathered.
|
||||
#! @param this The emitter.
|
||||
#! @param index The function.
|
||||
#! @param given The arguments.
|
||||
#! @param result The type it gives.
|
||||
#! @returns What it gives.
|
||||
pub def emitter::call_function(&mut this, index: u32, given: &gathered, result: u32): operand {
|
||||
var args := vector::<u32>::new();
|
||||
this.pass_args(given, &mut args);
|
||||
return this.call_with(op::call, index, 0, &mut args, result);
|
||||
}
|
||||
|
||||
#! Adds the words of the arguments gathered to a call's operands, which the call
|
||||
#! takes as its own.
|
||||
#! @param this The emitter.
|
||||
#! @param given The arguments.
|
||||
#! @param args The operands.
|
||||
def emitter::pass_args(&mut this, given: &gathered, args: &mut vector<u32>): void {
|
||||
for &each in given.values {
|
||||
this.adopt(&each);
|
||||
each.args(args);
|
||||
}
|
||||
}
|
||||
|
||||
#! Adds a call, writing what it gives to a cell the statement holds where it is
|
||||
#! held in memory, whose address the call is given last.
|
||||
#! @param this The emitter.
|
||||
#! @param kind The kind of call.
|
||||
#! @param aux The function or signature called.
|
||||
#! @param imm The slot of a vtable called through, or 0.
|
||||
#! @param args The operands.
|
||||
#! @param result The type it gives.
|
||||
#! @returns What it gives.
|
||||
pub def emitter::call_with(&mut this, kind: op, aux: u32, imm: u64, args: &mut vector<u32>, result: u32): operand {
|
||||
val held := this.c.shape_of(result);
|
||||
if in_memory(&held) {
|
||||
# A value of no bytes, as a struct of no fields, is returned as nothing, so
|
||||
# the call is given nowhere to write it.
|
||||
val address := this.temporary_of(result);
|
||||
if returned_in_memory(&held) {
|
||||
args.append(address);
|
||||
}
|
||||
this.build.effect(kind, args.view(), aux, imm);
|
||||
return operand::at(result, address);
|
||||
}
|
||||
|
||||
var gives := vector::<vt>::new();
|
||||
for _ in 0..word_count(&held) {
|
||||
gives.append(word_type(&held));
|
||||
}
|
||||
val index := this.build.emit(kind, args.view(), gives.view(), aux, imm);
|
||||
var made := operand { kind = result, count = word_count(&held) };
|
||||
val first: u32 = this.build.code.insts[index].result;
|
||||
for i in 0..made.count {
|
||||
made.words[i] = first + i as u32;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Calls a trait's method through the vtable of the reference it is given.
|
||||
#! @param this The emitter.
|
||||
#! @param decl The method's declaration.
|
||||
#! @param holder The trait's declaration.
|
||||
#! @param given The arguments, the trait reference first.
|
||||
#! @param result The type it gives.
|
||||
#! @returns What it gives.
|
||||
pub def emitter::call_trait(&mut this, decl: u32, holder: u32, given: &gathered, result: u32): operand {
|
||||
var args := vector::<u32>::new();
|
||||
this.pass_args(given, &mut args);
|
||||
# The reference's own trait numbers the slots its vtables hold; within a
|
||||
# default, `this` holds the vtable of the trait declaring it.
|
||||
val reached := given.values.length != 0 ? this.c.checker.types.first_of(this.c.checker.unalias(given.values[0].kind)) : 0;
|
||||
val plain := this.c.checker.unalias(reached);
|
||||
var owner := this.c.checker.named_kind(plain) == dk::trait_type ? this.c.checker.types.first_of(plain) : holder;
|
||||
if this.c.checker.types.kind_of(plain) == ty::param {
|
||||
val param := this.c.checker.types.first_of(plain);
|
||||
val declarer: u32 = this.c.checker.decls.owners.p[param];
|
||||
if this.c.checker.decls.names.p[param] == names::self_id && declarer != 0
|
||||
&& this.c.checker.decls.kinds.p[declarer] == dk::trait_type {
|
||||
owner = declarer;
|
||||
}
|
||||
}
|
||||
val slot := this.c.dispatch_index(owner, decl);
|
||||
val signature := this.c.trait_signature(decl, owner, result,
|
||||
this.c.checker.named_kind(plain) == dk::trait_type ? plain : 0);
|
||||
return this.call_with(op::call_trait, signature, slot as u64, &mut args, result);
|
||||
}
|
||||
|
||||
#! Calls a C function through its address.
|
||||
#! @param this The emitter.
|
||||
#! @param address The function's address.
|
||||
#! @param kind Its function type.
|
||||
#! @param given The arguments.
|
||||
#! @param result The type it gives.
|
||||
#! @returns What it gives.
|
||||
pub def emitter::call_address(&mut this, address: u32, kind: u32, given: &gathered, result: u32): operand {
|
||||
var args := vector::<u32>::new();
|
||||
args.append(address);
|
||||
this.pass_args(given, &mut args);
|
||||
return this.call_with(op::call_c, this.c.signature_of(kind), 0, &mut args, result);
|
||||
}
|
||||
|
||||
#! Lowers a call of a function value: a local, a field, or anything giving a
|
||||
#! function, or the address of a C function.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `call` node.
|
||||
#! @returns What it gives.
|
||||
def emitter::call_value(&mut this, node: u32): operand {
|
||||
val callee := this.c.checker.left_of(node);
|
||||
val made := this.value_of_type(callee);
|
||||
val function := this.through_references(&made);
|
||||
|
||||
# A function value has no defaults, but takes a view of the rest where its last
|
||||
# parameter is variadic, and a value of each type of a pack spread into it.
|
||||
var given := gathered { values = vector::<operand>::new() };
|
||||
this.gather(node, 0, 0, this.called_type(function.kind), 0, &mut given);
|
||||
return this.call_function_value(&function, &given);
|
||||
}
|
||||
|
||||
#! The function type a function value, or the address of a C function, is called
|
||||
#! as.
|
||||
#! @param this The emitter.
|
||||
#! @param kind The value's type.
|
||||
#! @returns The function type.
|
||||
pub def emitter::called_type(&mut this, kind: u32): u32 {
|
||||
val plain := this.c.checker.unalias(kind);
|
||||
return this.c.checker.is_std(plain, word::cfn)
|
||||
? this.c.checker.unalias(this.c.checker.types.part_at(plain, 0))
|
||||
: plain;
|
||||
}
|
||||
|
||||
#! Calls a function value, or the address of a C function, given its arguments.
|
||||
#! @param this The emitter.
|
||||
#! @param function The value.
|
||||
#! @param given The arguments, as its parameters take them.
|
||||
#! @returns What it gives.
|
||||
pub def emitter::call_function_value(&mut this, function: &operand, given: &gathered): operand {
|
||||
val plain := this.called_type(function.kind);
|
||||
val result := this.c.checker.types.first_of(plain);
|
||||
if this.c.checker.is_std(this.c.checker.unalias(function.kind), word::cfn) {
|
||||
return this.call_address(function.words[0], plain, given, result);
|
||||
}
|
||||
|
||||
var args := vector::<u32>::new();
|
||||
function.args(&mut args);
|
||||
this.pass_args(given, &mut args);
|
||||
return this.call_with(op::call_value, this.c.signature_of(this.c.call_type(plain)), 0, &mut args, result);
|
||||
}
|
||||
|
||||
#! Calls an accessor the compiler calls itself, as `at` indexing what implements
|
||||
#! `indexable`, given the value it is called on and its other argument.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node the call stands for.
|
||||
#! @param decl The accessor's declaration.
|
||||
#! @param object The node of the value it is called on.
|
||||
#! @param arg The node of its other argument, or 0.
|
||||
#! @returns What it gives.
|
||||
pub def emitter::accessor_call(&mut this, node: u32, decl: u32, object: u32, arg: u32): operand {
|
||||
val owner := this.c.checker.reached(this.object_type(object));
|
||||
val target := this.c.method_target(decl, owner);
|
||||
var given := gathered { values = vector::<operand>::new() };
|
||||
given.values.append(this.receiver(object, this.c.checker.types.part_at(target.kind, 0), decl));
|
||||
if arg != 0 && this.c.checker.types.part_count(target.kind) > 1 {
|
||||
given.values.append(this.value_as(arg, this.c.checker.types.part_at(target.kind, 1)));
|
||||
}
|
||||
val result := this.c.checker.types.first_of(target.kind);
|
||||
if target.holder != 0 {
|
||||
return this.call_trait(decl, target.holder, &given, result);
|
||||
}
|
||||
return this.call_function(target.function, &given, result);
|
||||
}
|
||||
|
||||
#! Calls a method on a value already lowered, as the compiler does where a loop
|
||||
#! asks an iterator for its next element, or a value is closed: given a
|
||||
#! reference to it, and the other arguments.
|
||||
#! @param this The emitter.
|
||||
#! @param decl The method's declaration.
|
||||
#! @param owner The type it is called on.
|
||||
#! @param receiver The reference `this` takes.
|
||||
#! @param others The other arguments.
|
||||
#! @returns What it gives.
|
||||
pub def emitter::method_call(&mut this, decl: u32, owner: u32, receiver: &operand, others: span<operand>): operand {
|
||||
val target := this.c.method_target(decl, owner);
|
||||
var given := gathered { values = vector::<operand>::new() };
|
||||
given.values.append(this.convert(receiver, this.c.checker.types.part_at(target.kind, 0)));
|
||||
given.values.extend(others);
|
||||
val result := this.c.checker.types.first_of(target.kind);
|
||||
if target.holder != 0 {
|
||||
return this.call_trait(decl, target.holder, &given, result);
|
||||
}
|
||||
return this.call_function(target.function, &given, result);
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
#! @file closures.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains functions as values: a function named, the instance of a generic
|
||||
#! one, the address of a C function, and anonymous functions, which refer to
|
||||
#! the locals of the function around them they name. An anonymous function
|
||||
#! naming any is a closure, given an environment of references to them after
|
||||
#! its parameters, which is a cell of the frame making it, as the locals are.
|
||||
#! So a closure is good while the locals it refers to are, and one outliving
|
||||
#! them is the program's mistake, as a reference outliving what it refers to
|
||||
#! is.
|
||||
|
||||
import sakura::analyzer;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! A function named as a value: its index plus one, with no environment, a C
|
||||
#! function's address, or the address of the entry C calls one of the program
|
||||
#! back through, where it is given as a `cfn`.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node naming it.
|
||||
#! @param decl The function's declaration.
|
||||
#! @returns The value.
|
||||
pub def emitter::function_value(&mut this, node: u32, decl: u32): operand {
|
||||
val kind := this.c.checker.type_at(node);
|
||||
if this.c.checker.decls.has(decl, df::foreign) {
|
||||
return operand::one(kind, this.build.value(op::c_address, span::<u32>::empty(), vt::word, this.c.linked_of(decl), 0));
|
||||
}
|
||||
if this.c.checker.decls.has(decl, df::callback) && this.c.checker.is_std(this.c.checker.unalias(kind), word::cfn) {
|
||||
val function := this.c.function_of(decl, 0);
|
||||
return operand::one(kind, this.build.value(op::callback, span::<u32>::empty(), vt::word, function, 0));
|
||||
}
|
||||
|
||||
var instance := this.called(node);
|
||||
# A generic type's function named through it is the instance its arguments give.
|
||||
if instance == 0 && this.c.checker.decls.has(decl, df::generic) && this.c.checker.kind_of(node) == nk::path {
|
||||
val target := this.c.checker.path_target(node);
|
||||
if target.owner != bt::error && this.c.checker.types.kind_of(target.owner) == ty::named {
|
||||
var args := this.c.checker.types.parts_of(target.owner);
|
||||
instance = this.c.checker.instance_of(decl, args.view(), node);
|
||||
}
|
||||
}
|
||||
val index := this.c.function_of(decl, instance);
|
||||
|
||||
# Named where another function type is expected, it is called through a
|
||||
# function of that type made for it.
|
||||
if this.c.checker.has_flag(node, rf::adapted) {
|
||||
val wanted := this.c.checker.converted(node);
|
||||
val adapter := this.c.adapter_of(this.c.checker.at.table, node, this.c.checker.at.file, wanted, index);
|
||||
this.c.names(this.function, adapter);
|
||||
return operand::two(wanted, this.build.word(adapter as u64 + 1), this.build.word(0));
|
||||
}
|
||||
this.c.program.functions[index].taken = true;
|
||||
this.c.names(this.function, index);
|
||||
return operand::two(kind, this.build.word(index as u64 + 1), this.build.word(0));
|
||||
}
|
||||
|
||||
#! An anonymous function as a value: its index plus one, and where it names
|
||||
#! locals of the functions around it, the environment holding a reference to
|
||||
#! each, in a cell of the frame.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `lambda` node.
|
||||
#! @returns The value.
|
||||
pub def emitter::lambda_value(&mut this, node: u32): operand {
|
||||
val kind := this.c.checker.type_at(node);
|
||||
var captures := this.captures_of(node);
|
||||
val index := this.c.lambda_of(this.c.checker.at.table, node, this.c.checker.at.file, kind, captures.length != 0);
|
||||
val outer: u32 = this.c.program.functions[this.function].decl != 0
|
||||
? this.c.program.functions[this.function].decl
|
||||
: this.c.program.functions[this.function].outer;
|
||||
this.c.program.functions[index].outer = outer;
|
||||
this.c.program.functions[index].taken = true;
|
||||
this.c.names(this.function, index);
|
||||
val function := this.build.word(index as u64 + 1);
|
||||
if captures.length == 0 {
|
||||
return operand::two(kind, function, this.build.word(0));
|
||||
}
|
||||
|
||||
# The environment is a fixed array of references, one to each local captured.
|
||||
val reference := this.c.checker.types.reference(bt::int64, false);
|
||||
val holder := this.c.checker.types.fixed(reference, captures.length as u32);
|
||||
val shape := this.c.shape_of(holder);
|
||||
val cell := this.build.code.add_cell(round_up(shape.size, word_size) as u32, word_size as u32, ck::local, 0);
|
||||
val environment := this.build.cell_address(cell);
|
||||
for i in 0..captures.length {
|
||||
val local := this.local_of(captures[i]);
|
||||
if local == 0 {
|
||||
this.problem(node, "A local the function captures is not where it is named.");
|
||||
continue;
|
||||
}
|
||||
val held: local_info = this.locals[local - 1];
|
||||
val made := this.reference_to(&held.place, reference);
|
||||
val at := location { kind = reference, address = environment, offset = i as u64 * word_size };
|
||||
this.store(&at, &made);
|
||||
}
|
||||
return operand::two(kind, function, environment);
|
||||
}
|
||||
|
||||
#! The locals of the functions around an anonymous function that it names, or
|
||||
#! that one within it names, in the order it first names them.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `lambda` node.
|
||||
#! @returns The nodes declaring them.
|
||||
pub def emitter::captures_of(&mut this, node: u32): vector<u32> {
|
||||
var made := vector::<u32>::new();
|
||||
val first := this.lowest_node(node);
|
||||
var walk := node_walk::new(node);
|
||||
while walk.more() {
|
||||
val at := walk.next();
|
||||
# A contract left out captures nothing.
|
||||
continue if this.c.checker.contracts_off && this.c.checker.kind_of(at) == nk::contract;
|
||||
if this.c.checker.kind_of(at) == nk::name {
|
||||
val ref := this.c.checker.ref_at(at);
|
||||
if (ref & ref_local) != 0 {
|
||||
val local := ref & ref_mask;
|
||||
if (local < first || local > node) && !made.view().contains(&local) {
|
||||
made.append(local);
|
||||
}
|
||||
}
|
||||
}
|
||||
walk.enter(this.c.checker.syn(), at);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The first node of what a node was parsed from, which the parser made before
|
||||
#! the node itself, one after another.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node.
|
||||
#! @returns The lowest node under it.
|
||||
pub def emitter::lowest_node(&mut this, node: u32): u32 {
|
||||
var lowest := node;
|
||||
var walk := node_walk::new(node);
|
||||
while walk.more() {
|
||||
val at := walk.next();
|
||||
lowest = at < lowest ? at : lowest;
|
||||
walk.enter(this.c.checker.syn(), at);
|
||||
}
|
||||
return lowest;
|
||||
}
|
||||
|
||||
#! The function an anonymous function is lowered to, made where it is new.
|
||||
#! @param this The compiler.
|
||||
#! @param table The result table its nodes' results are in.
|
||||
#! @param node Its `lambda` node.
|
||||
#! @param file The file it is in.
|
||||
#! @param kind Its function type.
|
||||
#! @param closure Whether it captures locals.
|
||||
#! @returns The function's index.
|
||||
pub def lowerer::lambda_of(&mut this, table: u32, node: u32, file: u32, kind: u32, closure: bool): u32 {
|
||||
val key := pair_key(table, node);
|
||||
if this.lambda_ids.get(&key) is some(got) {
|
||||
return got;
|
||||
}
|
||||
val index := this.add_function(string::from("<lambda>", nothing {}), this.signature_of(kind));
|
||||
this.lambda_ids.set(key, index);
|
||||
this.program.functions[index].node = node;
|
||||
this.program.functions[index].table = table;
|
||||
this.program.functions[index].file = file;
|
||||
this.program.functions[index].offset = this.node_offset(file, node);
|
||||
this.program.functions[index].closure = closure;
|
||||
this.want(index);
|
||||
return index;
|
||||
}
|
||||
|
||||
#! The adapter of a function named as a value of another function type: a
|
||||
#! function of that type, made where it is first named, which calls it as a call
|
||||
#! would, with the defaults of the parameters the type leaves out.
|
||||
#! @param this The compiler.
|
||||
#! @param table The result table holding the node.
|
||||
#! @param node The node naming the function.
|
||||
#! @param file The file the node is in.
|
||||
#! @param kind The function type the adapter is of.
|
||||
#! @param callee The function it calls.
|
||||
#! @returns The adapter.
|
||||
pub def lowerer::adapter_of(&mut this, table: u32, node: u32, file: u32, kind: u32, callee: u32): u32 {
|
||||
val key := pair_key(table, node);
|
||||
if this.adapter_ids.get(&key) is some(got) {
|
||||
return got;
|
||||
}
|
||||
var name := string::from(this.program.functions[callee].name.view(), nothing {});
|
||||
name.append(" (adapted)");
|
||||
val index := this.add_function(move(&mut name), this.signature_of(kind));
|
||||
this.adapter_ids.set(key, index);
|
||||
this.program.functions[index].adapted = callee + 1;
|
||||
this.program.functions[index].node = node;
|
||||
this.program.functions[index].table = table;
|
||||
this.program.functions[index].file = file;
|
||||
this.program.functions[index].offset = this.node_offset(file, node);
|
||||
this.program.functions[index].taken = true;
|
||||
this.want(index);
|
||||
return index;
|
||||
}
|
||||
|
||||
#! Lowers an adapter: each parameter of the type it is of is given to the
|
||||
#! function it calls as a call gives an argument: a value lent where it takes a
|
||||
#! reference, closed once the call returns, a reference read through where it
|
||||
#! takes what it reaches, and a value converted or moved where it takes a value.
|
||||
#! The parameters the type leaves out take their defaults, and what the function
|
||||
#! gives is converted to what the type gives.
|
||||
#! @param this The emitter.
|
||||
pub def emitter::lower_adapter(&mut this): void {
|
||||
val entry := this.function;
|
||||
val callee: u32 = this.c.program.functions[entry].adapted - 1;
|
||||
val node: u32 = this.c.program.functions[entry].node;
|
||||
this.table = this.c.program.functions[entry].table;
|
||||
this.use_own_table();
|
||||
this.at_node(node);
|
||||
val wanted := this.c.checker.unalias(this.c.checker.converted(node));
|
||||
val kind := this.c.checker.unalias(this.c.checker.type_at(node));
|
||||
this.result = this.c.checker.types.first_of(wanted);
|
||||
val signature: u32 = this.c.program.functions[entry].signature;
|
||||
val count := this.c.checker.types.part_count(wanted);
|
||||
|
||||
var next: u32 = 0;
|
||||
var given := gathered { values = vector::<operand>::new() };
|
||||
var lent := vector::<location>::new();
|
||||
for i in 0..count {
|
||||
val held := this.take_param(signature, i as u32, &mut next);
|
||||
val param := this.c.checker.types.part_at(kind, i as u32);
|
||||
val place := this.param_place(0, held);
|
||||
val takes_reference := this.c.is_reference_type(this.c.checker.unalias(param));
|
||||
if takes_reference && !this.c.is_reference_type(this.c.checker.unalias(held.kind)) {
|
||||
given.values.append(this.reference_to(&place, param));
|
||||
if this.c.checker.closes(held.kind) {
|
||||
lent.append(place);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
val value := this.load(&place);
|
||||
given.values.append(this.convert(&value, param));
|
||||
# What converts lends from what the adapter holds, as a string a view of its
|
||||
# text, and what doesn't is moved into the call.
|
||||
if !takes_reference && this.c.checker.closes(held.kind)
|
||||
&& this.c.checker.unalias(held.kind) != this.c.checker.unalias(param) {
|
||||
lent.append(place);
|
||||
}
|
||||
}
|
||||
|
||||
val decl: u32 = this.c.program.functions[callee].decl;
|
||||
val instance: u32 = this.c.program.functions[callee].instance;
|
||||
val total := this.c.checker.types.part_count(kind);
|
||||
if count < total {
|
||||
this.defaults_of(decl, instance, kind, count as u32, total, &mut given, node, 0);
|
||||
}
|
||||
val made := this.call_function(callee, &given, this.c.checker.types.first_of(kind));
|
||||
val result := this.convert(&made, this.result);
|
||||
for &each in lent.view() {
|
||||
this.close(&each);
|
||||
}
|
||||
var args := vector::<u32>::new();
|
||||
result.args(&mut args);
|
||||
this.give_back(args.view());
|
||||
}
|
||||
|
||||
#! Lowers an anonymous function: the locals it captures are reached through the
|
||||
#! references its environment holds, which it never closes, since the function
|
||||
#! declaring them owns them.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `lambda` node.
|
||||
pub def emitter::lower_lambda(&mut this, node: u32): void {
|
||||
this.table = this.c.program.functions[this.function].table;
|
||||
this.use_own_table();
|
||||
this.at_node(node);
|
||||
val kind := this.c.checker.type_at(node);
|
||||
this.result = this.c.checker.types.first_of(kind);
|
||||
val params := this.c.checker.left_of(node);
|
||||
val body := this.c.checker.record(node, lambda_slot::body);
|
||||
val signature: u32 = this.c.program.functions[this.function].signature;
|
||||
val total := this.c.program.signatures[signature].params.length as u32;
|
||||
|
||||
var next: u32 = 0;
|
||||
var taken := vector::<operand>::new();
|
||||
for i in 0..total {
|
||||
taken.append(this.take_param(signature, i as u32, &mut next));
|
||||
}
|
||||
|
||||
# The environment follows the parameters.
|
||||
if this.c.program.functions[this.function].closure {
|
||||
val environment := this.build.param(next);
|
||||
var captures := this.captures_of(node);
|
||||
val reference := this.c.checker.types.reference(bt::int64, false);
|
||||
for i in 0..captures.length {
|
||||
val at := location { kind = reference, address = environment, offset = i as u64 * word_size };
|
||||
val made := this.load(&at);
|
||||
val captured := captures[i];
|
||||
val place := location { kind = this.c.checker.type_at(captured), address = made.words[0] };
|
||||
this.declare(captured, place, false);
|
||||
}
|
||||
}
|
||||
|
||||
this.plan_lambda(node);
|
||||
for i in 0..this.c.checker.run_length(params) {
|
||||
break if i as u64 >= taken.length;
|
||||
val param := this.c.checker.run_at(params, i as u32);
|
||||
val place := this.param_place(param, taken[i]);
|
||||
this.declare(param, place, this.c.checker.closes(taken[i].kind));
|
||||
}
|
||||
this.safepoint();
|
||||
this.lower_body(body);
|
||||
}
|
||||
@@ -0,0 +1,553 @@
|
||||
#! @file composite.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the lowering of values built from others, and of what reads into
|
||||
#! them: struct and union literals, with the defaults of the fields they leave
|
||||
#! out, array literals, the members of a value, its properties through their
|
||||
#! accessors, and slices.
|
||||
|
||||
import sakura::analyzer;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! A struct or union literal, built in a cell the statement holds.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `construct` node.
|
||||
#! @returns The value.
|
||||
pub def emitter::construct(&mut this, node: u32): operand {
|
||||
return this.construct_of(this.c.checker.type_at(node), this.c.checker.right_of(node));
|
||||
}
|
||||
|
||||
#! A struct or union literal of a type, given its field inits, built in a cell
|
||||
#! the statement holds, as an attribute's value is too.
|
||||
#! @param this The emitter.
|
||||
#! @param kind The type.
|
||||
#! @param inits The run of `field_init` nodes.
|
||||
#! @returns The value.
|
||||
pub def emitter::construct_of(&mut this, kind: u32, inits: u32): operand {
|
||||
val plain := this.c.checker.unalias(kind);
|
||||
return operand::none(kind) if plain == bt::void_type;
|
||||
val index := this.c.layout_of(plain);
|
||||
val shape := this.c.layout_at(index);
|
||||
val address := this.temporary_of(kind);
|
||||
val decl := this.c.checker.types.first_of(plain);
|
||||
# A struct's fields given write themselves, so what is cleared is the rest:
|
||||
# the padding, and the fields left out, which take their defaults over zero.
|
||||
if shape.kind != lk::variant && this.c.checker.decls.kinds.p[decl] != dk::union_type {
|
||||
this.clear_unwritten(address, index, inits);
|
||||
} else {
|
||||
this.build.clear(address, shape.size);
|
||||
}
|
||||
val whole := location { kind = kind, address = address, framed = true };
|
||||
|
||||
# A union holds the one field it is given, whose index is its tag. A C union
|
||||
# holds it over the others, without a tag.
|
||||
if shape.kind == lk::variant {
|
||||
if this.c.checker.run_length(inits) == 0 {
|
||||
this.defaults(&whole);
|
||||
return operand::at(kind, address);
|
||||
}
|
||||
val init := this.c.checker.run_at(inits, 0);
|
||||
val field := this.c.checker.ref_at(init);
|
||||
for i in 0..shape.count {
|
||||
val each := this.c.field_at(index, i as u32);
|
||||
continue if each.decl != field;
|
||||
if shape.niche == 0 {
|
||||
this.build.store(access::i64, address, 0, this.build.word(i));
|
||||
}
|
||||
val value := this.value_as(this.c.checker.left_of(init), each.type_id);
|
||||
this.adopt(&value);
|
||||
val at := this.within(&whole, each.offset, each.type_id);
|
||||
this.store(&at, &value);
|
||||
}
|
||||
return operand::at(kind, address);
|
||||
}
|
||||
|
||||
var given := vector::<u32>::new();
|
||||
for i in 0..this.c.checker.run_length(inits) {
|
||||
val init := this.c.checker.run_at(inits, i as u32);
|
||||
val field := this.c.checker.ref_at(init);
|
||||
given.append(field);
|
||||
val at := this.field_in(&whole, plain, field, 0);
|
||||
val value := this.value_as(this.c.checker.left_of(init), at.kind);
|
||||
this.adopt(&value);
|
||||
this.store(&at, &value);
|
||||
}
|
||||
if this.c.checker.decls.kinds.p[decl] == dk::union_type {
|
||||
if given.length == 0 {
|
||||
this.defaults(&whole);
|
||||
}
|
||||
return operand::at(kind, address);
|
||||
}
|
||||
|
||||
# The fields left out take their defaults, or the defaults of what they hold.
|
||||
for i in 0..shape.count {
|
||||
val each := this.c.field_at(index, i as u32);
|
||||
var was_given := false;
|
||||
for &field in given {
|
||||
was_given = was_given || field == each.decl;
|
||||
}
|
||||
continue if was_given;
|
||||
val at := this.within(&whole, each.offset, each.type_id);
|
||||
this.default_of(&at, each.decl, each.spread);
|
||||
}
|
||||
return operand::at(kind, address);
|
||||
}
|
||||
|
||||
#! Clears the bytes of a struct literal's memory that none of the fields it
|
||||
#! gives writes, where each is written whole: those of its own fields, and not
|
||||
#! those a spread brings in, whose spread field is cleared whole.
|
||||
#! @param this The emitter.
|
||||
#! @param address Where the struct is built.
|
||||
#! @param index Its layout.
|
||||
#! @param inits The run of `field_init` nodes.
|
||||
def emitter::clear_unwritten(&mut this, address: u32, index: u32, inits: u32): void {
|
||||
val shape := this.c.layout_at(index);
|
||||
var written := vector::<bool>::new();
|
||||
written.resize(shape.size);
|
||||
for i in 0..this.c.checker.run_length(inits) {
|
||||
val field := this.c.checker.ref_at(this.c.checker.run_at(inits, i as u32));
|
||||
for k in 0..shape.count {
|
||||
val each := this.c.field_at(index, k as u32);
|
||||
continue if each.decl != field || each.spread;
|
||||
val end := each.offset + this.c.shape_of(each.type_id).size;
|
||||
for at in each.offset..end {
|
||||
written[at] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
var at: u64 = 0;
|
||||
while at < shape.size {
|
||||
if written[at] {
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
var end := at;
|
||||
while end < shape.size && !written[end] {
|
||||
end++;
|
||||
}
|
||||
this.clear_bytes(address, at, end);
|
||||
at = end;
|
||||
}
|
||||
}
|
||||
|
||||
#! Clears a run of bytes at an address: as stores of zero where it is a few
|
||||
#! words, as padding is, and otherwise at once.
|
||||
#! @param this The emitter.
|
||||
#! @param address The address.
|
||||
#! @param from The first byte.
|
||||
#! @param to Past the last.
|
||||
def emitter::clear_bytes(&mut this, address: u32, from: u64, to: u64): void {
|
||||
if to - from > 4 * word_size {
|
||||
val first := from == 0 ? address : this.build.binary(op::add, address, this.build.word(from));
|
||||
this.build.clear(first, to - from);
|
||||
return;
|
||||
}
|
||||
val zero := this.build.word(0);
|
||||
var at := from;
|
||||
while at < to {
|
||||
val left := to - at;
|
||||
val how := left >= 8 && at % 8 == 0 ? access::i64
|
||||
: left >= 4 && at % 4 == 0 ? access::u32
|
||||
: left >= 2 && at % 2 == 0 ? access::u16 : access::u8;
|
||||
this.build.store(how, address, at, zero);
|
||||
at += how.width();
|
||||
}
|
||||
}
|
||||
|
||||
#! `a..b`, or `a..=b`, as a value: std's `range<T>`, built in a cell the
|
||||
#! statement holds from its fields in the order std declares them, its start,
|
||||
#! its end, and whether it is still to give its end.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `range` node.
|
||||
#! @returns The value.
|
||||
pub def emitter::range_value(&mut this, node: u32): operand {
|
||||
val kind := this.c.checker.type_at(node);
|
||||
val plain := this.c.checker.unalias(kind);
|
||||
val index := this.c.layout_of(plain);
|
||||
val shape := this.c.layout_at(index);
|
||||
val address := this.temporary_of(kind);
|
||||
this.build.clear(address, shape.size);
|
||||
val whole := location { kind = kind, address = address, framed = true };
|
||||
|
||||
val start := this.c.field_at(index, 0);
|
||||
val first := this.value_as(this.c.checker.left_of(node), start.type_id);
|
||||
val at_start := this.within(&whole, start.offset, start.type_id);
|
||||
this.store(&at_start, &first);
|
||||
|
||||
val end := this.c.field_at(index, 1);
|
||||
val last := this.value_as(this.c.checker.right_of(node), end.type_id);
|
||||
val at_end := this.within(&whole, end.offset, end.type_id);
|
||||
this.store(&at_end, &last);
|
||||
|
||||
if this.c.checker.token_kind(node) == tk::cascadeeq {
|
||||
val held := this.c.field_at(index, 2);
|
||||
this.build.store(access::u8, address, held.offset, this.build.word(1));
|
||||
}
|
||||
return operand::at(kind, address);
|
||||
}
|
||||
|
||||
#! Sets the defaults of the fields of a zeroed struct, and of the first field a
|
||||
#! zeroed union holds, as a variable without a value is given them.
|
||||
#! @param this The emitter.
|
||||
#! @param place The place, zeroed.
|
||||
pub def emitter::defaults(&mut this, place: &location): void {
|
||||
val plain := this.c.checker.unalias(place.kind);
|
||||
return if this.c.checker.types.kind_of(plain) != ty::named;
|
||||
val index := this.c.layout_of(plain);
|
||||
val shape := this.c.layout_at(index);
|
||||
val decl := this.c.checker.types.first_of(plain);
|
||||
val named := this.c.checker.decls.kinds.p[decl];
|
||||
return if named != dk::struct_type && named != dk::union_type;
|
||||
|
||||
# A union is zeroed as its first field, and so is a C union.
|
||||
if named == dk::union_type {
|
||||
if shape.count != 0 {
|
||||
val first := this.c.field_at(index, 0);
|
||||
val inner := this.c.layout_at(first.layout);
|
||||
if inner.kind == lk::record {
|
||||
val at := this.within(place, first.offset, first.type_id);
|
||||
this.defaults(&at);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
for i in 0..shape.count {
|
||||
val each := this.c.field_at(index, i as u32);
|
||||
val at := this.within(place, each.offset, each.type_id);
|
||||
this.default_of(&at, each.decl, each.spread);
|
||||
}
|
||||
}
|
||||
|
||||
#! Gives a field of a zeroed struct its default: the value it is declared with,
|
||||
#! made where the struct is declared, or the defaults of a struct it holds.
|
||||
#! @param this The emitter.
|
||||
#! @param place The field's place, zeroed.
|
||||
#! @param field The field's declaration.
|
||||
#! @param spread Whether it spreads another struct's fields.
|
||||
def emitter::default_of(&mut this, place: &location, field: u32, spread: bool): void {
|
||||
val value := spread ? 0 : this.c.checker.field_default(field);
|
||||
if value == 0 {
|
||||
val inner := this.c.shape_of(place.kind);
|
||||
if inner.kind == lk::record {
|
||||
this.defaults(place);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
val file: u32 = this.c.checker.decls.files.p[field];
|
||||
val saved := this.c.checker.at;
|
||||
this.c.checker.use_table(this.c.checker.units[file].table);
|
||||
val made := this.value_as(value, place.kind);
|
||||
this.c.checker.at = saved;
|
||||
this.adopt(&made);
|
||||
this.store(place, &made);
|
||||
}
|
||||
|
||||
#! An array literal: a fixed array holding its elements, or, where a view is
|
||||
#! wanted, a view of such an array, which lives as long as the function does,
|
||||
#! since the view may outlive the statement.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `array` node.
|
||||
#! @param kind The type it is used as.
|
||||
#! @returns The value.
|
||||
pub def emitter::array_literal(&mut this, node: u32, kind: u32): operand {
|
||||
val run := this.c.checker.left_of(node);
|
||||
val count := this.c.checker.run_length(run);
|
||||
val plain := this.c.checker.unalias(kind);
|
||||
val viewed := this.c.viewed(plain);
|
||||
val element := viewed != 0 ? viewed : this.c.checker.types.first_of(plain);
|
||||
val inner := this.c.shape_of(element);
|
||||
|
||||
if viewed != 0 {
|
||||
val view := this.temporary_of(kind);
|
||||
if count == 0 {
|
||||
this.build.clear(view, 2 * word_size);
|
||||
return operand::at(kind, view);
|
||||
}
|
||||
|
||||
# A read-only view of what is known while compiling views data the program
|
||||
# holds, made once.
|
||||
if this.c.checker.is_std(plain, word::span) {
|
||||
val held := this.static_datum(node, element);
|
||||
if held != no_block {
|
||||
val data := this.build.value(op::datum, span::<u32>::empty(), vt::word, held, 0);
|
||||
this.build.store(access::i64, view, 0, data);
|
||||
this.build.store(access::i64, view, word_size, this.build.word(count as u64));
|
||||
return operand::at(kind, view);
|
||||
}
|
||||
}
|
||||
val array := this.c.checker.types.fixed(element, count);
|
||||
val held := this.c.shape_of(array);
|
||||
val cell := this.build.code.add_cell(round_up(held.size, word_size) as u32,
|
||||
held.align < word_size ? word_size as u32 : held.align as u32, ck::local, 0);
|
||||
val first := this.build.cell_address(cell);
|
||||
this.fill_array(run, element, inner.size, first);
|
||||
this.build.store(access::i64, view, 0, first);
|
||||
this.build.store(access::i64, view, word_size, this.build.word(count as u64));
|
||||
# What the array holds closes where the statement ends, since a view owns
|
||||
# nothing.
|
||||
var whole := operand::at(array, first);
|
||||
this.keep(&whole);
|
||||
return operand::at(kind, view);
|
||||
}
|
||||
|
||||
val address := this.temporary_of(kind);
|
||||
this.fill_array(run, element, inner.size, address);
|
||||
return operand::at(kind, address);
|
||||
}
|
||||
|
||||
#! The datum holding the elements of an array literal, where each is known
|
||||
#! while compiling: a number, text, or an array literal viewed of the same.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `array` node.
|
||||
#! @param element The elements' type.
|
||||
#! @returns The datum, or `no_block` where an element is not known.
|
||||
def emitter::static_datum(&mut this, node: u32, element: u32): u32 {
|
||||
val run := this.c.checker.left_of(node);
|
||||
val count := this.c.checker.run_length(run);
|
||||
val inner := this.c.shape_of(element);
|
||||
var bytes := vector::<u8>::new();
|
||||
bytes.resize(count as u64 * inner.size + 1);
|
||||
var moved := vector::<relocation>::new();
|
||||
for i in 0..count {
|
||||
val each := this.c.checker.run_at(run, i as u32);
|
||||
return no_block if !this.write_static(each, element, &mut bytes, i as u64 * inner.size, &mut moved);
|
||||
}
|
||||
val index := this.c.program.data.length as u32;
|
||||
this.c.program.data.append(datum {
|
||||
bytes = move(&mut bytes),
|
||||
align = inner.align < word_size ? word_size : inner.align,
|
||||
relocations = move(&mut moved)
|
||||
});
|
||||
return index;
|
||||
}
|
||||
|
||||
#! Writes a value known while compiling into the bytes of a datum, laid out as
|
||||
#! its type is.
|
||||
#! @param this The emitter.
|
||||
#! @param node The value's node.
|
||||
#! @param kind Its type.
|
||||
#! @param bytes The datum's bytes.
|
||||
#! @param at Where it is written.
|
||||
#! @param moved Where the addresses it holds are noted.
|
||||
#! @returns Whether it is known.
|
||||
def emitter::write_static(&mut this, node: u32, kind: u32, bytes: &mut vector<u8>, at: u64, moved: &mut vector<relocation>): bool {
|
||||
val shape := this.c.shape_of(kind);
|
||||
if this.c.is_scalar_type(kind) && this.c.checker.is_known(node) {
|
||||
val value := this.c.checker.value_at(node);
|
||||
var word: u64 = 0;
|
||||
if shape.kind == lk::floating {
|
||||
val real := value.as_real();
|
||||
word = shape.bits <= 32 ? bits_of_single(real as f32) as u64 : bits_of_real(real);
|
||||
} else {
|
||||
word = value.floating ? (value.real as i64) as u64 : value.bits();
|
||||
}
|
||||
write_number(bytes, at, shape.size, word);
|
||||
return true;
|
||||
}
|
||||
|
||||
val viewed := this.c.viewed(kind);
|
||||
return false if viewed == 0 || !this.c.checker.is_std(this.c.checker.unalias(kind), word::span);
|
||||
var target: u32 = no_block;
|
||||
var length: u64 = 0;
|
||||
if this.c.checker.kind_of(node) == nk::string {
|
||||
var text := string::new(nothing {});
|
||||
this.decode_literal(this.c.checker.text_of(node), &mut text);
|
||||
target = this.c.text_datum(text.view());
|
||||
length = text.length;
|
||||
} else if this.c.checker.kind_of(node) == nk::array {
|
||||
length = this.c.checker.run_length(this.c.checker.left_of(node)) as u64;
|
||||
target = length == 0 ? no_block : this.static_datum(node, viewed);
|
||||
return false if length != 0 && target == no_block;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
if length != 0 {
|
||||
moved.append(relocation { at = at, target = target, addend = 0 });
|
||||
}
|
||||
write_number(bytes, at + word_size, word_size, length);
|
||||
return true;
|
||||
}
|
||||
|
||||
#! The bits of an `f32`.
|
||||
#! @param value The value.
|
||||
#! @returns Its bits.
|
||||
def bits_of_single(value: f32): u32 {
|
||||
var held := value;
|
||||
return ((&mut held) as *mut u32)[0];
|
||||
}
|
||||
|
||||
#! Writes the elements of an array literal one after another from an address.
|
||||
#! @param this The emitter.
|
||||
#! @param run The run of the elements' nodes.
|
||||
#! @param element Their type.
|
||||
#! @param size The size of each.
|
||||
#! @param first Where the first goes.
|
||||
def emitter::fill_array(&mut this, run: u32, element: u32, size: u64, first: u32): void {
|
||||
for i in 0..this.c.checker.run_length(run) {
|
||||
val value := this.value_as(this.c.checker.run_at(run, i as u32), element);
|
||||
this.adopt(&value);
|
||||
val at := location { kind = element, address = first, offset = i as u64 * size, framed = true };
|
||||
this.store(&at, &value);
|
||||
}
|
||||
}
|
||||
|
||||
#! `x.name`: a field, read where it is, or a property, read through its `get`.
|
||||
#! The length of a fixed array is known while compiling, which its value gives.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `member` node.
|
||||
#! @returns The value.
|
||||
pub def emitter::member_value(&mut this, node: u32): operand {
|
||||
val property := this.property_of(node);
|
||||
if property != 0 {
|
||||
val object := this.c.checker.left_of(node);
|
||||
val receiver := this.receiver_of(object, false);
|
||||
return this.property_get(property, &receiver, node);
|
||||
}
|
||||
val place := this.place_of(node);
|
||||
return this.load(&place);
|
||||
}
|
||||
|
||||
#! The property a member names, or 0.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node.
|
||||
#! @returns The property's declaration, or 0.
|
||||
pub def emitter::property_of(&mut this, node: u32): u32 {
|
||||
val kind := this.c.checker.kind_of(node);
|
||||
return 0 if kind != nk::member && kind != nk::member_of;
|
||||
val ref := this.c.checker.ref_at(node);
|
||||
return 0 if ref == 0 || (ref & (ref_local | ref_type)) != 0;
|
||||
# `x.(d)` may name the accessor of the property.
|
||||
if this.c.checker.decls.kinds.p[ref] == dk::function && this.c.checker.decls.has(ref, df::accessor) {
|
||||
return this.c.checker.decls.owners.p[ref];
|
||||
}
|
||||
return this.c.checker.decls.kinds.p[ref] == dk::property ? ref : 0;
|
||||
}
|
||||
|
||||
#! The reference a method or a property's accessors take to the value they are
|
||||
#! of: the reference the value already is, read through to the last, or one to
|
||||
#! the place it is, or to a copy of it where it is no place.
|
||||
#! @param this The emitter.
|
||||
#! @param object The node of the value.
|
||||
#! @param writes Whether it is written.
|
||||
#! @returns The reference.
|
||||
pub def emitter::receiver_of(&mut this, object: u32, writes: bool): operand {
|
||||
val kind := this.c.checker.type_at(object);
|
||||
return this.through_one(object) if this.c.is_reference_type(kind);
|
||||
return this.reference_arg(object, this.c.checker.types.reference(kind, writes));
|
||||
}
|
||||
|
||||
#! The accessor of a property: its `set`, or its `get`.
|
||||
#! @param this The emitter.
|
||||
#! @param property The property's declaration.
|
||||
#! @param setter Whether the `set` is wanted.
|
||||
#! @returns The accessor's declaration, or 0.
|
||||
pub def emitter::accessor_of(&mut this, property: u32, setter: bool): u32 {
|
||||
val run: u32 = this.c.checker.decls.children.p[property];
|
||||
for i in 0..this.c.checker.decls.list_length(run) {
|
||||
val each := this.c.checker.decls.list_at(run, i as u32);
|
||||
return each if this.c.checker.decls.has(each, df::setter) == setter;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! Reads a property through its `get`.
|
||||
#! @param this The emitter.
|
||||
#! @param property The property's declaration.
|
||||
#! @param receiver The reference to the value it is of.
|
||||
#! @param node The node reading it.
|
||||
#! @returns What its `get` gives.
|
||||
pub def emitter::property_get(&mut this, property: u32, receiver: &operand, node: u32): operand {
|
||||
val getter := this.accessor_of(property, false);
|
||||
if getter == 0 {
|
||||
this.problem(node, "The property has no `get`.");
|
||||
return this.zero_value(this.c.checker.type_at(node));
|
||||
}
|
||||
val owner := this.c.checker.types.first_of(this.c.checker.unalias(receiver.kind));
|
||||
val made := this.method_call(getter, owner, receiver, span::<operand>::empty());
|
||||
this.keep(&made);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Writes a property through its `set`.
|
||||
#! @param this The emitter.
|
||||
#! @param property The property's declaration.
|
||||
#! @param receiver The reference to the value it is of.
|
||||
#! @param value The value written.
|
||||
#! @param node The node writing it.
|
||||
pub def emitter::property_set(&mut this, property: u32, receiver: &operand, value: &operand, node: u32): void {
|
||||
val setter := this.accessor_of(property, true);
|
||||
if setter == 0 {
|
||||
this.problem(node, "The property has no `set`.");
|
||||
return;
|
||||
}
|
||||
val owner := this.c.checker.types.first_of(this.c.checker.unalias(receiver.kind));
|
||||
var others: operand[1] = [value];
|
||||
this.method_call(setter, owner, receiver, others[0:1]);
|
||||
}
|
||||
|
||||
#! `x[start:count]`: a view of the elements of a fixed array, of what a pointer
|
||||
#! points at, or of another view, checked against how many there are where that
|
||||
#! is known. Either bound may be left out but a pointer's count.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `slice` node.
|
||||
#! @returns The view.
|
||||
pub def emitter::slice(&mut this, node: u32): operand {
|
||||
val object := this.c.checker.left_of(node);
|
||||
val start := this.c.checker.record(node, slice_slot::start);
|
||||
val count := this.c.checker.record(node, slice_slot::count);
|
||||
val kind := this.c.checker.type_at(node);
|
||||
val through := this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(object)));
|
||||
var data: u32 = 0;
|
||||
var held: u32 = 0;
|
||||
var element: u32 = 0;
|
||||
|
||||
match this.c.checker.types.kind_of(through) {
|
||||
ty::fixed => {
|
||||
val whole := this.object(object);
|
||||
val shape := this.c.shape_of(through);
|
||||
data = this.address_of(&whole);
|
||||
held = this.build.word(shape.count as u64);
|
||||
element = this.c.checker.types.first_of(through);
|
||||
}
|
||||
ty::pointer => {
|
||||
val pointer := this.value_of_type(object);
|
||||
data = this.through_references(&pointer).words[0];
|
||||
element = this.c.checker.types.first_of(through);
|
||||
}
|
||||
else => {
|
||||
val whole := this.object(object);
|
||||
data = this.build.load(access::i64, whole.address, whole.offset);
|
||||
held = this.build.load(access::i64, whole.address, whole.offset + word_size);
|
||||
element = this.c.viewed(through);
|
||||
}
|
||||
}
|
||||
|
||||
val size := this.c.shape_of(element).size;
|
||||
var from := this.build.word(0);
|
||||
if start != 0 {
|
||||
from = this.value_as(start, bt::uint64).words[0];
|
||||
if held != 0 && this.checking() {
|
||||
this.build.check(this.build.binary(op::leu, from, held), fault::out_of_bounds as u32);
|
||||
}
|
||||
}
|
||||
var many: u32 = 0;
|
||||
if count != 0 {
|
||||
many = this.value_as(count, bt::uint64).words[0];
|
||||
if held != 0 && this.checking() {
|
||||
val rest := this.build.binary(op::sub, held, from);
|
||||
this.build.check(this.build.binary(op::leu, many, rest), fault::out_of_bounds as u32);
|
||||
}
|
||||
} else {
|
||||
many = held != 0 ? this.build.binary(op::sub, held, from) : this.build.word(0);
|
||||
}
|
||||
|
||||
val first := this.build.binary(op::add, data, this.scaled(from, size));
|
||||
val view := this.temporary_of(kind);
|
||||
this.build.store(access::i64, view, 0, first);
|
||||
this.build.store(access::i64, view, word_size, many);
|
||||
return operand::at(kind, view);
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
#! @file formatting.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the lowering of text a program writes while it runs: interpolated
|
||||
#! strings, whose holes are written as the values they hold, and the text of
|
||||
#! literals, decoded from how they are written.
|
||||
|
||||
import sakura::analyzer;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! An interpolated string: its text and the values of its holes, written in
|
||||
#! order into text a `string` then owns. A view of bytes, and a string, are
|
||||
#! written as the text they hold.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `istring` node.
|
||||
#! @returns The string.
|
||||
pub def emitter::interpolated(&mut this, node: u32): operand {
|
||||
this.build.effect(op::format, span::<u32>::empty(), 0, 0);
|
||||
val run := this.c.checker.left_of(node);
|
||||
val count := this.c.checker.run_length(run);
|
||||
|
||||
# The lines of a block are written without the indentation its closing
|
||||
# delimiter stands at, as a block of plain text is.
|
||||
var indent: u64 = 0;
|
||||
var block := false;
|
||||
if count != 0 && this.c.checker.kind_of(this.c.checker.run_at(run, 0)) == nk::string {
|
||||
val opened := this.c.checker.text_of(this.c.checker.run_at(run, 0));
|
||||
block = opened.length >= 4 && opened.substr(0, 4) == "$\"\"\"";
|
||||
}
|
||||
if block && this.c.checker.kind_of(this.c.checker.run_at(run, count - 1)) == nk::string {
|
||||
val closed := this.c.checker.text_of(this.c.checker.run_at(run, count - 1));
|
||||
var line := closed.length;
|
||||
while line > 0 && closed[line - 1] != '\n' {
|
||||
line--;
|
||||
}
|
||||
if line != 0 && closed.length >= 3 {
|
||||
indent = closed.length - 3 - line;
|
||||
}
|
||||
}
|
||||
|
||||
for i in 0..count {
|
||||
val piece := this.c.checker.run_at(run, i as u32);
|
||||
if this.c.checker.kind_of(piece) == nk::string {
|
||||
var text := string::new(nothing {});
|
||||
if block {
|
||||
this.block_piece(piece, i == 0, indent, &mut text);
|
||||
} else {
|
||||
this.piece_text(piece, &mut text);
|
||||
}
|
||||
if text.length != 0 {
|
||||
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(text.view()), 0);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
val mark := this.cell_mark();
|
||||
val value := this.value(piece);
|
||||
this.format_value(&value);
|
||||
this.release(mark);
|
||||
}
|
||||
|
||||
# Text written where a view is wanted is made as a string all the same, which
|
||||
# the statement closes, so the view is only good while it runs.
|
||||
val made := this.c.checker.type_at(node);
|
||||
val text := this.owned_text(made);
|
||||
val wanted := this.c.checker.converted(node);
|
||||
return text if wanted == made;
|
||||
return this.convert(&text, wanted);
|
||||
}
|
||||
|
||||
#! Writes a value into the text being made: the bytes a view of them or a
|
||||
#! string holds, or the value as its layout says it is written.
|
||||
#! @param this The emitter.
|
||||
#! @param value The value.
|
||||
pub def emitter::format_value(&mut this, value: &operand): void {
|
||||
val kind := this.c.checker.unalias(value.kind);
|
||||
val viewed := this.c.is_reference_type(kind) ? 0 : this.c.viewed(kind);
|
||||
if viewed != 0 {
|
||||
val element := this.c.shape_of(viewed);
|
||||
if element.size == 1 && element.kind != lk::record {
|
||||
var args: u32[2] = [this.build.load(access::i64, value.address, 0), this.build.load(access::i64, value.address, word_size)];
|
||||
this.build.effect(op::format_bytes, args[0:2], 0, 0);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if !this.c.is_reference_type(kind) && this.c.is_string(kind) {
|
||||
val index := this.c.layout_of(kind);
|
||||
val data := this.c.field_at(index, 1);
|
||||
val count := this.c.field_at(index, 2);
|
||||
var args: u32[2] = [this.build.load(access::i64, value.address, data.offset), this.build.load(access::i64, value.address, count.offset)];
|
||||
this.build.effect(op::format_bytes, args[0:2], 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
var args := vector::<u32>::new();
|
||||
value.args(&mut args);
|
||||
this.build.effect(op::format_value, args.view(), this.c.layout_of(kind), 0);
|
||||
}
|
||||
|
||||
#! The text of a piece of an interpolated block, decoded: each of its lines
|
||||
#! without the spaces trailing it and followed by a line break, and each line
|
||||
#! after one without the indentation the block's closing delimiter stands at.
|
||||
#! The first piece begins below the line the block opens.
|
||||
#! @param this The emitter.
|
||||
#! @param piece The `string` node of the piece.
|
||||
#! @param first Whether it is the first piece.
|
||||
#! @param indent How far the block's lines are indented.
|
||||
#! @param out Where the bytes are written.
|
||||
def emitter::block_piece(&mut this, piece: u32, first: bool, indent: u64, out: &mut string): void {
|
||||
val written := this.c.checker.text_of(piece);
|
||||
var from := 0u;
|
||||
var to := written.length;
|
||||
if written.length >= 4 && written.substr(0, 4) == "$\"\"\"" {
|
||||
from = 4;
|
||||
} else if written.length >= 1 && written[0] == '}' {
|
||||
from = 1;
|
||||
}
|
||||
if to >= from + 3 && written.substr(to - 3, 3) == "\"\"\"" {
|
||||
to -= 3;
|
||||
} else if to > from && written[to - 1] == '{' {
|
||||
to -= 1;
|
||||
}
|
||||
|
||||
var at := from;
|
||||
if first {
|
||||
while at < to && written[at] != '\n' {
|
||||
at++;
|
||||
}
|
||||
return if at >= to;
|
||||
at = past_indent(written, at + 1, to, indent);
|
||||
}
|
||||
var start := at;
|
||||
while at < to {
|
||||
if written[at] != '\n' {
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
var stop := at;
|
||||
while stop > start && (written[stop - 1] == ' ' || written[stop - 1] == '\t') {
|
||||
stop--;
|
||||
}
|
||||
this.c.checker.decode_text(written.substr(start, stop - start), out);
|
||||
out.push('\n');
|
||||
at = past_indent(written, at + 1, to, indent);
|
||||
start = at;
|
||||
}
|
||||
this.c.checker.decode_text(written.substr(start, to - start), out);
|
||||
}
|
||||
|
||||
#! Where a line begins past the indentation of a block.
|
||||
#! @param text The text.
|
||||
#! @param at Where the line begins.
|
||||
#! @param end Where the text ends.
|
||||
#! @param indent How far the block's lines are indented.
|
||||
#! @returns Where the line begins past it.
|
||||
def past_indent(text: strview, at: u64, end: u64, indent: u64): u64 {
|
||||
var made := at;
|
||||
var skipped: u64 = 0;
|
||||
while skipped < indent && made < end && (text[made] == ' ' || text[made] == '\t') {
|
||||
made++;
|
||||
skipped++;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The text of a piece of an interpolated string, without what opens and
|
||||
#! closes it, decoded.
|
||||
#! @param this The emitter.
|
||||
#! @param piece The `string` node of the piece.
|
||||
#! @param out Where the bytes are written.
|
||||
def emitter::piece_text(&mut this, piece: u32, out: &mut string): void {
|
||||
val written := this.c.checker.text_of(piece);
|
||||
var from := 0u;
|
||||
var to := written.length;
|
||||
if written.length >= 4 && written.substr(0, 4) == "$\"\"\"" {
|
||||
from = 4;
|
||||
} else if written.length >= 2 && written.substr(0, 2) == "$\"" {
|
||||
from = 2;
|
||||
} else if written.length >= 1 && written[0] == '}' {
|
||||
from = 1;
|
||||
}
|
||||
if to >= from + 3 && written.substr(to - 3, 3) == "\"\"\"" {
|
||||
to -= 3;
|
||||
} else if to > from && (written[to - 1] == '"' || written[to - 1] == '{') {
|
||||
to -= 1;
|
||||
}
|
||||
this.c.checker.decode_text(written.substr(from, to - from), out);
|
||||
}
|
||||
|
||||
#! Decodes the text a literal is written as: between its quotes, with its
|
||||
#! escapes, or of text spanning lines, each of its lines without the
|
||||
#! indentation the closing quotes stand at, and each followed by a line break.
|
||||
#! @param this The emitter.
|
||||
#! @param written The literal, with its quotes.
|
||||
#! @param out Where the bytes are written.
|
||||
pub def emitter::decode_literal(&mut this, written: strview, out: &mut string): void {
|
||||
if written.length < 6 || written.substr(0, 3) != "\"\"\"" {
|
||||
this.c.checker.decode_text(written.substr(1, written.length < 2 ? 0 : written.length - 2), out);
|
||||
return;
|
||||
}
|
||||
|
||||
# The text begins below the line the block opens, and the closing quotes' own
|
||||
# line says how far every line of it is indented.
|
||||
val inner := written.substr(3, written.length - 6);
|
||||
var first := 0u;
|
||||
while first < inner.length && inner[first] != '\n' {
|
||||
first++;
|
||||
}
|
||||
var last := inner.length;
|
||||
while last > 0 && inner[last - 1] != '\n' {
|
||||
last--;
|
||||
}
|
||||
return if first >= inner.length || last <= first;
|
||||
|
||||
val indent := inner.length - last;
|
||||
var line := first + 1;
|
||||
while line < last {
|
||||
var stop := line;
|
||||
while stop < last && inner[stop] != '\n' {
|
||||
stop++;
|
||||
}
|
||||
var at := line;
|
||||
var skipped := 0u;
|
||||
while skipped < indent && at < stop && (inner[at] == ' ' || inner[at] == '\t') {
|
||||
at++;
|
||||
skipped++;
|
||||
}
|
||||
var text := stop;
|
||||
while text > at && (inner[text - 1] == ' ' || inner[text - 1] == '\t') {
|
||||
text--;
|
||||
}
|
||||
this.c.checker.decode_text(inner.substr(at, text - at), out);
|
||||
out.push('\n');
|
||||
line = stop + 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,546 @@
|
||||
#! @file intrinsics.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the intrinsics, the functions std declares `@intrinsic` that the
|
||||
#! compiler gives: an operation of their own, or a value worked out while
|
||||
#! compiling, rather than a call.
|
||||
|
||||
import sakura::analyzer;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! Lowers a call of an intrinsic.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `call` node.
|
||||
#! @param decl The intrinsic's declaration.
|
||||
#! @returns What it gives.
|
||||
pub def emitter::intrinsic(&mut this, node: u32, decl: u32): operand {
|
||||
val name := this.c.checker.names.text(this.c.checker.decls.names.p[decl]);
|
||||
val kind := this.c.checker.type_at(node);
|
||||
val run := this.c.checker.right_of(node);
|
||||
|
||||
# A type's layout is known while compiling.
|
||||
if name == "size_of" || name == "align_of" {
|
||||
val instance := this.called(node);
|
||||
var size: u64 = 0;
|
||||
if instance != 0 {
|
||||
val args: u32 = this.c.checker.instances[instance - 1].args;
|
||||
val held := this.c.shape_of(this.c.checker.types.part_at(args, 0));
|
||||
size = name == "size_of" ? held.size : held.align;
|
||||
}
|
||||
return operand::one(kind, this.build.word(size));
|
||||
}
|
||||
if name == "os" || name == "arch" || name == "backend" {
|
||||
val value := name == "os" ? this.c.checker.target.os : name == "arch" ? this.c.checker.target.arch : this.c.checker.target.backend;
|
||||
return this.text_value(this.c.checker.names.text(value), kind);
|
||||
}
|
||||
if name == "call_site" {
|
||||
return this.call_site(node, kind);
|
||||
}
|
||||
if name == "contracts" || name == "checking" {
|
||||
val off := name == "contracts" ? this.c.checker.contracts_off : this.c.checker.checks_off;
|
||||
return operand::one(kind, this.build.word(off ? 0 : 1));
|
||||
}
|
||||
# These read the argument as it is written: in a default, the argument the
|
||||
# call wrote for the parameter it names.
|
||||
if name == "source_of" || name == "values_of" {
|
||||
val arg := this.c.checker.run_length(run) != 0 ? this.c.checker.run_at(run, 0) : 0;
|
||||
val written := arg != 0 ? this.written_argument(arg) : 0;
|
||||
val saved := this.c.checker.at;
|
||||
if written != 0 {
|
||||
this.c.checker.use_table(this.defaulting.table);
|
||||
}
|
||||
val chosen := written != 0 ? written : arg;
|
||||
var made := operand {};
|
||||
if name == "source_of" {
|
||||
var text := string::new(nothing {});
|
||||
if chosen != 0 {
|
||||
this.source_text(chosen, &mut text);
|
||||
}
|
||||
this.c.checker.at = saved;
|
||||
made = this.text_value(text.view(), kind);
|
||||
} else {
|
||||
val outer := this.defaulting;
|
||||
this.defaulting = default_site {};
|
||||
made = this.values_of(chosen, kind);
|
||||
this.defaulting = outer;
|
||||
this.c.checker.at = saved;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
if name == "name_of" || name == "path_of" {
|
||||
# The checker keeps the type named as the callee's.
|
||||
val named := this.c.checker.type_at(this.c.checker.left_of(node));
|
||||
var text := string::new(nothing {});
|
||||
if named != 0 && named != bt::error {
|
||||
text = name == "path_of" ? this.c.checker.describe_path(named) : this.c.checker.describe(named);
|
||||
}
|
||||
return this.text_value(text.view(), kind);
|
||||
}
|
||||
if name == "value_of" {
|
||||
if this.c.checker.is_known(node) && this.c.is_scalar_type(kind) {
|
||||
return this.known(&this.c.checker.value_at(node), kind);
|
||||
}
|
||||
val ref := this.c.checker.ref_at(node);
|
||||
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::enum_member {
|
||||
var value := constant {};
|
||||
this.c.checker.decl_value(ref, &mut value);
|
||||
return this.known(&value, kind);
|
||||
}
|
||||
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::variable {
|
||||
val place := this.global_place(ref);
|
||||
return this.load(&place);
|
||||
}
|
||||
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::function {
|
||||
return this.function_value(node, ref);
|
||||
}
|
||||
# An attribute is the value it writes, made where it is read.
|
||||
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::attribute {
|
||||
val saved := this.c.checker.at;
|
||||
this.c.checker.use_table(this.c.checker.units[this.c.checker.decls.files.p[ref]].table);
|
||||
val made := this.construct_of(this.c.checker.decls.types.p[ref], this.c.checker.right_of(this.c.checker.decls.nodes.p[ref]));
|
||||
this.c.checker.at = saved;
|
||||
return made;
|
||||
}
|
||||
this.problem(node, "`value_of` reaches nothing lowering knows.");
|
||||
return this.zero_value(kind);
|
||||
}
|
||||
if name == "attached" {
|
||||
return this.attached(node, kind);
|
||||
}
|
||||
if name == "compile_error" {
|
||||
this.build.unreachable();
|
||||
return operand::none(kind);
|
||||
}
|
||||
if name == "lanes_have" || name == "lanes_apply" {
|
||||
return this.lanes(node, name == "lanes_have", kind);
|
||||
}
|
||||
# Vectors are values held in registers between operations in an executable
|
||||
# optimized with inlining and promotion, and nowhere else.
|
||||
if name == "lanes_held" {
|
||||
val native := !this.c.options.evaluating && this.c.checker.names.text(this.c.checker.target.backend) == "native";
|
||||
return operand::one(kind, this.build.word(native && this.c.options.level >= 2 ? 1 : 0));
|
||||
}
|
||||
|
||||
if name.starts_with("atomic_") {
|
||||
return this.atomic(node, name, kind);
|
||||
}
|
||||
|
||||
# `fault` takes its text's two words, wherever the view is.
|
||||
if name == "fault" {
|
||||
val text := this.value(this.c.checker.run_at(run, 0));
|
||||
var words: u32[2] = [0, 0];
|
||||
if text.address != 0 {
|
||||
words[0] = this.build.load(access::i64, text.address, 0);
|
||||
words[1] = this.build.load(access::i64, text.address, word_size);
|
||||
} else {
|
||||
words[0] = text.words[0];
|
||||
words[1] = text.words[1];
|
||||
}
|
||||
this.build.effect(op::fault, words[0:2], 0, 0);
|
||||
return operand::none(kind);
|
||||
}
|
||||
|
||||
# The rest are operations, given their arguments' values.
|
||||
var args := vector::<u32>::new();
|
||||
for i in 0..this.c.checker.run_length(run) {
|
||||
val made := this.value(this.c.checker.run_at(run, i as u32));
|
||||
made.args(&mut args);
|
||||
}
|
||||
# A member of an enum's place among the values of its members, and the member
|
||||
# at a place, by which a range of its members counts.
|
||||
if name == "rank_of" || name == "member_at" {
|
||||
val instance := this.called(node);
|
||||
val members := instance != 0 ? this.c.checker.types.part_at(this.c.checker.instances[instance - 1].args, 0) : bt::error;
|
||||
if members == bt::error || this.c.checker.named_kind(this.c.checker.unalias(members)) != dk::enum_type {
|
||||
this.problem(node, "`rank_of` and `member_at` count the members of an enum.");
|
||||
return this.zero_value(kind);
|
||||
}
|
||||
val made := name == "rank_of" ? this.member_rank(args[0], members) : this.member_of_rank(args[0], members);
|
||||
return operand::one(kind, made);
|
||||
}
|
||||
if name == "raw_allocate" || name == "raw_allocate_zeroed" {
|
||||
val uncleared: u32 = name == "raw_allocate" ? 1 : 0;
|
||||
return operand::one(kind, this.build.value(op::allocate, args.view(), vt::word, uncleared, 0));
|
||||
}
|
||||
if name == "raw_release" {
|
||||
this.build.effect(op::release, args.view(), 0, 0);
|
||||
return operand::none(kind);
|
||||
}
|
||||
# `core::close` closes a value where it is, as its scope ending would: its own
|
||||
# `close`, then what it holds that closes.
|
||||
if name == "close_where_it_is" {
|
||||
val instance := this.called(node);
|
||||
if instance != 0 && args.length > 0 {
|
||||
val closed := this.c.checker.types.part_at(this.c.checker.instances[instance - 1].args, 0);
|
||||
val place := location { kind = closed, address = args[0] };
|
||||
this.close(&place);
|
||||
}
|
||||
return operand::none(kind);
|
||||
}
|
||||
if name == "raw_resize" {
|
||||
return operand::one(kind, this.build.value(op::resize, args.view(), vt::word, 0, 0));
|
||||
}
|
||||
if name == "syscall" {
|
||||
return operand::one(kind, this.build.value(op::syscall, args.view(), vt::word, 0, 0));
|
||||
}
|
||||
if name == "frame" || name == "executable" || name == "environ" || name == "take_signals" || name == "current" {
|
||||
val chosen := name == "frame" ? op::frame : name == "executable" ? op::image : name == "environ" ? op::environ
|
||||
: name == "current" ? op::current : op::signals;
|
||||
return operand::one(kind, this.build.value(chosen, span::<u32>::empty(), vt::word, 0, 0));
|
||||
}
|
||||
# A thread runs the function value, of two words, given the context, a word;
|
||||
# the runtime starts one of the system on a record's stacks.
|
||||
if name == "start" || name == "clone_thread" {
|
||||
return operand::one(kind, this.build.value(name == "start" ? op::start : op::clone, args.view(), vt::word, 0, 0));
|
||||
}
|
||||
if name == "catch_signal" {
|
||||
return operand::one(kind, this.build.value(op::catch, args.view(), vt::word, 0, 0));
|
||||
}
|
||||
if name == "exit" {
|
||||
this.build.effect(op::exit, args.view(), 0, 0);
|
||||
return operand::none(kind);
|
||||
}
|
||||
if name == "abort" {
|
||||
this.build.effect(op::abort, span::<u32>::empty(), 0, 0);
|
||||
return operand::none(kind);
|
||||
}
|
||||
if name == "trap" {
|
||||
this.build.effect(op::trap, args.view(), 0, 0);
|
||||
return operand::none(kind);
|
||||
}
|
||||
# Operations of the machine on a whole real or word, which `std::math` narrows
|
||||
# for the other types.
|
||||
if name == "square_root" {
|
||||
return operand::one(kind, this.build.unary(op::fsqrt, args[0]));
|
||||
}
|
||||
if name == "ones_in" || name == "zeros_leading" || name == "zeros_trailing" || name == "bytes_reversed" {
|
||||
val chosen := name == "ones_in" ? op::ones : name == "zeros_leading" ? op::clz : name == "zeros_trailing" ? op::ctz : op::bswap;
|
||||
return operand::one(kind, this.build.unary(chosen, args[0]));
|
||||
}
|
||||
this.problem(node, "The intrinsic is not lowered.");
|
||||
return this.zero_value(kind);
|
||||
}
|
||||
|
||||
#! `lanes_have` and `lanes_apply`, of an operation on lanes: in an executable,
|
||||
#! whether the processor it runs on has the vector instructions working it, as
|
||||
#! it found when it started, and the lanes worked with them. The virtual machine
|
||||
#! and constants have none, so never reach the second.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `call` node.
|
||||
#! @param have Whether it is `lanes_have`.
|
||||
#! @param kind What it gives.
|
||||
#! @returns What it gives.
|
||||
def emitter::lanes(&mut this, node: u32, have: bool, kind: u32): operand {
|
||||
# Its type arguments are the type of lane, the operation, and how many lanes.
|
||||
var lane := lane_none;
|
||||
var operation: u32 = 0;
|
||||
var count: u64 = 0;
|
||||
val instance := this.called(node);
|
||||
if instance != 0 {
|
||||
val args: u32 = this.c.checker.instances[instance - 1].args;
|
||||
lane = this.lane_of(this.c.checker.types.part_at(args, 0));
|
||||
operation = this.constant_argument(this.c.checker.types.part_at(args, 1)) as u32;
|
||||
count = this.constant_argument(this.c.checker.types.part_at(args, 2));
|
||||
}
|
||||
val native := !this.c.options.evaluating && this.c.checker.names.text(this.c.checker.target.backend) == "native";
|
||||
val need := native && lane != lane_none ? lanes_needs(operation, lane, count * lane_bits(lane) / 8) : cpu_never;
|
||||
|
||||
if have {
|
||||
return operand::one(kind, this.build.word(0)) if need == cpu_never;
|
||||
return operand::one(kind, this.build.word(1)) if need == cpu_sse2;
|
||||
val found := this.build.value(op::cpu, span::<u32>::empty(), vt::word, 0, 0);
|
||||
val held := this.build.binary(op::band, found, this.build.word(need));
|
||||
return operand::one(kind, this.build.binary(op::eq, held, this.build.word(need)));
|
||||
}
|
||||
if need == cpu_never {
|
||||
this.build.unreachable();
|
||||
return operand::none(kind);
|
||||
}
|
||||
# The pointers: where the result goes, then the operands.
|
||||
var pointers := vector::<u32>::new();
|
||||
val run := this.c.checker.right_of(node);
|
||||
for i in 0..this.c.checker.run_length(run) {
|
||||
val made := this.value(this.c.checker.run_at(run, i as u32));
|
||||
made.args(&mut pointers);
|
||||
}
|
||||
|
||||
# The operands are read, worked as values, and the result written, so a
|
||||
# vector a cell holds is a value wherever the cell is promoted.
|
||||
val bytes := count * lane_bits(lane) / 8;
|
||||
var args := vector::<u32>::new();
|
||||
for k in 0..lanes_operands(operation) {
|
||||
val how := lanes_operand_access(operation, lane, bytes, k);
|
||||
args.append(this.build.load(how, pointers[1 + k as u64], 0));
|
||||
}
|
||||
val result := lanes_result_access(operation, lane, bytes);
|
||||
val made := operation == lanes_copy ? args[0]
|
||||
: this.build.value(op::lanes, args.view(), result.value_type(), operation, lane as u64 | bytes << 8);
|
||||
this.build.store(result, pointers[0], 0, made);
|
||||
return operand::none(kind);
|
||||
}
|
||||
|
||||
#! The atomics of `core::atomic`: an operation on the `T` at an address, in one
|
||||
#! step, which is the first type argument, and of `atomic_fetch` the operation
|
||||
#! the second. A compare-exchange gives whether it wrote, and writes what it
|
||||
#! found where a pointer it is given points.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `call` node.
|
||||
#! @param name The intrinsic's name.
|
||||
#! @param kind What it gives.
|
||||
#! @returns What it gives.
|
||||
def emitter::atomic(&mut this, node: u32, name: strview, kind: u32): operand {
|
||||
var operation := name == "atomic_load" ? atomic_load : name == "atomic_store" ? atomic_store
|
||||
: name == "atomic_exchange" ? atomic_exchange : name == "atomic_compare_exchange" ? atomic_compare_exchange
|
||||
: name == "atomic_fence" ? atomic_fence : atomic_add;
|
||||
var how := access::i64;
|
||||
var unsigned: u64 = 0;
|
||||
val instance := this.called(node);
|
||||
if instance != 0 && operation != atomic_fence {
|
||||
val args: u32 = this.c.checker.instances[instance - 1].args;
|
||||
val held := this.c.checker.types.part_at(args, 0);
|
||||
how = this.c.shape_of(held).how;
|
||||
if this.c.checker.types.kind_of(this.c.checker.unalias(held)) == ty::unsigned {
|
||||
unsigned = atomic_unsigned;
|
||||
}
|
||||
if name == "atomic_fetch" {
|
||||
operation = this.constant_argument(this.c.checker.types.part_at(args, 1)) as u32;
|
||||
}
|
||||
}
|
||||
|
||||
var values := vector::<u32>::new();
|
||||
val run := this.c.checker.right_of(node);
|
||||
for i in 0..this.c.checker.run_length(run) {
|
||||
val made := this.value(this.c.checker.run_at(run, i as u32));
|
||||
made.args(&mut values);
|
||||
}
|
||||
if operation == atomic_fence {
|
||||
this.build.effect(op::atomic, values.view(), operation, 0);
|
||||
return operand::none(kind);
|
||||
}
|
||||
|
||||
# While compiling, what it reaches is checked as a read through a pointer is.
|
||||
this.reaches(values[0], this.build.word(1), how.width());
|
||||
if operation == atomic_compare_exchange {
|
||||
this.reaches(values[3], this.build.word(1), how.width());
|
||||
var args: u32[5] = [values[0], values[1], values[2], values[4], values[5]];
|
||||
val found := this.build.value(op::atomic, args[0:5], vt::word, operation, how as u64 | unsigned);
|
||||
this.build.store(how, values[3], 0, found);
|
||||
return operand::one(kind, this.build.binary(op::eq, found, values[1]));
|
||||
}
|
||||
if atomic_gives(operation) {
|
||||
return operand::one(kind, this.build.value(op::atomic, values.view(), vt::word, operation, how as u64 | unsigned));
|
||||
}
|
||||
this.build.effect(op::atomic, values.view(), operation, how as u64 | unsigned);
|
||||
return operand::none(kind);
|
||||
}
|
||||
|
||||
#! The type of lane a number is, as vector instructions take it.
|
||||
#! @param this The emitter.
|
||||
#! @param kind The type.
|
||||
#! @returns The type of lane, or `lane_none` where it is no number.
|
||||
def emitter::lane_of(&mut this, kind: u32): u32 {
|
||||
val plain := this.c.checker.unalias(kind);
|
||||
val of := this.c.checker.types.kind_of(plain);
|
||||
val bits := this.c.checker.types.first_of(plain);
|
||||
if of == ty::floating {
|
||||
return bits == 32 ? lane_f32 : lane_f64;
|
||||
}
|
||||
return lane_none if of != ty::signed && of != ty::unsigned;
|
||||
val width: u32 = bits == 8 ? 0 : bits == 16 ? 2 : bits == 32 ? 4 : 6;
|
||||
return width + (of == ty::unsigned ? 1 : 0);
|
||||
}
|
||||
|
||||
#! The number a constant type argument is.
|
||||
#! @param this The emitter.
|
||||
#! @param arg The type argument.
|
||||
#! @returns The number, or 0 where it is none.
|
||||
def emitter::constant_argument(&mut this, arg: u32): u64 {
|
||||
return 0 if this.c.checker.types.kind_of(arg) != ty::value;
|
||||
return this.c.checker.known_at(this.c.checker.types.second_of(arg)).value.magnitude;
|
||||
}
|
||||
|
||||
#! Where a call is written, as `core::site`: its file, line, and column, and the
|
||||
#! signature of the function holding it.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `call` node.
|
||||
#! @param kind The `site` type.
|
||||
#! @returns The value.
|
||||
def emitter::call_site(&mut this, node: u32, kind: u32): operand {
|
||||
# In a default, it is where the call leaving the parameter out is.
|
||||
val file := this.defaulting.node != 0 ? this.defaulting.file : this.c.checker.at.file;
|
||||
val site := this.defaulting.node != 0 ? this.defaulting.node : node;
|
||||
val held := &this.c.checker.units[file].source;
|
||||
val offset := this.c.node_offset(file, site);
|
||||
val at := held.lines.place_of(offset);
|
||||
val plain := this.c.checker.unalias(kind);
|
||||
val index := this.c.layout_of(plain);
|
||||
val shape := this.c.layout_at(index);
|
||||
val address := this.temporary_of(kind);
|
||||
this.build.clear(address, shape.size);
|
||||
val whole := location { kind = kind, address = address, framed = true };
|
||||
|
||||
var signature := string::new(nothing {});
|
||||
val decl: u32 = this.c.program.functions[this.function].decl;
|
||||
if decl != 0 {
|
||||
this.c.signature_text(decl, &mut signature);
|
||||
}
|
||||
for i in 0..shape.count {
|
||||
val field := this.c.field_at(index, i as u32);
|
||||
val name := this.c.checker.names.text(field.name);
|
||||
val place := this.within(&whole, field.offset, field.type_id);
|
||||
var value := operand {};
|
||||
if name == "path" {
|
||||
value = this.text_value(held.path, field.type_id);
|
||||
} else if name == "line" {
|
||||
value = operand::one(field.type_id, this.build.word(at.line as u64));
|
||||
} else if name == "column" {
|
||||
value = operand::one(field.type_id, this.build.word(at.column as u64));
|
||||
} else if name == "signature" {
|
||||
value = this.text_value(signature.view(), field.type_id);
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
this.store(&place, &value);
|
||||
}
|
||||
return operand::at(kind, address);
|
||||
}
|
||||
|
||||
#! The text an expression is written as, without the spaces around it.
|
||||
#! @param this The emitter.
|
||||
#! @param node The expression.
|
||||
#! @param out Where the text is written.
|
||||
pub def emitter::source_text(&mut this, node: u32, out: &mut string): void {
|
||||
val file := this.c.checker.at.file;
|
||||
val syntax := &this.c.checker.units[file].syntax;
|
||||
val held := &this.c.checker.units[file].source;
|
||||
# A node's own token may come after those of what it was parsed from, as an
|
||||
# operator's comes after its left operand, so the first is the least of all.
|
||||
var first: u32 = syntax.node_tokens[node];
|
||||
var walk := node_walk::new(node);
|
||||
while walk.more() {
|
||||
val at := walk.next();
|
||||
val token := syntax.node_tokens[at];
|
||||
first = token < first ? token : first;
|
||||
walk.enter(&syntax, at);
|
||||
}
|
||||
val last := syntax.node_end(node);
|
||||
val begin := syntax.token_offsets[first];
|
||||
val end := syntax.token_offsets[last] + syntax.token_length(last, this.c.checker.names);
|
||||
return if end <= begin;
|
||||
out.append(held.make_lexeme(begin, end - begin));
|
||||
}
|
||||
|
||||
#! What the operands of an expression held, as `values_of` gives it: both
|
||||
#! operands of a comparison, or the expression itself, each as `text = value`,
|
||||
#! but for literals, which say what they hold already.
|
||||
#! @param this The emitter.
|
||||
#! @param node The expression, or 0.
|
||||
#! @param kind The `string` type.
|
||||
#! @returns The text.
|
||||
def emitter::values_of(&mut this, node: u32, kind: u32): operand {
|
||||
this.build.effect(op::format, span::<u32>::empty(), 0, 0);
|
||||
if node != 0 {
|
||||
this.write_values(node, "");
|
||||
}
|
||||
return this.owned_text(kind);
|
||||
}
|
||||
|
||||
#! Writes what the operands of an expression held into the text being made, as
|
||||
#! `values_of` gives it, after a lead where there are any.
|
||||
#! @param this The emitter.
|
||||
#! @param node The expression.
|
||||
#! @param lead What comes before the first, as `, with `, or nothing.
|
||||
pub def emitter::write_values(&mut this, node: u32, lead: strview): void {
|
||||
var named := vector::<u32>::new();
|
||||
val shape := this.c.checker.kind_of(node);
|
||||
if shape == nk::binary {
|
||||
val operator := this.c.checker.token_kind(node);
|
||||
if operator.compares() {
|
||||
named.append(this.c.checker.left_of(node));
|
||||
named.append(this.c.checker.right_of(node));
|
||||
}
|
||||
} else if shape != nk::unary {
|
||||
named.append(node);
|
||||
}
|
||||
|
||||
var first := true;
|
||||
for &each in named {
|
||||
val literal := this.c.checker.kind_of(each);
|
||||
continue if literal == nk::number || literal == nk::string || literal == nk::character || literal == nk::boolean
|
||||
|| literal == nk::null_lit;
|
||||
if !first {
|
||||
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(", "), 0);
|
||||
} else if lead.length != 0 {
|
||||
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(lead), 0);
|
||||
}
|
||||
first = false;
|
||||
var text := string::new(nothing {});
|
||||
this.source_text(each, &mut text);
|
||||
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(text.view()), 0);
|
||||
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(" = "), 0);
|
||||
val mark := this.cell_mark();
|
||||
val value := this.value(each);
|
||||
this.format_value(&value);
|
||||
this.release(mark);
|
||||
}
|
||||
}
|
||||
|
||||
#! `attached::<A>(d)`: a view of the values of the attributes of the type `A`
|
||||
#! written on the declaration `d` describes, in the order they are written, each
|
||||
#! made as the struct literal it is, where the declaration is. They are held as
|
||||
#! long as the function runs, since the view may outlive the statement.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `call` node.
|
||||
#! @param kind The view's type.
|
||||
#! @returns The view.
|
||||
def emitter::attached(&mut this, node: u32, kind: u32): operand {
|
||||
val view := this.temporary_of(kind);
|
||||
this.build.clear(view, 2 * word_size);
|
||||
val run := this.c.checker.right_of(node);
|
||||
val wanted := this.c.viewed(kind);
|
||||
return operand::at(kind, view) if wanted == 0 || this.c.checker.run_length(run) == 0;
|
||||
val one := this.c.checker.reflected_one(this.c.checker.run_at(run, 0));
|
||||
return operand::at(kind, view) if one == checker::no_reflection;
|
||||
val held: desc = this.c.checker.descs[one];
|
||||
return operand::at(kind, view) if held.param != 0;
|
||||
|
||||
# The attributes of the type, in the order they are written.
|
||||
val decl := held.decl;
|
||||
var types := this.c.checker.attribute_types(decl);
|
||||
val saved := this.c.checker.at;
|
||||
this.c.checker.use_table(this.c.checker.units[this.c.checker.decls.files.p[decl]].table);
|
||||
val attrs := this.c.checker.attributes_of(this.c.checker.decls.nodes.p[decl]);
|
||||
var chosen := vector::<u32>::new();
|
||||
var at: u64 = 0;
|
||||
for i in 0..this.c.checker.run_length(attrs) {
|
||||
val attr := this.c.checker.run_at(attrs, i as u32);
|
||||
continue if this.c.checker.kind_of(attr) != nk::attribute;
|
||||
if at < types.length && this.c.checker.strip(types[at], 0) == this.c.checker.strip(wanted, 0) {
|
||||
chosen.append(attr);
|
||||
}
|
||||
at++;
|
||||
}
|
||||
if chosen.length == 0 {
|
||||
this.c.checker.at = saved;
|
||||
return operand::at(kind, view);
|
||||
}
|
||||
|
||||
val shape := this.c.shape_of(wanted);
|
||||
val array := this.c.checker.types.fixed(wanted, chosen.length as u32);
|
||||
val whole := this.c.shape_of(array);
|
||||
val cell := this.build.code.add_cell(round_up(whole.size, word_size) as u32,
|
||||
whole.align < word_size ? word_size as u32 : whole.align as u32, ck::local, 0);
|
||||
val first := this.build.cell_address(cell);
|
||||
for i in 0..chosen.length {
|
||||
val made := this.construct_of(wanted, this.c.checker.right_of(chosen[i]));
|
||||
val place := location { kind = wanted, address = first, offset = i * shape.size, framed = true };
|
||||
this.store(&place, &made);
|
||||
}
|
||||
this.c.checker.at = saved;
|
||||
this.build.store(access::i64, view, 0, first);
|
||||
this.build.store(access::i64, view, word_size, this.build.word(chosen.length));
|
||||
return operand::at(kind, view);
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
#! @file loops.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the lowering of `for`: counting through a range, walking the
|
||||
#! elements of a fixed array or a view, each bound by reference, asking an
|
||||
#! iterator for each element until it gives none, and `for const`, whose body
|
||||
#! the checker checked once for each value of a pack.
|
||||
|
||||
import sakura::analyzer;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! Lowers `for`.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `for_stmt` node.
|
||||
pub def emitter::for_statement(&mut this, node: u32): void {
|
||||
val iterated := this.c.checker.record(node, for_slot::iterated);
|
||||
val end := this.c.checker.record(node, for_slot::end);
|
||||
if this.c.checker.node_has(node, nf::constant) {
|
||||
this.unrolled(node);
|
||||
return;
|
||||
}
|
||||
if end != 0 {
|
||||
this.for_range(node);
|
||||
return;
|
||||
}
|
||||
|
||||
# What's walked is of the type it's converted to, as a literal of text is a
|
||||
# `strview`.
|
||||
val through := this.c.checker.unalias(this.c.checker.reached(this.c.checker.converted(iterated)));
|
||||
if this.c.checker.types.kind_of(through) == ty::fixed || this.c.viewed(through) != 0 {
|
||||
this.for_elements(node, through);
|
||||
return;
|
||||
}
|
||||
this.for_iterator(node, through);
|
||||
}
|
||||
|
||||
#! A loop's blocks: where each pass begins, its body, where `continue` goes, and
|
||||
#! where it ends.
|
||||
struct loop_blocks {
|
||||
var head: u32; #! Where each pass asks whether there is another.
|
||||
var body: u32; #! The body.
|
||||
var next: u32; #! Where `continue` goes, which steps to the next pass.
|
||||
var exit: u32; #! Where it ends.
|
||||
}
|
||||
|
||||
#! Makes the blocks of a loop, and goes to its head.
|
||||
#! @param this The emitter.
|
||||
#! @returns The blocks.
|
||||
def emitter::begin_loop(&mut this): loop_blocks {
|
||||
val made := loop_blocks {
|
||||
head = this.build.new_block(),
|
||||
body = this.build.new_block(),
|
||||
next = this.build.new_block(),
|
||||
exit = this.build.new_block()
|
||||
};
|
||||
this.build.jump(made.head);
|
||||
this.build.switch_to(made.head);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Lowers a loop's body, with `break` and `continue` going where the loop says,
|
||||
#! then goes to the step to the next pass.
|
||||
#! @param this The emitter.
|
||||
#! @param blocks The loop's blocks.
|
||||
#! @param body The body's node.
|
||||
#! @param locals How many locals there were before the loop's variables,
|
||||
#! which each pass closes past.
|
||||
def emitter::loop_body(&mut this, blocks: &loop_blocks, body: u32, locals: u64): void {
|
||||
this.safepoint();
|
||||
this.loops.append(loop_info { exit = blocks.exit, next = blocks.next, locals = locals, kept = this.kept.length });
|
||||
this.lower_block(body);
|
||||
this.loops.truncate();
|
||||
this.close_locals(locals, 0);
|
||||
this.build.jump(blocks.next);
|
||||
this.build.seal(blocks.next);
|
||||
this.build.switch_to(blocks.next);
|
||||
}
|
||||
|
||||
#! Goes into a loop's body where there is another pass, and leaves it where not.
|
||||
#! @param this The emitter.
|
||||
#! @param blocks The loop's blocks.
|
||||
#! @param more Whether there is another pass.
|
||||
#! @returns How many locals there were before the pass's own.
|
||||
def emitter::enter_pass(&mut this, blocks: &loop_blocks, more: u32): u64 {
|
||||
this.build.branch(more, blocks.body, blocks.exit);
|
||||
this.build.seal(blocks.body);
|
||||
this.build.switch_to(blocks.body);
|
||||
return this.scope_mark();
|
||||
}
|
||||
|
||||
#! Lowers the body of a counted pass, then counts it and ends the loop.
|
||||
#! @param this The emitter.
|
||||
#! @param blocks The loop's blocks.
|
||||
#! @param node The `for_stmt` node.
|
||||
#! @param locals How many locals there were before the pass's own.
|
||||
#! @param counter The variable counting the passes.
|
||||
def emitter::end_pass(&mut this, blocks: &loop_blocks, node: u32, locals: u64, counter: u32): void {
|
||||
this.loop_body(blocks, this.c.checker.right_of(node), locals);
|
||||
this.forget_locals(locals);
|
||||
this.count_on(counter, blocks.head, blocks.exit);
|
||||
}
|
||||
|
||||
#! Ends a loop: the step jumps back to its head, and what follows goes on from
|
||||
#! its exit.
|
||||
#! @param this The emitter.
|
||||
#! @param blocks The loop's blocks.
|
||||
def emitter::end_loop(&mut this, blocks: &loop_blocks): void {
|
||||
this.close_loop(blocks.head, blocks.exit);
|
||||
}
|
||||
|
||||
#! Ends a loop of the blocks given: where the code is jumps back to its head,
|
||||
#! every way into which is known then, and what follows goes on from its exit.
|
||||
#! @param this The emitter.
|
||||
#! @param head The loop's head.
|
||||
#! @param exit The block after it.
|
||||
def emitter::close_loop(&mut this, head: u32, exit: u32): void {
|
||||
this.build.jump(head);
|
||||
this.build.seal(head);
|
||||
this.build.seal(exit);
|
||||
this.build.switch_to(exit);
|
||||
}
|
||||
|
||||
#! Goes into a loop counting a variable up to a count, as one over the elements
|
||||
#! of a fixed array does: its head goes into its body while the variable is
|
||||
#! below the count, and out of the loop otherwise, and what follows is the body.
|
||||
#! @param this The emitter.
|
||||
#! @param index The variable, which holds where the count begins.
|
||||
#! @param count The count, which the variable stays below.
|
||||
#! @param head The loop's head.
|
||||
#! @param body Its body.
|
||||
#! @param exit The block after it.
|
||||
#! @returns What the variable holds in the body.
|
||||
def emitter::count_up(&mut this, index: u32, count: u64, head: u32, body: u32, exit: u32): u32 {
|
||||
this.build.jump(head);
|
||||
this.build.switch_to(head);
|
||||
val at := this.build.read(index);
|
||||
this.build.branch(this.build.binary(op::ltu, at, this.build.word(count)), body, exit);
|
||||
this.build.seal(body);
|
||||
this.build.switch_to(body);
|
||||
return at;
|
||||
}
|
||||
|
||||
#! Ends the pass of a loop counting a variable up: counts it, and ends the loop.
|
||||
#! @param this The emitter.
|
||||
#! @param index The variable.
|
||||
#! @param head The loop's head.
|
||||
#! @param exit The block after it.
|
||||
def emitter::count_on(&mut this, index: u32, head: u32, exit: u32): void {
|
||||
this.build.assign(index, this.build.binary(op::add, this.build.read(index), this.build.word(1)));
|
||||
this.close_loop(head, exit);
|
||||
}
|
||||
|
||||
#! Declares the variable of a loop's pass, and its index, where it has one.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `for_stmt` node.
|
||||
#! @param value The value the variable is given.
|
||||
#! @param counter The index of the pass, a word.
|
||||
#! @param closes Whether the variable is the loop's own, closed where each
|
||||
#! pass ends.
|
||||
def emitter::bind_pass(&mut this, node: u32, value: &operand, counter: u32, closes: bool): void {
|
||||
val variable := this.c.checker.record(node, for_slot::variable);
|
||||
val index := this.c.checker.record(node, for_slot::index);
|
||||
if variable != 0 {
|
||||
val kind := this.c.checker.type_at(variable);
|
||||
val place := this.new_place(variable, kind);
|
||||
val made := this.convert(value, kind);
|
||||
this.store(&place, &made);
|
||||
this.declare(variable, place, closes);
|
||||
}
|
||||
if index != 0 {
|
||||
val place := this.new_place(index, bt::uint64);
|
||||
val made := operand::one(bt::uint64, counter);
|
||||
this.store(&place, &made);
|
||||
this.declare(index, place, false);
|
||||
}
|
||||
}
|
||||
|
||||
#! `for i in a..b`: counts from the start to just before the end, or through it
|
||||
#! where the loop is `a..=b`, each count a variable of the body's own. A range
|
||||
#! of an enum's members counts their places among the values of its members,
|
||||
#! each pass's variable the member at its place.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `for_stmt` node.
|
||||
def emitter::for_range(&mut this, node: u32): void {
|
||||
val mark := this.begin_statement();
|
||||
val variable := this.c.checker.record(node, for_slot::variable);
|
||||
val kind := variable != 0 ? this.c.checker.type_at(variable) : this.c.checker.converted(this.c.checker.record(node, for_slot::iterated));
|
||||
val start := this.value_as(this.c.checker.record(node, for_slot::iterated), kind);
|
||||
val limit := this.value_as(this.c.checker.record(node, for_slot::end), kind);
|
||||
val members := this.c.checker.named_kind(this.c.checker.unalias(kind)) == dk::enum_type;
|
||||
val first := members ? this.member_rank(start.words[0], kind) : start.words[0];
|
||||
val last := members ? this.member_rank(limit.words[0], kind) : limit.words[0];
|
||||
val count := this.build.variable(vt::word);
|
||||
this.build.assign(count, first);
|
||||
|
||||
# `a..=b` gives `b` too, so whether another pass follows is kept apart from the
|
||||
# count, which may pass the end of its type after `b`.
|
||||
val inclusive := this.c.checker.node_has(node, nf::inclusive);
|
||||
val signed := !members && this.is_signed(kind);
|
||||
var keep: u32 = 0;
|
||||
if inclusive {
|
||||
keep = this.build.variable(vt::word);
|
||||
this.build.assign(keep, this.build.binary(signed ? op::les : op::leu, first, last));
|
||||
}
|
||||
|
||||
val blocks := this.begin_loop();
|
||||
val more := inclusive
|
||||
? this.build.read(keep)
|
||||
: this.build.binary(signed ? op::lts : op::ltu, this.build.read(count), last);
|
||||
val locals := this.enter_pass(&blocks, more);
|
||||
if variable != 0 {
|
||||
val place := this.new_place(variable, kind);
|
||||
val counted := this.build.read(count);
|
||||
val made := operand::one(kind, members ? this.member_of_rank(counted, kind) : counted);
|
||||
this.store(&place, &made);
|
||||
this.declare(variable, place, false);
|
||||
}
|
||||
if inclusive {
|
||||
this.loop_body(&blocks, this.c.checker.right_of(node), locals);
|
||||
this.forget_locals(locals);
|
||||
this.build.assign(keep, this.build.binary(op::ne, this.build.read(count), last));
|
||||
this.count_on(count, blocks.head, blocks.exit);
|
||||
} else {
|
||||
this.end_pass(&blocks, node, locals, count);
|
||||
}
|
||||
this.end_statement(mark);
|
||||
}
|
||||
|
||||
#! Walks the elements of a fixed array or a view, which lie one after another,
|
||||
#! binding a reference to each.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `for_stmt` node.
|
||||
#! @param through The type walked, read through its references.
|
||||
def emitter::for_elements(&mut this, node: u32, through: u32): void {
|
||||
val mark := this.begin_statement();
|
||||
val whole := this.object(this.c.checker.record(node, for_slot::iterated));
|
||||
var first: u32 = 0;
|
||||
var limit: u32 = 0;
|
||||
var element: u32 = 0;
|
||||
if this.c.checker.types.kind_of(through) == ty::fixed {
|
||||
val shape := this.c.shape_of(through);
|
||||
first = this.address_of(&whole);
|
||||
limit = this.build.word(shape.count as u64);
|
||||
element = this.c.checker.types.first_of(through);
|
||||
} else {
|
||||
first = this.build.load(access::i64, whole.address, whole.offset);
|
||||
limit = this.build.load(access::i64, whole.address, whole.offset + word_size);
|
||||
element = this.c.viewed(through);
|
||||
}
|
||||
val size := this.c.shape_of(element).size;
|
||||
val counter := this.build.variable(vt::word);
|
||||
this.build.assign(counter, this.build.word(0));
|
||||
|
||||
val blocks := this.begin_loop();
|
||||
val locals := this.enter_pass(&blocks, this.build.binary(op::ltu, this.build.read(counter), limit));
|
||||
val address := this.build.binary(op::add, first, this.scaled(this.build.read(counter), size));
|
||||
val reference := operand::one(this.c.checker.types.reference(element, true), address);
|
||||
this.bind_pass(node, &reference, this.build.read(counter), false);
|
||||
this.end_pass(&blocks, node, locals, counter);
|
||||
this.end_statement(mark);
|
||||
}
|
||||
|
||||
#! Asks an iterator for each element until it gives `none`. The iterator is the
|
||||
#! one the loop is given, advanced where it is, or the one what it walks lends
|
||||
#! through `iter`, which the loop holds and closes where it ends. An element
|
||||
#! given by value is the loop's own, closed where each pass ends.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `for_stmt` node.
|
||||
#! @param through The type walked, read through its references.
|
||||
def emitter::for_iterator(&mut this, node: u32, through: u32): void {
|
||||
val mark := this.begin_statement();
|
||||
val iterated := this.c.checker.record(node, for_slot::iterated);
|
||||
val mutable := this.c.checker.node_has(node, nf::mutable);
|
||||
val locals := this.scope_mark();
|
||||
|
||||
# The iterator, where it is: what the loop is given, or what `iter` lends.
|
||||
var cursor_place := location {};
|
||||
var cursor_type := through;
|
||||
if !this.c.checker.has_method(through, word::next) {
|
||||
val lends := this.c.checker.pick_iter(through, mutable);
|
||||
val receiver := this.c.is_reference_type(this.c.checker.type_at(iterated))
|
||||
? this.through_one(iterated)
|
||||
: this.reference_arg(iterated, this.c.checker.types.reference(through, mutable));
|
||||
val made := this.method_call(lends, through, &receiver, span::<operand>::empty());
|
||||
this.adopt(&made);
|
||||
cursor_type = this.c.checker.unalias(made.kind);
|
||||
cursor_place = this.fresh_place(made.kind);
|
||||
this.store(&cursor_place, &made);
|
||||
this.declare(this.c.checker.right_of(node), cursor_place, this.c.checker.closes(made.kind));
|
||||
} else if this.c.is_reference_type(this.c.checker.type_at(iterated)) {
|
||||
val made := this.through_one(iterated);
|
||||
cursor_place = this.referent(&made);
|
||||
} else if this.c.checker.is_place(iterated) {
|
||||
cursor_place = this.place_of(iterated);
|
||||
} else {
|
||||
val made := this.value_of_type(iterated);
|
||||
this.adopt(&made);
|
||||
cursor_place = this.fresh_place(made.kind);
|
||||
this.store(&cursor_place, &made);
|
||||
this.declare(this.c.checker.right_of(node), cursor_place, this.c.checker.closes(made.kind));
|
||||
}
|
||||
|
||||
val next := this.c.checker.find_member(cursor_type, word::next);
|
||||
val counter := this.build.variable(vt::word);
|
||||
this.build.assign(counter, this.build.word(0));
|
||||
val blocks := this.begin_loop();
|
||||
|
||||
# `next` gives `some` of the element while there are more, and `none` after.
|
||||
val receiver := this.reference_to(&cursor_place, this.c.checker.types.reference(cursor_type, true));
|
||||
val given := this.method_call(next.decl, cursor_type, &receiver, span::<operand>::empty());
|
||||
val maybe := this.hold(&given);
|
||||
val plain := this.c.checker.unalias(given.kind);
|
||||
val index := this.c.layout_of(plain);
|
||||
var some: u32 = 0;
|
||||
for i in 0..this.c.layout_at(index).count {
|
||||
if this.c.field_at(index, i as u32).name == word::some {
|
||||
some = i as u32;
|
||||
}
|
||||
}
|
||||
val passes := this.enter_pass(&blocks, this.tag_is(&maybe, some));
|
||||
val field := this.c.field_at(index, some);
|
||||
val payload := this.within(&maybe, field.offset, field.type_id);
|
||||
val element := this.load(&payload);
|
||||
this.bind_pass(node, &element, this.build.read(counter), !this.c.is_reference_type(field.type_id) && this.c.checker.closes(field.type_id));
|
||||
this.end_pass(&blocks, node, passes, counter);
|
||||
|
||||
# Leaving the loop, by its end or a `break`, closes the iterator it holds.
|
||||
this.end_scope(locals, 0);
|
||||
this.end_statement(mark);
|
||||
}
|
||||
|
||||
#! The reference a node is, read through the references it refers to until one
|
||||
#! refers to what is no reference.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node, of a reference type.
|
||||
#! @returns The reference.
|
||||
def emitter::through_one(&mut this, node: u32): operand {
|
||||
var made := this.value_of_type(node);
|
||||
while this.c.is_reference_type(this.c.checker.types.first_of(this.c.checker.unalias(made.kind))) {
|
||||
val place := this.referent(&made);
|
||||
made = this.load(&place);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! `for const`: the body the checker checked once for each value of a pack, or
|
||||
#! each declaration reflection gives, each with a result table of its own, run
|
||||
#! one after another. `continue` goes on to the next, and `break` past the last.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `for_stmt` node.
|
||||
def emitter::unrolled(&mut this, node: u32): void {
|
||||
val variable := this.c.checker.record(node, for_slot::variable);
|
||||
val iterated := this.c.checker.record(node, for_slot::iterated);
|
||||
val body := this.c.checker.right_of(node);
|
||||
val outer := this.c.checker.at.table;
|
||||
val pack := this.c.checker.unalias(this.c.checker.reached(this.c.checker.type_at(iterated)));
|
||||
val is_pack := this.c.checker.types.kind_of(pack) == ty::pack;
|
||||
|
||||
# The tables the checker made for each pass, in order.
|
||||
var tables := vector::<u32>::new();
|
||||
for t in 0..this.c.checker.tables.length {
|
||||
val held: rtable = this.c.checker.tables.p[t];
|
||||
if held.parent == outer + 1 && held.base == variable && held.count == body - variable + 1 {
|
||||
tables.append(t as u32);
|
||||
}
|
||||
}
|
||||
|
||||
# The pack is named in the table around the passes, which theirs do not hold.
|
||||
var values := vector::<location>::new();
|
||||
if is_pack {
|
||||
for i in 0..this.c.checker.types.part_count(pack) {
|
||||
values.append(this.pack_place(iterated, i as u32));
|
||||
}
|
||||
}
|
||||
|
||||
val exit := this.build.new_block();
|
||||
for i in 0..tables.length {
|
||||
val next := this.build.new_block();
|
||||
this.c.checker.use_table(tables[i]);
|
||||
val locals := this.scope_mark();
|
||||
if is_pack {
|
||||
# The variable is the pack's value itself, so writing it writes the pack.
|
||||
val place: location = i < values.length ? values[i] : location { kind = bt::error };
|
||||
this.declare(variable, place, false);
|
||||
} else if this.c.checker.record(node, for_slot::end) != 0 {
|
||||
# The variable is the number this pass counts.
|
||||
val kind := this.c.checker.type_at(variable);
|
||||
val made := this.known(&this.c.checker.value_at(variable), kind);
|
||||
val place := this.new_place(variable, kind);
|
||||
this.store(&place, &made);
|
||||
this.declare(variable, place, false);
|
||||
} else {
|
||||
this.reflected_pass(variable);
|
||||
}
|
||||
this.loops.append(loop_info { exit = exit, next = next, locals = locals, kept = this.kept.length });
|
||||
this.lower_block(body);
|
||||
this.loops.truncate();
|
||||
this.end_scope(locals, 0);
|
||||
this.build.jump(next);
|
||||
this.build.seal(next);
|
||||
this.build.switch_to(next);
|
||||
this.c.checker.use_table(outer);
|
||||
}
|
||||
this.build.jump(exit);
|
||||
this.build.seal(exit);
|
||||
this.build.switch_to(exit);
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
#! @file match.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the lowering of `match`: the first arm naming the field a union
|
||||
#! holds, or the member an enum is, or a value equal to the subject, runs, or
|
||||
#! else the `else` arm. A union's arm may name the value its field holds, a
|
||||
#! copy of it, taken out where it closes, or with `&` or `&mut` a reference to
|
||||
#! it. A match used as a value gives what its arm gives.
|
||||
|
||||
import sakura::analyzer;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! A `match` used as a value.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `match_value` node.
|
||||
#! @returns What the arm taken gives.
|
||||
pub def emitter::match_value(&mut this, node: u32): operand {
|
||||
return this.lower_match(node, true);
|
||||
}
|
||||
|
||||
#! Lowers a match, as a statement or as a value.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `match_stmt` or `match_value` node.
|
||||
#! @param value Whether it is used as a value.
|
||||
#! @returns What the arm taken gives, where it is used as a value.
|
||||
pub def emitter::lower_match(&mut this, node: u32, value: bool): operand {
|
||||
val subject := this.c.checker.left_of(node);
|
||||
val arms := this.c.checker.right_of(node);
|
||||
val kind := value ? this.c.checker.type_at(node) : bt::void_type;
|
||||
val whole := this.object(subject);
|
||||
val plain := this.c.checker.unalias(whole.kind);
|
||||
val union_like := this.c.checker.named_kind(plain) == dk::union_type;
|
||||
|
||||
# Values are compared with the subject as read once, before any arm runs.
|
||||
var held := operand {};
|
||||
if !union_like {
|
||||
held = this.load(&whole);
|
||||
}
|
||||
|
||||
val result := value ? this.result_place(kind) : location {};
|
||||
val join := this.build.new_block();
|
||||
var otherwise := false;
|
||||
for i in 0..this.c.checker.run_length(arms) {
|
||||
val arm := this.c.checker.run_at(arms, i as u32);
|
||||
val patterns := this.c.checker.left_of(arm);
|
||||
val body := this.c.checker.right_of(arm);
|
||||
if patterns == 0 {
|
||||
this.lower_arm(arm, body, value, kind, &result, &whole, 0, 0);
|
||||
this.build.jump(join);
|
||||
otherwise = true;
|
||||
break;
|
||||
}
|
||||
|
||||
# The arm runs where any of its patterns does.
|
||||
val taken := this.build.new_block();
|
||||
val next := this.build.new_block();
|
||||
var field: u32 = 0;
|
||||
var binding: u32 = 0;
|
||||
for j in 0..this.c.checker.run_length(patterns) {
|
||||
val pattern := this.c.checker.run_at(patterns, j as u32);
|
||||
val failed := j + 1 == this.c.checker.run_length(patterns) as u64 ? next : this.build.new_block();
|
||||
var test: u32 = 0;
|
||||
if union_like {
|
||||
field = this.c.checker.ref_at(pattern);
|
||||
if this.c.checker.kind_of(pattern) == nk::call {
|
||||
val given := this.c.checker.right_of(pattern);
|
||||
if this.c.checker.run_length(given) == 1 {
|
||||
binding = this.c.checker.named_binding(this.c.checker.run_at(given, 0));
|
||||
}
|
||||
}
|
||||
test = this.tag_is(&whole, this.field_index(plain, field));
|
||||
} else {
|
||||
test = this.equals_value(&held, pattern, plain);
|
||||
}
|
||||
this.build.branch(test, taken, failed);
|
||||
if failed != next {
|
||||
this.build.seal(failed);
|
||||
this.build.switch_to(failed);
|
||||
}
|
||||
}
|
||||
this.build.seal(taken);
|
||||
this.build.seal(next);
|
||||
|
||||
this.build.switch_to(taken);
|
||||
this.lower_arm(arm, body, value, kind, &result, &whole, field, binding);
|
||||
this.build.jump(join);
|
||||
this.build.switch_to(next);
|
||||
}
|
||||
|
||||
# A match used as a value with no `else` finds no arm only for a value no enum
|
||||
# member has, which only memory written through pointers can hold, and which
|
||||
# only code that checks looks for.
|
||||
if !otherwise {
|
||||
if value && this.checking() {
|
||||
this.build.trap(fault::not_member as u32);
|
||||
} else if value {
|
||||
this.build.unreachable();
|
||||
} else {
|
||||
this.build.jump(join);
|
||||
}
|
||||
}
|
||||
this.build.seal(join);
|
||||
this.build.switch_to(join);
|
||||
return operand::none(bt::void_type) if !value;
|
||||
val made := this.load_result(&result);
|
||||
this.keep(&made);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The index of a union's field among its fields.
|
||||
#! @param this The emitter.
|
||||
#! @param kind The union's type, without aliases.
|
||||
#! @param field The field's declaration.
|
||||
#! @returns Its index.
|
||||
pub def emitter::field_index(&mut this, kind: u32, field: u32): u32 {
|
||||
val index := this.c.layout_of(kind);
|
||||
for i in 0..this.c.layout_at(index).count {
|
||||
return i as u32 if this.c.field_at(index, i as u32).decl == field;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! Whether a value equals a pattern's: as words, or through `equals`, or part by
|
||||
#! part for what the language compares that way.
|
||||
#! @param this The emitter.
|
||||
#! @param held The value.
|
||||
#! @param pattern The pattern's node.
|
||||
#! @param kind The type compared, without aliases.
|
||||
#! @returns A word of 1 where they are equal.
|
||||
def emitter::equals_value(&mut this, held: &operand, pattern: u32, kind: u32): u32 {
|
||||
val given := this.value_as(pattern, kind);
|
||||
val shape := this.c.shape_of(kind);
|
||||
if !in_memory(&shape) {
|
||||
if this.c.checker.has_method(kind, word::equals) && this.c.checker.named_kind(kind) != dk::enum_type
|
||||
&& !this.c.checker.types.is_numeric(kind) && this.c.checker.types.kind_of(kind) != ty::pointer
|
||||
&& !this.c.checker.types.is_boolean(kind) {
|
||||
return this.equals_call(held, &given, kind);
|
||||
}
|
||||
val floating := shape.kind == lk::floating;
|
||||
return this.build.binary(floating ? op::feq : op::eq, held.words[0], given.words[0]);
|
||||
}
|
||||
if this.c.checker.has_method(kind, word::equals) {
|
||||
return this.equals_call(held, &given, kind);
|
||||
}
|
||||
var args: u32[2] = [held.address, given.address];
|
||||
return this.build.value(op::equal, args[0:2], vt::word, this.c.layout_of(kind), 0);
|
||||
}
|
||||
|
||||
#! Calls a type's `equals` on two values, given references to each.
|
||||
#! @param this The emitter.
|
||||
#! @param a One value.
|
||||
#! @param b The other.
|
||||
#! @param kind Their type, without aliases.
|
||||
#! @returns A word of 1 where they are equal.
|
||||
def emitter::equals_call(&mut this, a: &operand, b: &operand, kind: u32): u32 {
|
||||
val method := this.pick_method(kind, word::equals, true);
|
||||
val reference := this.c.checker.types.reference(kind, false);
|
||||
val left := this.hold(a);
|
||||
val right := this.hold(b);
|
||||
val subject := this.reference_to(&left, reference);
|
||||
var others: operand[1] = [this.reference_to(&right, reference)];
|
||||
val made := this.method_call(method, kind, &subject, others[0:1]);
|
||||
return made.words[0];
|
||||
}
|
||||
|
||||
#! Lowers an arm: the value its pattern names, where it names one, and its body,
|
||||
#! whose value the match gives where it is used as one.
|
||||
#! @param this The emitter.
|
||||
#! @param arm The arm's node.
|
||||
#! @param body Its body's node.
|
||||
#! @param value Whether the match is used as a value.
|
||||
#! @param kind The match's type.
|
||||
#! @param result Where its value goes.
|
||||
#! @param whole The place of the subject.
|
||||
#! @param field The field the arm names of a union, or 0.
|
||||
#! @param binding The node naming the field's value, or 0.
|
||||
def emitter::lower_arm(
|
||||
&mut this,
|
||||
arm: u32,
|
||||
body: u32,
|
||||
value: bool,
|
||||
kind: u32,
|
||||
result: &location,
|
||||
whole: &location,
|
||||
field: u32,
|
||||
binding: u32
|
||||
): void {
|
||||
val locals := this.scope_mark();
|
||||
var named: u32 = 0;
|
||||
if binding != 0 && field != 0 {
|
||||
val refers := this.c.checker.kind_of(binding) == nk::reference;
|
||||
named = refers ? this.c.checker.left_of(binding) : binding;
|
||||
val plain := this.c.checker.unalias(whole.kind);
|
||||
val held := this.c.field_at(this.c.layout_of(plain), this.field_index(plain, field));
|
||||
val payload := this.within(whole, held.offset, held.type_id);
|
||||
val bound := this.c.checker.type_at(named);
|
||||
val place := this.new_place(named, bound);
|
||||
if refers {
|
||||
# A field holding a reference gives that reference, since references
|
||||
# never stack.
|
||||
var made := operand {};
|
||||
if this.c.checker.has_flag(binding, rf::relent) {
|
||||
val inner := this.load(&payload);
|
||||
made = this.convert(&inner, bound);
|
||||
} else {
|
||||
made = this.reference_to(&payload, bound);
|
||||
}
|
||||
this.store(&place, &made);
|
||||
this.declare(named, place, false);
|
||||
} else {
|
||||
val made := this.load(&payload);
|
||||
val converted := this.convert(&made, bound);
|
||||
this.store(&place, &converted);
|
||||
val closes := this.c.checker.closes(held.type_id);
|
||||
if closes {
|
||||
this.zero(&payload);
|
||||
}
|
||||
this.declare(named, place, closes);
|
||||
}
|
||||
}
|
||||
|
||||
# An arm giving the value its name took hands it over to the match.
|
||||
var given: u32 = 0;
|
||||
if value {
|
||||
if this.c.checker.kind_of(body) == nk::name && named != 0 && (this.c.checker.ref_at(body) & ref_mask) == named {
|
||||
given = named;
|
||||
}
|
||||
val made := this.value_as(body, kind);
|
||||
this.adopt(&made);
|
||||
this.store(result, &made);
|
||||
} else {
|
||||
this.lower_block(body);
|
||||
}
|
||||
this.end_scope(locals, given);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,146 @@
|
||||
#! @file ownership.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains closing values: a value of a type naming `owning` is closed by its
|
||||
#! own `close`, and then what it holds is closed, in the reverse of the order
|
||||
#! it was written, as a scope closes its locals. Also contains the text a
|
||||
#! format made, which a `string` holding no allocator owns.
|
||||
|
||||
import sakura::analyzer;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! Closes a value where it is: its own `close` first, then the fields it holds
|
||||
#! that close, the last first, or of a union the one it holds, or of a fixed
|
||||
#! array each element, the last first. Closing a zeroed value closes nothing.
|
||||
#! @param this The emitter.
|
||||
#! @param place The value's place.
|
||||
pub def emitter::close(&mut this, place: &location): void {
|
||||
return if place.held || !this.c.checker.closes(place.kind);
|
||||
val plain := this.c.checker.unalias(place.kind);
|
||||
val index := this.c.layout_of(plain);
|
||||
val shape := this.c.layout_at(index);
|
||||
|
||||
if shape.kind == lk::fixed {
|
||||
this.close_elements(place, plain, &shape);
|
||||
return;
|
||||
}
|
||||
|
||||
# Its own `close`, where it names `owning`.
|
||||
val owning := this.c.checker.std_decl(word::owning);
|
||||
if owning != 0 && this.c.checker.satisfies(plain, this.c.checker.decls.types.p[owning]) {
|
||||
val closer := this.closer_of(plain);
|
||||
if closer != 0 {
|
||||
val receiver := this.reference_to(place, this.c.checker.types.reference(plain, true));
|
||||
this.method_call(closer, plain, &receiver, span::<operand>::empty());
|
||||
}
|
||||
}
|
||||
|
||||
# A union holds one of its fields, so only that one is closed.
|
||||
if shape.kind == lk::variant {
|
||||
var at := shape.count;
|
||||
while at > 0 {
|
||||
at--;
|
||||
val each := this.c.field_at(index, at as u32);
|
||||
continue if !this.c.checker.closes(each.type_id);
|
||||
val holding := this.build.new_block();
|
||||
val after := this.build.new_block();
|
||||
this.build.branch(this.tag_is(place, at as u32), holding, after);
|
||||
this.build.seal(holding);
|
||||
this.build.switch_to(holding);
|
||||
val inner := this.within(place, each.offset, each.type_id);
|
||||
this.close(&inner);
|
||||
this.build.jump(after);
|
||||
this.build.seal(after);
|
||||
this.build.switch_to(after);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var at := shape.count;
|
||||
while at > 0 {
|
||||
at--;
|
||||
val each := this.c.field_at(index, at as u32);
|
||||
continue if !this.c.checker.closes(each.type_id);
|
||||
val inner := this.within(place, each.offset, each.type_id);
|
||||
this.close(&inner);
|
||||
}
|
||||
}
|
||||
|
||||
#! The `close(&mut this): void` of `owning` a type gives, or 0.
|
||||
#! @param this The emitter.
|
||||
#! @param kind The type.
|
||||
#! @returns The method's declaration, or 0.
|
||||
pub def emitter::closer_of(&mut this, kind: u32): u32 {
|
||||
val found := this.c.checker.find_member(kind, word::close);
|
||||
return 0 if found.decl == 0;
|
||||
var walk := this.c.checker.decls.walk_overloads(found.decl);
|
||||
while true {
|
||||
val at := walk.next();
|
||||
break if at == 0;
|
||||
this.c.checker.resolve(at);
|
||||
if this.c.checker.decls.kinds.p[at] == dk::function && this.c.checker.decls.has(at, df::mut_this)
|
||||
&& this.c.checker.types.part_count(this.c.checker.decls.types.p[at]) == 1 {
|
||||
return at;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! Closes the elements of a fixed array, the last first, by a loop.
|
||||
#! @param this The emitter.
|
||||
#! @param place The array's place.
|
||||
#! @param kind Its type, without aliases.
|
||||
#! @param shape Its layout.
|
||||
def emitter::close_elements(&mut this, place: &location, kind: u32, shape: &layout): void {
|
||||
return if shape.count == 0;
|
||||
val element := this.c.checker.types.first_of(kind);
|
||||
val size := this.c.layout_at(shape.element - 1).size;
|
||||
val first := this.address_of(place);
|
||||
val left := this.build.variable(vt::word);
|
||||
this.build.assign(left, this.build.word(shape.count as u64));
|
||||
|
||||
val head := this.build.new_block();
|
||||
val body := this.build.new_block();
|
||||
val exit := this.build.new_block();
|
||||
this.build.jump(head);
|
||||
this.build.switch_to(head);
|
||||
val count := this.build.read(left);
|
||||
this.build.branch(this.build.binary(op::ne, count, this.build.word(0)), body, exit);
|
||||
this.build.seal(body);
|
||||
this.build.switch_to(body);
|
||||
val index := this.build.binary(op::sub, this.build.read(left), this.build.word(1));
|
||||
this.build.assign(left, index);
|
||||
val address := this.build.binary(op::add, first, this.scaled(index, size));
|
||||
val inner := location { kind = element, address = address, framed = place.framed };
|
||||
this.close(&inner);
|
||||
this.close_loop(head, exit);
|
||||
}
|
||||
|
||||
#! The text a format made, taken from what the program manages itself and
|
||||
#! handed to a `string` holding no allocator, which gives it back with
|
||||
#! `raw_release` where it closes. The statement keeps it until a place takes it.
|
||||
#! @param this The emitter.
|
||||
#! @param kind The `string` type.
|
||||
#! @returns The string.
|
||||
pub def emitter::owned_text(&mut this, kind: u32): operand {
|
||||
var gives: vt[2] = [vt::word, vt::word];
|
||||
val made := this.build.emit(op::format_owned, span::<u32>::empty(), gives[0:2], 0, 0);
|
||||
val pointer: u32 = this.build.code.insts[made].result;
|
||||
val length := pointer + 1;
|
||||
|
||||
val index := this.c.layout_of(this.c.checker.unalias(kind));
|
||||
val shape := this.c.layout_at(index);
|
||||
val address := this.temporary_of(kind);
|
||||
this.build.clear(address, shape.size);
|
||||
for i in 1..shape.count {
|
||||
break if i >= 4;
|
||||
val field := this.c.field_at(index, i as u32);
|
||||
this.build.store(access::i64, address, field.offset, i == 1 ? pointer : length);
|
||||
}
|
||||
var text := operand::at(kind, address);
|
||||
this.keep(&text);
|
||||
return text;
|
||||
}
|
||||
@@ -0,0 +1,617 @@
|
||||
#! @file places.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains places: where what a name, a field, an element, or what a pointer
|
||||
#! or reference reaches is, how what is there is read and written, and the
|
||||
#! references made to it. A reference is read through to what it refers to,
|
||||
#! as many as it takes, wherever a place is reached through it.
|
||||
|
||||
import sakura::analyzer;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! The address a place's memory begins at.
|
||||
#! @param this The emitter.
|
||||
#! @param place The place, in memory.
|
||||
#! @returns The address.
|
||||
pub def emitter::address_of(&mut this, place: &location): u32 {
|
||||
return place.address if place.offset == 0;
|
||||
return this.build.binary(op::add, place.address, this.build.word(place.offset));
|
||||
}
|
||||
|
||||
#! Reads what a place holds. What is held in memory is copied to a cell of the
|
||||
#! statement's own, so writing the place afterwards leaves the value as it was.
|
||||
#! @param this The emitter.
|
||||
#! @param place The place.
|
||||
#! @returns The value.
|
||||
pub def emitter::load(&mut this, place: &location): operand {
|
||||
val held := this.c.shape_of(place.kind);
|
||||
var made := operand { kind = place.kind, count = word_count(&held) };
|
||||
if place.held {
|
||||
for i in 0..made.count {
|
||||
made.words[i] = this.build.read(place.vars[i]);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
if in_memory(&held) {
|
||||
val copy := this.temporary_of(place.kind);
|
||||
this.build.copy(copy, this.address_of(place), held.size);
|
||||
return operand::at(place.kind, copy);
|
||||
}
|
||||
if made.count == 1 {
|
||||
made.words[0] = this.build.load(held.how, place.address, place.offset);
|
||||
return made;
|
||||
}
|
||||
for i in 0..made.count {
|
||||
made.words[i] = this.build.load(access::i64, place.address, place.offset + i as u64 * word_size);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Writes a value to a place, which is of the value's type.
|
||||
#! @param this The emitter.
|
||||
#! @param place The place.
|
||||
#! @param value The value.
|
||||
pub def emitter::store(&mut this, place: &location, value: &operand): void {
|
||||
val held := this.c.shape_of(place.kind);
|
||||
if place.held {
|
||||
for i in 0..word_count(&held) {
|
||||
this.build.assign(place.vars[i], value.words[i]);
|
||||
this.bind(place.vars[i], value.words[i]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if in_memory(&held) {
|
||||
return if value.address == 0;
|
||||
this.build.copy(this.address_of(place), value.address, held.size);
|
||||
return;
|
||||
}
|
||||
if word_count(&held) == 1 {
|
||||
this.build.store(held.how, place.address, place.offset, value.words[0]);
|
||||
return;
|
||||
}
|
||||
for i in 0..word_count(&held) {
|
||||
this.build.store(access::i64, place.address, place.offset + i as u64 * word_size, value.words[i]);
|
||||
}
|
||||
}
|
||||
|
||||
#! Zeroes what a place holds.
|
||||
#! @param this The emitter.
|
||||
#! @param place The place.
|
||||
pub def emitter::zero(&mut this, place: &location): void {
|
||||
val held := this.c.shape_of(place.kind);
|
||||
if place.held {
|
||||
for i in 0..word_count(&held) {
|
||||
val zero := word_type(&held) == vt::real ? this.build.real(0) : this.build.word(0);
|
||||
this.build.assign(place.vars[i], zero);
|
||||
this.bind(place.vars[i], zero);
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.build.clear(this.address_of(place), held.size);
|
||||
}
|
||||
|
||||
#! A reference to a place, as the word a reference is: where the value is. A
|
||||
#! place held in variables has no address, so a copy of its value is referred
|
||||
#! to instead, which the storage worked out before lowering avoids for what a
|
||||
#! reference must reach.
|
||||
#! @param this The emitter.
|
||||
#! @param place The place.
|
||||
#! @param kind The reference's type.
|
||||
#! @returns The reference.
|
||||
pub def emitter::reference_to(&mut this, place: &location, kind: u32): operand {
|
||||
if place.held {
|
||||
val value := this.load(place);
|
||||
val copy := location { kind = place.kind, address = this.temporary_of(place.kind), framed = true };
|
||||
this.store(©, &value);
|
||||
return this.reference_to(©, kind);
|
||||
}
|
||||
|
||||
# A reference to a trait the value implements is given its type's vtable.
|
||||
val wanted := this.c.checker.unalias(kind);
|
||||
if this.c.checker.types.kind_of(wanted) == ty::reference {
|
||||
val referent := this.c.checker.unalias(this.c.checker.types.first_of(wanted));
|
||||
if this.c.checker.named_kind(referent) == dk::trait_type && this.c.checker.named_kind(this.c.checker.unalias(place.kind)) != dk::trait_type {
|
||||
val own := this.c.checker.types.reference(place.kind, this.c.checker.types.second_of(wanted) != 0);
|
||||
val made := operand::one(own, this.address_of(place));
|
||||
return this.convert(&made, kind);
|
||||
}
|
||||
}
|
||||
return operand::one(kind, this.address_of(place));
|
||||
}
|
||||
|
||||
#! The place a reference refers to.
|
||||
#! @param this The emitter.
|
||||
#! @param value The reference.
|
||||
#! @returns The place.
|
||||
pub def emitter::referent(&mut this, value: &operand): location {
|
||||
val kind := this.c.checker.types.first_of(this.c.checker.unalias(value.kind));
|
||||
# Running with its memory checked, what a reference refers to is where the
|
||||
# program holds memory, as what a pointer points at is.
|
||||
if this.c.options.checks && this.c.checker.named_kind(this.c.checker.unalias(kind)) != dk::trait_type {
|
||||
this.reaches(value.words[0], this.build.word(1), this.c.shape_of(kind).size);
|
||||
}
|
||||
return location { kind = kind, address = value.words[0] };
|
||||
}
|
||||
|
||||
#! A place within another, at an offset, as a field is.
|
||||
#! @param this The emitter.
|
||||
#! @param place The place holding it.
|
||||
#! @param offset How many bytes in it is.
|
||||
#! @param kind Its type.
|
||||
#! @returns The place.
|
||||
pub def emitter::within(&mut this, place: &location, offset: u64, kind: u32): location {
|
||||
var made: location = place;
|
||||
if place.held {
|
||||
# A value held in variables is no struct, so this is never reached; it is
|
||||
# copied to memory where it is.
|
||||
val value := this.load(place);
|
||||
made = location { kind = place.kind, address = this.temporary_of(place.kind), framed = true };
|
||||
this.store(&made, &value);
|
||||
}
|
||||
made.kind = kind;
|
||||
made.offset = made.offset + offset;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The place a node's value is at, read through as many references as it holds
|
||||
#! until what they refer to is no reference, or as many as `levels` says.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node.
|
||||
#! @param levels How many references to read through at most.
|
||||
#! @returns The place.
|
||||
pub def emitter::object_by(&mut this, node: u32, levels: u32): location {
|
||||
var kind := this.c.checker.type_at(node);
|
||||
if !this.c.is_reference_type(kind) || levels == 0 {
|
||||
return this.place_of(node);
|
||||
}
|
||||
|
||||
var value := this.value_of_type(node);
|
||||
var place := this.referent(&value);
|
||||
var steps: u32 = 1;
|
||||
while steps < levels && this.c.is_reference_type(place.kind) && steps < 16 {
|
||||
value = this.load(&place);
|
||||
place = this.referent(&value);
|
||||
steps++;
|
||||
}
|
||||
return place;
|
||||
}
|
||||
|
||||
#! The place a node's value is at, read through every reference it holds.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node.
|
||||
#! @returns The place.
|
||||
pub def emitter::object(&mut this, node: u32): location {
|
||||
return this.object_by(node, 16);
|
||||
}
|
||||
|
||||
#! The place a node names: a local, a global, a field, an element, or what a
|
||||
#! pointer points at; or else a cell of the statement's own holding its value.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node.
|
||||
#! @returns The place.
|
||||
pub def emitter::place_of(&mut this, node: u32): location {
|
||||
val saved := this.build.pos;
|
||||
this.at_node(node);
|
||||
val made := this.place_node(node);
|
||||
this.build.pos = saved;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The place a node names, by the kind of the node.
|
||||
#! @param this The emitter.
|
||||
#! @param node The node.
|
||||
#! @returns The place.
|
||||
def emitter::place_node(&mut this, node: u32): location {
|
||||
match this.c.checker.kind_of(node) {
|
||||
nk::name, nk::path => {
|
||||
val ref := this.c.checker.ref_at(node);
|
||||
if (ref & ref_local) != 0 {
|
||||
val index := this.local_of(ref & ref_mask);
|
||||
if index != 0 {
|
||||
val held: local_info = this.locals[index - 1];
|
||||
return held.place;
|
||||
}
|
||||
if this.pass_variable(ref & ref_mask) {
|
||||
val held: local_info = this.locals[this.local_of(ref & ref_mask) - 1];
|
||||
return held.place;
|
||||
}
|
||||
this.problem(node, "The local is not where it is named.");
|
||||
} else if ref != 0 && (ref & ref_type) == 0 && this.c.checker.decls.kinds.p[ref] == dk::variable
|
||||
&& !this.c.checker.is_known(node) {
|
||||
return this.global_place(ref);
|
||||
}
|
||||
}
|
||||
nk::member => {
|
||||
val ref := this.c.checker.ref_at(node);
|
||||
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::field {
|
||||
return this.field_place(node, ref);
|
||||
}
|
||||
}
|
||||
nk::member_of => {
|
||||
val ref := this.c.checker.ref_at(node);
|
||||
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::field {
|
||||
return this.field_place(node, ref);
|
||||
}
|
||||
# What else a description names is no place.
|
||||
if this.property_of(node) == 0 {
|
||||
this.problem(node, "The member a description names is not lowered.");
|
||||
return location { kind = this.c.checker.type_at(node), address = this.build.word(0) };
|
||||
}
|
||||
}
|
||||
nk::index => {
|
||||
# Through `at`, it is the reference `at` gives, held as any value is.
|
||||
if !this.indexes_through_at(node) {
|
||||
return this.element_place(node);
|
||||
}
|
||||
}
|
||||
nk::call => {
|
||||
# `value_of(d)` of a variable is the variable.
|
||||
val ref := this.c.checker.ref_at(node);
|
||||
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::variable
|
||||
&& !this.c.checker.is_known(node) {
|
||||
return this.global_place(ref);
|
||||
}
|
||||
}
|
||||
nk::unary => {
|
||||
if this.c.checker.token_kind(node) == tk::star {
|
||||
# A reference to a pointer is read through to the pointer.
|
||||
val given := this.value_of_type(this.c.checker.left_of(node));
|
||||
val pointer := this.through_references(&given);
|
||||
val kind := this.c.checker.type_at(node);
|
||||
this.reaches(pointer.words[0], this.build.word(1), this.c.shape_of(kind).size);
|
||||
return location { kind = kind, address = pointer.words[0] };
|
||||
}
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
|
||||
# Anything else is a value, held where the statement holds what it makes.
|
||||
val value := this.value_of_type(node);
|
||||
return this.hold(&value);
|
||||
}
|
||||
|
||||
#! A place holding a value: its own memory, where it is in memory, or a cell of
|
||||
#! the statement's own the value is written to.
|
||||
#! @param this The emitter.
|
||||
#! @param value The value.
|
||||
#! @returns The place.
|
||||
pub def emitter::hold(&mut this, value: &operand): location {
|
||||
if value.address != 0 {
|
||||
return location { kind = value.kind, address = value.address, framed = true };
|
||||
}
|
||||
val place := location { kind = value.kind, address = this.temporary_of(value.kind), framed = true };
|
||||
this.store(&place, value);
|
||||
return place;
|
||||
}
|
||||
|
||||
#! The place of a global, where it is placed among the globals.
|
||||
#! @param this The emitter.
|
||||
#! @param decl The global's declaration.
|
||||
#! @returns The place.
|
||||
pub def emitter::global_place(&mut this, decl: u32): location {
|
||||
val kind: u32 = this.c.checker.decls.types.p[decl];
|
||||
val constant := this.c.checker.decls.has(decl, df::constant);
|
||||
|
||||
# While compiling, a constant is read once it is evaluated, and a variable
|
||||
# given its value once the program runs is not read at all.
|
||||
if this.c.options.evaluating {
|
||||
if !constant {
|
||||
this.build.trap(fault::not_constant as u32);
|
||||
val nowhere := this.build.word(0);
|
||||
return location { kind = kind, address = nowhere };
|
||||
}
|
||||
val index := this.c.evaluation_of(decl_key(decl), decl, 0, 0, false);
|
||||
this.build.effect(op::ready, span::<u32>::empty(), index, 0);
|
||||
val offset: u64 = this.c.evaluations[index].offset;
|
||||
val address := this.build.value(op::global, span::<u32>::empty(), vt::word, 0, offset);
|
||||
return location { kind = kind, address = address };
|
||||
}
|
||||
|
||||
# A constant evaluated is read where the program holds its value as data.
|
||||
if constant {
|
||||
val datum := this.c.evaluated_datum(decl_key(decl), kind);
|
||||
if datum != no_block {
|
||||
val address := this.build.value(op::datum, span::<u32>::empty(), vt::word, datum, 0);
|
||||
return location { kind = kind, address = address };
|
||||
}
|
||||
}
|
||||
|
||||
val offset := this.c.global_of(decl);
|
||||
val address := this.build.value(op::global, span::<u32>::empty(), vt::word, 0, offset);
|
||||
return location { kind = kind, address = address };
|
||||
}
|
||||
|
||||
#! Whether the code checks what only a checked build does: indexes and slices,
|
||||
#! the field a union holds, an integer converted to an enum, and a `match`
|
||||
#! finding no arm. A constant is evaluated checked in every build.
|
||||
#! @param this The emitter.
|
||||
#! @returns Whether it does.
|
||||
pub def emitter::checking(&this): bool {
|
||||
return !this.c.checker.checks_off || this.c.options.evaluating;
|
||||
}
|
||||
|
||||
#! Stops the program where a pointer is null, which only the code of a checked
|
||||
#! program reaching an element past the first page asks. Elsewhere reading or
|
||||
#! writing through null stops the program where it does, in every build: the
|
||||
#! machine compares each address it reads or writes through with the first
|
||||
#! page, and an executable faults there, which its runtime reports as the same.
|
||||
#! @param this The emitter.
|
||||
#! @param pointer The pointer.
|
||||
def emitter::compare_null(&mut this, pointer: u32): void {
|
||||
val zero := this.build.word(0);
|
||||
this.build.check(this.build.binary(op::ne, pointer, zero), fault::null_reference as u32);
|
||||
}
|
||||
|
||||
#! The place of a field of a struct or union, read through the references the
|
||||
#! object is reached by. A field a struct's spread brings in is reached through
|
||||
#! the spread field holding it, and a field of a union only where the union
|
||||
#! holds it.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `member` node.
|
||||
#! @param field The field's declaration.
|
||||
#! @returns The place.
|
||||
pub def emitter::field_place(&mut this, node: u32, field: u32): location {
|
||||
val object := this.c.checker.left_of(node);
|
||||
val whole := this.object(object);
|
||||
val kind := this.c.checker.type_at(node);
|
||||
val owner := this.c.checker.unalias(whole.kind);
|
||||
return this.field_in(&whole, owner, field, kind);
|
||||
}
|
||||
|
||||
#! The place of a field within a place holding a struct or union of a type.
|
||||
#! @param this The emitter.
|
||||
#! @param whole The place of the struct or union.
|
||||
#! @param owner Its type, without aliases.
|
||||
#! @param field The field's declaration.
|
||||
#! @param kind The field's type, as checked.
|
||||
#! @returns The place.
|
||||
pub def emitter::field_in(&mut this, whole: &location, owner: u32, field: u32, kind: u32): location {
|
||||
val index := this.c.layout_of(owner);
|
||||
val shape := this.c.layout_at(index);
|
||||
for i in 0..shape.count {
|
||||
val each := this.c.field_at(index, i as u32);
|
||||
if each.decl == field {
|
||||
if shape.kind == lk::variant {
|
||||
this.check_held(whole, i as u32);
|
||||
}
|
||||
return this.within(whole, each.offset, each.type_id);
|
||||
}
|
||||
}
|
||||
|
||||
# Reached through a spread field, which holds the struct declaring it.
|
||||
for i in 0..shape.count {
|
||||
val each := this.c.field_at(index, i as u32);
|
||||
continue if !each.spread;
|
||||
val inner := this.within(whole, each.offset, each.type_id);
|
||||
val plain := this.c.checker.unalias(each.type_id);
|
||||
if this.holds_field(plain, field, 0) {
|
||||
return this.field_in(&inner, plain, field, kind);
|
||||
}
|
||||
}
|
||||
this.problem(0, "A field is not in the layout of what holds it.");
|
||||
return this.within(whole, 0, kind);
|
||||
}
|
||||
|
||||
#! Whether a struct holds a field, its own or one a spread brings in.
|
||||
#! @param this The emitter.
|
||||
#! @param kind The struct's type.
|
||||
#! @param field The field's declaration.
|
||||
#! @param depth How deeply spreads have been followed.
|
||||
#! @returns Whether it holds it.
|
||||
def emitter::holds_field(&mut this, kind: u32, field: u32, depth: u32): bool {
|
||||
return false if depth > 16;
|
||||
val index := this.c.layout_of(kind);
|
||||
val shape := this.c.layout_at(index);
|
||||
for i in 0..shape.count {
|
||||
val each := this.c.field_at(index, i as u32);
|
||||
return true if each.decl == field;
|
||||
if each.spread && this.holds_field(this.c.checker.unalias(each.type_id), field, depth + 1) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Stops the program unless a union holds its field of an index, where the code
|
||||
#! checks.
|
||||
#! @param this The emitter.
|
||||
#! @param whole The place of the union.
|
||||
#! @param index The field's index.
|
||||
pub def emitter::check_held(&mut this, whole: &location, index: u32): void {
|
||||
return if !this.checking();
|
||||
val holds := this.tag_is(whole, index);
|
||||
this.build.check(holds, fault::not_held as u32);
|
||||
}
|
||||
|
||||
#! Whether a union holds its field of an index, as a word of 0 or 1.
|
||||
#! @param this The emitter.
|
||||
#! @param whole The place of the union.
|
||||
#! @param index The field's index.
|
||||
#! @returns The word.
|
||||
pub def emitter::tag_is(&mut this, whole: &location, index: u32): u32 {
|
||||
var tag: u32 = 0;
|
||||
if whole.held {
|
||||
tag = this.build.read(whole.vars[0]);
|
||||
} else {
|
||||
tag = this.build.load(access::i64, whole.address, whole.offset);
|
||||
}
|
||||
# A union without a tag holds the field it is laid out for where its first word
|
||||
# is not null, and the empty one where it is.
|
||||
val shape := this.c.shape_of(whole.kind);
|
||||
if shape.niche != 0 {
|
||||
return this.build.binary(index + 1 == shape.niche ? op::ne : op::eq, tag, this.build.word(0));
|
||||
}
|
||||
return this.build.binary(op::eq, tag, this.build.word(index as u64));
|
||||
}
|
||||
|
||||
#! The place of an element: of a fixed array, at an index checked against its
|
||||
#! length; of what a pointer points at, which is not checked; of a view, checked
|
||||
#! against how many it views; of a pack, at an index known while compiling; or
|
||||
#! of what implements `indexable`, the place its `at` refers to.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `index` node.
|
||||
#! @returns The place.
|
||||
pub def emitter::element_place(&mut this, node: u32): location {
|
||||
val object := this.c.checker.left_of(node);
|
||||
val at := this.c.checker.right_of(node);
|
||||
val kind := this.c.checker.type_at(node);
|
||||
val whole_type := this.object_type(object);
|
||||
val through := this.c.checker.unalias(this.c.checker.reached(whole_type));
|
||||
|
||||
match this.c.checker.types.kind_of(through) {
|
||||
ty::fixed => {
|
||||
val whole := this.object(object);
|
||||
val shape := this.c.shape_of(through);
|
||||
val element := this.c.layout_at(shape.element - 1);
|
||||
if this.c.checker.is_known(at) {
|
||||
val index := this.c.checker.value_at(at).magnitude;
|
||||
if index < shape.count as u64 {
|
||||
return this.within(&whole, index * element.size, this.c.checker.types.first_of(through));
|
||||
}
|
||||
}
|
||||
val index := this.value_as(at, bt::uint64);
|
||||
if this.checking() {
|
||||
val within := this.build.binary(op::ltu, index.words[0], this.build.word(shape.count as u64));
|
||||
this.build.check(within, fault::out_of_bounds as u32);
|
||||
}
|
||||
val first := this.address_of(&whole);
|
||||
val address := this.build.binary(op::add, first, this.scaled(index.words[0], element.size));
|
||||
return location { kind = this.c.checker.types.first_of(through), address = address, framed = whole.framed };
|
||||
}
|
||||
ty::pointer => {
|
||||
val pointer := this.value_of_type(object);
|
||||
val reached := this.through_references(&pointer);
|
||||
val element := this.c.shape_of(this.c.checker.types.first_of(through));
|
||||
# An element past the first page is no fault there, so a checked program
|
||||
# compares the pointer with null first, unless the index is known to
|
||||
# stay within it.
|
||||
val near := this.c.checker.is_known(at) && (element.size == 0 || this.c.checker.value_at(at).magnitude < null_page / element.size);
|
||||
if this.checking() && !near {
|
||||
this.compare_null(reached.words[0]);
|
||||
}
|
||||
val index := this.value_as(at, bt::uint64);
|
||||
val address := this.build.binary(op::add, reached.words[0], this.scaled(index.words[0], element.size));
|
||||
this.reaches(address, this.build.word(1), element.size);
|
||||
return location { kind = this.c.checker.types.first_of(through), address = address };
|
||||
}
|
||||
ty::pack => {
|
||||
val index := this.c.checker.value_at(at).magnitude;
|
||||
return this.pack_place(object, index as u32);
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
|
||||
# A view holds where its elements are and how many, so an element of one is the
|
||||
# place that many along, once the index is checked against the count. A view
|
||||
# holding any element is never over null, as std makes every view, so the
|
||||
# index's check is all it needs.
|
||||
val viewed := this.c.viewed(through);
|
||||
if viewed != 0 {
|
||||
val whole := this.object(object);
|
||||
val data := this.build.load(access::i64, whole.address, whole.offset);
|
||||
val count := this.build.load(access::i64, whole.address, whole.offset + word_size);
|
||||
val index := this.value_as(at, bt::uint64);
|
||||
if this.checking() {
|
||||
this.build.check(this.build.binary(op::ltu, index.words[0], count), fault::out_of_bounds as u32);
|
||||
}
|
||||
val element := this.c.shape_of(viewed);
|
||||
val address := this.build.binary(op::add, data, this.scaled(index.words[0], element.size));
|
||||
return location { kind = viewed, address = address };
|
||||
}
|
||||
|
||||
# What implements `indexable` gives a reference to the element through `at`.
|
||||
val method := this.c.checker.ref_at(node);
|
||||
if method != 0 && (method & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[method] == dk::function {
|
||||
val made := this.accessor_call(node, method, object, at);
|
||||
if this.c.is_reference_type(made.kind) {
|
||||
return this.referent(&made);
|
||||
}
|
||||
return this.hold(&made);
|
||||
}
|
||||
this.problem(node, "Nothing is indexed here.");
|
||||
return location { kind = kind, address = this.temporary_of(kind) };
|
||||
}
|
||||
|
||||
#! The type of what an element or a member is reached through: its own, or,
|
||||
#! for a constant, the one it settles as, so `"text"[0]` is a `strview`'s.
|
||||
#! @param this The emitter.
|
||||
#! @param object The node of the value reached through.
|
||||
#! @returns The type.
|
||||
pub def emitter::object_type(&mut this, object: u32): u32 {
|
||||
val own := this.c.checker.type_at(object);
|
||||
return this.c.checker.types.is_untyped(own) ? this.c.checker.converted(object) : own;
|
||||
}
|
||||
|
||||
#! Whether `x[k]` is indexed through `at`, and so is the reference it gives
|
||||
#! rather than a place of its own.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `index` node.
|
||||
#! @returns Whether it is.
|
||||
pub def emitter::indexes_through_at(&mut this, node: u32): bool {
|
||||
val method := this.c.checker.ref_at(node);
|
||||
return method != 0 && (method & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[method] == dk::function
|
||||
&& this.c.is_reference_type(this.c.checker.type_at(node));
|
||||
}
|
||||
|
||||
#! The reference `x[k]` gives through `at`: the one `at` gives, or, for a view,
|
||||
#! which is indexed without calling it, one to the element it covers.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `index` node.
|
||||
#! @returns The reference.
|
||||
pub def emitter::indexed_reference(&mut this, node: u32): operand {
|
||||
val object := this.c.checker.left_of(node);
|
||||
val through := this.c.checker.unalias(this.c.checker.reached(this.object_type(object)));
|
||||
if this.c.viewed(through) != 0 {
|
||||
val place := this.element_place(node);
|
||||
return this.reference_to(&place, this.c.checker.type_at(node));
|
||||
}
|
||||
return this.accessor_call(node, this.c.checker.ref_at(node), object, this.c.checker.right_of(node));
|
||||
}
|
||||
|
||||
#! A count of elements of a size, in bytes.
|
||||
#! @param this The emitter.
|
||||
#! @param count The count, a word.
|
||||
#! @param size The size of each.
|
||||
#! @returns The bytes.
|
||||
pub def emitter::scaled(&mut this, count: u32, size: u64): u32 {
|
||||
return count if size == 1;
|
||||
return this.build.binary(op::mul, count, this.build.word(size));
|
||||
}
|
||||
|
||||
#! A value read through every reference it is, until it is no reference.
|
||||
#! @param this The emitter.
|
||||
#! @param value The value.
|
||||
#! @returns What it reaches.
|
||||
pub def emitter::through_references(&mut this, value: &operand): operand {
|
||||
var at: operand = value;
|
||||
var steps := 0;
|
||||
while this.c.is_reference_type(at.kind) && steps < 16 {
|
||||
val place := this.referent(&at);
|
||||
at = this.load(&place);
|
||||
steps++;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
#! The place of a value of a pack, by its index.
|
||||
#! @param this The emitter.
|
||||
#! @param object The node naming the pack.
|
||||
#! @param index The value's index.
|
||||
#! @returns The place.
|
||||
pub def emitter::pack_place(&mut this, object: u32, index: u32): location {
|
||||
val ref := this.c.checker.ref_at(object);
|
||||
val local := (ref & ref_local) != 0 ? this.local_of(ref & ref_mask) : 0;
|
||||
if local != 0 {
|
||||
val held: local_info = this.locals[local - 1];
|
||||
if index < held.count {
|
||||
return this.packs[held.pack as u64 + index as u64];
|
||||
}
|
||||
}
|
||||
this.problem(object, "The pack holds no value at the index.");
|
||||
return location { kind = bt::error };
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
#! @file reflection.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains what reflection gives a program: descriptions of its declarations,
|
||||
#! as `core::decl`s, which the checker found while compiling. They are written
|
||||
#! as data the program holds as long as it runs, the text they name among it,
|
||||
#! and read where the program stands.
|
||||
|
||||
import sakura::analyzer;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! What reflection gives an expression: one description, read from the data
|
||||
#! holding it, or a view of a list of them.
|
||||
#! @param this The emitter.
|
||||
#! @param node The expression.
|
||||
#! @returns The value.
|
||||
pub def emitter::reflected_value(&mut this, node: u32): operand {
|
||||
val kind := this.c.checker.type_at(node);
|
||||
val at := this.c.checker.reflected_at(node);
|
||||
if at == checker::no_reflection {
|
||||
this.problem(node, "Reflection gives nothing here.");
|
||||
return this.zero_value(kind);
|
||||
}
|
||||
|
||||
var items := vector::<u32>::new();
|
||||
for i in 0..this.c.checker.reflected_count(at) {
|
||||
items.append(this.c.checker.reflected_item(at, i as u32));
|
||||
}
|
||||
if this.c.checker.reflected_kind(at) == rk::one as u32 {
|
||||
val datum := this.c.descriptions(items.view(), kind);
|
||||
val address := this.build.value(op::datum, span::<u32>::empty(), vt::word, datum, 0);
|
||||
val place := location { kind = kind, address = address };
|
||||
return this.load(&place);
|
||||
}
|
||||
|
||||
val view := this.temporary_of(kind);
|
||||
if items.length == 0 {
|
||||
this.build.clear(view, 2 * word_size);
|
||||
return operand::at(kind, view);
|
||||
}
|
||||
val element := this.c.viewed(kind);
|
||||
val datum := this.c.descriptions(items.view(), element);
|
||||
val first := this.build.value(op::datum, span::<u32>::empty(), vt::word, datum, 0);
|
||||
this.build.store(access::i64, view, 0, first);
|
||||
this.build.store(access::i64, view, word_size, this.build.word(items.length));
|
||||
return operand::at(kind, view);
|
||||
}
|
||||
|
||||
#! Declares the variable of a pass of `for const` over a list reflection gives:
|
||||
#! the description the pass is of.
|
||||
#! @param this The emitter.
|
||||
#! @param variable The node of the loop's variable.
|
||||
pub def emitter::reflected_pass(&mut this, variable: u32): void {
|
||||
val kind := this.c.checker.type_at(variable);
|
||||
val made := this.reflected_value(variable);
|
||||
val place := this.new_place(variable, kind);
|
||||
this.store(&place, &made);
|
||||
this.declare(variable, place, false);
|
||||
}
|
||||
|
||||
#! Declares the variable of a pass of `for const` over a list reflection gives
|
||||
#! where a function the pass doesn't run in names it, as the one evaluating the
|
||||
#! condition of an `if const` within the pass does: the description the pass is
|
||||
#! of, as it is in the pass.
|
||||
#! @param this The emitter.
|
||||
#! @param variable The node of the loop's variable.
|
||||
#! @returns Whether it is such a variable, and was declared.
|
||||
pub def emitter::pass_variable(&mut this, variable: u32): bool {
|
||||
val at := this.c.checker.reflected_at(variable);
|
||||
return false if at == checker::no_reflection || this.c.checker.reflected_kind(at) != rk::one as u32;
|
||||
this.reflected_pass(variable);
|
||||
return true;
|
||||
}
|
||||
|
||||
#! The datum holding descriptions as `core::decl`s one after another, made where
|
||||
#! it is new, with the text each names among the program's data.
|
||||
#! @param this The compiler.
|
||||
#! @param items The descriptions' indices among the checker's.
|
||||
#! @param kind The type of each, `core::decl`.
|
||||
#! @returns The datum's index.
|
||||
pub def lowerer::descriptions(&mut this, items: span<u32>, kind: u32): u32 {
|
||||
val plain := this.checker.unalias(kind);
|
||||
val index := this.layout_of(plain);
|
||||
val shape := this.layout_at(index);
|
||||
var bytes := vector::<u8>::new();
|
||||
bytes.resize(shape.size * items.length);
|
||||
var relocations := vector::<relocation>::new();
|
||||
|
||||
for i in 0..items.length {
|
||||
val held: desc = this.checker.descs[items[i]];
|
||||
val base := i * shape.size;
|
||||
var name := string::new(nothing {});
|
||||
var path := string::new(nothing {});
|
||||
var signature := string::new(nothing {});
|
||||
val decl := held.decl;
|
||||
if held.param != 0 {
|
||||
this.param_name(decl, held.param - 1, &mut name);
|
||||
} else {
|
||||
name.append(this.checker.names.text(this.checker.decls.names.p[decl]));
|
||||
}
|
||||
this.qualified_name(decl, &mut path);
|
||||
this.signature_text(decl, &mut signature);
|
||||
|
||||
val file: u32 = this.checker.decls.files.p[decl];
|
||||
val source := &this.checker.units[file].source;
|
||||
val place := source.lines.place_of(this.node_offset(file, this.checker.decls.nodes.p[decl]));
|
||||
for f in 0..shape.count {
|
||||
val field := this.field_at(index, f as u32);
|
||||
val field_name := this.checker.names.text(field.name);
|
||||
val at := base + field.offset;
|
||||
if field_name == "id" {
|
||||
write_number(&mut bytes, at, this.layout_at(field.layout).size, decl as u64);
|
||||
} else if field_name == "kind" {
|
||||
val bit := held.param != 0 ? 0x2000u : this.checker.target_bit(decl);
|
||||
write_number(&mut bytes, at, this.layout_at(field.layout).size, bit);
|
||||
} else if field_name == "exported" {
|
||||
write_number(&mut bytes, at, 1, held.param == 0 && this.checker.decls.has(decl, df::exported) ? 1 : 0);
|
||||
} else if field_name == "generic" {
|
||||
write_number(&mut bytes, at, 1, held.param == 0 && this.checker.own_param_count(decl) != 0 ? 1 : 0);
|
||||
} else if field_name == "name" {
|
||||
this.write_text(&mut bytes, &mut relocations, at, name.view());
|
||||
} else if field_name == "path" {
|
||||
this.write_text(&mut bytes, &mut relocations, at, path.view());
|
||||
} else if field_name == "at" {
|
||||
val inner := this.layout_at(field.layout);
|
||||
for s in 0..inner.count {
|
||||
val part := this.field_at(field.layout, s as u32);
|
||||
val part_name := this.checker.names.text(part.name);
|
||||
val within := at + part.offset;
|
||||
if part_name == "path" {
|
||||
this.write_text(&mut bytes, &mut relocations, within, source.path);
|
||||
} else if part_name == "line" {
|
||||
write_number(&mut bytes, within, this.layout_at(part.layout).size, place.line as u64);
|
||||
} else if part_name == "column" {
|
||||
write_number(&mut bytes, within, this.layout_at(part.layout).size, place.column as u64);
|
||||
} else if part_name == "signature" {
|
||||
this.write_text(&mut bytes, &mut relocations, within, signature.view());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val datum := this.program.data.length as u32;
|
||||
bytes.append(0);
|
||||
this.program.data.append(datum {
|
||||
bytes = move(&mut bytes),
|
||||
align = shape.align < word_size ? word_size : shape.align,
|
||||
relocations = move(&mut relocations)
|
||||
});
|
||||
return datum;
|
||||
}
|
||||
|
||||
#! Writes a number into bytes, as wide as it says, least significant first.
|
||||
#! @param bytes Where it is written.
|
||||
#! @param at The first byte.
|
||||
#! @param size How many bytes it takes.
|
||||
#! @param value The number.
|
||||
pub def write_number(bytes: &mut vector<u8>, at: u64, size: u64, value: u64): void {
|
||||
for i in 0..size {
|
||||
bytes[at + i] = ((value >> (i * 8)) & 0xFF) as u8;
|
||||
}
|
||||
}
|
||||
|
||||
#! Writes a view of text into bytes: where the text is, as the address of a
|
||||
#! datum holding it, and how many bytes it holds. Empty text points nowhere.
|
||||
#! @param this The compiler.
|
||||
#! @param bytes Where the view is written.
|
||||
#! @param relocations Where the address is noted.
|
||||
#! @param at The first byte of the view.
|
||||
#! @param text The text.
|
||||
def lowerer::write_text(&mut this, bytes: &mut vector<u8>, relocations: &mut vector<relocation>, at: u64, text: strview): void {
|
||||
if text.length != 0 {
|
||||
relocations.append(relocation { at = at, target = this.text_datum(text), addend = 0 });
|
||||
}
|
||||
write_number(bytes, at + word_size, word_size, text.length);
|
||||
}
|
||||
|
||||
#! The name a function's parameter is declared with.
|
||||
#! @param this The compiler.
|
||||
#! @param decl The function's declaration.
|
||||
#! @param index The parameter's position.
|
||||
#! @param out Where the name is written.
|
||||
def lowerer::param_name(&mut this, decl: u32, index: u32, out: &mut string): void {
|
||||
val saved := this.checker.at;
|
||||
this.checker.use_table(this.checker.units[this.checker.decls.files.p[decl]].table);
|
||||
val node: u32 = this.checker.decls.nodes.p[decl];
|
||||
val params := this.checker.decls.has(decl, df::accessor) ? this.checker.left_of(node) : this.checker.record(node, function_slot::params);
|
||||
if index < this.checker.run_length(params) {
|
||||
out.append(this.checker.names.text(this.checker.param_name(this.checker.run_at(params, index))));
|
||||
}
|
||||
this.checker.at = saved;
|
||||
}
|
||||
|
||||
#! The name a declaration is reached by from outside its module, as
|
||||
#! `sakura::analyzer::interns_keywords`.
|
||||
#! @param this The compiler.
|
||||
#! @param decl The declaration.
|
||||
#! @param out Where the name is written.
|
||||
pub def lowerer::qualified_name(&mut this, decl: u32, out: &mut string): void {
|
||||
var modules := vector::<u32>::new();
|
||||
var at: u32 = this.checker.decls.modules.p[decl];
|
||||
var steps := 0;
|
||||
while at != 0 && steps < 64 {
|
||||
modules.append(at);
|
||||
at = this.checker.modules.parents[at];
|
||||
steps++;
|
||||
}
|
||||
var i := modules.length;
|
||||
while i > 0 {
|
||||
i--;
|
||||
out.append(this.checker.names.text(this.checker.modules.names[modules[i]]));
|
||||
out.append("::");
|
||||
}
|
||||
var holder: u32 = this.checker.decls.owners.p[decl];
|
||||
if holder != 0 && this.checker.decls.kinds.p[holder] == dk::property {
|
||||
holder = this.checker.decls.owners.p[holder];
|
||||
}
|
||||
if holder != 0 && this.checker.decls.kinds.p[holder] != dk::type_param {
|
||||
out.append(this.checker.names.text(this.checker.decls.names.p[holder]));
|
||||
out.append("::");
|
||||
}
|
||||
out.append(this.checker.names.text(this.checker.decls.names.p[decl]));
|
||||
}
|
||||
|
||||
#! The signature a declaration is written with: its text from where it begins
|
||||
#! to its body, or its first line.
|
||||
#! @param this The compiler.
|
||||
#! @param decl The declaration.
|
||||
#! @param out Where the text is written.
|
||||
pub def lowerer::signature_text(&mut this, decl: u32, out: &mut string): void {
|
||||
val file: u32 = this.checker.decls.files.p[decl];
|
||||
val node: u32 = this.checker.decls.nodes.p[decl];
|
||||
return if node == 0;
|
||||
val syntax := &this.checker.units[file].syntax;
|
||||
val source := &this.checker.units[file].source;
|
||||
val begin := syntax.token_offsets[syntax.start_of(node)];
|
||||
val end_token := syntax.node_end(node);
|
||||
val end := syntax.token_offsets[end_token] + syntax.token_length(end_token, this.checker.names);
|
||||
return if end <= begin;
|
||||
val whole := source.make_lexeme(begin, end - begin);
|
||||
var stop := 0u;
|
||||
while stop < whole.length && whole[stop] != '{' && whole[stop] != '\n' {
|
||||
stop++;
|
||||
}
|
||||
while stop > 0 && (whole[stop - 1] == ' ' || whole[stop - 1] == '\t') {
|
||||
stop--;
|
||||
}
|
||||
out.append(whole.substr(0, stop));
|
||||
}
|
||||
@@ -0,0 +1,653 @@
|
||||
#! @file statements.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the lowering of statements: blocks and the locals declared in
|
||||
#! them, branches, `if const` and `when`, loops, contracts, and leaving by
|
||||
#! `return`, `break`, and `continue`, each closing what it leaves behind.
|
||||
|
||||
import sakura::analyzer;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! Lowers a block, whose locals close where it ends. Statements after one the
|
||||
#! checker found always leaves, as decided while checking, were never checked,
|
||||
#! so they are not lowered either.
|
||||
#! @param this The emitter.
|
||||
#! @param node The block, or a statement standing for one.
|
||||
pub def emitter::lower_block(&mut this, node: u32): void {
|
||||
return if node == 0;
|
||||
if this.c.checker.kind_of(node) != nk::block {
|
||||
this.lower_statement(node);
|
||||
return;
|
||||
}
|
||||
|
||||
val mark := this.scope_mark();
|
||||
val run := this.c.checker.left_of(node);
|
||||
for i in 0..this.c.checker.run_length(run) {
|
||||
val each := this.c.checker.run_at(run, i as u32);
|
||||
this.lower_statement(each);
|
||||
break if this.skips(each);
|
||||
}
|
||||
this.end_scope(mark, 0);
|
||||
}
|
||||
|
||||
#! Whether a statement leaves where it was decided while checking, so the
|
||||
#! checker checked nothing after it: an `if const` whose branch taken leaves,
|
||||
#! with no `else`, or a block or `when` holding one.
|
||||
#! @param this The emitter.
|
||||
#! @param node The statement.
|
||||
#! @returns Whether it does.
|
||||
pub def emitter::skips(&mut this, node: u32): bool {
|
||||
match this.c.checker.kind_of(node) {
|
||||
nk::block => {
|
||||
val run := this.c.checker.left_of(node);
|
||||
for i in 0..this.c.checker.run_length(run) {
|
||||
return true if this.skips(this.c.checker.run_at(run, i as u32));
|
||||
}
|
||||
}
|
||||
nk::when_block => return this.skips(this.c.checker.when_branch(node));
|
||||
nk::if_const => {
|
||||
val condition := this.c.checker.left_of(node);
|
||||
return false if !this.c.checker.is_known(condition);
|
||||
val then := this.c.checker.record(node, if_slot::then);
|
||||
val other := this.c.checker.record(node, if_slot::other);
|
||||
if this.c.checker.value_at(condition).magnitude != 0 {
|
||||
return this.skips(then) || (other == 0 && this.c.checker.has_flag(then, rf::leaves));
|
||||
}
|
||||
return other != 0 && this.skips(other);
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Lowers a statement.
|
||||
#! @param this The emitter.
|
||||
#! @param node The statement.
|
||||
pub def emitter::lower_statement(&mut this, node: u32): void {
|
||||
# A contract left out is no statement at all, so what follows takes no
|
||||
# place of it.
|
||||
return if this.c.checker.contracts_off && this.c.checker.kind_of(node) == nk::contract;
|
||||
this.at_node(node);
|
||||
match this.c.checker.kind_of(node) {
|
||||
nk::block => this.lower_block(node);
|
||||
nk::variable => this.local_statement(node);
|
||||
nk::if_stmt => this.if_statement(node);
|
||||
nk::if_const => this.if_const(node);
|
||||
nk::when_block => this.lower_block(this.c.checker.when_branch(node));
|
||||
nk::while_stmt => this.while_statement(node);
|
||||
nk::for_stmt => this.for_statement(node);
|
||||
nk::match_stmt => {
|
||||
val mark := this.begin_statement();
|
||||
this.lower_match(node, false);
|
||||
this.end_statement(mark);
|
||||
}
|
||||
nk::return_stmt => {
|
||||
val mark := this.begin_statement();
|
||||
val value := this.c.checker.left_of(node);
|
||||
if value != 0 && this.result != bt::void_type {
|
||||
this.return_value(value, mark);
|
||||
return;
|
||||
}
|
||||
# `return;` from a function giving more than nothing gives `void`, as a
|
||||
# `result<void, E>` holds it.
|
||||
if value == 0 && this.c.checker.unalias(this.result) != bt::void_type {
|
||||
val none := operand::none(bt::void_type);
|
||||
var made := this.convert(&none, this.result);
|
||||
this.return_made(&mut made, 0, mark);
|
||||
return;
|
||||
}
|
||||
# What gives nothing, returned from a function giving nothing, is done first.
|
||||
if value != 0 {
|
||||
this.value(value);
|
||||
}
|
||||
this.close_kept(mark.kept);
|
||||
this.leave_kept(0);
|
||||
this.close_locals(0, 0);
|
||||
this.build.ret(span::<u32>::empty());
|
||||
}
|
||||
nk::break_stmt, nk::continue_stmt => this.leave_loop(this.c.checker.kind_of(node) == nk::break_stmt);
|
||||
nk::contract => this.contract_statement(node);
|
||||
nk::expr_stmt => {
|
||||
val mark := this.begin_statement();
|
||||
val inner := this.c.checker.left_of(node);
|
||||
this.value(inner);
|
||||
this.end_statement(mark);
|
||||
# A call that ends the program, as `exit`, is never returned from.
|
||||
if this.ends_program(inner) {
|
||||
this.build.unreachable();
|
||||
}
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
}
|
||||
|
||||
#! Lowers a contract, as only a program checking contracts does: `expects` and
|
||||
#! `asserts` are checked where they are, and an `ensures` is an entry among the
|
||||
#! locals, which closing checks on each way out of its block, once what each
|
||||
#! `old` within it reads is kept.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `contract` node.
|
||||
def emitter::contract_statement(&mut this, node: u32): void {
|
||||
if this.c.checker.clause_of(node) != clause::ensures {
|
||||
val mark := this.begin_statement();
|
||||
this.check_contract(node);
|
||||
this.end_statement(mark);
|
||||
return;
|
||||
}
|
||||
this.keep_earlier(this.c.checker.left_of(node));
|
||||
val index := this.declare(node, location {}, true);
|
||||
this.locals[index].checks = true;
|
||||
}
|
||||
|
||||
#! Keeps what each `old(e)` in an `ensures`'s condition reads, where the
|
||||
#! `ensures` is reached, as a local the `old_value` node declares.
|
||||
#! @param this The emitter.
|
||||
#! @param condition The condition.
|
||||
def emitter::keep_earlier(&mut this, condition: u32): void {
|
||||
var walk := node_walk::new(condition);
|
||||
while walk.more() {
|
||||
val at := walk.next();
|
||||
if this.c.checker.kind_of(at) == nk::old_value {
|
||||
val held := this.c.checker.type_at(at);
|
||||
val mark := this.begin_statement();
|
||||
val made := this.value_as(this.c.checker.left_of(at), held);
|
||||
val place := this.fresh_place(held);
|
||||
this.store(&place, &made);
|
||||
this.end_statement(mark);
|
||||
this.declare(at, place, false);
|
||||
continue;
|
||||
}
|
||||
this.c.scan_children(at, &mut walk);
|
||||
}
|
||||
}
|
||||
|
||||
#! Checks an `ensures` where its block is left, the name it gives what the
|
||||
#! function returns standing for that. Where the way out returns nothing, as
|
||||
#! where every way through the block returned before its end, it is never
|
||||
#! reached.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `contract` node.
|
||||
pub def emitter::check_ensures(&mut this, node: u32): void {
|
||||
return if this.build.ended();
|
||||
val bound := this.c.checker.record(node, contract_slot::bound);
|
||||
return if bound != 0 && !this.returning;
|
||||
val locals := this.scope_mark();
|
||||
if bound != 0 {
|
||||
val place := this.new_place(bound, this.returned.kind);
|
||||
this.store(&place, &this.returned);
|
||||
this.declare(bound, place, false);
|
||||
}
|
||||
val mark := this.begin_statement();
|
||||
this.check_contract(node);
|
||||
this.end_statement(mark);
|
||||
this.forget_locals(locals);
|
||||
}
|
||||
|
||||
#! Lowers a contract's check: where its condition holds, the program goes on,
|
||||
#! and where it does not, a block of its own, which nothing comes back from,
|
||||
#! makes the report and stops the program with it, so a contract that holds
|
||||
#! costs its condition and a branch.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `contract` node.
|
||||
def emitter::check_contract(&mut this, node: u32): void {
|
||||
val saved := this.build.pos;
|
||||
this.at_node(node);
|
||||
val fine := this.build.new_block();
|
||||
val failing := this.build.new_block();
|
||||
this.branch_on(this.c.checker.left_of(node), fine, failing);
|
||||
this.build.seal(failing);
|
||||
this.build.switch_to(failing);
|
||||
this.report_contract(node);
|
||||
this.build.seal(fine);
|
||||
this.build.switch_to(fine);
|
||||
this.build.pos = saved;
|
||||
}
|
||||
|
||||
#! Stops the program where a contract failed, saying which kind failed, what it
|
||||
#! checked, as written or as its text says, and what the condition's operands
|
||||
#! held, as `A pre-condition failed: b != 0, with b = 0.`
|
||||
#! @param this The emitter.
|
||||
#! @param node The `contract` node.
|
||||
def emitter::report_contract(&mut this, node: u32): void {
|
||||
val mark := this.begin_statement();
|
||||
val condition := this.c.checker.left_of(node);
|
||||
val text := this.c.checker.record(node, contract_slot::text);
|
||||
val lead := match this.c.checker.clause_of(node) {
|
||||
expects => "A pre-condition failed: ",
|
||||
asserts => "An assertion failed: ",
|
||||
ensures => "A post-condition failed: "
|
||||
};
|
||||
this.build.effect(op::format, span::<u32>::empty(), 0, 0);
|
||||
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(lead), 0);
|
||||
|
||||
# Text written as a literal ends where the report's own full stop does.
|
||||
if text != 0 && this.c.checker.kind_of(text) == nk::string {
|
||||
var said := string::new(nothing {});
|
||||
this.decode_literal(this.c.checker.text_of(text), &mut said);
|
||||
if said.length != 0 && said[said.length - 1] == '.' {
|
||||
said.resize(said.length - 1);
|
||||
}
|
||||
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(said.view()), 0);
|
||||
} else if text != 0 {
|
||||
val said := this.value(text);
|
||||
this.format_sentence(&said);
|
||||
} else {
|
||||
var written := string::new(nothing {});
|
||||
this.source_text(condition, &mut written);
|
||||
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(written.view()), 0);
|
||||
}
|
||||
this.write_values(condition, ", with ");
|
||||
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum("."), 0);
|
||||
|
||||
# The program stops with the report, so nothing made here is closed.
|
||||
var report := this.owned_text(this.c.checker.type_at(node));
|
||||
this.adopt(&report);
|
||||
val index := this.c.layout_of(this.c.checker.unalias(report.kind));
|
||||
val data := this.c.field_at(index, 1);
|
||||
val count := this.c.field_at(index, 2);
|
||||
var words: u32[2] = [this.build.load(access::i64, report.address, data.offset), this.build.load(access::i64, report.address, count.offset)];
|
||||
this.build.effect(op::fault, words[0:2], 0, 0);
|
||||
this.build.unreachable();
|
||||
this.drop_kept(mark.kept);
|
||||
this.release(mark.cells);
|
||||
}
|
||||
|
||||
#! Writes a view of text into the text being made without a full stop it ends
|
||||
#! with, where the report's own ends it.
|
||||
#! @param this The emitter.
|
||||
#! @param text The view.
|
||||
def emitter::format_sentence(&mut this, text: &operand): void {
|
||||
var data := text.words[0];
|
||||
var length := text.words[1];
|
||||
if text.address != 0 {
|
||||
data = this.build.load(access::i64, text.address, 0);
|
||||
length = this.build.load(access::i64, text.address, word_size);
|
||||
}
|
||||
val held := this.build.variable(vt::word);
|
||||
this.build.assign(held, length);
|
||||
val looking := this.build.new_block();
|
||||
val dropping := this.build.new_block();
|
||||
val after := this.build.new_block();
|
||||
this.build.branch(this.build.binary(op::ne, length, this.build.word(0)), looking, after);
|
||||
this.build.seal(looking);
|
||||
this.build.switch_to(looking);
|
||||
val last := this.build.load(access::u8, this.build.binary(op::add, data, this.build.binary(op::sub, length, this.build.word(1))), 0);
|
||||
this.build.branch(this.build.binary(op::eq, last, this.build.word('.' as u64)), dropping, after);
|
||||
this.build.seal(dropping);
|
||||
this.build.switch_to(dropping);
|
||||
this.build.assign(held, this.build.binary(op::sub, length, this.build.word(1)));
|
||||
this.build.jump(after);
|
||||
this.build.seal(after);
|
||||
this.build.switch_to(after);
|
||||
var args: u32[2] = [data, this.build.read(held)];
|
||||
this.build.effect(op::format_bytes, args[0:2], 0, 0);
|
||||
}
|
||||
|
||||
#! Whether an expression ends the program: a call of `exit` or `abort`, which
|
||||
#! the checker treats as leaving.
|
||||
#! @param this The emitter.
|
||||
#! @param node The expression.
|
||||
#! @returns Whether it does.
|
||||
def emitter::ends_program(&mut this, node: u32): bool {
|
||||
return false if this.c.checker.kind_of(node) != nk::call;
|
||||
val decl := this.c.checker.ref_at(node);
|
||||
return false if decl == 0 || (decl & (ref_local | ref_type)) != 0;
|
||||
return false if !this.c.checker.decls.has(decl, df::intrinsic);
|
||||
val name := this.c.checker.names.text(this.c.checker.decls.names.p[decl]);
|
||||
return name == "exit" || name == "abort" || name == "fault";
|
||||
}
|
||||
|
||||
#! Lowers a local variable or constant. A constant known while compiling is no
|
||||
#! local at all, being written wherever it is named.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `variable` node.
|
||||
def emitter::local_statement(&mut this, node: u32): void {
|
||||
val value := this.c.checker.record(node, variable_slot::value);
|
||||
val kind := this.c.checker.type_at(node);
|
||||
if this.c.checker.node_has(node, nf::constant) && this.c.checker.is_known(node) {
|
||||
return;
|
||||
}
|
||||
|
||||
# A constant the checker did not work out is evaluated: read where it is
|
||||
# once it is, while compiling, and where the program holds it as data after.
|
||||
if this.c.checker.node_has(node, nf::constant) {
|
||||
val key := node_key(this.table, node);
|
||||
if this.c.options.evaluating {
|
||||
val index := this.c.evaluation_of(key, 0, this.table, node, false);
|
||||
this.build.effect(op::ready, span::<u32>::empty(), index, 0);
|
||||
val offset: u64 = this.c.evaluations[index].offset;
|
||||
val address := this.build.value(op::global, span::<u32>::empty(), vt::word, 0, offset);
|
||||
this.declare(node, location { kind = kind, address = address }, false);
|
||||
return;
|
||||
}
|
||||
val datum := this.c.evaluated_datum(key, kind);
|
||||
if datum != no_block {
|
||||
val address := this.build.value(op::datum, span::<u32>::empty(), vt::word, datum, 0);
|
||||
this.declare(node, location { kind = kind, address = address }, false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
# A function declared within a block is named in its own body, so its local
|
||||
# is declared before its value is made.
|
||||
if this.c.checker.node_has(node, nf::function) {
|
||||
val place := this.new_place(node, kind);
|
||||
this.declare(node, place, false);
|
||||
val mark := this.begin_statement();
|
||||
val made := this.value(value);
|
||||
this.store(&place, &made);
|
||||
this.end_statement(mark);
|
||||
return;
|
||||
}
|
||||
|
||||
val mark := this.begin_statement();
|
||||
if value != 0 && this.refers_to_temporary(value) {
|
||||
this.bound_temporary(node, value, kind, mark);
|
||||
return;
|
||||
}
|
||||
# `undefined` leaves a cell as it is, and words, which cost nothing to give
|
||||
# a value, are zero. Running with its memory checked, the cell is marked as
|
||||
# never written, so reading it first stops the program.
|
||||
if value != 0 && this.c.checker.kind_of(value) == nk::undefined {
|
||||
val left := this.new_place(node, kind, ck::undefined);
|
||||
if left.held {
|
||||
this.zero(&left);
|
||||
} else if this.c.options.checks {
|
||||
this.build.forget(left.address, this.c.shape_of(kind).size);
|
||||
}
|
||||
this.end_statement(mark);
|
||||
this.declare(node, left, false);
|
||||
return;
|
||||
}
|
||||
val place := this.new_place(node, kind);
|
||||
if value == 0 {
|
||||
this.zero(&place);
|
||||
this.defaults(&place);
|
||||
} else {
|
||||
val made := this.value_as(value, kind);
|
||||
this.adopt(&made);
|
||||
this.store(&place, &made);
|
||||
}
|
||||
this.end_statement(mark);
|
||||
this.declare(node, place, this.c.checker.closes(kind));
|
||||
}
|
||||
|
||||
#! Whether a value is a reference to a value that is no place, as
|
||||
#! `&point { x = 1 }` or `&make()`, which the statement would hold.
|
||||
#! @param this The emitter.
|
||||
#! @param node The value's node.
|
||||
#! @returns Whether it is.
|
||||
def emitter::refers_to_temporary(&mut this, node: u32): bool {
|
||||
return false if this.c.checker.kind_of(node) != nk::reference;
|
||||
val inner := this.c.checker.left_of(node);
|
||||
return false if this.c.checker.has_flag(node, rf::relent);
|
||||
return !(this.c.checker.is_place(inner) && (!this.c.checker.is_known(inner) || this.stored(inner)));
|
||||
}
|
||||
|
||||
#! Lowers a local whose value is a reference to a value that is no place, which
|
||||
#! lives as long as the name does, as C++ has a temporary bound to a reference:
|
||||
#! held in a cell of its own, as a local declared just before the name is, and
|
||||
#! closed just after the name is.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `variable` node.
|
||||
#! @param value The `reference` node.
|
||||
#! @param kind The local's type.
|
||||
#! @param mark What the statement held before.
|
||||
def emitter::bound_temporary(&mut this, node: u32, value: u32, kind: u32, mark: statement_mark): void {
|
||||
val taken := this.c.checker.type_at(value);
|
||||
val referent := this.c.checker.types.first_of(this.c.checker.unalias(taken));
|
||||
val made := this.value_as(this.c.checker.left_of(value), referent);
|
||||
this.adopt(&made);
|
||||
val shape := this.c.shape_of(referent);
|
||||
val cell := this.build.code.add_cell(round_up(shape.size == 0 ? word_size : shape.size, word_size) as u32,
|
||||
shape.align < word_size ? word_size as u32 : shape.align as u32, ck::local, 0);
|
||||
val held := location { kind = referent, address = this.build.cell_address(cell), framed = true };
|
||||
this.store(&held, &made);
|
||||
val referred := this.reference_to(&held, taken);
|
||||
val converted := this.convert(&referred, kind);
|
||||
val place := this.new_place(node, kind);
|
||||
this.store(&place, &converted);
|
||||
this.end_statement(mark);
|
||||
this.declare(value, held, this.c.checker.closes(referent));
|
||||
this.declare(node, place, this.c.checker.closes(kind));
|
||||
}
|
||||
|
||||
#! Lowers `if`: the names its condition's tests give are declared before it runs,
|
||||
#! and close where it ends, but those an `is not` test gives the rest of the
|
||||
#! block where its branch always leaves.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `if_stmt` node.
|
||||
def emitter::if_statement(&mut this, node: u32): void {
|
||||
val condition := this.c.checker.left_of(node);
|
||||
val then := this.c.checker.record(node, if_slot::then);
|
||||
val other := this.c.checker.record(node, if_slot::other);
|
||||
val mark := this.begin_statement();
|
||||
val locals := this.scope_mark();
|
||||
this.declare_tests(condition);
|
||||
|
||||
val then_block := this.build.new_block();
|
||||
val join := this.build.new_block();
|
||||
val else_block := other != 0 ? this.build.new_block() : join;
|
||||
this.branch_on(condition, then_block, else_block);
|
||||
this.lower_branches(then, other, then_block, else_block, join);
|
||||
|
||||
# The names an `is not` test gives stay for the rest of the block, where the
|
||||
# branch it guards always leaves.
|
||||
val gives_rest := other == 0 && this.c.checker.has_flag(then, rf::leaves) && this.binds_where(condition, false);
|
||||
if !gives_rest {
|
||||
this.end_scope(locals, 0);
|
||||
}
|
||||
this.end_statement(mark);
|
||||
}
|
||||
|
||||
#! Lowers `if const`: the branch the checker decided it takes, or where only the
|
||||
#! program running decides it, as in a generic's instance whose condition the
|
||||
#! checker left unknown, both, by the condition's value.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `if_const` node.
|
||||
def emitter::if_const(&mut this, node: u32): void {
|
||||
val condition := this.c.checker.left_of(node);
|
||||
val then := this.c.checker.record(node, if_slot::then);
|
||||
val other := this.c.checker.record(node, if_slot::other);
|
||||
if this.c.checker.is_known(condition) {
|
||||
val taken := this.c.checker.value_at(condition).magnitude != 0 ? then : other;
|
||||
this.lower_block(taken);
|
||||
return;
|
||||
}
|
||||
|
||||
# A condition evaluated decides the branch as one the checker decided does.
|
||||
if this.c.evaluated.decisions.get(&node_key(this.table, node)) is some(holds) {
|
||||
val taken := holds ? then : other;
|
||||
this.lower_block(taken);
|
||||
return;
|
||||
}
|
||||
|
||||
val mark := this.begin_statement();
|
||||
val then_block := this.build.new_block();
|
||||
val join := this.build.new_block();
|
||||
val else_block := other != 0 ? this.build.new_block() : join;
|
||||
val cond := this.value_as(condition, bt::boolean);
|
||||
this.build.branch(cond.words[0], then_block, else_block);
|
||||
this.lower_branches(then, other, then_block, else_block, join);
|
||||
this.end_statement(mark);
|
||||
}
|
||||
|
||||
#! Lowers the branches of an `if` its condition branched to, each going on
|
||||
#! where they join, and goes on there.
|
||||
#! @param this The emitter.
|
||||
#! @param then The block taken where the condition holds.
|
||||
#! @param other The one taken where it does not, or 0.
|
||||
#! @param then_block Where the first begins.
|
||||
#! @param else_block Where the second begins, or `join`.
|
||||
#! @param join Where they join.
|
||||
def emitter::lower_branches(&mut this, then: u32, other: u32, then_block: u32, else_block: u32, join: u32): void {
|
||||
this.build.seal(then_block);
|
||||
if other != 0 {
|
||||
this.build.seal(else_block);
|
||||
}
|
||||
this.build.switch_to(then_block);
|
||||
this.lower_block(then);
|
||||
this.build.jump(join);
|
||||
if other != 0 {
|
||||
this.build.switch_to(else_block);
|
||||
this.lower_block(other);
|
||||
this.build.jump(join);
|
||||
}
|
||||
this.build.seal(join);
|
||||
this.build.switch_to(join);
|
||||
}
|
||||
|
||||
#! Lowers `while`. Each pass, and each `continue`, closes what the condition
|
||||
#! made, and the names its tests gave, before making them again.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `while_stmt` node.
|
||||
def emitter::while_statement(&mut this, node: u32): void {
|
||||
val condition := this.c.checker.left_of(node);
|
||||
val body := this.c.checker.right_of(node);
|
||||
val head := this.build.new_block();
|
||||
val exit := this.build.new_block();
|
||||
val next := this.build.new_block();
|
||||
this.build.jump(head);
|
||||
this.build.switch_to(head);
|
||||
|
||||
val mark := this.begin_statement();
|
||||
val locals := this.scope_mark();
|
||||
this.declare_tests(condition);
|
||||
val inside := this.build.new_block();
|
||||
this.branch_on(condition, inside, exit);
|
||||
this.build.seal(inside);
|
||||
|
||||
this.build.switch_to(inside);
|
||||
this.safepoint();
|
||||
this.loops.append(loop_info { exit = exit, next = next, locals = this.locals.length, kept = this.kept.length });
|
||||
this.lower_block(body);
|
||||
this.loops.truncate();
|
||||
this.build.jump(next);
|
||||
this.build.seal(next);
|
||||
|
||||
this.build.switch_to(next);
|
||||
this.close_locals(locals, 0);
|
||||
this.leave_kept(mark.kept);
|
||||
|
||||
# A `break` leaves with the names the test gave, which close here, and what the
|
||||
# condition made closes where the statement ends.
|
||||
this.close_loop(head, exit);
|
||||
this.end_scope(locals, 0);
|
||||
this.end_statement(mark);
|
||||
}
|
||||
|
||||
#! Lowers `break` or `continue`: what the statements and scopes of the loop's
|
||||
#! body hold is closed, and control goes to the loop's exit or its next pass.
|
||||
#! @param this The emitter.
|
||||
#! @param leaves Whether it is `break`.
|
||||
def emitter::leave_loop(&mut this, leaves: bool): void {
|
||||
return if this.loops.length == 0;
|
||||
val held: loop_info = this.loops.last();
|
||||
this.leave_kept(held.kept);
|
||||
this.close_locals(held.locals, 0);
|
||||
this.build.jump(leaves ? held.exit : held.next);
|
||||
}
|
||||
|
||||
#! Lowers a condition as a branch: where it holds, to one block, and to another
|
||||
#! where it does not. `&&` and `||` go to the second only where the first does
|
||||
#! not decide.
|
||||
#! @param this The emitter.
|
||||
#! @param node The condition.
|
||||
#! @param then Where it goes where the condition holds.
|
||||
#! @param other Where it goes where it does not.
|
||||
pub def emitter::branch_on(&mut this, node: u32, then: u32, other: u32): void {
|
||||
if this.c.checker.is_known(node) {
|
||||
this.build.jump(this.c.checker.value_at(node).magnitude != 0 ? then : other);
|
||||
return;
|
||||
}
|
||||
if this.c.checker.kind_of(node) == nk::binary {
|
||||
val operator := this.c.checker.token_kind(node);
|
||||
if operator == tk::logand || operator == tk::logor {
|
||||
val middle := this.build.new_block();
|
||||
if operator == tk::logand {
|
||||
this.branch_on(this.c.checker.left_of(node), middle, other);
|
||||
} else {
|
||||
this.branch_on(this.c.checker.left_of(node), then, middle);
|
||||
}
|
||||
this.build.seal(middle);
|
||||
this.build.switch_to(middle);
|
||||
this.branch_on(this.c.checker.right_of(node), then, other);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if this.c.checker.kind_of(node) == nk::unary && this.c.checker.token_kind(node) == tk::negate {
|
||||
this.branch_on(this.c.checker.left_of(node), other, then);
|
||||
return;
|
||||
}
|
||||
|
||||
val made := this.value_as(node, bt::boolean);
|
||||
this.build.branch(made.words[0], then, other);
|
||||
}
|
||||
|
||||
#! Declares the locals the tests of a condition name their values in, before
|
||||
#! any of it runs, since `&&` and `||` may leave a test that would set one
|
||||
#! unrun. One that closes starts zeroed, so closing it where it was never given
|
||||
#! closes nothing.
|
||||
#! @param this The emitter.
|
||||
#! @param node The condition.
|
||||
pub def emitter::declare_tests(&mut this, node: u32): void {
|
||||
return if node == 0;
|
||||
match this.c.checker.kind_of(node) {
|
||||
nk::is_test => {
|
||||
val binding := this.c.checker.named_binding(this.c.checker.record(node, is_slot::binding));
|
||||
return if binding == 0;
|
||||
val named := this.c.checker.kind_of(binding) == nk::reference ? this.c.checker.left_of(binding) : binding;
|
||||
return if !this.c.checker.has_flag(named, rf::narrowed) || this.local_of(named) != 0;
|
||||
val kind := this.c.checker.type_at(named);
|
||||
val place := this.new_place(named, kind);
|
||||
val closes := this.c.checker.closes(kind);
|
||||
if closes {
|
||||
this.zero(&place);
|
||||
}
|
||||
this.declare(named, place, closes);
|
||||
}
|
||||
nk::binary => {
|
||||
val operator := this.c.checker.token_kind(node);
|
||||
if operator == tk::logand || operator == tk::logor {
|
||||
this.declare_tests(this.c.checker.left_of(node));
|
||||
this.declare_tests(this.c.checker.right_of(node));
|
||||
}
|
||||
}
|
||||
nk::unary => {
|
||||
if this.c.checker.token_kind(node) == tk::negate {
|
||||
this.declare_tests(this.c.checker.left_of(node));
|
||||
}
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether a condition's tests name a value where it holds as `positive` says,
|
||||
#! through `&&`, `||`, and `!`.
|
||||
#! @param this The emitter.
|
||||
#! @param node The condition.
|
||||
#! @param positive Whether the condition holds where the value is named.
|
||||
#! @returns Whether they do.
|
||||
pub def emitter::binds_where(&mut this, node: u32, positive: bool): bool {
|
||||
return false if node == 0;
|
||||
match this.c.checker.kind_of(node) {
|
||||
nk::is_test => {
|
||||
return this.c.checker.named_binding(this.c.checker.record(node, is_slot::binding)) != 0
|
||||
&& this.c.checker.node_has(node, nf::negated) != positive;
|
||||
}
|
||||
nk::binary => {
|
||||
val operator := this.c.checker.token_kind(node);
|
||||
return false if !((operator == tk::logand && positive) || (operator == tk::logor && !positive));
|
||||
return this.binds_where(this.c.checker.left_of(node), positive)
|
||||
|| this.binds_where(this.c.checker.right_of(node), positive);
|
||||
}
|
||||
nk::unary => {
|
||||
return this.c.checker.token_kind(node) == tk::negate && this.binds_where(this.c.checker.left_of(node), !positive);
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
#! @file storage.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains where a function's locals are held, worked out before its body is
|
||||
#! lowered from where its references are made, as `escapes.sakura` finds it. A
|
||||
#! local is held in variables of the builder unless a reference to it is made,
|
||||
#! and then in a cell of the frame, which the reference refers to while the
|
||||
#! local lives. Nothing is moved to the heap: a reference that outlives what it
|
||||
#! refers to is the program's mistake, which the checker warns of where it is
|
||||
#! sure of it.
|
||||
|
||||
import sakura::analyzer;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! Works out where the locals of a function's body are held, given what its
|
||||
#! parameters are.
|
||||
#! @param this The emitter.
|
||||
#! @param decl The function's declaration.
|
||||
#! @param params The run of its parameters' nodes.
|
||||
#! @param kind Its function type, given its type arguments.
|
||||
#! @param body The body's node.
|
||||
pub def emitter::plan_function(&mut this, decl: u32, params: u32, kind: u32, body: u32): void {
|
||||
var s := escape_scan::new(scratch());
|
||||
s.result = this.c.checker.types.first_of(kind);
|
||||
this.c.scan_params(&mut s, params, kind, this.c.packs_last(decl));
|
||||
this.c.scan_body(&mut s, body);
|
||||
this.apply_plan(&mut s, body);
|
||||
}
|
||||
|
||||
#! Works out where the locals of an anonymous function's body are held. What it
|
||||
#! captures is the function's around it, reached through its environment, as
|
||||
#! what a parameter refers to is the caller's.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `lambda` node.
|
||||
pub def emitter::plan_lambda(&mut this, node: u32): void {
|
||||
var s := escape_scan::new(scratch());
|
||||
val kind := this.c.checker.type_at(node);
|
||||
s.result = this.c.checker.types.first_of(kind);
|
||||
var captures := this.captures_of(node);
|
||||
for &each in captures {
|
||||
val outer := s.graph.new_spot(spot_kind::outer, each, 0);
|
||||
val inner := s.graph.new_spot(spot_kind::inner, each, 0);
|
||||
s.graph.add(s.graph.held_by(outer), inner);
|
||||
s.graph.add(s.graph.held_by(inner), inner);
|
||||
s.slots.set(each, outer);
|
||||
}
|
||||
this.c.scan_params(&mut s, this.c.checker.left_of(node), kind, false);
|
||||
val body := this.c.checker.record(node, lambda_slot::body);
|
||||
this.c.scan_body(&mut s, body);
|
||||
this.apply_plan(&mut s, body);
|
||||
}
|
||||
|
||||
#! Works out where the locals of a value evaluated into a global are held,
|
||||
#! which keeps what it holds.
|
||||
#! @param this The emitter.
|
||||
#! @param value The value's node.
|
||||
pub def emitter::plan_storage(&mut this, value: u32): void {
|
||||
var s := escape_scan::new(scratch());
|
||||
s.graph.keep(this.c.value_flow(&mut s, value));
|
||||
this.apply_plan(&mut s, value);
|
||||
}
|
||||
|
||||
#! Holds in a cell each local a reference is made to. What is within an
|
||||
#! anonymous function is left to its own plan.
|
||||
#! @param this The emitter.
|
||||
#! @param s The scan.
|
||||
#! @param body The body scanned.
|
||||
def emitter::apply_plan(&mut this, s: &mut escape_scan, body: u32): void {
|
||||
for at in 0..s.graph.spots.length {
|
||||
val held: spot = s.graph.spots[at];
|
||||
continue if held.depth != 0;
|
||||
if held.kind == spot_kind::local && held.taken {
|
||||
this.raise(held.node, held_as::cell);
|
||||
}
|
||||
}
|
||||
this.check_plan(s, body);
|
||||
}
|
||||
|
||||
#! Holds in a cell any local a reference is made to that the scan did not see
|
||||
#! made, which it always sees, so no reference refers to a local held in
|
||||
#! variables: the operand of `&`, what a parameter taking a reference is given,
|
||||
#! a method's receiver, the operands of an operator's method, what a loop
|
||||
#! walks, a union a match names a field of by `&`, and what an anonymous
|
||||
#! function captures.
|
||||
#! @param this The emitter.
|
||||
#! @param s The scan.
|
||||
#! @param body The body scanned.
|
||||
def emitter::check_plan(&mut this, s: &mut escape_scan, body: u32): void {
|
||||
var walk := node_walk::new(body);
|
||||
while walk.more() {
|
||||
val at := walk.next();
|
||||
# A contract left out refers to nothing.
|
||||
continue if this.c.checker.contracts_off && this.c.checker.kind_of(at) == nk::contract;
|
||||
match this.c.checker.kind_of(at) {
|
||||
nk::reference => {
|
||||
val inner := this.c.checker.left_of(at);
|
||||
if this.c.checker.is_place(inner) && (!this.c.checker.is_known(inner) || this.stored(inner)) {
|
||||
this.check_taken(s, inner);
|
||||
}
|
||||
}
|
||||
nk::lambda => {
|
||||
var captures := this.captures_of(at);
|
||||
for &each in captures {
|
||||
this.check_local(s, each);
|
||||
}
|
||||
}
|
||||
nk::member => {
|
||||
# A property's accessors are given a reference to the value.
|
||||
if this.property_of(at) != 0 {
|
||||
this.check_taken(s, this.c.checker.left_of(at));
|
||||
}
|
||||
}
|
||||
nk::index => {
|
||||
# So is `at`, but for what the language indexes itself.
|
||||
val ref := this.c.checker.ref_at(at);
|
||||
val through := this.c.checker.unalias(this.c.checker.reached(this.object_type(this.c.checker.left_of(at))));
|
||||
val kind := this.c.checker.types.kind_of(through);
|
||||
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.c.checker.decls.kinds.p[ref] == dk::function
|
||||
&& kind != ty::fixed && kind != ty::pointer && kind != ty::pack && this.c.viewed(through) == 0 {
|
||||
this.check_taken(s, this.c.checker.left_of(at));
|
||||
}
|
||||
}
|
||||
nk::binary, nk::assign => {
|
||||
if this.operator_method(at) != 0 {
|
||||
this.check_taken(s, this.c.checker.left_of(at));
|
||||
this.check_taken(s, this.c.checker.right_of(at));
|
||||
}
|
||||
}
|
||||
nk::unary => {
|
||||
val token := this.c.checker.token_kind(at);
|
||||
if (token == tk::minus || token == tk::bitnot) && this.operator_decl(at) != 0 {
|
||||
this.check_taken(s, this.c.checker.left_of(at));
|
||||
}
|
||||
}
|
||||
nk::for_stmt => {
|
||||
val iterated := this.c.checker.record(at, for_slot::iterated);
|
||||
val through := this.c.checker.unalias(this.c.checker.type_at(iterated));
|
||||
if this.c.checker.record(at, for_slot::end) == 0 && !this.c.checker.node_has(at, nf::constant)
|
||||
&& this.c.viewed(through) == 0 && this.c.checker.types.kind_of(through) != ty::pointer {
|
||||
this.check_taken(s, iterated);
|
||||
}
|
||||
}
|
||||
nk::is_test => {
|
||||
val binding := this.c.checker.record(at, is_slot::binding);
|
||||
if binding != 0 && this.c.checker.kind_of(binding) == nk::reference {
|
||||
this.check_taken(s, this.c.checker.left_of(at));
|
||||
}
|
||||
}
|
||||
nk::match_stmt, nk::match_value => {
|
||||
if this.c.refers_in_arm(at) {
|
||||
this.check_taken(s, this.c.checker.left_of(at));
|
||||
}
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
if this.c.checker.has_flag(at, rf::borrowed) {
|
||||
this.check_taken(s, at);
|
||||
}
|
||||
if this.c.checker.kind_of(at) != nk::lambda {
|
||||
this.c.scan_children(at, &mut walk);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Holds in a cell the local whose own storage a place is within, past fields
|
||||
#! and the elements of fixed arrays, where a reference to it is made that the
|
||||
#! scan did not see.
|
||||
#! @param this The emitter.
|
||||
#! @param s The scan.
|
||||
#! @param node The place's node.
|
||||
def emitter::check_taken(&mut this, s: &mut escape_scan, node: u32): void {
|
||||
var at := node;
|
||||
var steps := 0;
|
||||
while at != 0 && steps < 64 {
|
||||
steps++;
|
||||
val kind := this.c.checker.kind_of(at);
|
||||
if kind == nk::member {
|
||||
val ref := this.c.checker.ref_at(at);
|
||||
return if ref == 0 || (ref & (ref_local | ref_type)) != 0 || this.c.checker.decls.kinds.p[ref] != dk::field;
|
||||
val inner := this.c.checker.left_of(at);
|
||||
return if this.c.is_reference_type(this.c.checker.type_at(inner));
|
||||
at = inner;
|
||||
continue;
|
||||
}
|
||||
if kind == nk::index {
|
||||
val inner := this.c.checker.left_of(at);
|
||||
return if this.c.checker.types.kind_of(this.c.checker.unalias(this.c.checker.type_at(inner))) != ty::fixed;
|
||||
at = inner;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return if at == 0 || this.c.checker.kind_of(at) != nk::name;
|
||||
val ref := this.c.checker.ref_at(at);
|
||||
return if (ref & ref_local) == 0 || this.c.is_reference_type(this.c.checker.type_at(at));
|
||||
this.check_local(s, ref & ref_mask);
|
||||
}
|
||||
|
||||
#! Holds a local in a cell where the scan did not see a reference to it made.
|
||||
#! @param this The emitter.
|
||||
#! @param s The scan.
|
||||
#! @param local The node declaring the local.
|
||||
def emitter::check_local(&mut this, s: &mut escape_scan, local: u32): void {
|
||||
if s.slots.get(&local) is some(at) {
|
||||
return if s.graph.spots[at as u64].taken || s.graph.spots[at as u64].kind != spot_kind::local;
|
||||
}
|
||||
this.raise(local, held_as::cell);
|
||||
}
|
||||
|
||||
#! Holds a local at least as the way given: a cell over variables.
|
||||
#! @param this The emitter.
|
||||
#! @param local The node declaring the local.
|
||||
#! @param how How it must be held.
|
||||
def emitter::raise(&mut this, local: u32, how: held_as): void {
|
||||
val held := this.storage.get_or(&local, held_as::words);
|
||||
if (how as u8) > (held as u8) {
|
||||
this.storage.set(local, how);
|
||||
}
|
||||
}
|
||||
|
||||
#! The method an operator calls, where the language does not operate on its
|
||||
#! operands itself: the one the checker chose for arithmetic, or the `equals`
|
||||
#! or `compare` of what implements `equatable` or `ordered`, or 0.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `binary` or `assign` node.
|
||||
#! @returns The method's declaration, or 0.
|
||||
pub def emitter::operator_method(&mut this, node: u32): u32 {
|
||||
return 0 if this.c.checker.kind_of(node) == nk::unary;
|
||||
val operator := this.c.checker.token_kind(node);
|
||||
return 0 if operator == tk::logand || operator == tk::logor || operator == tk::assign;
|
||||
val chosen := this.operator_decl(node);
|
||||
return chosen if chosen != 0;
|
||||
val kind := this.c.checker.type_at(this.c.checker.left_of(node));
|
||||
val plain := this.c.checker.unalias(this.c.layout_type(this.c.checker.read_type(kind)));
|
||||
val named := this.c.checker.named_kind(plain);
|
||||
return 0 if named != dk::struct_type && named != dk::union_type;
|
||||
|
||||
if operator.compares() {
|
||||
val equal := operator == tk::equals || operator == tk::noteq;
|
||||
return this.pick_method(plain, equal ? word::equals : word::compare, true);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
#! @file values.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the lowering of expressions to their values: what each kind of
|
||||
#! node gives, the constants the checker worked out, and the conversions the
|
||||
#! checker recorded, by which a value of one type is taken where another is
|
||||
#! expected.
|
||||
|
||||
import sakura::analyzer;
|
||||
module sakura::compiler;
|
||||
|
||||
|
||||
#! The value of an expression as the type it is used as: the type the checker
|
||||
#! converts it to, or its own.
|
||||
#! @param this The emitter.
|
||||
#! @param node The expression.
|
||||
#! @returns The value.
|
||||
pub def emitter::value(&mut this, node: u32): operand {
|
||||
var to := this.c.checker.converted(node);
|
||||
if this.c.checker.is_known(node) && this.c.is_scalar_type(to) {
|
||||
# An integer constant past what an `i64` holds is unsigned, as `1 << 63` is.
|
||||
val held := this.c.checker.value_at(node);
|
||||
if this.c.checker.types.kind_of(to) == ty::untyped_int && !held.floating && !held.negative
|
||||
&& held.magnitude > 0x7FFFFFFFFFFFFFFF {
|
||||
to = bt::uint64;
|
||||
}
|
||||
return this.known(&held, to);
|
||||
}
|
||||
val own := this.raw(node);
|
||||
return this.convert(&own, to);
|
||||
}
|
||||
|
||||
#! The value of an expression as its own type, before any conversion.
|
||||
#! @param this The emitter.
|
||||
#! @param node The expression.
|
||||
#! @returns The value.
|
||||
pub def emitter::value_of_type(&mut this, node: u32): operand {
|
||||
val own := this.c.checker.type_at(node);
|
||||
if this.c.checker.is_known(node) && this.c.is_scalar_type(own) {
|
||||
return this.known(&this.c.checker.value_at(node), own);
|
||||
}
|
||||
return this.raw(node);
|
||||
}
|
||||
|
||||
#! The value of an expression converted to a type.
|
||||
#! @param this The emitter.
|
||||
#! @param node The expression.
|
||||
#! @param to The type.
|
||||
#! @returns The value.
|
||||
pub def emitter::value_as(&mut this, node: u32, to: u32): operand {
|
||||
if this.c.checker.is_known(node) && this.c.is_scalar_type(to) {
|
||||
return this.known(&this.c.checker.value_at(node), to);
|
||||
}
|
||||
val made := this.value(node);
|
||||
return this.convert(&made, to);
|
||||
}
|
||||
|
||||
#! A constant the checker worked out, as a value of a type.
|
||||
#! @param this The emitter.
|
||||
#! @param value The constant.
|
||||
#! @param kind The type, a number, `bool`, enum, or pointer.
|
||||
#! @returns The value.
|
||||
pub def emitter::known(&mut this, value: &constant, kind: u32): operand {
|
||||
val held := this.c.shape_of(kind);
|
||||
if held.kind == lk::floating {
|
||||
var real := value.as_real();
|
||||
if held.bits <= 32 {
|
||||
real = (real as f32) as f64;
|
||||
}
|
||||
return operand::one(kind, this.build.real(bits_of_real(real)));
|
||||
}
|
||||
var bits := value.floating ? (value.real < 0.0 ? 0 - ((0.0 - value.real) as u64) : value.real as u64) : value.bits();
|
||||
return operand::one(kind, this.build.word(bits));
|
||||
}
|
||||
|
||||
#! The value of an expression as its own type, of each kind of node. What it
|
||||
#! lowers is from the node, as what its operands lower is from theirs, and
|
||||
#! what is lowered after it is from where it was before.
|
||||
#! @param this The emitter.
|
||||
#! @param node The expression.
|
||||
#! @returns The value.
|
||||
pub def emitter::raw(&mut this, node: u32): operand {
|
||||
val saved := this.build.pos;
|
||||
this.at_node(node);
|
||||
val made := this.raw_node(node);
|
||||
this.build.pos = saved;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The value of an expression as its own type, by the kind of its node.
|
||||
#! @param this The emitter.
|
||||
#! @param node The expression.
|
||||
#! @returns The value.
|
||||
def emitter::raw_node(&mut this, node: u32): operand {
|
||||
val kind := this.c.checker.type_at(node);
|
||||
if this.c.checker.has_flag(node, rf::reflected) {
|
||||
return this.reflected_value(node);
|
||||
}
|
||||
|
||||
match this.c.checker.kind_of(node) {
|
||||
nk::number, nk::character, nk::boolean => return this.known(&this.c.checker.value_at(node), kind);
|
||||
nk::string => {
|
||||
# Text given to what is not text, as a union holding a view, is made as the
|
||||
# view it settles as, which is then converted.
|
||||
val to := this.c.checker.converted(node);
|
||||
val own := this.c.is_string(to) || this.c.viewed(to) != 0 ? to : this.c.checker.settle(kind);
|
||||
return this.text_literal(node, own);
|
||||
}
|
||||
nk::istring => return this.interpolated(node);
|
||||
nk::null_lit => return this.zero_value(this.c.checker.converted(node));
|
||||
nk::name, nk::path => return this.name_value(node);
|
||||
nk::unary => return this.unary(node);
|
||||
nk::postfix => return this.step(node, this.c.checker.left_of(node), false);
|
||||
nk::reference => return this.reference(node);
|
||||
nk::binary => return this.binary(node);
|
||||
nk::assign => return this.assign(node);
|
||||
nk::ternary => return this.ternary(node);
|
||||
nk::fallback => return this.fallback(node);
|
||||
nk::call => {
|
||||
val made := this.call(node);
|
||||
this.keep(&made);
|
||||
return made;
|
||||
}
|
||||
nk::index => {
|
||||
if this.indexes_through_at(node) {
|
||||
return this.indexed_reference(node);
|
||||
}
|
||||
val place := this.place_of(node);
|
||||
return this.load(&place);
|
||||
}
|
||||
# `x.(d)` reads the field or property a description names.
|
||||
nk::member_of => return this.member_value(node);
|
||||
# `value_of(d)::<i64>` is the instance its type arguments make.
|
||||
nk::type_args => return this.function_value(node, this.c.checker.ref_at(node));
|
||||
nk::slice => return this.slice(node);
|
||||
nk::member => return this.member_value(node);
|
||||
nk::cast => return this.cast(node);
|
||||
nk::is_test => return this.is_test(node);
|
||||
nk::construct => {
|
||||
val made := this.construct(node);
|
||||
this.keep(&made);
|
||||
return made;
|
||||
}
|
||||
nk::array => {
|
||||
val made := this.array_literal(node, this.c.checker.converted(node));
|
||||
this.keep(&made);
|
||||
return made;
|
||||
}
|
||||
nk::lambda => return this.lambda_value(node);
|
||||
nk::match_value => return this.match_value(node);
|
||||
nk::range => return this.range_value(node);
|
||||
# What `e` was is kept where its `ensures` was reached.
|
||||
nk::old_value => {
|
||||
val local := this.local_of(node);
|
||||
if local != 0 {
|
||||
val held: location = this.locals[local as u64 - 1].place;
|
||||
return this.load(&held);
|
||||
}
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
this.problem(node, "The expression is not lowered.");
|
||||
return this.zero_value(kind);
|
||||
}
|
||||
|
||||
#! The zero value of a type: zero words, or a zeroed cell.
|
||||
#! @param this The emitter.
|
||||
#! @param kind The type.
|
||||
#! @returns The value.
|
||||
pub def emitter::zero_value(&mut this, kind: u32): operand {
|
||||
val held := this.c.shape_of(kind);
|
||||
if in_memory(&held) {
|
||||
val address := this.temporary_of(kind);
|
||||
this.build.clear(address, held.size);
|
||||
return operand::at(kind, address);
|
||||
}
|
||||
var made := operand { kind = kind, count = word_count(&held) };
|
||||
for i in 0..made.count {
|
||||
made.words[i] = word_type(&held) == vt::real ? this.build.real(0) : this.build.word(0);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The value a name or path gives: a local, a global, a constant, an enum
|
||||
#! member, a constant parameter, or a function.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `name` or `path` node.
|
||||
#! @returns The value.
|
||||
pub def emitter::name_value(&mut this, node: u32): operand {
|
||||
val ref := this.c.checker.ref_at(node);
|
||||
val kind := this.c.checker.type_at(node);
|
||||
if (ref & ref_local) != 0 {
|
||||
val place := this.place_of(node);
|
||||
return this.load(&place);
|
||||
}
|
||||
if (ref & ref_type) != 0 {
|
||||
return this.known_argument(ref & ref_mask, kind);
|
||||
}
|
||||
if ref == 0 {
|
||||
this.problem(node, "The name refers to nothing.");
|
||||
return this.zero_value(kind);
|
||||
}
|
||||
|
||||
match this.c.checker.decls.kinds.p[ref] {
|
||||
dk::function => return this.function_value(node, ref);
|
||||
dk::variable => {
|
||||
val place := this.global_place(ref);
|
||||
return this.load(&place);
|
||||
}
|
||||
dk::enum_member => {
|
||||
var value := constant {};
|
||||
this.c.checker.decl_value(ref, &mut value);
|
||||
return this.known(&value, kind);
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
this.problem(node, "The name is no value.");
|
||||
return this.zero_value(kind);
|
||||
}
|
||||
|
||||
#! The value of a constant type argument a constant parameter names.
|
||||
#! @param this The emitter.
|
||||
#! @param arg The type argument, a constant.
|
||||
#! @param kind The type of its value.
|
||||
#! @returns The value.
|
||||
pub def emitter::known_argument(&mut this, arg: u32, kind: u32): operand {
|
||||
if this.c.checker.types.kind_of(arg) != ty::value {
|
||||
this.problem(0, "A constant parameter is given no value.");
|
||||
return this.zero_value(kind);
|
||||
}
|
||||
return this.known_object(this.c.checker.types.second_of(arg), kind);
|
||||
}
|
||||
|
||||
#! A value the checker worked out, as a value of a type: a number, text, a
|
||||
#! struct, union, or array of them, `null`, a function, or the address of a
|
||||
#! constant.
|
||||
#! @param this The emitter.
|
||||
#! @param id The value's ID among the checker's known values.
|
||||
#! @param kind The type.
|
||||
#! @returns The value.
|
||||
pub def emitter::known_object(&mut this, id: u32, kind: u32): operand {
|
||||
val held: known = this.c.checker.known_at(id);
|
||||
val shape := this.c.shape_of(kind);
|
||||
match held.kind {
|
||||
kk::number, kk::real => return this.known(&held.value, kind);
|
||||
kk::null_lit => return this.zero_value(kind);
|
||||
kk::text => return this.text_value(this.c.checker.known_text(id), kind);
|
||||
kk::function => {
|
||||
val index := this.c.function_of(held.decl, 0);
|
||||
this.c.program.functions[index].taken = true;
|
||||
this.c.names(this.function, index);
|
||||
return operand::two(kind, this.build.word(index as u64 + 1), this.build.word(0));
|
||||
}
|
||||
kk::address => {
|
||||
val place := this.global_place(held.decl);
|
||||
return this.reference_to(&place, kind);
|
||||
}
|
||||
kk::fields => {
|
||||
val address := this.temporary_of(kind);
|
||||
this.build.clear(address, shape.size);
|
||||
val whole := location { kind = kind, address = address, framed = true };
|
||||
val plain := this.c.checker.unalias(kind);
|
||||
if shape.kind == lk::fixed {
|
||||
val element := this.c.checker.types.first_of(plain);
|
||||
val inner := this.c.shape_of(element);
|
||||
for i in 0..this.c.checker.known_count(id) {
|
||||
val part := this.known_object(this.c.checker.known_part(id, i as u32), element);
|
||||
val at := this.within(&whole, i as u64 * inner.size, element);
|
||||
this.store(&at, &part);
|
||||
}
|
||||
return operand::at(kind, address);
|
||||
}
|
||||
val index := this.c.layout_of(plain);
|
||||
for i in 0..this.c.checker.known_count(id) {
|
||||
break if i >= shape.count as u64;
|
||||
val field := this.c.field_at(index, i as u32);
|
||||
val part := this.known_object(this.c.checker.known_part(id, i as u32), field.type_id);
|
||||
val at := this.within(&whole, field.offset, field.type_id);
|
||||
this.store(&at, &part);
|
||||
}
|
||||
return operand::at(kind, address);
|
||||
}
|
||||
kk::held => {
|
||||
val address := this.temporary_of(kind);
|
||||
this.build.clear(address, shape.size);
|
||||
val tag := held.value.magnitude as u32;
|
||||
if shape.niche == 0 {
|
||||
this.build.store(access::i64, address, 0, this.build.word(tag as u64));
|
||||
}
|
||||
val index := this.c.layout_of(this.c.checker.unalias(kind));
|
||||
if tag < shape.count && this.c.checker.known_count(id) != 0 {
|
||||
val field := this.c.field_at(index, tag);
|
||||
val part := this.known_object(this.c.checker.known_part(id, 0), field.type_id);
|
||||
val at := location { kind = field.type_id, address = address, offset = field.offset, framed = true };
|
||||
this.store(&at, &part);
|
||||
}
|
||||
return operand::at(kind, address);
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
this.problem(0, "A constant argument is not worked out.");
|
||||
return this.zero_value(kind);
|
||||
}
|
||||
|
||||
#! The value text written as a literal is, as the type it is used as: a view of
|
||||
#! the bytes it was written with, which stand as long as the program runs, or a
|
||||
#! `string` holding a copy of them it owns.
|
||||
#! @param this The emitter.
|
||||
#! @param node The `string` node.
|
||||
#! @param kind The type it is used as.
|
||||
#! @returns The value.
|
||||
pub def emitter::text_literal(&mut this, node: u32, kind: u32): operand {
|
||||
var text := string::new(nothing {});
|
||||
this.decode_literal(this.c.checker.text_of(node), &mut text);
|
||||
return this.text_value(text.view(), kind);
|
||||
}
|
||||
|
||||
#! Text as a value of a type: a view of a datum holding its bytes, or a
|
||||
#! `string` holding a copy of them.
|
||||
#! @param this The emitter.
|
||||
#! @param text The bytes.
|
||||
#! @param kind The type: a view of bytes, or `string`.
|
||||
#! @returns The value.
|
||||
pub def emitter::text_value(&mut this, text: strview, kind: u32): operand {
|
||||
val datum := this.c.text_datum(text);
|
||||
if this.c.is_string(kind) {
|
||||
this.build.effect(op::format, span::<u32>::empty(), 0, 0);
|
||||
this.build.effect(op::format_text, span::<u32>::empty(), datum, 0);
|
||||
return this.owned_text(kind);
|
||||
}
|
||||
|
||||
val address := this.temporary_of(kind);
|
||||
val data := text.length == 0 ? this.build.word(0) : this.build.value(op::datum, span::<u32>::empty(), vt::word, datum, 0);
|
||||
this.build.store(access::i64, address, 0, data);
|
||||
this.build.store(access::i64, address, word_size, this.build.word(text.length));
|
||||
return operand::at(kind, address);
|
||||
}
|
||||
|
||||
#! A value of a type taken as another, as the checker converts it: widened,
|
||||
#! read through references, given to a union, referred to as a trait, or lent
|
||||
#! as a view.
|
||||
#! @param this The emitter.
|
||||
#! @param value The value.
|
||||
#! @param to The type it is taken as.
|
||||
#! @returns The value converted.
|
||||
pub def emitter::convert(&mut this, value: &operand, to: u32): operand {
|
||||
var made: operand = value;
|
||||
return made if value.kind == to || to == bt::error || to == 0 || value.kind == bt::error;
|
||||
|
||||
val from := this.c.layout_type(value.kind);
|
||||
val target := this.c.layout_type(to);
|
||||
made.kind = to;
|
||||
return made if from == target || this.c.checker.strip(from, 0) == this.c.checker.strip(target, 0);
|
||||
|
||||
val fk := this.c.checker.types.kind_of(from);
|
||||
val tok := this.c.checker.types.kind_of(target);
|
||||
|
||||
# Numbers widen within their kind, which their words already hold, and an
|
||||
# integer operating with a float operates as the float.
|
||||
if this.c.checker.types.is_numeric(from) && this.c.checker.types.is_numeric(target) {
|
||||
if this.c.checker.types.is_float(target) && !this.c.checker.types.is_float(from) {
|
||||
val signed := this.c.checker.types.is_signed(from);
|
||||
var real := this.build.unary(signed ? op::itof : op::utof, value.words[0]);
|
||||
if this.c.checker.types.first_of(target) <= 32 {
|
||||
real = this.build.unary(op::fsingle, real);
|
||||
}
|
||||
return operand::one(to, real);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# An enum is its integer.
|
||||
if this.c.checker.named_kind(from) == dk::enum_type && this.c.checker.types.is_integer(target) {
|
||||
return made;
|
||||
}
|
||||
|
||||
if fk == ty::reference && tok == ty::reference {
|
||||
val inner_from := this.c.checker.unalias(this.c.checker.types.first_of(from));
|
||||
val inner_to := this.c.checker.unalias(this.c.checker.types.first_of(target));
|
||||
val from_trait := this.c.checker.named_kind(inner_from) == dk::trait_type;
|
||||
val to_trait := this.c.checker.named_kind(inner_to) == dk::trait_type;
|
||||
|
||||
# A reference to a value becomes one to a trait it implements, given the
|
||||
# vtable of its type for the trait.
|
||||
if to_trait && !from_trait && this.c.checker.types.kind_of(inner_from) != ty::reference {
|
||||
val vtable := this.c.vtable_of(this.c.checker.types.first_of(from), inner_to);
|
||||
return operand::two(to, value.words[0], this.build.word(vtable as u64));
|
||||
}
|
||||
# A reference to a trait becomes one to another the value also implements.
|
||||
if to_trait && from_trait {
|
||||
return made if inner_from == inner_to;
|
||||
var args: u32[1] = [value.words[1]];
|
||||
val map := this.c.retrait_of(inner_from, inner_to);
|
||||
val vtable := this.build.value(op::retrait, args[0:1], vt::word, map, 0);
|
||||
return operand::two(to, value.words[0], vtable);
|
||||
}
|
||||
# A reference to a reference is read through to the one it holds.
|
||||
if this.c.checker.types.kind_of(inner_from) == ty::reference && this.c.checker.types.kind_of(inner_to) != ty::reference {
|
||||
val place := this.referent(value);
|
||||
val inner := this.load(&place);
|
||||
return this.convert(&inner, to);
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# A union holds a value as the field of its type, another union's too, and
|
||||
# a reference where one of its fields is one; and otherwise a reference is
|
||||
# read through first.
|
||||
if this.c.checker.named_kind(target) == dk::union_type && this.c.checker.united_field(value.kind, target) != 0 {
|
||||
return this.unite(value, target, to);
|
||||
}
|
||||
|
||||
# A reference written as one becomes a pointer at what it refers to, which
|
||||
# holds the same word.
|
||||
if fk == ty::reference && tok == ty::pointer
|
||||
&& this.c.checker.unalias(this.c.checker.types.first_of(from)) == this.c.checker.unalias(this.c.checker.types.first_of(target)) {
|
||||
return made;
|
||||
}
|
||||
|
||||
# A plain reference is read through where its value is expected.
|
||||
if fk == ty::reference {
|
||||
val place := this.referent(value);
|
||||
val inner := this.load(&place);
|
||||
return this.convert(&inner, to);
|
||||
}
|
||||
|
||||
# Bytes become a string by being copied, which the statement keeps, from the
|
||||
# view's two words wherever they are.
|
||||
if this.c.is_string(target) && this.c.checker.is_byte_view(from) && (value.address != 0 || value.count == 2) {
|
||||
var args: u32[2] = [0, 0];
|
||||
if value.address != 0 {
|
||||
args[0] = this.build.load(access::i64, value.address, 0);
|
||||
args[1] = this.build.load(access::i64, value.address, word_size);
|
||||
} else {
|
||||
args[0] = value.words[0];
|
||||
args[1] = value.words[1];
|
||||
}
|
||||
this.build.effect(op::format, span::<u32>::empty(), 0, 0);
|
||||
this.build.effect(op::format_bytes, args[0:2], 0, 0);
|
||||
return this.owned_text(to);
|
||||
}
|
||||
|
||||
# A string lends a view of its text: where its bytes begin, and how many.
|
||||
if this.c.is_string(from) && this.c.viewed(target) != 0 {
|
||||
val index := this.c.layout_of(from);
|
||||
val data := this.c.field_at(index, 1);
|
||||
val count := this.c.field_at(index, 2);
|
||||
val address := this.temporary_of(to);
|
||||
this.build.store(access::i64, address, 0, this.build.load(access::i64, value.address, data.offset));
|
||||
this.build.store(access::i64, address, word_size, this.build.load(access::i64, value.address, count.offset));
|
||||
return operand::at(to, address);
|
||||
}
|
||||
|
||||
# What else converts holds the same words: a writable view lending a
|
||||
# read-only one, a function by another name, `null` becoming a pointer.
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A union holding a value, as the field the checker finds of its type.
|
||||
#! @param this The emitter.
|
||||
#! @param value The value.
|
||||
#! @param target The union's type, without aliases.
|
||||
#! @param to The type it is taken as.
|
||||
#! @returns The union.
|
||||
pub def emitter::unite(&mut this, value: &operand, target: u32, to: u32): operand {
|
||||
val field := this.c.checker.united_field(value.kind, target);
|
||||
val index := this.c.layout_of(target);
|
||||
val shape := this.c.layout_at(index);
|
||||
val address := this.temporary_of(to);
|
||||
this.build.clear(address, shape.size);
|
||||
for i in 0..shape.count {
|
||||
val each := this.c.field_at(index, i as u32);
|
||||
continue if each.decl != field;
|
||||
if shape.niche == 0 {
|
||||
this.build.store(access::i64, address, 0, this.build.word(i));
|
||||
}
|
||||
val held := this.convert(value, each.type_id);
|
||||
val at := location { kind = each.type_id, address = address, offset = each.offset, framed = true };
|
||||
this.store(&at, &held);
|
||||
this.adopt(value);
|
||||
return operand::at(to, address);
|
||||
}
|
||||
this.problem(0, "A union holds no field of the value's type.");
|
||||
return operand::at(to, address);
|
||||
}
|
||||
Loaded 100 of 706 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user