Initial Commit
This commit is contained in:
789 files changed
+149185
No files matched your search
@@ -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].span;
|
||||
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>, spannable<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>, assignable<u64, T>, spannable<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>, assignable<u64, u8>, spannable<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,569 @@
|
||||
#! @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.
|
||||
#!
|
||||
#! What it checks whole is the program's own files. The bodies and values of a
|
||||
#! library's declarations are checked once something checked reaches them, so
|
||||
#! what nothing in the program uses of a library is not checked, nor are notes
|
||||
#! made of it, but where every declaration is asked for, as `check --all` does.
|
||||
#!
|
||||
#! 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 newest nodes, where its checking begins.
|
||||
var segments: vector<u32>; #! Its result tables, each of a run of its nodes after the one before, the first of those it was parsed with, and each after of those an edit added.
|
||||
var parses: u32; #! How many times its syntax had been parsed whole again when it was last checked.
|
||||
pub var own: bool; #! Whether it is one of the program's own files, which are checked whole, rather than a library's.
|
||||
}
|
||||
|
||||
#! The results of a run of nodes of a file: those it was parsed with, those an
|
||||
#! edit added, or those 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; #! The instance it is of, or 0 for a file's.
|
||||
pub var parent: u32; #! 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 {
|
||||
pub var decl: u32; #! The template.
|
||||
pub var args: u32; #! The pack of its type arguments, its owner's first.
|
||||
pub var table: u32; #! Its result table, once its body is checked, or 0.
|
||||
pub var kind: u32; #! Its function type, or of a variable's instance, its type.
|
||||
pub var value: u32; #! Of a constant's instance, its value among the checker's known values, or 0 where checking did not work it out.
|
||||
pub var flawed: bool; #! Whether checking its body found an error, so it is never run while compiling.
|
||||
var made_file: u32; #! The file of the node first asking for it, as the call making it.
|
||||
var made_node: u32; #! That node, or 0 where nothing written asked for it.
|
||||
var made_in: u32; #! The instance that node was checked in, or 0 outside one.
|
||||
}
|
||||
|
||||
#! 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; #! The instance being checked, which notes name, or 0.
|
||||
var marks: u32; #! Where the bindings of the body begin.
|
||||
var given: bool; #! Whether the declaration's type parameters are given types, as where a constant kept as its expression is worked out again, so it is no template.
|
||||
|
||||
# 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::iterator` 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 note said while a body is checked once for each case it holds in, held
|
||||
#! until it is, so it is said once.
|
||||
pub struct checker::held_note {
|
||||
var key: u64; #! Its file, node, and code, by which it is said once.
|
||||
var serial: u64; #! The pass it was last said in.
|
||||
var passes: u32; #! How many passes said it.
|
||||
var made: note; #! The note.
|
||||
var text: string; #! What the case it was first said in says.
|
||||
}
|
||||
|
||||
#! A type parameter standing for a pack's type at an index while the pack's
|
||||
#! types are not known, as `Ts...[0]`.
|
||||
pub struct checker::element_in {
|
||||
var pack: u32; #! The pack's type.
|
||||
var index: u32; #! The index.
|
||||
var param: u32; #! The declaration of the parameter standing for it.
|
||||
var generic: u32; #! The generic whose parameter at the index it stands for in a shape, as `vector` of `T is vector`, or 0.
|
||||
var rest: bool; #! Whether it stands for the types from the index on, as a generic's pack parameter takes them.
|
||||
var at: u32; #! The constant type argument the index is, where only each instance knows it, as `I` of `Ts...[I]`, or 0.
|
||||
}
|
||||
|
||||
#! 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 an unchecked program and `--contracts off` ask.
|
||||
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.
|
||||
pub var whole: bool; #! Whether every declaration is checked, a library's too, rather than those the program's own files reach.
|
||||
|
||||
# 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, the first standing for none.
|
||||
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 value each node is, a number among `knowns`, by its row, where it is known.
|
||||
var converts: keyed<table_node>; #! The type a node no table holds converts to, by its table and node.
|
||||
var values: keyed<table_node>; #! The value a node no table holds is, a number among `knowns`, by its table and node.
|
||||
|
||||
# Bindings: the locals, parameters, and type parameters names refer to, a
|
||||
# stack cut back where each scope ends, the first standing for none.
|
||||
# `innermost` holds 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, or 0.
|
||||
var innermost: vector<u32>; #! The binding of each name nearest the top, by its name, or 0.
|
||||
|
||||
# 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<file_node>; #! Each import, resolved once every module is declared.
|
||||
pub var libraries: vector<file_node>; #! Each `extern import` the target takes, 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>; #! The value each constant and enum member holds, a number among `knowns`, or 0, by its declaration.
|
||||
|
||||
# Generics.
|
||||
pub var instances: vector<instance>; #! The instances of generic functions, the first standing for none.
|
||||
var instanced: keymap; #! 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>; #! The run of the traits a struct, union, or trait names, once `df::composed` says they are worked out, 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: keyed<table_node>; #! The instance a call uses, by its table and 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 walked: vector<u64>; #! The places the loops around what is checked walk, each its table then its node, which changing whole may move what the loop reads.
|
||||
var undecided: u32; #! How many `if const` and `for const` around what is checked are not decided.
|
||||
|
||||
# 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: keyed<table_node>; #! The run of `reflected` each node gives, by its table and node.
|
||||
var lengths: keyed<table_node>; #! How many values a view of reflection holds, by its table and node.
|
||||
var consent: u32; #! A declaration reflection reaches, which its attribute consents to.
|
||||
var attr_decls: keyed<file_node>; #! The declaration each attribute is as `attributes_of` gives it, by its file and 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.
|
||||
var queued: vector<u32>; #! The declarations checking reached, in the order it did, each once, whose own checking follows.
|
||||
var queued_checked: u64; #! How many of `queued` have been checked, which checking goes on from.
|
||||
pub var checked_globals: u32; #! How many globals have been checked, which tells lowering whether checking late reached one.
|
||||
|
||||
# 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.
|
||||
|
||||
# What runs code while checking, where a value must be known that folding does
|
||||
# not give: the program's machine, which whoever checks a program to run or
|
||||
# build it gives.
|
||||
pub var evaluator: maybe<def(&evaluation_ask, &mut evaluation_answer): void>; #! The program's evaluator, or nothing.
|
||||
var projections: keymap; #! The parameter standing for a type a bound asks for: `param << 32 | asked`.
|
||||
var shape_params: keymap; #! The parameter standing for a generic's parameter in a shape: `pack << 32 | generic << 8 | index`.
|
||||
var stand_ins: vector<checker::stand_in>; #! Each parameter standing for a type a bound asks for, which substituting its type parameter resolves.
|
||||
var element_ins: vector<checker::element_in>; #! Each parameter standing for a pack's type at an index, which substituting the pack resolves.
|
||||
var settling_index: u32; #! How deeply substituting works out an index of a pack's type, within which those it reads are left as they are.
|
||||
var indexed: keymap; #! The declarations of the parameters substituting which resolves a parameter standing for a pack's type at an index, each as `decl -> 1`.
|
||||
|
||||
# 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.
|
||||
var worked_again: keymap; #! What each value kept as its expression within a template is, worked out again given types: by `id << 32 | given`, 1 more than its ID, or 0 while being worked out.
|
||||
# Following aliases reaches nearly all of the checker, as choosing a type may
|
||||
# work out a constant again, so `unalias` calls it through this: calling
|
||||
# nothing directly, `unalias` is optimized before whatever calls it, which
|
||||
# then inlines it, however the checker's calls loop.
|
||||
var follows: def(&mut checker, u32): u32; #! `follow_aliases`.
|
||||
var value_index: id_index; #! The numbers and floats of no type in particular, by the hash of the constant each is, which nodes and declarations are, found quickly.
|
||||
|
||||
# What an `if const` branch or a `match const` arm says of a type parameter
|
||||
# within a generic's own body, for what it guards: a bound it has, by its
|
||||
# declaration, or with `fit_known` added, a pattern it fits, or with
|
||||
# `unfit_known` added, one it does not.
|
||||
var proved_params: vector<u32>; #! The type parameters an `if const` proved bounds of.
|
||||
var proved_bounds: vector<u32>; #! The bound proved of each.
|
||||
# A body checked once for each case its condition holds in, as `if const A ||
|
||||
# B` or an arm of several patterns, says each note once, with the case where
|
||||
# only one case says it.
|
||||
var repeating: u32; #! How many such bodies are being checked within one another.
|
||||
var held_notes: vector<checker::held_note>; #! The notes said while one is, said once it ends.
|
||||
var case_serial: u64; #! Which pass in a case is checking, counted up.
|
||||
var using_ways: u32; #! How many uses of values of types not chosen yet are checked within one another.
|
||||
var choices: u32; #! How many types `match const` and `C ? A : B` made, without which no type is one not chosen yet.
|
||||
var sealed_depth: u32; #! How many sealed traits' constants the cases of a condition are worked out within.
|
||||
var case_text: string; #! What the case a note is said in says, or empty.
|
||||
|
||||
# Notes.
|
||||
pub 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.
|
||||
# What is checked for its results alone, whose notes are not the program's:
|
||||
# a type written for `this`, which `this` is whatever it says; an attribute's
|
||||
# type as reflection reads it, which checking its declaration reports; and
|
||||
# what a query for an editor checks.
|
||||
var quiet: u32; #! Whether notes are left out, where more than 0.
|
||||
var waits_for: u32; #! The call being checked where it may wait for its parameter's type, as `waiting` checks one.
|
||||
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 named_paths: vector<checker::named>; #! What each path checked names, as `path_target` found it, the first standing for none.
|
||||
var named_ids: keyed<table_node>; #! Each path's index in `named_paths`, by its table and node.
|
||||
var chosen_arms: keyed<table_node>; #! The arm each `match const` decided chose, by its table and node.
|
||||
var reducing: u32; #! How many `match const` types are being chosen within one another.
|
||||
var scratch: u32; #! A type parameter bounded by nothing, which what one bound alone gives is asked of, or 0 before it is made.
|
||||
var exact_facts: u32; #! How many of what is proved say a parameter is a type, as `T is strview` does, by which the types of what is checked are read.
|
||||
var rest_cases: checker::cases; #! The cases what follows an `if const` whose branch leaves is checked in, where they are several.
|
||||
var rest_pending: bool; #! Whether `rest_cases` waits for the block holding the `if const` to check what follows it.
|
||||
var choosing_aliases: u32; #! How many aliases of `match const` are declared, so a type is looked through for them only where there are.
|
||||
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 = keyed::<table_node>::new(),
|
||||
values = keyed::<table_node>::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::<file_node>::new(),
|
||||
libraries = vector::<file_node>::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 = keyed::<table_node>::new(),
|
||||
mirrors = column::<u32>::new(),
|
||||
shapes = dict::<u32, u32>::new(),
|
||||
only_bounds = dict::<u32, bool>::new(),
|
||||
outers = dict::<u32, u32>::new(),
|
||||
walked = vector::<u64>::new(),
|
||||
descs = vector::<desc>::new(),
|
||||
desc_ids = keymap::new(),
|
||||
reflected = runs::<u32>::new(),
|
||||
reflections = keyed::<table_node>::new(),
|
||||
lengths = keyed::<table_node>::new(),
|
||||
attr_decls = keyed::<file_node>::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(),
|
||||
queued = vector::<u32>::new(),
|
||||
projections = keymap::new(),
|
||||
shape_params = keymap::new(),
|
||||
indexed = keymap::new(),
|
||||
stand_ins = vector::<checker::stand_in>::new(),
|
||||
element_ins = vector::<checker::element_in>::new(),
|
||||
knowns = column::<known>::new(),
|
||||
known_parts = runs::<u32>::new(),
|
||||
known_texts = vector::<string>::new(),
|
||||
known_index = id_index::new(),
|
||||
worked_again = keymap::new(),
|
||||
value_index = id_index::new(),
|
||||
generic_names = vector::<bool>::new(),
|
||||
named_paths = vector::<checker::named>::new(),
|
||||
named_ids = keyed::<table_node>::new(),
|
||||
chosen_arms = keyed::<table_node>::new(),
|
||||
proved_params = vector::<u32>::new(),
|
||||
proved_bounds = vector::<u32>::new(),
|
||||
held_notes = vector::<checker::held_note>::new(),
|
||||
rest_cases = checker::cases::none(),
|
||||
case_text = string::new(nothing {}),
|
||||
evaluator = nothing {},
|
||||
follows = checker::follow_aliases
|
||||
};
|
||||
|
||||
# Known value 0 stands for none, which reads as a zero, and is never interned,
|
||||
# so a zero interned is a value of its own; so do path 0, table 0, and
|
||||
# instance 0.
|
||||
made.knowns.append(known {});
|
||||
made.named_paths.append(checker::named {});
|
||||
made.tables.append(rtable {});
|
||||
made.instances.append(instance {});
|
||||
made.declare_builtins();
|
||||
made.target = target {
|
||||
os = made.names.intern(&"linux"),
|
||||
arch = made.names.intern(&"x86_64"),
|
||||
backend = made.names.intern(&"vm")
|
||||
};
|
||||
# Binding 0 stands for none too.
|
||||
made.bind_names.append(0);
|
||||
made.bind_values.append(0);
|
||||
made.bind_prev.append(0);
|
||||
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.
|
||||
#! @param own Whether it is one of the program's own files, checked whole,
|
||||
#! rather than a library's, whose declarations are checked
|
||||
#! where the program reaches them.
|
||||
#! @returns The index of the file, which its notes give.
|
||||
pub def checker::add(&mut this, source: &source, syntax: &syntax, root: u32, own: bool = true): u32 {
|
||||
val file := this.units.length as u32;
|
||||
val table := this.add_table(file, 0, syntax.node_count as u32, 0);
|
||||
var segments := vector::<u32>::new();
|
||||
segments.append(table);
|
||||
this.units.append(unit {
|
||||
source = source,
|
||||
syntax = syntax,
|
||||
root = root,
|
||||
table = table,
|
||||
parses = syntax.parses,
|
||||
own = own,
|
||||
segments = move(&mut segments)
|
||||
});
|
||||
return file;
|
||||
}
|
||||
|
||||
#! Checks the files given: declares what each declares and resolves what each
|
||||
#! declaration is, then checks the bodies of the functions and the values of
|
||||
#! the variables of the program's own files, then of what those reach, a
|
||||
#! library's declarations and the instances of generics, until they reach
|
||||
#! nothing new. Every declaration's signature is resolved first, whatever
|
||||
#! reaches it, since much of checking reads what one is without asking.
|
||||
#! @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 {
|
||||
if this.is_root(id as u32) {
|
||||
this.check_decl(id as u32);
|
||||
}
|
||||
}
|
||||
|
||||
this.check_reached();
|
||||
return !this.failed;
|
||||
}
|
||||
|
||||
#! Whether a declaration is checked whatever reaches it: one of the program's
|
||||
#! own files, or any where every declaration is checked.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns Whether it is.
|
||||
def checker::is_root(&this, id: u32): bool {
|
||||
return this.whole || this.decls.nodes.p[id] != 0 && this.units[this.decls.files.p[id]].own;
|
||||
}
|
||||
|
||||
#! Checks what checking reached and has not checked yet: the declarations it
|
||||
#! resolved, and the instances of generics it used, and what those reach in
|
||||
#! turn, until they reach nothing new. What calls `system::handle` has its
|
||||
#! signals handled by `system::dispatch`, which the compiler calls where nothing
|
||||
#! written does, so it is reached with it.
|
||||
#! @param this The checker.
|
||||
pub def checker::check_reached(&mut this): void {
|
||||
while true {
|
||||
while this.queued_checked < this.queued.length {
|
||||
val id: u32 = this.queued[this.queued_checked];
|
||||
this.queued_checked++;
|
||||
this.check_decl(id);
|
||||
}
|
||||
this.check_wanted();
|
||||
if this.queued_checked == this.queued.length {
|
||||
val dispatch := this.dispatch_needed();
|
||||
if dispatch != 0 {
|
||||
this.reach(dispatch);
|
||||
}
|
||||
}
|
||||
break if this.queued_checked == this.queued.length && this.wants_checked == this.wants.length;
|
||||
}
|
||||
}
|
||||
|
||||
#! `system::dispatch`, where something reached `system::handle` and nothing
|
||||
#! reached it.
|
||||
#! @param this The checker.
|
||||
#! @returns Its declaration, or 0.
|
||||
def checker::dispatch_needed(&mut this): u32 {
|
||||
val sys := this.modules.find(0, word::system);
|
||||
return 0 if sys == 0;
|
||||
val handle := this.modules.decl(sys, this.names.intern(&"handle"));
|
||||
return 0 if handle == 0 || !this.is_depended(handle);
|
||||
val dispatch := this.modules.decl(sys, this.names.intern(&"dispatch"));
|
||||
return 0 if dispatch == 0 || this.is_depended(dispatch);
|
||||
return dispatch;
|
||||
}
|
||||
|
||||
#! 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);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,319 @@
|
||||
#! @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, and before each of a
|
||||
#! function's parameters.
|
||||
#! @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);
|
||||
if this.run_length(attrs) != 0 {
|
||||
this.check_attribute_run(id, attrs, this.target_bit(id), this.target_word(id));
|
||||
}
|
||||
return if this.kind_of(node) != nk::function;
|
||||
for ¶m in this.run_view(this.record(node, function_slot::params)) {
|
||||
val written := this.record(param, parameter_slot::attributes);
|
||||
if this.run_length(written) != 0 {
|
||||
this.check_attribute_run(id, written, this.target_named("parameters"), "parameters");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! Checks a run of attributes, written on a declaration or one of its
|
||||
#! parameters: each names a struct declaring `attribute`, is a literal of it,
|
||||
#! is written on what its `@usage` allows, and once, unless it allows more.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration, or the function whose parameter they are on.
|
||||
#! @param attrs The run.
|
||||
#! @param bit The bit of `core::target` they are written on, or 0 for any.
|
||||
#! @param words What they are written on, as a note says it.
|
||||
def checker::check_attribute_run(&mut this, id: u32, attrs: u32, bit: u64, words: strview): void {
|
||||
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.span);
|
||||
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);
|
||||
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(words);
|
||||
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.span.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 {
|
||||
return this.target_named(this.target_name(id));
|
||||
}
|
||||
|
||||
#! The bit of a member of `core::target`, by its name.
|
||||
#! @param this The checker.
|
||||
#! @param name The member's name, as `parameters`.
|
||||
#! @returns The bit, or 0 where `core::target` has no such member.
|
||||
def checker::target_named(&mut this, name: strview): u64 {
|
||||
val holder := this.std_decl(this.names.intern(&"target"));
|
||||
return 0 if holder == 0;
|
||||
|
||||
val member := this.decls.member(holder, this.names.intern(&name));
|
||||
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.span);
|
||||
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,401 @@
|
||||
#! @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, and one that
|
||||
# does not is never run while compiling.
|
||||
val errors := this.errors;
|
||||
val recorded := this.begin_lifetimes(id);
|
||||
this.check_function_body(id, this.decls.types.p[id]);
|
||||
if recorded {
|
||||
this.end_lifetimes(this.errors == errors);
|
||||
}
|
||||
if this.errors != errors {
|
||||
this.decls.mark(id, df::flawed);
|
||||
}
|
||||
this.leave(saved);
|
||||
}
|
||||
dk::variable, dk::field => {
|
||||
if this.decls.kinds.p[id] == dk::variable {
|
||||
this.checked_globals++;
|
||||
}
|
||||
val errors := this.errors;
|
||||
this.check_value(id);
|
||||
if this.errors != errors {
|
||||
this.decls.mark(id, df::flawed);
|
||||
}
|
||||
}
|
||||
dk::struct_type, dk::union_type => {
|
||||
# Its fields are part of it, and a value made of it leaving one out takes
|
||||
# the field's default, so they are checked with it.
|
||||
for &member in this.decls.list_view(this.decls.children.p[id]) {
|
||||
if this.decls.kinds.p[member] == dk::field {
|
||||
this.reach(member);
|
||||
}
|
||||
}
|
||||
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);
|
||||
this.check_sealed(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.record(node, accessor_slot::body) != 0;
|
||||
}
|
||||
return syntax.record(node, function_slot::body) != 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`.");
|
||||
}
|
||||
# A trait's defaults are made where a call through it leaves them out, as
|
||||
# `C::span_of(&c)` of a `C: spannable<T>` does, so they are checked here.
|
||||
if !accessor && this.enclosing_trait(id) != 0 {
|
||||
for i in 0..this.run_length(params) {
|
||||
val param := this.run_at(params, i as u32);
|
||||
val held: u32 = (i as u32) < this.types.part_count(kind) ? this.types.part_at(kind, i as u32) : bt::error;
|
||||
val value := this.record(param, parameter_slot::value);
|
||||
if value != 0 {
|
||||
this.check_expr(value, held);
|
||||
}
|
||||
this.declare_local(param, this.param_name(param), held);
|
||||
}
|
||||
}
|
||||
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.span)
|
||||
: this.types.pack(rest.span, 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.span);
|
||||
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.span);
|
||||
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");
|
||||
if this.decls.kinds.p[missing] == dk::function && this.gives_defaults(missing) {
|
||||
text.append(", with a default for each parameter the trait gives one");
|
||||
}
|
||||
}
|
||||
text.append(".");
|
||||
this.report_decl(id, ec::bound, text.span);
|
||||
}
|
||||
}
|
||||
|
||||
#! 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.span);
|
||||
}
|
||||
}
|
||||
|
||||
#! 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.span.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
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,608 @@
|
||||
#! @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>::blank());
|
||||
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.span, 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);
|
||||
if this.types.kind_of(this.unalias(held)) == ty::pack {
|
||||
# A field holding a pack is given a pack of its types whole, whose values
|
||||
# that close are moved to it, as `...` moves them to a call.
|
||||
this.check_pack_moved(value, held, held);
|
||||
} else {
|
||||
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 => return this.param_zeroable(plain);
|
||||
ty::pack => {
|
||||
return this.param_zeroable(plain) if this.types.is_open_pack(plain);
|
||||
for i in 0..this.types.part_count(plain) {
|
||||
return false if !this.has_zero(this.types.part_at(plain, i as u32), depth + 1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
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,
|
||||
#! and `T::element` has one where `T: array` does.
|
||||
#! @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))
|
||||
|| (this.types.kind_of(kind) == ty::param && this.element_zeroable(kind));
|
||||
}
|
||||
|
||||
#! 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.span);
|
||||
text.append("` holds `");
|
||||
text.append(described.span);
|
||||
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.span);
|
||||
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.span);
|
||||
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.span, 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();
|
||||
val scope := this.lifetime_open(node);
|
||||
for i in 0..this.run_length(params) {
|
||||
val param := this.run_at(params, i as u32);
|
||||
this.set_type(param, kinds[i]);
|
||||
this.mark_local(param);
|
||||
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);
|
||||
}
|
||||
|
||||
# A body that is a value is what the function returns.
|
||||
if this.kind_of(body) != nk::block {
|
||||
this.lifetime_event(node, lifetime_kind_of_event::returned);
|
||||
}
|
||||
this.lifetime_close(scope);
|
||||
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.span {
|
||||
return bt::error if kind == bt::error;
|
||||
}
|
||||
return this.types.function(kinds.span, 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,895 @@
|
||||
#! @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.span);
|
||||
}
|
||||
|
||||
#! 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 {
|
||||
if this.types.kind_of(kind) == ty::matched {
|
||||
return this.reduce_match(kind) if this.choosable(kind);
|
||||
val chosen := this.proved_choice(kind);
|
||||
return chosen != 0 ? chosen : kind;
|
||||
}
|
||||
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.span, args.span);
|
||||
}
|
||||
|
||||
#! 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, and every
|
||||
#! `match const` choosing by a type it knows to the type it chooses.
|
||||
#! @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, or the error type where they do not end.
|
||||
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;
|
||||
val follows := this.follows;
|
||||
return follows(this, 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. Those not ended in
|
||||
# as many steps as `max_aliases` says never end, as a `match const` choosing
|
||||
# by itself does, and are reported.
|
||||
def checker::follow_aliases(&mut this, kind: u32): u32 {
|
||||
var at := kind;
|
||||
var steps := 0u;
|
||||
while this.aliases(at) {
|
||||
if steps == checker::max_aliases {
|
||||
this.report_endless(kind);
|
||||
return bt::error;
|
||||
}
|
||||
at = this.alias_target(at);
|
||||
steps++;
|
||||
}
|
||||
return at;
|
||||
}
|
||||
|
||||
#! The most aliases, and types `match const` chooses, a type is followed through.
|
||||
pub const checker::max_aliases: u64 = 32;
|
||||
|
||||
#! Whether the type is an alias, as `is_alias` says, or a type `match const`
|
||||
#! chooses once it knows the type it chooses by, or within a generic's own body
|
||||
#! where what is proved decides it, worked out once and kept in its flags, as
|
||||
#! nearly every type `unalias` is given is neither.
|
||||
#! @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;
|
||||
# One within a generic's own body is chosen where what is proved of the type
|
||||
# parameter it chooses by decides it, which changes as checking goes, so what
|
||||
# it is is never kept.
|
||||
if this.types.kind_of(kind) == ty::matched && !this.choosable(kind) {
|
||||
return this.proved_choice(kind) != 0;
|
||||
}
|
||||
val alias := this.is_alias(kind) || this.choosable(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);
|
||||
val from := this.type_at(node);
|
||||
val how := this.fits(from, to, &value, this.is_known(node), 0);
|
||||
return how if how != fit::none || this.choices == 0;
|
||||
return this.fits_unchosen(from, to, &value, this.is_known(node));
|
||||
}
|
||||
|
||||
#! 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;
|
||||
# Within a template, a pack's types fit each other, as its values did before
|
||||
# they were reached at an index: each instance checks the types it gives.
|
||||
val pack := this.pack_of_param(from);
|
||||
return fit::exact if pack != 0 && pack == this.pack_of_param(to);
|
||||
|
||||
val target := this.unalias(to);
|
||||
val source := this.unalias(from);
|
||||
# A type parameter known to have a shape, as `T: array` or `T is vector` says,
|
||||
# is one with that shape, and converts as it does.
|
||||
if this.types.kind_of(source) == ty::param || this.types.kind_of(target) == ty::param {
|
||||
val from_shape := this.param_shape(source);
|
||||
return fit::exact if from_shape != 0 && this.unalias(from_shape) == target;
|
||||
if from_shape != 0 && this.types.kind_of(this.unalias(from_shape)) != ty::param {
|
||||
val how := this.fits(from_shape, to, value, known, depth + 1);
|
||||
return how if how != fit::none;
|
||||
}
|
||||
val to_shape := this.param_shape(target);
|
||||
return fit::exact if to_shape != 0 && this.unalias(to_shape) == source;
|
||||
}
|
||||
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>::blank());
|
||||
}
|
||||
val length := this.types.parts_of(plain);
|
||||
return this.types.intern(this.types.kind_of(plain), inner, this.types.second_of(plain), length.span);
|
||||
}
|
||||
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.span);
|
||||
}
|
||||
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 {
|
||||
# A type a generic's own body has not chosen yet, which every other way of
|
||||
# fitting leaves to this, fits where each way it can be chosen does, and is
|
||||
# fitted by what fits each.
|
||||
if this.choices != 0 && (this.types.kind_of(from) == ty::matched || this.types.kind_of(to) == ty::matched) && from != to {
|
||||
return this.fits_ways(from, to, value, known, depth);
|
||||
}
|
||||
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.span);
|
||||
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 {
|
||||
val chosen := this.chosen_arm(node);
|
||||
return this.lends_temporary(chosen) if chosen != 0;
|
||||
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.span);
|
||||
text.append("`, but the value is `");
|
||||
text.append(given.span);
|
||||
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>::blank());
|
||||
return view != bt::error ? view : this.std_type(word::string, span::<u32>::blank());
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
#! The pack a type parameter stands for, or for one of whose types it stands,
|
||||
#! as `Ts` or `Ts...[0]`.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns The pack parameter's declaration, or 0 where the type is neither.
|
||||
def checker::pack_of_param(&mut this, kind: u32): u32 {
|
||||
return 0 if this.types.kind_of(kind) != ty::param || this.element_ins.length == 0;
|
||||
val decl := this.types.first_of(kind);
|
||||
for &each in this.element_ins {
|
||||
return this.types.first_of(each.pack) if each.param == decl;
|
||||
return decl if this.types.first_of(each.pack) == decl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,653 @@
|
||||
#! @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(file_node { file = file, node = 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].file == 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(file_node { file = file, node = 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 the attributes written on a declaration, or on one of a
|
||||
#! function's parameters, in the table of the declaration's file, or 0.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @param param One more than the index of the parameter, or 0 for the
|
||||
#! declaration itself.
|
||||
#! @returns The run, or 0.
|
||||
pub def checker::attributes_at(&this, id: u32, param: u32): u32 {
|
||||
val node: u32 = this.decls.nodes.p[id];
|
||||
return this.attributes_of(node) if param == 0;
|
||||
return 0 if this.kind_of(node) != nk::function || this.decls.has(id, df::accessor);
|
||||
val params := this.record(node, function_slot::params);
|
||||
return param <= this.run_length(params) ? this.record(this.run_at(params, param - 1), parameter_slot::attributes) : 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); }
|
||||
# An alias of a `match const`, or of `C ? A : B`, stands for the type it
|
||||
# chooses, which is told from what it is written as, before it is resolved.
|
||||
if kind == dk::alias_type
|
||||
&& (this.kind_of(this.right_of(node)) == nk::type_match || this.kind_of(this.right_of(node)) == nk::type_cond) {
|
||||
this.decls.mark(id, df::chooses);
|
||||
this.choosing_aliases++;
|
||||
}
|
||||
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.span);
|
||||
} else {
|
||||
this.decls.params.p[id] = this.decls.make_list(own.span);
|
||||
}
|
||||
|
||||
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.span);
|
||||
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.span);
|
||||
}
|
||||
|
||||
#! 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);
|
||||
} else if name == word::sealed && this.decls.kinds.p[id] == dk::trait_type {
|
||||
this.decls.mark(id, df::sealed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! 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 or a property is
|
||||
#! reached through a value, and a type declared through the type through the
|
||||
#! type, so those may share a name, as `kind` and `token::kind`, or a property
|
||||
#! `iterator` and `list<T>::iterator`, the type it gives. 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 value := this.decls.kinds.p[types ? other : id];
|
||||
val shares := other == 0 || value == dk::field || value == dk::property;
|
||||
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,583 @@
|
||||
#! @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.
|
||||
composed = 0x200000, #! A struct, union, or trait whose traits, those `composed` holds the run of, are worked out, or being worked out.
|
||||
flawed = 0x400000, #! A function or constant whose body or value checking found an error in, which is never run.
|
||||
chooses = 0x800000, #! An alias of a `match const`, which stands for the type it chooses, as `type strip_pointer<T> = match const T { ... }`.
|
||||
sealed = 0x1000000, #! A trait nothing implements, whose constants and types are its own: `@sealed`.
|
||||
}
|
||||
|
||||
#! 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.
|
||||
pub 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.span.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].span : span::<u32>::blank();
|
||||
}
|
||||
|
||||
#! 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,234 @@
|
||||
#! @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.span);
|
||||
}
|
||||
}
|
||||
# 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 => {
|
||||
# A type a bound asks of a type parameter is named as it is written, as
|
||||
# `T::target`, as a constant asked so is.
|
||||
val owner: u32 = this.decls.owners.p[first];
|
||||
if owner != 0 && this.decls.kinds.p[owner] == dk::trait_type && !this.decls.has(first, df::valued) {
|
||||
for &each in this.stand_ins {
|
||||
continue if each.param != first;
|
||||
this.describe_into(each.base, out, depth + 1);
|
||||
out.append("::");
|
||||
break;
|
||||
}
|
||||
}
|
||||
out.append(this.names.text(this.decls.names.p[first]));
|
||||
}
|
||||
# A type `match const` chooses, before it is chosen, says what it chooses by.
|
||||
ty::matched => {
|
||||
# `C ? A : B` chooses `A` where `C` is `true`, and `B` otherwise, and a part
|
||||
# of `C` testing a type says what it tests, as `T is reference ? A : B`.
|
||||
val pattern := this.types.part_count(kind) == 5 ? this.types.part_at(kind, 1) : 0;
|
||||
val written := first < this.units.length as u32
|
||||
&& (this.units[first].syntax.node_kinds[this.types.second_of(kind)] == nk::type_cond
|
||||
|| this.units[first].syntax.node_kinds[this.types.second_of(kind)] == nk::ternary);
|
||||
if this.types.part_count(kind) == 5 && this.types.part_at(kind, 3) == 0 && (written || this.is_truth(pattern)) {
|
||||
this.describe_into(this.types.part_at(kind, 0), out, depth + 1);
|
||||
if !this.is_truth(pattern) {
|
||||
out.append(this.types.kind_of(pattern) == ty::value ? " == " : " is ");
|
||||
this.describe_into(pattern, out, depth + 1);
|
||||
}
|
||||
out.append(" ? ");
|
||||
this.describe_into(this.types.part_at(kind, 2), out, depth + 1);
|
||||
out.append(" : ");
|
||||
this.describe_into(this.types.part_at(kind, 4), out, depth + 1);
|
||||
} else {
|
||||
out.append("match const ");
|
||||
this.describe_into(this.types.part_at(kind, 0), out, depth + 1);
|
||||
}
|
||||
}
|
||||
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,147 @@
|
||||
#! @file evaluating.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains what the checker asks of the program's evaluator, which runs code
|
||||
#! while checking, where a value must be known that folding does not give: an
|
||||
#! array's length a function gives, the condition of an `if const`, a local
|
||||
#! constant's value, a range's end for `for const`, a constant type argument,
|
||||
#! or the text of `compile_error`. The analyzer has no evaluator of its own: the
|
||||
#! program's machine is one, which whoever checks a program to run or build it
|
||||
#! gives the checker before checking.
|
||||
#!
|
||||
#! What is asked for is lowered with what it calls, each checked as lowering
|
||||
#! reaches it, and run, unless what it calls had an error checking it, which is
|
||||
#! never run. A checker given no evaluator, as one answering an editor's
|
||||
#! queries, knows what folding gives and nothing more.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! What the checker asks the evaluator for.
|
||||
pub enum evaluation_kind : u8 {
|
||||
value, #! The value of an expression: `table` and the node.
|
||||
local, #! A local constant's value: `table` and its `variable` node.
|
||||
condition, #! Whether the condition of an `if const` holds: `table` and the `if_const` node.
|
||||
text, #! The text `compile_error` reports: `table` and the `call` node.
|
||||
}
|
||||
|
||||
#! What the checker asks the evaluator to work out, and where.
|
||||
pub struct evaluation_ask {
|
||||
pub var what: evaluation_kind; #! What it is.
|
||||
pub var table: u32; #! The result table the node was checked in.
|
||||
pub var node: u32; #! The node.
|
||||
}
|
||||
|
||||
#! What the evaluator worked out of what was asked.
|
||||
pub struct evaluation_answer {
|
||||
pub var worked: bool; #! Whether it was worked out.
|
||||
pub var noted: bool; #! Where it was not, whether the evaluator noted why, so the checker notes nothing more.
|
||||
pub var scalar: bool; #! Whether the value is a number, `bool`, character, or member of an enum, which `value` holds.
|
||||
pub var value: constant; #! The value, where it is one of those, or whether a condition holds.
|
||||
pub var text: string; #! The text `compile_error` reports, where that was asked for.
|
||||
}
|
||||
|
||||
#! What the checker keeps of where checking is while the evaluator runs, which
|
||||
#! checks what checking reached first: what one body's checking holds that
|
||||
#! another's must begin without.
|
||||
struct checker::outside {
|
||||
var at: checker::frame; #! Where checking was.
|
||||
var quiet: u32; #! Whether notes were left out.
|
||||
var undecided: u32; #! How many undecided `if const` and `for const` were around it.
|
||||
var waits_for: u32; #! The call that might wait for its parameter's type.
|
||||
var free_result: bool; #! Whether a lambda takes its result from its body.
|
||||
var walked: u64; #! How many places loops walked.
|
||||
}
|
||||
|
||||
#! Asks the program's evaluator for what only running gives, once what checking
|
||||
#! reached is checked.
|
||||
#! @param this The checker.
|
||||
#! @param what What is asked for.
|
||||
#! @param node The node it is asked of, in the table being written.
|
||||
#! @param out Where the answer is written.
|
||||
#! @returns Whether it was worked out.
|
||||
pub def checker::ask_evaluator(&mut this, what: evaluation_kind, node: u32, out: &mut evaluation_answer): bool {
|
||||
out.worked = false;
|
||||
out.noted = false;
|
||||
return false if this.quiet != 0 || this.waits_for_instance();
|
||||
# An expression checking found an error in is never run.
|
||||
return false if what == evaluation_kind::value && this.type_at(node) == bt::error;
|
||||
val run := this.evaluator else { return false; };
|
||||
val ask := evaluation_ask { what = what, table = this.table_node_of(node).table, node = node };
|
||||
|
||||
val held := this.step_outside();
|
||||
run(&ask, out);
|
||||
this.step_back(&held);
|
||||
return out.worked;
|
||||
}
|
||||
|
||||
#! Keeps where checking is and begins as checking a declaration of its own does,
|
||||
#! so what is checked meanwhile, as what an evaluation lowers, sees nothing of
|
||||
#! the body being checked.
|
||||
#! @param this The checker.
|
||||
#! @returns What was kept, which `step_back` puts back.
|
||||
def checker::step_outside(&mut this): checker::outside {
|
||||
val made := checker::outside {
|
||||
at = this.at,
|
||||
quiet = this.quiet,
|
||||
undecided = this.undecided,
|
||||
waits_for = this.waits_for,
|
||||
free_result = this.free_result,
|
||||
walked = this.walked.length
|
||||
};
|
||||
this.quiet = 0;
|
||||
this.undecided = 0;
|
||||
this.waits_for = 0;
|
||||
this.free_result = false;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Puts back where checking was, as `step_outside` kept it.
|
||||
#! @param this The checker.
|
||||
#! @param held What was kept.
|
||||
def checker::step_back(&mut this, held: &checker::outside): void {
|
||||
this.at = held.at;
|
||||
this.quiet = held.quiet;
|
||||
this.undecided = held.undecided;
|
||||
this.waits_for = held.waits_for;
|
||||
this.free_result = held.free_result;
|
||||
this.walked.resize(held.walked);
|
||||
}
|
||||
|
||||
#! Asks the evaluator for the value of an expression of a number, `bool`,
|
||||
#! character, or enum, and records it at the node where it was worked out. One
|
||||
#! reading a local only the program running gives a value is not asked for.
|
||||
#! @param this The checker.
|
||||
#! @param node The expression.
|
||||
#! @param out Where the answer is written.
|
||||
#! @returns Whether its value is known now.
|
||||
pub def checker::run_value(&mut this, node: u32, out: &mut evaluation_answer): bool {
|
||||
return false if this.runtime_local_read(node) != 0;
|
||||
if this.ask_evaluator(evaluation_kind::value, node, out) && out.scalar {
|
||||
this.set_value(node, out.value);
|
||||
}
|
||||
return this.is_known(node);
|
||||
}
|
||||
|
||||
#! 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::wrap_constant(&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);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,847 @@
|
||||
#! @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.span, 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 => {
|
||||
# A type parameter known to have a shape, as `T: pointer` says, gives what
|
||||
# it is a shape of, as `through(p)` takes `T::target` from a `T`.
|
||||
var plain := this.unalias(actual);
|
||||
if this.types.kind_of(plain) == ty::param {
|
||||
plain = this.shaped_plain(plain);
|
||||
}
|
||||
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 => {
|
||||
var plain := this.unalias(this.reached_value(actual));
|
||||
if this.types.kind_of(plain) == ty::param {
|
||||
plain = this.shaped_plain(plain);
|
||||
}
|
||||
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.span, 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.span, into.given.span);
|
||||
}
|
||||
|
||||
#! 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.span, to.span);
|
||||
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.span, to.span);
|
||||
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.span, to.span);
|
||||
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.span, inferred.binds.span);
|
||||
}
|
||||
|
||||
#! 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.span, to.span);
|
||||
}
|
||||
|
||||
#! 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 The instance, 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.span, args),
|
||||
made_file = node != 0 ? this.at.file : 0,
|
||||
made_node = node,
|
||||
made_in = node != 0 ? this.at.instance : 0
|
||||
});
|
||||
this.instanced.set(key, id);
|
||||
this.wants.append(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
#! 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 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];
|
||||
# A constant's default is worked out for each type taking it, as a default
|
||||
# compiled for each type is.
|
||||
val typed := this.typed_default(method) || this.constant_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.span);
|
||||
for &each in args {
|
||||
return 0 if each == bt::error;
|
||||
}
|
||||
|
||||
val pack := this.types.pack(args.span, 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.span, to.span)
|
||||
});
|
||||
this.instanced.set(key, id);
|
||||
this.wants.append(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
#! The instance of a sealed trait's constant its arguments give, checked as a
|
||||
#! generic type's constant is, with the trait's parameters bound to them and
|
||||
#! each of its types the one they give.
|
||||
#! @param this The checker.
|
||||
#! @param decl The constant's declaration.
|
||||
#! @param owner The trait, given its arguments.
|
||||
#! @param node The node a note is placed at, where too many instances are
|
||||
#! made.
|
||||
#! @returns The instance, or 0 where the arguments hold type parameters, or the
|
||||
#! program has made as many instances as it may.
|
||||
pub def checker::sealed_instance(&mut this, decl: u32, owner: u32, node: u32): u32 {
|
||||
val args := this.types.parts_of(owner);
|
||||
return 0 if args.length == 0 || this.any_open(args.span);
|
||||
for &each in args.span {
|
||||
return 0 if each == bt::error;
|
||||
}
|
||||
|
||||
val pack := this.types.pack(args.span, 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 kind := this.sealed_given(this.decls.types.p[decl], owner, 0);
|
||||
val id := this.instances.length as u32;
|
||||
this.instances.append(instance {
|
||||
decl = decl,
|
||||
args = pack,
|
||||
kind = kind,
|
||||
made_file = node != 0 ? this.at.file : 0,
|
||||
made_node = node,
|
||||
made_in = node != 0 ? this.at.instance : 0
|
||||
});
|
||||
this.instanced.set(key, id);
|
||||
this.wants.append(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
#! 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, or of a variable of a
|
||||
#! generic type, its value.
|
||||
#! @param this The checker.
|
||||
#! @param id The instance's index.
|
||||
pub def checker::check_instance(&mut this, id: u32): void {
|
||||
val held: instance = this.instances[id];
|
||||
val decl := held.decl;
|
||||
return if held.table != 0 || 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);
|
||||
this.instances[id].table = table;
|
||||
|
||||
val saved := this.at;
|
||||
val errors := this.errors;
|
||||
this.enter_decl(decl, held.args);
|
||||
this.use_table(table);
|
||||
this.at.instance = id;
|
||||
if this.decls.kinds.p[decl] == dk::variable {
|
||||
this.check_variable_instance(id, decl, held.kind);
|
||||
} else {
|
||||
this.check_function_body(decl, held.kind);
|
||||
}
|
||||
this.leave(saved);
|
||||
this.instances[id].flawed = this.errors != errors;
|
||||
}
|
||||
|
||||
#! Checks an instance now, where what reads it needs it checked, as a constant
|
||||
#! is for its value, as checking a declaration of its own begins.
|
||||
#! @param this The checker.
|
||||
#! @param id The instance's index.
|
||||
pub def checker::check_instance_now(&mut this, id: u32): void {
|
||||
return if this.instances[id].table != 0;
|
||||
# Notes are its own, said now, not held with those of cases checked around it.
|
||||
val held := this.step_outside();
|
||||
val repeating := this.repeating;
|
||||
this.repeating = 0;
|
||||
this.check_instance(id);
|
||||
this.repeating = repeating;
|
||||
this.step_back(&held);
|
||||
}
|
||||
|
||||
#! Checks the instance of a variable or constant of a generic type: its value,
|
||||
#! as of the type its type arguments give, and of a constant, works out what
|
||||
#! the value is, which reading it reads. Each is a global of the program.
|
||||
#! @param this The checker.
|
||||
#! @param id The instance's index.
|
||||
#! @param decl The variable's declaration.
|
||||
#! @param kind The instance's type.
|
||||
def checker::check_variable_instance(&mut this, id: u32, decl: u32, kind: u32): void {
|
||||
this.checked_globals++;
|
||||
val node: u32 = this.decls.nodes.p[decl];
|
||||
this.set_type(node, kind);
|
||||
val value := this.record(node, variable_slot::value);
|
||||
if value != 0 {
|
||||
this.check_expr(value, kind);
|
||||
this.set_flag(value, rf::checked);
|
||||
if this.decls.has(decl, df::constant) {
|
||||
this.instances[id].value = this.known_or_run(value, kind);
|
||||
}
|
||||
} else if !this.has_zero(kind, 0) {
|
||||
var text := string::from("`", nothing {});
|
||||
val named := this.describe(kind);
|
||||
text.append(named.span);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,650 @@
|
||||
#! @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;
|
||||
this.reach(id);
|
||||
return if !this.tracks;
|
||||
this.add_dependency(from, id);
|
||||
}
|
||||
|
||||
#! Records that checking reached a declaration, which is checked in its turn,
|
||||
#! where it was not reached before.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
pub def checker::reach(&mut this, id: u32): void {
|
||||
if id as u64 >= this.depended.length {
|
||||
this.depended.resize(this.decls.count > id as u64 ? this.decls.count : id as u64 + 1);
|
||||
}
|
||||
return if this.depended[id];
|
||||
this.depended[id] = true;
|
||||
this.queued.append(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::<file_node>::new();
|
||||
for &each in this.libraries {
|
||||
if each.file != 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;
|
||||
|
||||
# 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;
|
||||
|
||||
# The nodes kept keep their results where they are. Those an edit added, past
|
||||
# the file's last, have a table of their own, and a file parsed whole again a
|
||||
# table of all of them.
|
||||
val count := this.units[file].syntax.node_count as u32;
|
||||
val last: rtable = this.tables.p[this.units[file].table];
|
||||
if whole {
|
||||
val fresh := this.add_table(file, 0, count, 0);
|
||||
this.units[file].table = fresh;
|
||||
this.units[file].segments.clear();
|
||||
this.units[file].segments.append(fresh);
|
||||
} else if count > last.base + last.count {
|
||||
val fresh := this.add_table(file, last.base + last.count, count - last.base - last.count, 0);
|
||||
this.units[file].table = fresh;
|
||||
this.units[file].segments.append(fresh);
|
||||
}
|
||||
this.use_table(this.units[file].table);
|
||||
|
||||
# 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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
# 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.span);
|
||||
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_reached();
|
||||
this.recount_notes();
|
||||
this.at = saved;
|
||||
return checked.length as u32;
|
||||
}
|
||||
|
||||
#! 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.span);
|
||||
} else {
|
||||
this.decls.params.p[decl] = this.decls.make_list(own.span);
|
||||
}
|
||||
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.span);
|
||||
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);
|
||||
for id in 1..this.decls.count {
|
||||
this.decls.flags.p[id] &= ~(df::composed as u32);
|
||||
}
|
||||
this.known.clear();
|
||||
this.worked_again.clear();
|
||||
this.forget_paths();
|
||||
}
|
||||
|
||||
#! Forgets what the paths an argument's checking looked at name, which checking
|
||||
#! again finds anew.
|
||||
#! @param this The checker.
|
||||
def checker::forget_paths(&mut this): void {
|
||||
this.named_ids.clear();
|
||||
this.named_paths.resize(1);
|
||||
this.chosen_arms.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);
|
||||
this.forget_paths();
|
||||
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 1..this.instances.length {
|
||||
val held: instance = this.instances[i];
|
||||
continue if !family.span.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.span, args.span);
|
||||
this.instances[i].kind = kind;
|
||||
this.instances[i].table = 0;
|
||||
this.instances[i].value = 0;
|
||||
this.wants.append(i as u32);
|
||||
}
|
||||
}
|
||||
|
||||
#! Lets go of what was worked out of a declaration's nodes in its file's tables.
|
||||
#! @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 first := this.first_node(decl);
|
||||
val last: u32 = this.decls.nodes.p[decl];
|
||||
for node in first..(last + 1) {
|
||||
val n := node as u32;
|
||||
val table := this.file_table_of(file, n);
|
||||
continue if table == checker::no_table;
|
||||
val held: rtable = this.tables.p[table];
|
||||
this.drop_results(held.offset as u64 + (n - held.base) as u64);
|
||||
val key := table_node { table = table, node = 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,677 @@
|
||||
#! @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, or a
|
||||
#! `var` no assignment changes, an anonymous function naming the local, a
|
||||
#! struct, union, or array literal holding one, or a call keeping one. A call
|
||||
#! keeps an argument where the function says so of its parameter, with
|
||||
#! `@kept`, as `function::new` and `thread::spawn` do, or where the parameter's
|
||||
#! type is a type parameter of the function's own that its result's type
|
||||
#! holds, as an adapter holding the function it is given does. 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 else a call does with what it is given, the checker
|
||||
#! does not follow, and says nothing of.
|
||||
#!
|
||||
#! What the warnings need is recorded as the checker checks a function's body,
|
||||
#! rather than by walking it again: the scope each local is declared in, and
|
||||
#! each value returned, written, or bound to a name, with the scopes around it.
|
||||
#! Once the body checks, each is looked at in the order it is written. Only what
|
||||
#! checking decides is recorded: not what is within an `if const` or `for const`
|
||||
#! only evaluating or an instance decides, nor a pass of `for const`, whose
|
||||
#! results are its own.
|
||||
#!
|
||||
#! Only functions that are no generic's are recorded, 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 the checker records of the bodies it checks for the warnings, and what
|
||||
#! looking at a body's record holds. A body's check may start another's, as
|
||||
#! evaluating a constant checks the function it calls, so each body checked
|
||||
#! has a session of its own on a stack, and what it records follows what the
|
||||
#! sessions around it recorded.
|
||||
struct lifetime_walk {
|
||||
var sessions: vector<lifetime_session>; #! The bodies being recorded, innermost last.
|
||||
var opened: vector<lifetime_scope>; #! The scopes entered while recording, the first standing for none.
|
||||
var events: vector<lifetime_event>; #! What was returned, written, or bound while recording.
|
||||
var notes: keyed<table_node>; #! The scope each local is declared in, by its table and node.
|
||||
var current: u32; #! The innermost scope entered, of the innermost session.
|
||||
var table: u32; #! The table the innermost session's body is checked in, outside which nothing is recorded.
|
||||
|
||||
# Where looking at an event is: the scopes around it, outermost first, and
|
||||
# the function and anonymous functions among them.
|
||||
var scopes: vector<u32>; #! The scopes' nodes.
|
||||
var functions: vector<u32>; #! The functions' nodes.
|
||||
}
|
||||
|
||||
#! A body being recorded: the function, and where its record begins.
|
||||
struct lifetime_session {
|
||||
var decl: u32; #! The function's declaration.
|
||||
var table: u32; #! The table its body is checked in.
|
||||
var scopes: u32; #! Where its scopes begin in `opened`.
|
||||
var events: u32; #! Where its events begin in `events`.
|
||||
var current: u32; #! The innermost scope of the session around it, as it was.
|
||||
var outer: u32; #! The table of the session around it.
|
||||
}
|
||||
|
||||
#! A scope entered while recording: a function, block, loop, `if`, arm, or
|
||||
#! anonymous function.
|
||||
struct lifetime_scope {
|
||||
var node: u32; #! The node opening it.
|
||||
var parent: u32; #! The scope around it, in `opened`, or 0.
|
||||
var function: bool; #! Whether it is a function's or an anonymous function's.
|
||||
}
|
||||
|
||||
#! What a value returned, written, or bound is, as an event of a record.
|
||||
enum lifetime_kind_of_event : u8 {
|
||||
returned, #! A `return`, or the value an anonymous function's body is.
|
||||
written, #! An assignment.
|
||||
bound, #! A local declared with a value.
|
||||
}
|
||||
|
||||
#! A value returned, written, or bound, and the scope it was checked in.
|
||||
struct lifetime_event {
|
||||
var node: u32; #! The `return_stmt`, `lambda`, `assign`, or `variable` node.
|
||||
var kind: lifetime_kind_of_event; #! Which it is.
|
||||
var scope: u32; #! The innermost scope around it, in `opened`.
|
||||
}
|
||||
|
||||
#! Where a local is declared: its scope, and the function or anonymous
|
||||
#! function that scope is in.
|
||||
struct lifetime_note {
|
||||
var scope: u32; #! The scope's node, or 0 where nothing was recorded of it.
|
||||
var owner: u32; #! The function's node.
|
||||
}
|
||||
|
||||
#! Makes a walk, which records nothing until a body begins.
|
||||
#! @returns The walk.
|
||||
def lifetime_walk::new(): lifetime_walk {
|
||||
var made := lifetime_walk {
|
||||
sessions = vector::<lifetime_session>::new(),
|
||||
opened = vector::<lifetime_scope>::new(),
|
||||
events = vector::<lifetime_event>::new(),
|
||||
notes = keyed::<table_node>::new(),
|
||||
scopes = vector::<u32>::new(),
|
||||
functions = vector::<u32>::new()
|
||||
};
|
||||
made.opened.append(lifetime_scope {});
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Where the local was declared, as the session looked at recorded it.
|
||||
#! @param this The walk.
|
||||
#! @param local The node declaring the local.
|
||||
#! @returns The note, or nothing noted where none was recorded.
|
||||
def lifetime_walk::note_of(&this, local: u32): lifetime_note {
|
||||
val at := this.notes.get_or(&table_node { table = this.table, node = local }, 0);
|
||||
return lifetime_note {} if at == 0;
|
||||
var owner := at;
|
||||
while owner != 0 && !this.opened[owner].function {
|
||||
owner = this.opened[owner].parent;
|
||||
}
|
||||
return lifetime_note { scope = this.opened[at].node, owner = this.opened[owner].node };
|
||||
}
|
||||
|
||||
#! Whether what is checked now is recorded: within a body a session records,
|
||||
#! in its own table, where checking decides it.
|
||||
#! @param this The checker.
|
||||
#! @returns Whether it is.
|
||||
@inline
|
||||
def checker::recording(&this): bool {
|
||||
return this.lifetimes.sessions.length != 0 && this.undecided == 0 && this.at.table == this.lifetimes.table;
|
||||
}
|
||||
|
||||
#! Begins recording a function's body, 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, whose body is about to be checked.
|
||||
#! @returns Whether it is recorded, which `end_lifetimes` ends.
|
||||
pub def checker::begin_lifetimes(&mut this, id: u32): bool {
|
||||
return false 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 false if node == 0 || this.kind_of(node) != nk::function || this.at.instance != 0;
|
||||
val walk := &mut this.lifetimes;
|
||||
if walk.sessions.length == 0 {
|
||||
walk.notes.clear();
|
||||
}
|
||||
walk.sessions.append(lifetime_session {
|
||||
decl = id,
|
||||
table = this.at.table,
|
||||
scopes = walk.opened.length as u32,
|
||||
events = walk.events.length as u32,
|
||||
current = walk.current,
|
||||
outer = walk.table
|
||||
});
|
||||
walk.table = this.at.table;
|
||||
walk.current = 0;
|
||||
_ = this.lifetime_open(node);
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Ends the record of the body last begun, warning of what it keeps past what
|
||||
#! it refers to where it checked.
|
||||
#! @param this The checker.
|
||||
#! @param checks Whether the body checked, without errors.
|
||||
pub def checker::end_lifetimes(&mut this, checks: bool): void {
|
||||
if checks {
|
||||
this.lifetime_warn();
|
||||
}
|
||||
val walk := &mut this.lifetimes;
|
||||
val held: lifetime_session = walk.sessions.last;
|
||||
walk.opened.resize(held.scopes as u64);
|
||||
walk.events.resize(held.events as u64);
|
||||
walk.current = held.current;
|
||||
walk.table = held.outer;
|
||||
walk.sessions.truncate();
|
||||
}
|
||||
|
||||
#! Enters the scope a node opens, where what is checked is recorded.
|
||||
#! @param this The checker.
|
||||
#! @param node The function, block, loop, `if`, arm, or anonymous function.
|
||||
#! @returns The scope it was within, which `lifetime_close` goes back to.
|
||||
def checker::lifetime_open(&mut this, node: u32): u32 {
|
||||
val walk := &mut this.lifetimes;
|
||||
val outer := walk.current;
|
||||
return outer if !this.recording();
|
||||
val kind := this.kind_of(node);
|
||||
walk.current = walk.opened.length as u32;
|
||||
walk.opened.append(lifetime_scope { node = node, parent = outer, function = kind == nk::function || kind == nk::lambda });
|
||||
return outer;
|
||||
}
|
||||
|
||||
#! Leaves the scope last entered.
|
||||
#! @param this The checker.
|
||||
#! @param outer The scope it was within, as `lifetime_open` gave it.
|
||||
def checker::lifetime_close(&mut this, outer: u32): void {
|
||||
this.lifetimes.current = outer;
|
||||
}
|
||||
|
||||
#! Makes a node a local, noting the scope it is declared in where what is
|
||||
#! checked is recorded.
|
||||
#! @param this The checker.
|
||||
#! @param node The node declaring the local.
|
||||
pub def checker::mark_local(&mut this, node: u32): void {
|
||||
this.set_flag(node, rf::local);
|
||||
if this.recording() {
|
||||
this.lifetimes.notes.set(table_node { table = this.at.table, node = node }, this.lifetimes.current);
|
||||
}
|
||||
}
|
||||
|
||||
#! Records a value returned, written, or bound, where what is checked is.
|
||||
#! @param this The checker.
|
||||
#! @param node The `return_stmt`, `lambda`, `assign`, or `variable` node.
|
||||
#! @param kind Which it is.
|
||||
def checker::lifetime_event(&mut this, node: u32, kind: lifetime_kind_of_event): void {
|
||||
return if !this.recording();
|
||||
this.lifetimes.events.append(lifetime_event { node = node, kind = kind, scope = this.lifetimes.current });
|
||||
}
|
||||
|
||||
#! An event's place in the order its body is written: after what it holds, and
|
||||
#! before what follows it.
|
||||
struct lifetime_order {
|
||||
var end: u32; #! The last token of its node.
|
||||
var start: u32; #! Its node's token.
|
||||
var index: u32; #! The event, in `events`.
|
||||
}
|
||||
|
||||
#! Warns of what the body last begun keeps past what it refers to, looking at
|
||||
#! each value it returned, wrote, or bound, in the order they are written, once
|
||||
#! each however many times checking reached it.
|
||||
#! @param this The checker.
|
||||
def checker::lifetime_warn(&mut this): void {
|
||||
val first: u32 = this.lifetimes.sessions.last.events;
|
||||
var order := vector::<lifetime_order>::new();
|
||||
for i in first..this.lifetimes.events.length as u32 {
|
||||
val node := this.lifetimes.events[i].node;
|
||||
order.append(lifetime_order { end = this.syn().node_end(node), start = this.token_of(node), index = i });
|
||||
}
|
||||
order.sort_by(def(a: &lifetime_order, b: &lifetime_order): bool {
|
||||
return a.end < b.end || a.end == b.end && (a.start > b.start || a.start == b.start && a.index < b.index);
|
||||
});
|
||||
|
||||
var last: u32 = 0;
|
||||
for i in 0..order.length {
|
||||
val held: lifetime_event = this.lifetimes.events[order[i].index];
|
||||
continue if i != 0 && held.node == last;
|
||||
last = held.node;
|
||||
|
||||
# The scopes around it, outermost first.
|
||||
val walk := &mut this.lifetimes;
|
||||
walk.scopes.clear();
|
||||
walk.functions.clear();
|
||||
var depth: u64 = 0;
|
||||
var at := held.scope;
|
||||
while at != 0 {
|
||||
depth++;
|
||||
at = walk.opened[at].parent;
|
||||
}
|
||||
walk.scopes.resize(depth);
|
||||
at = held.scope;
|
||||
while at != 0 {
|
||||
depth--;
|
||||
walk.scopes[depth] = walk.opened[at].node;
|
||||
at = walk.opened[at].parent;
|
||||
}
|
||||
for i in 0..walk.scopes.length {
|
||||
val scope := walk.scopes[i];
|
||||
val kind := this.kind_of(scope);
|
||||
if kind == nk::function || kind == nk::lambda {
|
||||
walk.functions.append(scope);
|
||||
}
|
||||
}
|
||||
|
||||
match held.kind {
|
||||
lifetime_kind_of_event::returned => {
|
||||
val value := this.kind_of(held.node) == nk::lambda ? this.record(held.node, lambda_slot::body) : this.left_of(held.node);
|
||||
this.lifetime_returned(walk, value);
|
||||
}
|
||||
lifetime_kind_of_event::written => {
|
||||
if this.token_kind(held.node) == tk::assign {
|
||||
this.lifetime_written(walk, this.left_of(held.node), this.right_of(held.node));
|
||||
}
|
||||
}
|
||||
lifetime_kind_of_event::bound => {
|
||||
# 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(held.node, variable_slot::value);
|
||||
if value != 0 && this.kind_of(value) != nk::reference {
|
||||
val got := this.lifetime_of(walk, value, 0);
|
||||
if got.kind == lifetime_kind::temporary {
|
||||
this.warn(got.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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#! 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.span);
|
||||
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, as does a `var` no assignment
|
||||
# changes, and one bound to a value its statement makes refers to it as
|
||||
# long as it 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;
|
||||
return none if this.node_has(local, nf::mutable) && !this.lifetime_unwritten(walk, local);
|
||||
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::call => {
|
||||
# A call refers to what each argument it keeps does.
|
||||
val args := this.right_of(node);
|
||||
for i in 0..this.run_length(args) {
|
||||
continue if !this.call_keeps(node, i as u32);
|
||||
val held := this.lifetime_of(walk, this.run_at(args, i as u32), depth + 1);
|
||||
return held if held.kind != lifetime_kind::none;
|
||||
}
|
||||
return none;
|
||||
}
|
||||
nk::fallback => {
|
||||
# `x else y` refers to what `x` does where `x` holds a value.
|
||||
return this.lifetime_of(walk, this.left_of(node), depth);
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
#! Whether no assignment of the body being looked at writes a local whole.
|
||||
#! @param this The checker.
|
||||
#! @param walk The walk.
|
||||
#! @param local The node declaring the local.
|
||||
#! @returns Whether none does.
|
||||
def checker::lifetime_unwritten(&this, walk: &lifetime_walk, local: u32): bool {
|
||||
val first: u32 = walk.sessions.last.events;
|
||||
for i in first..walk.events.length as u32 {
|
||||
val held: lifetime_event = walk.events[i];
|
||||
continue if held.kind != lifetime_kind_of_event::written;
|
||||
val target := this.left_of(held.node);
|
||||
continue if this.kind_of(target) != nk::name;
|
||||
val ref := this.ref_at(target);
|
||||
return false if (ref & ref_local) != 0 && (ref & ref_mask) == local;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#! Whether what a call gives back keeps one of its arguments: the parameter it
|
||||
#! is given for is `@kept`, or its type is a type parameter of the function's
|
||||
#! own that the result's type holds.
|
||||
#! @param this The checker.
|
||||
#! @param call The `call` node.
|
||||
#! @param arg The argument's index among those written.
|
||||
#! @returns Whether it keeps it.
|
||||
def checker::call_keeps(&mut this, call: u32, arg: u32): bool {
|
||||
val callee := this.left_of(call);
|
||||
val ref := this.ref_at(callee);
|
||||
return false if ref == 0 || (ref & (ref_local | ref_type)) != 0;
|
||||
val decl := ref & ref_mask;
|
||||
return false if this.decls.kinds.p[decl] != dk::function || this.decls.nodes.p[decl] == 0;
|
||||
# A method called on a value takes it as `this`, the first parameter.
|
||||
val object := this.kind_of(callee) == nk::member && this.decls.has(decl, df::method);
|
||||
val index := arg + (object ? 1u : 0u);
|
||||
|
||||
val saved := this.at;
|
||||
this.use_table(this.units[this.decls.files.p[decl]].table);
|
||||
val node: u32 = this.decls.nodes.p[decl];
|
||||
val params := this.record(node, function_slot::params);
|
||||
var keeps := false;
|
||||
if this.kind_of(node) == nk::function && index < this.run_length(params) {
|
||||
val param := this.run_at(params, index);
|
||||
for &attr in this.run_view(this.record(param, parameter_slot::attributes)) {
|
||||
continue if this.kind_of(attr) != nk::attribute;
|
||||
val named := this.left_of(attr);
|
||||
keeps = keeps || this.segment_name(named, this.segment_count(named) - 1) == word::kept;
|
||||
}
|
||||
# A type parameter of its own the result's type holds.
|
||||
val written := this.left_of(param);
|
||||
if !keeps && written != 0 && this.kind_of(written) == nk::type_name && this.segment_count(written) == 1 {
|
||||
val name := this.segment_name(written, 0);
|
||||
var own := false;
|
||||
for &each in this.run_view(this.record(node, function_slot::type_params)) {
|
||||
own = own || this.name_of(each) == name;
|
||||
}
|
||||
keeps = own && this.type_names(this.record(node, function_slot::result), name);
|
||||
}
|
||||
}
|
||||
this.at = saved;
|
||||
return keeps;
|
||||
}
|
||||
|
||||
#! Whether a type written names a type, as a type parameter, anywhere within it.
|
||||
#! @param this The checker.
|
||||
#! @param node The type written, or 0.
|
||||
#! @param name The name's ID.
|
||||
#! @returns Whether it does.
|
||||
def checker::type_names(&mut this, node: u32, name: u32): bool {
|
||||
return false if node == 0;
|
||||
var todo := vector::<u32>::new();
|
||||
todo.append(node);
|
||||
var seen := 0;
|
||||
while todo.length != 0 && seen < 4096 {
|
||||
seen++;
|
||||
val at: u32 = todo.last;
|
||||
todo.truncate();
|
||||
return true if this.kind_of(at) == nk::type_name && this.segment_count(at) == 1 && this.segment_name(at, 0) == name;
|
||||
this.syn().children(at, &mut todo);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! 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.span.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;
|
||||
}
|
||||
|
||||
#! 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,288 @@
|
||||
#! @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 := each.file;
|
||||
val node := each.node;
|
||||
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].span);
|
||||
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.span);
|
||||
|
||||
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.span);
|
||||
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;
|
||||
}
|
||||
|
||||
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.span);
|
||||
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.
|
||||
var made: u32 = 0;
|
||||
for &each in syntax.run_view(syntax.record(node, decl_slot::type_params)) {
|
||||
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,507 @@
|
||||
#! @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;
|
||||
}
|
||||
|
||||
# A sealed trait gives the names of its types too.
|
||||
val sealed := this.is_sealed(decl);
|
||||
val member := types && !sealed ? 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 => types ? 0 : member,
|
||||
dk::assoc_type => sealed ? member : 0,
|
||||
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, dk::assoc_type => {}
|
||||
else => return 0;
|
||||
}
|
||||
|
||||
# A sealed trait gives its constants and types the names of the others, of
|
||||
# the trait given the same arguments.
|
||||
if this.decls.kinds.p[id] == dk::trait_type && this.is_sealed(id) {
|
||||
return args == 0 ? this.decls.types.p[id] : this.types.named(id, this.types.parts_of(args).span);
|
||||
}
|
||||
if (this.decls.kinds.p[id] == dk::variable || this.decls.kinds.p[id] == dk::assoc_type || this.decls.kinds.p[id] == dk::function)
|
||||
&& this.is_sealed(owner) {
|
||||
return this.decls.types.p[owner] if args == 0;
|
||||
var given := vector::<u32>::new();
|
||||
for i in 0..this.decls.list_length(this.decls.params.p[owner]) {
|
||||
given.append(i < this.types.part_count(args) ? this.types.part_at(args, i as u32) : bt::error);
|
||||
}
|
||||
return this.types.named(owner, given.span);
|
||||
}
|
||||
# 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.span);
|
||||
}
|
||||
|
||||
#! 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.span);
|
||||
}
|
||||
|
||||
#! 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.span);
|
||||
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.span);
|
||||
text.append("` for the first, or rename one of them.");
|
||||
} else {
|
||||
text.append("` and `");
|
||||
var second := this.path_text(other);
|
||||
text.append(second.span);
|
||||
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).span);
|
||||
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.span);
|
||||
}
|
||||
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 a path whose first name names both a module and a type names the
|
||||
#! type: where the module declares nothing of the path's next name, as
|
||||
#! `uri::parse` where the module `uri` declares the type `uri`, whose function
|
||||
#! `parse` is.
|
||||
#! @param this The checker.
|
||||
#! @param home The module the first name names.
|
||||
#! @param node The `path` or `type_name` node, of two segments or more.
|
||||
#! @returns Whether the type is named.
|
||||
pub def checker::type_over_module(&mut this, home: u32, node: u32): bool {
|
||||
val next := this.segment_name(node, 1);
|
||||
return false if this.modules.decl(home, next) != 0 || this.modules.find(home, next) != 0;
|
||||
val found := this.lookup_named(this.segment_name(node, 0), 0, true);
|
||||
return found.decl != 0 && this.is_type_decl(found.decl);
|
||||
}
|
||||
|
||||
#! 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.decls.kinds.p[id] != dk::function || !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 is a constant a trait asks for and gives a default of,
|
||||
#! which a type naming the trait and giving none of its own takes, worked out
|
||||
#! with `self` that type. A sealed trait's constants are its own instead.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::constant_default(&this, id: u32): bool {
|
||||
return this.decls.kinds.p[id] == dk::variable && this.trait_asks(id)
|
||||
&& !this.is_sealed(this.decls.owners.p[id]) && this.record_in(id, variable_slot::value) != 0;
|
||||
}
|
||||
|
||||
#! Whether a constant a trait declares is one constant of the program, rather
|
||||
#! than one for each type taking it or each list of arguments the trait is
|
||||
#! given: one of a sealed trait without type parameters.
|
||||
#! @param this The checker.
|
||||
#! @param decl The constant's declaration.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::sealed_alone(&this, decl: u32): bool {
|
||||
val holder: u32 = this.decls.owners.p[decl];
|
||||
return this.is_sealed(holder) && this.decls.list_length(this.decls.params.p[holder]) == 0;
|
||||
}
|
||||
|
||||
#! 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.record(node, decl_slot::receiver) != 0;
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
#! @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));
|
||||
}
|
||||
|
||||
#! Writes an expression as it is written, from its first token to its last, as
|
||||
#! `v.items` or `b != 0`.
|
||||
#! @param this The checker.
|
||||
#! @param node The expression.
|
||||
#! @param out Where it is written.
|
||||
pub def checker::written_text(&this, node: u32, out: &mut string): void {
|
||||
val syntax := &this.syn();
|
||||
# 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.names);
|
||||
return if end <= begin;
|
||||
out.append(this.src().make_lexeme(begin, end - begin));
|
||||
}
|
||||
|
||||
#! 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 shape := shapes[this.at.kinds[node] as u64];
|
||||
asserts(index < shape.record.length, "The node's record has the slot.");
|
||||
val at: u32 = shape.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,320 @@
|
||||
#! @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 left out, as one
|
||||
#! made where what is checked is quiet, 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.span);
|
||||
}
|
||||
|
||||
#! 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 {
|
||||
return if this.quiet != 0;
|
||||
# A body checked once for each case it holds in says each note once, which is
|
||||
# held until it ends.
|
||||
val key := ((file as u64) << 40) | ((node as u64) << 8) | (code as u64);
|
||||
if this.repeating != 0 {
|
||||
for &mut each in this.held_notes {
|
||||
continue if each.key != key;
|
||||
if each.serial != this.case_serial {
|
||||
each.serial = this.case_serial;
|
||||
each.passes++;
|
||||
}
|
||||
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
|
||||
};
|
||||
if related.length == 0 {
|
||||
this.relate_instance(&mut made);
|
||||
}
|
||||
if this.repeating != 0 {
|
||||
this.held_notes.append(checker::held_note {
|
||||
key = key, serial = this.case_serial, passes = 1, made = move(&mut made), text = string::copy_of(&this.case_text)
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.sink.give(&mut made);
|
||||
}
|
||||
|
||||
#! Relates a note made in an instance to where what is written made it, where
|
||||
#! it relates to nothing else.
|
||||
#! @param this The checker.
|
||||
#! @param made The note.
|
||||
def checker::relate_instance(&mut this, made: &mut note): void {
|
||||
return if this.at.instance == 0;
|
||||
val at := this.instance_made(this.at.instance);
|
||||
return if at.node == 0;
|
||||
val syntax := &this.units[at.file].syntax;
|
||||
val token := this.made_token(at);
|
||||
made.related_file = at.file;
|
||||
made.related_offset = syntax.token_offsets[token];
|
||||
made.related_length = syntax.token_length(token, this.names);
|
||||
made.related = string::from("The instance is made here.", nothing {});
|
||||
}
|
||||
|
||||
#! 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.span, 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.quiet != 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 {});
|
||||
} else {
|
||||
this.relate_instance(&mut made);
|
||||
}
|
||||
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>`",
|
||||
#! with where what is written made it, as ", made at main.sakura:4:12", or
|
||||
#! nothing outside an instance. An instance an instance made is made by what
|
||||
#! made that one, so the place is in the program's own code where it can be.
|
||||
#! @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];
|
||||
var text := string::from("In `", nothing {});
|
||||
# A variable of a generic type is written through the type, as
|
||||
# `counter<u8>::count`.
|
||||
val variable := this.decls.kinds.p[held.decl] == dk::variable && this.decls.owners.p[held.decl] != 0;
|
||||
text.append(this.names.text(this.decls.names.p[variable ? this.decls.owners.p[held.decl] : 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(">");
|
||||
if variable {
|
||||
text.append("::");
|
||||
text.append(this.names.text(this.decls.names.p[held.decl]));
|
||||
}
|
||||
text.append("`");
|
||||
val made := this.instance_made(this.at.instance);
|
||||
if made.node != 0 {
|
||||
val source := &this.units[made.file].source;
|
||||
val syntax := &this.units[made.file].syntax;
|
||||
val place := source.lines.place_of(syntax.token_offsets[this.made_token(made)]);
|
||||
text.append($", made at {source.path}:{place.line}:{place.column}");
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
#! The token a note says an instance was made at: of the function a call
|
||||
#! calls, where a call made it, as `max` of `max::<u8>(a, b)`, or else of the
|
||||
#! node.
|
||||
#! @param this The checker.
|
||||
#! @param made The file and node, as `instance_made` gives them.
|
||||
#! @returns The token's index.
|
||||
def checker::made_token(&this, made: file_node): u32 {
|
||||
val syntax := &this.units[made.file].syntax;
|
||||
val node: u32 = syntax.node_kinds[made.node] == nk::call && syntax.node_lefts[made.node] != 0
|
||||
? syntax.node_lefts[made.node] : made.node;
|
||||
return syntax.node_tokens[node];
|
||||
}
|
||||
|
||||
#! Where what is written made an instance: the node first asking for it, or for
|
||||
#! the outermost instance whose checking made it, or none where nothing written
|
||||
#! asked for it.
|
||||
#! @param this The checker.
|
||||
#! @param id The instance.
|
||||
#! @returns The file and node, or node 0.
|
||||
def checker::instance_made(&this, id: u32): file_node {
|
||||
var at := id;
|
||||
while this.instances[at].made_in != 0 && this.instances[this.instances[at].made_in].made_node != 0 {
|
||||
at = this.instances[at].made_in;
|
||||
}
|
||||
return file_node { file = this.instances[at].made_file, node = this.instances[at].made_node };
|
||||
}
|
||||
|
||||
#! 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,342 @@
|
||||
#! @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 the warning where a loop's body changes whole what the
|
||||
#! loop walks, which may move what the loop reads next.
|
||||
|
||||
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);
|
||||
}
|
||||
# A pack held by a field closes what of it closes, and one whose types are
|
||||
# not known yet what its bounds say does.
|
||||
ty::pack => {
|
||||
if this.types.is_open_pack(plain) {
|
||||
val owning := this.std_decl(word::owning);
|
||||
made = owning != 0 && this.param_bounded(plain, owning);
|
||||
} else {
|
||||
for i in 0..this.types.part_count(plain) {
|
||||
made = made || this.closes(this.types.part_at(plain, i as u32));
|
||||
}
|
||||
}
|
||||
}
|
||||
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.span);
|
||||
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.span);
|
||||
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.span);
|
||||
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);
|
||||
}
|
||||
|
||||
#! Checks a pack given whole, as `...args` gives it to a call, or a literal to a
|
||||
#! field holding a pack: each value that closes is moved to where it goes,
|
||||
#! which takes it by value, leaving the pack's place empty, so the pack is a
|
||||
#! variadic parameter, which the function owns, a new value's, as a call's
|
||||
#! result's, or a place that can be written.
|
||||
#! @param this The checker.
|
||||
#! @param node The pack's node.
|
||||
#! @param pack The pack's type.
|
||||
#! @param to The pack of the types its values go to.
|
||||
pub def checker::check_pack_moved(&mut this, node: u32, pack: u32, to: u32): void {
|
||||
val plain := this.unalias(this.reached(pack));
|
||||
return if this.types.kind_of(plain) != ty::pack || this.types.kind_of(to) != ty::pack;
|
||||
return if this.kind_of(node) == nk::name || !this.closes(plain);
|
||||
var moves := false;
|
||||
for j in 0..this.types.part_count(plain) {
|
||||
val each := this.types.part_at(plain, j as u32);
|
||||
val goes := j < this.types.part_count(to) ? this.types.part_at(to, j as u32) : bt::error;
|
||||
moves = moves || (this.closes(each) && this.types.kind_of(this.unalias(goes)) != ty::reference);
|
||||
}
|
||||
return if !moves || !this.is_place(node) || this.is_writable(node);
|
||||
var text := string::from("`", nothing {});
|
||||
val named := this.describe(plain);
|
||||
text.append(named.span);
|
||||
text.append("` holds what is closed where its scope ends, which is moved out of the pack, leaving it empty, so the pack is one that can be written: a `var`'s field, or one reached through `&mut`.");
|
||||
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;
|
||||
}
|
||||
|
||||
#! Whether a node reads a property, `x.name` or `x.(d)` of one, whose value its
|
||||
#! getter makes, as a call's makes one, rather than being a place.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns Whether it does.
|
||||
pub def checker::reads_property(&this, node: u32): bool {
|
||||
val kind := this.kind_of(node);
|
||||
return false if kind != nk::member && kind != nk::member_of;
|
||||
val ref := this.ref_at(node);
|
||||
return false if ref == 0 || (ref & (ref_local | ref_type)) != 0;
|
||||
val decl: dk = this.decls.kinds.p[ref];
|
||||
return decl == dk::property || (decl == dk::function && this.decls.has(ref, df::accessor));
|
||||
}
|
||||
|
||||
#! The place a loop walks what it reads from, which changing whole may move or
|
||||
#! release: what is iterated, or what it is lent from, as `v` of a slice of it,
|
||||
#! `v[1:]`, of a property of it giving a view or an iterator, `v.span`, and of
|
||||
#! its `iter()`. What another method or property gives may hold nothing of the
|
||||
#! value, so it is no place the loop is sure to walk. It is 0 where that is no
|
||||
#! place `same_place` tells apart, or where nothing moves what the loop reads: a
|
||||
#! fixed array, a view, or an iterator, which the loop and its body advance
|
||||
#! alike.
|
||||
#! @param this The checker.
|
||||
#! @param iterated The node of what the loop iterates.
|
||||
#! @returns The place's node, or 0.
|
||||
pub def checker::walked_place(&mut this, iterated: u32): u32 {
|
||||
var at := iterated;
|
||||
var steps := 0;
|
||||
while steps < 16 {
|
||||
steps++;
|
||||
if this.kind_of(at) == nk::slice || (this.reads_property(at) && this.lends_walk(this.type_at(at))) {
|
||||
at = this.left_of(at);
|
||||
continue;
|
||||
}
|
||||
if this.kind_of(at) == nk::call {
|
||||
val callee := this.left_of(at);
|
||||
val decl := this.ref_at(at);
|
||||
if this.kind_of(callee) == nk::member && decl != 0 && (decl & (ref_local | ref_type)) == 0
|
||||
&& this.decls.kinds.p[decl] == dk::function && this.decls.has(decl, df::method)
|
||||
&& this.decls.names.p[decl] == word::iter {
|
||||
at = this.left_of(callee);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
return 0 if !this.plain_place(at) || this.lends_walk(this.type_at(at));
|
||||
return 0 if this.types.kind_of(this.unalias(this.reached(this.type_at(at)))) != ty::named;
|
||||
return at;
|
||||
}
|
||||
|
||||
#! Whether a value of a type walks what something else holds without owning it:
|
||||
#! a view, or an iterator, as what `v.span` and `v.iter()` give.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @returns Whether it does.
|
||||
def checker::lends_walk(&mut this, kind: u32): bool {
|
||||
val held := this.unalias(this.reached(kind));
|
||||
return this.is_std(held, word::span) || this.is_std(held, word::slice)
|
||||
|| (this.types.kind_of(held) == ty::named && this.find_member(held, word::next).decl != 0);
|
||||
}
|
||||
|
||||
#! Whether a node is a place written with names, fields, `*`, and indexes that
|
||||
#! are names or constants alone, which `same_place` tells apart.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns Whether it is.
|
||||
def checker::plain_place(&mut this, node: u32): bool {
|
||||
var at := node;
|
||||
var steps := 0;
|
||||
while steps < 32 {
|
||||
steps++;
|
||||
match this.kind_of(at) {
|
||||
nk::name, nk::path => {
|
||||
val ref := this.ref_at(at);
|
||||
return ref != 0 && (ref & ref_type) == 0;
|
||||
}
|
||||
nk::member => {
|
||||
val ref := this.ref_at(at);
|
||||
return false if ref == 0 || (ref & (ref_local | ref_type)) != 0 || this.decls.kinds.p[ref] != dk::field;
|
||||
}
|
||||
nk::index => {
|
||||
val at_index := this.right_of(at);
|
||||
return false if !this.is_known(at_index) && (this.kind_of(at_index) != nk::name || this.ref_at(at_index) == 0);
|
||||
}
|
||||
nk::unary => {
|
||||
return false if this.token_kind(at) != tk::star;
|
||||
}
|
||||
else => return false;
|
||||
}
|
||||
at = this.left_of(at);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Whether two places are written alike: the same local or global, its same
|
||||
#! fields, through `*` alike, at indexes of the same names or constants.
|
||||
#! @param this The checker.
|
||||
#! @param a One place's node.
|
||||
#! @param b The other's.
|
||||
#! @returns Whether they are.
|
||||
def checker::same_place(&mut this, a: u32, b: u32): bool {
|
||||
var x := a;
|
||||
var y := b;
|
||||
var steps := 0;
|
||||
while steps < 32 {
|
||||
steps++;
|
||||
val kind := this.kind_of(x);
|
||||
return false if kind != this.kind_of(y);
|
||||
match kind {
|
||||
nk::name, nk::path => return this.ref_at(x) != 0 && this.ref_at(x) == this.ref_at(y);
|
||||
nk::member => {
|
||||
return false if this.ref_at(x) == 0 || this.ref_at(x) != this.ref_at(y);
|
||||
}
|
||||
nk::index => {
|
||||
val i := this.right_of(x);
|
||||
val j := this.right_of(y);
|
||||
if this.is_known(i) && this.is_known(j) {
|
||||
return false if this.value_at(i).magnitude != this.value_at(j).magnitude;
|
||||
} else {
|
||||
return false if this.kind_of(i) != nk::name || this.kind_of(j) != nk::name
|
||||
|| this.ref_at(i) == 0 || this.ref_at(i) != this.ref_at(j);
|
||||
}
|
||||
}
|
||||
nk::unary => {
|
||||
return false if this.token_kind(x) != tk::star || this.token_kind(y) != tk::star;
|
||||
}
|
||||
else => return false;
|
||||
}
|
||||
x = this.left_of(x);
|
||||
y = this.left_of(y);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Warns where a loop around the node walks the place it is, which changing
|
||||
#! whole, as a method taking `&mut this` does, `&mut` of it, or assigning it,
|
||||
#! may move or release, so what the loop reads next may be gone. What changes
|
||||
#! what it holds in place, as `v[i] = x` or `v.first = x`, moves nothing, and
|
||||
#! is not warned of; nor is what changes what holds it, which may not change it.
|
||||
#! @param this The checker.
|
||||
#! @param node The node of what is changed.
|
||||
pub def checker::check_walked(&mut this, node: u32): void {
|
||||
return if this.walked.length == 0;
|
||||
for i in 0..this.walked.length {
|
||||
val held := this.walked[i];
|
||||
continue if (held >> 32) as u32 != this.at.table;
|
||||
val place := (held & 0xFFFFFFFF) as u32;
|
||||
continue if !this.same_place(place, node);
|
||||
var text := string::from("`", nothing {});
|
||||
this.written_text(place, &mut text);
|
||||
text.append("` is walked by the loop around this, and changing it whole, as this may, can move or release what the loop reads next. Walk a copy of it, or its indexes, to change it.");
|
||||
this.warn_text(node, ec::lifetime, &text, 0);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,632 @@
|
||||
#! @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.span));
|
||||
}
|
||||
}
|
||||
|
||||
#! 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.span);
|
||||
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.span);
|
||||
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.span);
|
||||
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.span);
|
||||
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.span);
|
||||
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;
|
||||
}
|
||||
|
||||
#! What a trait the compiler decides asks of a type it decides: what `signature`
|
||||
#! asks of a function, what a pointer points at or a reference refers to, its
|
||||
#! `target`, an array's `element`, and the `args` a generic type is given.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param asked The declaration of the type the trait asks for.
|
||||
#! @returns The type, or 0 where the trait asking is none of these, or the type
|
||||
#! is not one it decides.
|
||||
pub def checker::decided_part(&mut this, kind: u32, asked: u32): u32 {
|
||||
val holder: u32 = this.decls.owners.p[asked];
|
||||
return 0 if holder == 0;
|
||||
val trait_name: u32 = this.decls.names.p[holder];
|
||||
return 0 if this.std_decl(trait_name) != holder;
|
||||
return this.signature_part(kind, asked) if trait_name == word::signature;
|
||||
|
||||
val plain := this.unalias(kind);
|
||||
val name: u32 = this.decls.names.p[asked];
|
||||
val of := this.types.kind_of(plain);
|
||||
if name == word::target && ((trait_name == word::pointer && of == ty::pointer) || (trait_name == word::reference && of == ty::reference)) {
|
||||
return this.types.first_of(plain);
|
||||
}
|
||||
if name == word::element && trait_name == word::array && of == ty::fixed {
|
||||
return this.types.first_of(plain);
|
||||
}
|
||||
if name == word::args && trait_name == word::generic && this.generic_instance(plain) {
|
||||
return this.type_args_pack(plain);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#! Whether a type is a generic type given its type arguments: a named type of
|
||||
#! a declaration with type parameters, its own or its owner's.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type, with no alias.
|
||||
#! @returns Whether it is.
|
||||
pub def checker::generic_instance(&this, kind: u32): bool {
|
||||
return this.types.kind_of(kind) == ty::named && this.types.part_count(kind) != 0;
|
||||
}
|
||||
|
||||
#! The pack of a generic type's type arguments, in the order they are written,
|
||||
#! with what a pack parameter was given in its place. Where that is a pack whose
|
||||
#! types are not known, it is that pack where it is the only argument, since
|
||||
#! where the types after it go is not known until it is.
|
||||
#! @param this The checker.
|
||||
#! @param kind The generic type, with no alias.
|
||||
#! @returns The pack, or 0 where it cannot be one.
|
||||
pub def checker::type_args_pack(&mut this, kind: u32): u32 {
|
||||
var items := vector::<u32>::new();
|
||||
val count := this.types.part_count(kind);
|
||||
for i in 0..count {
|
||||
val part := this.types.part_at(kind, i as u32);
|
||||
if this.types.kind_of(part) != ty::pack {
|
||||
items.append(part);
|
||||
continue;
|
||||
}
|
||||
if this.types.is_open_pack(part) {
|
||||
return count == 1 ? part : 0;
|
||||
}
|
||||
items.extend(this.types.parts_view(part));
|
||||
}
|
||||
return this.types.pack(items.span, 0);
|
||||
}
|
||||
|
||||
#! The value of a constant a trait the compiler decides asks of a type it
|
||||
#! decides: whether a pointer or reference writes its target, `mutable`, and how
|
||||
#! many elements an array holds, `length`.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type.
|
||||
#! @param asked The declaration of the constant the trait asks for.
|
||||
#! @param value Where the value is written.
|
||||
#! @returns Whether the constant is one of these and the type decides it.
|
||||
pub def checker::decided_value(&mut this, kind: u32, asked: u32, value: &mut constant): bool {
|
||||
return false if asked == 0 || kind == bt::error || this.decls.kinds.p[asked] != dk::variable;
|
||||
val holder: u32 = this.decls.owners.p[asked];
|
||||
return false if holder == 0;
|
||||
val trait_name: u32 = this.decls.names.p[holder];
|
||||
return false if this.std_decl(trait_name) != holder;
|
||||
|
||||
val plain := this.unalias(kind);
|
||||
val name: u32 = this.decls.names.p[asked];
|
||||
val of := this.types.kind_of(plain);
|
||||
if name == word::mutable && ((trait_name == word::pointer && of == ty::pointer) || (trait_name == word::reference && of == ty::reference)) {
|
||||
value = constant::truth(this.types.second_of(plain) == 1);
|
||||
return true;
|
||||
}
|
||||
# Within a template, a length only each instance knows is no constant there.
|
||||
if name == word::length && trait_name == word::array && of == ty::fixed && this.types.part_count(plain) == 0 {
|
||||
value = constant::integer(this.types.second_of(plain) as u64, false);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! The constant one of a type parameter's bounds, or those an `if const` the
|
||||
#! instance decided gave it, asks for of the name, where the bound is a trait the
|
||||
#! compiler decides and the type given decides it, as `T::mutable` where
|
||||
#! `T: pointer` is given `*mut u8`.
|
||||
#! @param this The checker.
|
||||
#! @param kind The type given.
|
||||
#! @param param The type parameter's declaration.
|
||||
#! @param name The ID of the name.
|
||||
#! @returns The constant's declaration, or 0.
|
||||
pub def checker::decided_constant_of_bounds(&mut this, kind: u32, param: u32, name: u32): u32 {
|
||||
this.resolve(param);
|
||||
var bounds := vector::<u32>::new();
|
||||
val run: u32 = this.decls.children.p[param];
|
||||
for i in 0..this.decls.list_length(run) {
|
||||
bounds.append(this.decls.list_at(run, i as u32));
|
||||
}
|
||||
for i in 0..this.proved_params.length {
|
||||
if this.proved_params[i] == param {
|
||||
bounds.append(this.proved_bounds[i]);
|
||||
}
|
||||
}
|
||||
for &bound in bounds {
|
||||
continue if this.types.kind_of(bound) != ty::named;
|
||||
val member := this.trait_member(this.types.first_of(bound), name);
|
||||
var value := constant {};
|
||||
return member if this.decided_value(kind, member, &mut value);
|
||||
}
|
||||
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,528 @@
|
||||
#! @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.table_node_of(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.table_node_of(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.span);
|
||||
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.span);
|
||||
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.span);
|
||||
}
|
||||
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.span);
|
||||
|
||||
# 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.span);
|
||||
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.span);
|
||||
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.span);
|
||||
}
|
||||
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;
|
||||
val kinds := this.attribute_types(held.decl, held.param);
|
||||
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();
|
||||
val made := this.attribute_decls(held.decl, held.param);
|
||||
for &each in made {
|
||||
items.append(this.describe_decl(each, 0));
|
||||
}
|
||||
this.set_reflected(node, rk::list, items.span);
|
||||
return result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
#! The attributes written on a declaration, or on one of a function's
|
||||
#! parameters, 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.
|
||||
#! @param param One more than the index of the parameter, or 0 for the
|
||||
#! declaration itself.
|
||||
#! @returns The attributes' declarations.
|
||||
def checker::attribute_decls(&mut this, id: u32, param: u32 = 0): vector<u32> {
|
||||
var made := vector::<u32>::new();
|
||||
val kinds := this.attribute_types(id, param);
|
||||
val file: u32 = this.decls.files.p[id];
|
||||
val saved := this.at;
|
||||
this.use_table(this.units[file].table);
|
||||
val attrs := this.attributes_at(id, param);
|
||||
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 := file_node { file = file, node = 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.span);
|
||||
val decl := this.decls.add(dk::attribute, this.names.intern(&name.span), 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.table_node_of(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, or before one of
|
||||
#! a function's parameters, resolved where the declaration is.
|
||||
#! @param this The checker.
|
||||
#! @param id The declaration.
|
||||
#! @param param One more than the index of the parameter, or 0 for the
|
||||
#! declaration itself.
|
||||
#! @returns The attributes' types, in the order they are written.
|
||||
pub def checker::attribute_types(&mut this, id: u32, param: u32 = 0): vector<u32> {
|
||||
var made := vector::<u32>::new();
|
||||
val saved := this.at;
|
||||
this.enter_decl(id, 0);
|
||||
val attrs := this.attributes_at(id, param);
|
||||
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.quiet++;
|
||||
val kind := this.resolve_type(node);
|
||||
this.quiet--;
|
||||
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.span);
|
||||
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 || this.at.given;
|
||||
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, as
|
||||
# is a constant of a trait, worked out for each type or list of arguments,
|
||||
# but of a sealed trait without parameters, which is one constant.
|
||||
val decl := this.at.decl;
|
||||
return !this.sealed_alone(decl) if this.decls.kinds.p[decl] == dk::variable && this.trait_asks(decl);
|
||||
return this.decls.kinds.p[decl] == dk::function && this.typed_default(decl);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,415 @@
|
||||
#! @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 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;
|
||||
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.span.data;
|
||||
this.at.tokens = syntax.node_tokens.span.data;
|
||||
this.at.lefts = syntax.node_lefts.span.data;
|
||||
this.at.rights = syntax.node_rights.span.data;
|
||||
this.at.extras = syntax.extras.span.data;
|
||||
this.at.names = syntax.token_names.span.data;
|
||||
this.at.tkinds = syntax.token_kinds.span.data;
|
||||
}
|
||||
|
||||
#! The table holding the node's results: the one being written, or the one it
|
||||
#! was made within that holds the node, or, outside an instance, the one of
|
||||
#! the file's own that does, 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];
|
||||
return table if node >= held.base && node - held.base < held.count;
|
||||
table = held.parent;
|
||||
steps++;
|
||||
}
|
||||
return checker::no_table if this.tables.p[this.at.table].instance != 0;
|
||||
return this.file_table_of(this.at.file, node);
|
||||
}
|
||||
|
||||
#! The table of a file's own holding a node's results: of the nodes it was
|
||||
#! parsed with, or of those an edit added.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param node The node.
|
||||
#! @returns The table's index, or `no_table` where the node is past the file's.
|
||||
pub def checker::file_table_of(&this, file: u32, node: u32): u32 {
|
||||
val segments := &this.units[file].segments;
|
||||
var low: u64 = 0;
|
||||
var high := segments.length;
|
||||
while low < high {
|
||||
val middle := (low + high) / 2;
|
||||
val held: rtable = this.tables.p[segments[middle]];
|
||||
if node < held.base {
|
||||
high = middle;
|
||||
} else if node - held.base >= held.count {
|
||||
low = middle + 1;
|
||||
} else {
|
||||
return segments[middle];
|
||||
}
|
||||
}
|
||||
return checker::no_table;
|
||||
}
|
||||
|
||||
#! Where a node's results are among its file's own, in the result vectors.
|
||||
#! @param this The checker.
|
||||
#! @param file The file.
|
||||
#! @param node The node.
|
||||
#! @returns The index of its results, or past their end where no table of the
|
||||
#! file holds it.
|
||||
pub def checker::file_row(&this, file: u32, node: u32): u64 {
|
||||
val table := this.file_table_of(file, 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;
|
||||
}
|
||||
|
||||
#! 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 node as the table holding its results holds it, for the results kept
|
||||
#! apart from the tables: the one being written, or one around it.
|
||||
#! @param this The checker.
|
||||
#! @param node The node.
|
||||
#! @returns Its table and node.
|
||||
pub def checker::table_node_of(&this, node: u32): table_node {
|
||||
val table := this.holding(node);
|
||||
return table_node { table = table == checker::no_table ? this.at.table : table, node = 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.table_node_of(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.table_node_of(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.value_known(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.table_node_of(node), id);
|
||||
this.set_flag(node, rf::known);
|
||||
}
|
||||
|
||||
#! The ID among `knowns` of a number, `bool`, character, member of an enum, or
|
||||
#! float, of no type in particular, as the values of nodes and declarations
|
||||
#! are kept, interned, 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 value.
|
||||
#! @returns Its ID.
|
||||
pub def checker::value_known(&mut this, value: constant): u32 {
|
||||
val hash := mix(mix(value.word, value.negative ? 1 : 0), value.floating ? 1 : 0);
|
||||
var walk := this.value_index.walk(hash);
|
||||
var at := this.value_index.next(&mut walk);
|
||||
while at != 0 {
|
||||
return at - 1 if this.knowns.p[at - 1].value.same(&value);
|
||||
at = this.value_index.next(&mut walk);
|
||||
}
|
||||
val id := this.intern_known(known { kind = value.floating ? kk::real : kk::number, value = value }, span::<u32>::blank(), "");
|
||||
this.value_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.knowns.p[this.r_values.get_or(&at, 0)].value : constant {};
|
||||
}
|
||||
val key := this.table_node_of(node);
|
||||
return this.knowns.p[this.values.get_or(&key, 0)].value;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
#! @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 - 1;
|
||||
}
|
||||
|
||||
#! 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;
|
||||
|
||||
# What the body checked around a declaration checked within it binds is no
|
||||
# binding of the declaration's.
|
||||
val at: u32 = this.innermost[name];
|
||||
return 0 if at < this.at.marks;
|
||||
return this.bind_values[at];
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,583 @@
|
||||
#! @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.
|
||||
matched, #! `match const T { ... }` as a type, while `T` holds a type parameter: `parts` are `T`, then a pattern and the type it gives for each of the arms' patterns, a pattern of 0 being `else`, and `first` and `second` the file and node it was written at.
|
||||
}
|
||||
|
||||
#! 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.
|
||||
reported = 0x40, #! A `match const` type no arm of which fits, or that is not chosen within as many steps as aliases are followed, was reported.
|
||||
}
|
||||
|
||||
#! 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>::blank();
|
||||
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>::blank());
|
||||
}
|
||||
|
||||
#! 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>::blank());
|
||||
}
|
||||
|
||||
#! 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>::blank());
|
||||
}
|
||||
|
||||
#! 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.span);
|
||||
}
|
||||
|
||||
#! 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>::blank());
|
||||
}
|
||||
|
||||
#! 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.span) : this.pack(items.span, 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>::blank());
|
||||
}
|
||||
# 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,55 @@
|
||||
#! @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.
|
||||
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.
|
||||
|
||||
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,157 @@
|
||||
#! @file keyed.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the two ways a node is told apart from the nodes of other files,
|
||||
#! whose indexes count from 0 as its own file's do: a `file_node`, its file and
|
||||
#! itself, and a `table_node`, the result table it was checked in and itself,
|
||||
#! which tells a node of a template checked for one instance from the same node
|
||||
#! checked for another. What is kept of nodes across files or tables is keyed
|
||||
#! by one of these, in a `keyed` map, which takes no bare node.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! What a `keyed` map's keys are: values each one word.
|
||||
pub trait keyable {
|
||||
#! The word the value is, which no other value of its type is.
|
||||
#! @param this The value.
|
||||
#! @returns The word.
|
||||
def key(&this): u64;
|
||||
}
|
||||
|
||||
#! A node of a file.
|
||||
pub struct file_node : keyable, hashable, equatable {
|
||||
pub var file: u32; #! The file's index.
|
||||
pub var node: u32; #! The node, among the file's.
|
||||
}
|
||||
|
||||
#! The word a file's node is: its file, then the node.
|
||||
#! @param this The file's node.
|
||||
#! @returns The word.
|
||||
pub def file_node::key(&this): u64 {
|
||||
return pair_key(this.file, this.node);
|
||||
}
|
||||
|
||||
#! Hashes a file's node, as a map keyed by them finds it.
|
||||
#! @param this The file's node.
|
||||
#! @returns The hash.
|
||||
pub def file_node::hash(&this): u64 {
|
||||
return mix(this.key(), 0);
|
||||
}
|
||||
|
||||
#! Whether two are the same node of the same file.
|
||||
#! @param this The file's node.
|
||||
#! @param other The other.
|
||||
#! @returns Whether they are.
|
||||
pub def file_node::equals(&this, other: &file_node): bool {
|
||||
return this.file == other.file && this.node == other.node;
|
||||
}
|
||||
|
||||
#! A node as a result table holds it: the table of its file, of an instance of
|
||||
#! a generic, or of a pass of `for const`, and the node.
|
||||
pub struct table_node : keyable, hashable, equatable {
|
||||
pub var table: u32; #! The result table.
|
||||
pub var node: u32; #! The node, among its file's.
|
||||
}
|
||||
|
||||
#! The word a table's node is: its table, then the node.
|
||||
#! @param this The table's node.
|
||||
#! @returns The word.
|
||||
pub def table_node::key(&this): u64 {
|
||||
return pair_key(this.table, this.node);
|
||||
}
|
||||
|
||||
#! Hashes a table's node, as a map keyed by them finds it.
|
||||
#! @param this The table's node.
|
||||
#! @returns The hash.
|
||||
pub def table_node::hash(&this): u64 {
|
||||
return mix(this.key(), 0);
|
||||
}
|
||||
|
||||
#! Whether two are the same node of the same table.
|
||||
#! @param this The table's node.
|
||||
#! @param other The other.
|
||||
#! @returns Whether they are.
|
||||
pub def table_node::equals(&this, other: &table_node): bool {
|
||||
return this.table == other.table && this.node == other.node;
|
||||
}
|
||||
|
||||
#! A map from keys of one kind, as nodes of files or of tables, to IDs, held in a `keymap` by
|
||||
#! the word each key is, which takes no key of another kind.
|
||||
pub struct keyed<K> : owning where K: keyable {
|
||||
var map: keymap; #! The IDs, by the word each key is.
|
||||
}
|
||||
|
||||
#! Makes a map holding nothing.
|
||||
#! @returns The map.
|
||||
pub def keyed<K>::new(): keyed<K> {
|
||||
return keyed::<K> { map = keymap::new() };
|
||||
}
|
||||
|
||||
#! Lets go of what the map holds.
|
||||
#! @param this The map.
|
||||
pub def keyed<K>::close(&mut this): void {
|
||||
this.map.close();
|
||||
}
|
||||
|
||||
#! How many keys the map holds.
|
||||
#! @param this The map.
|
||||
#! @returns How many.
|
||||
pub val keyed<K>::length: u64 { get => this.map.length; }
|
||||
|
||||
#! The ID a key has.
|
||||
#! @param this The map.
|
||||
#! @param at The key.
|
||||
#! @returns The ID, or nothing where the key has none.
|
||||
pub def keyed<K>::get(&this, at: &K): maybe<u32> {
|
||||
return this.map.get(&at.key());
|
||||
}
|
||||
|
||||
#! The ID a key has, or another where it has none.
|
||||
#! @param this The map.
|
||||
#! @param at The key.
|
||||
#! @param missing What is given where the key has none.
|
||||
#! @returns The ID.
|
||||
pub def keyed<K>::get_or(&this, at: &K, missing: u32): u32 {
|
||||
return this.map.get_or(&at.key(), missing);
|
||||
}
|
||||
|
||||
#! Whether a key has an ID.
|
||||
#! @param this The map.
|
||||
#! @param at The key.
|
||||
#! @returns Whether it has.
|
||||
pub def keyed<K>::contains(&this, at: &K): bool {
|
||||
return this.map.contains(&at.key());
|
||||
}
|
||||
|
||||
#! Gives a key an ID, in place of any it had.
|
||||
#! @param this The map.
|
||||
#! @param at The key.
|
||||
#! @param value The ID.
|
||||
pub def keyed<K>::set(&mut this, at: K, value: u32): void {
|
||||
this.map.set(at.key(), value);
|
||||
}
|
||||
|
||||
#! Gives a key an ID, where it has none.
|
||||
#! @param this The map.
|
||||
#! @param at The key.
|
||||
#! @param value The ID.
|
||||
#! @returns Whether the key had none, and has the ID now.
|
||||
pub def keyed<K>::insert(&mut this, at: K, value: u32): bool {
|
||||
return this.map.insert(at.key(), value);
|
||||
}
|
||||
|
||||
#! Takes a key's ID away, where it has one.
|
||||
#! @param this The map.
|
||||
#! @param at The key.
|
||||
pub def keyed<K>::remove(&mut this, at: &K): void {
|
||||
this.map.remove(&at.key());
|
||||
}
|
||||
|
||||
#! Takes every key's ID away.
|
||||
#! @param this The map.
|
||||
pub def keyed<K>::clear(&mut this): void {
|
||||
this.map.clear();
|
||||
}
|
||||
@@ -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.span.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);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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.span.upper_bound(&offset) - 1;
|
||||
return place {
|
||||
line = (low + 1) as u32,
|
||||
column = offset - this[low] + 1
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
#! @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. Each
|
||||
# is interned outside its contract, which a program built without checks
|
||||
# leaves out.
|
||||
for &each in _known {
|
||||
val id := made.intern(each.text);
|
||||
expects(id == each.id);
|
||||
}
|
||||
val this_id := made.intern("this");
|
||||
val get_id := made.intern("get");
|
||||
val set_id := made.intern("set");
|
||||
val type_of_id := made.intern("type_of");
|
||||
val old_id := made.intern("old");
|
||||
val self_id := made.intern("self");
|
||||
expects(this_id == names::this_id);
|
||||
expects(get_id == names::get_id);
|
||||
expects(set_id == names::set_id);
|
||||
expects(type_of_id == names::type_of_id);
|
||||
expects(old_id == names::old_id);
|
||||
expects(self_id == 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.span;
|
||||
}
|
||||
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 block[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`.
|
||||
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`.
|
||||
kept, #! `kept`.
|
||||
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`.
|
||||
span_of, #! `span_of`, which `x[a:n]` calls where `x` is no view.
|
||||
slice_of, #! `slice_of`, which it calls where `x` can be written.
|
||||
main, #! `main`.
|
||||
some, #! `some`.
|
||||
none, #! `none`.
|
||||
error, #! `error`.
|
||||
os, #! `os`.
|
||||
arch, #! `arch`.
|
||||
backend, #! `backend`.
|
||||
reference, #! `reference`.
|
||||
array, #! `array`.
|
||||
generic, #! `generic`.
|
||||
target, #! `target`, what `pointer` and `reference` name a type's target by.
|
||||
mutable, #! `mutable`, what they name whether it writes the target by.
|
||||
element, #! `element`, what `array` names a type's elements by.
|
||||
args, #! `args`, what `generic` names a type's arguments by.
|
||||
sealed, #! `sealed`.
|
||||
}
|
||||
|
||||
#! 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[93] = [
|
||||
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 = "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 = "kept", id = word::kept },
|
||||
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 = "span_of", id = word::span_of },
|
||||
names::known { text = "slice_of", id = word::slice_of },
|
||||
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 },
|
||||
names::known { text = "reference", id = word::reference },
|
||||
names::known { text = "array", id = word::array },
|
||||
names::known { text = "generic", id = word::generic },
|
||||
names::known { text = "target", id = word::target },
|
||||
names::known { text = "mutable", id = word::mutable },
|
||||
names::known { text = "element", id = word::element },
|
||||
names::known { text = "args", id = word::args },
|
||||
names::known { text = "sealed", id = word::sealed },
|
||||
];
|
||||
@@ -0,0 +1,138 @@
|
||||
#! @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.
|
||||
type_match, #! `match const T { ... }` as a type: the type it chooses by, and arms whose patterns are traits or types and whose bodies are types.
|
||||
type_cond, #! `C ? A : B` as a type: the constant it chooses by, and a record of the types it chooses from.
|
||||
|
||||
# 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...`, or a field holding a value of each of a pack's types, `name: Ts...`.
|
||||
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,64 @@
|
||||
#! @file node_walk.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the walk of a node of the syntax tree and the nodes under it, which
|
||||
#! the scans lowering makes of what a body names share, and the checker's writing
|
||||
#! of an expression as it is written.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! A walk of a node of the syntax tree and the nodes under it, each before the
|
||||
#! nodes it holds. The walk goes under a node only where it is asked to, so a
|
||||
#! scan may pass over what a node holds, or go under only some of it.
|
||||
pub struct node_walk {
|
||||
var todo: vector<u32>; #! The nodes yet to be given, the next last, 0 standing for one absent.
|
||||
}
|
||||
|
||||
#! Walks a node and the nodes under it.
|
||||
#! @param node The node, or 0 for none.
|
||||
#! @returns The walk.
|
||||
pub def node_walk::new(node: u32): node_walk {
|
||||
var made := node_walk { todo = vector::<u32>::new() };
|
||||
made.todo.append(node);
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Whether the walk has another node to give, passing over those absent.
|
||||
#! @param this The walk.
|
||||
#! @returns Whether it has.
|
||||
pub def node_walk::more(&mut this): bool {
|
||||
# It answers from within the loop, which keeps it small enough to be inlined.
|
||||
while this.todo.length != 0 {
|
||||
return true if this.todo.last != 0;
|
||||
this.todo.truncate();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Gives the next node, once `more` says there is one.
|
||||
#! @param this The walk.
|
||||
#! @returns The node.
|
||||
pub def node_walk::next(&mut this): u32 {
|
||||
val at: u32 = this.todo.last;
|
||||
this.todo.truncate();
|
||||
return at;
|
||||
}
|
||||
|
||||
#! Goes under a node: the nodes it holds are given next, the last its shape
|
||||
#! lists first.
|
||||
#! @param this The walk.
|
||||
#! @param tree The syntax tree.
|
||||
#! @param node The node.
|
||||
pub def node_walk::enter(&mut this, tree: &syntax, node: u32): void {
|
||||
tree.children(node, &mut this.todo);
|
||||
}
|
||||
|
||||
#! Goes under a node to one node it holds only, which is given next.
|
||||
#! @param this The walk.
|
||||
#! @param node The node held, or 0 for none.
|
||||
pub def node_walk::add(&mut this, node: u32): void {
|
||||
this.todo.append(node);
|
||||
}
|
||||
@@ -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,129 @@
|
||||
#! @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;
|
||||
# Whether the type about to be parsed is what `as` or `is` takes, where a `?`
|
||||
# after it goes on with the expression's ternary rather than a type's.
|
||||
var plain_type: bool;
|
||||
var type_argument: bool; #! Whether the type `type_expr` reads next is a type argument, where a condition is one only where a type follows its `?`, as `T is integer ? 4 : 8` is a constant.
|
||||
|
||||
# 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,923 @@
|
||||
#! @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.span;
|
||||
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) {
|
||||
# A parameter's attributes come before its name, as a declaration's do. An
|
||||
# anonymous function's parameters, which are no declaration's, take none.
|
||||
val attrs := this.check(tk::attr) ? this.attributes() : 0;
|
||||
if lambda && attrs != 0 {
|
||||
this.report(ec::token, "An anonymous function's parameters take no attributes; a declared function's do.");
|
||||
}
|
||||
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, attrs)));
|
||||
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), 0));
|
||||
}
|
||||
|
||||
#! 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();
|
||||
}
|
||||
|
||||
# `name: Ts...` holds a value of each of a pack's types, which only a struct's
|
||||
# field does, as the checker says.
|
||||
var packed := false;
|
||||
if type_expr != 0 && this.syntax.node_kinds[type_expr] != nk::spread && this.check(tk::spread) {
|
||||
this.advance();
|
||||
packed = true;
|
||||
}
|
||||
|
||||
# `{` 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 packed {
|
||||
this.report(ec::token, "A property's value is one value, so its type is no pack.");
|
||||
}
|
||||
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)
|
||||
| parser::bit(packed, nf::variadic);
|
||||
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. A
|
||||
#! `get mut` reads it where the value can be written, beside or instead of the
|
||||
#! `get`, as a method's `&mut this` overload is called there.
|
||||
#! @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 writer := 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;
|
||||
}
|
||||
|
||||
# `get mut` is the `get` of a value that can be written.
|
||||
val writes := get && this.peek(1) == tk::kw_mut;
|
||||
if (get && !writes && getter) || (writes && writer) || (set && setter) {
|
||||
this.fail(ec::token, writes
|
||||
? "The property already has a `get mut`."
|
||||
: get ? "The property already has a `get`." : "The property already has a `set`.");
|
||||
break;
|
||||
}
|
||||
|
||||
if writes && in_trait {
|
||||
this.fail(ec::token,
|
||||
"A trait asks for a property's `get` and `set`; a `get mut` is the implementer's own.");
|
||||
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, writes));
|
||||
getter = getter || (get && !writes);
|
||||
writer = writer || writes;
|
||||
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 && !writer {
|
||||
this.report_at(declared.name, ec::decl, "A property is read through `get`, or `get mut`, 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`, `get mut`, 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 `get mut` and a `set` write, and a `set`'s `value`, of the property's
|
||||
#! type. `=>` gives what a getter 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 a getter.
|
||||
#! @param writes Whether it is the `get mut`, taking `&mut this`.
|
||||
#! @returns The `accessor` node, or an `error` node.
|
||||
def parser::accessor(&mut this, exported: bool, methods: bool, get: bool, writes: bool): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
if writes {
|
||||
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 || writes, nf::mutable) | nf::implied as u32, 0)));
|
||||
if !get {
|
||||
this.push(this.make_node(nk::param, token, 0, this.make_record(0, nf::implied as u32, 0)));
|
||||
}
|
||||
}
|
||||
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,349 @@
|
||||
#! @file expressions.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the expression parser, a Pratt parser, which reads each operator
|
||||
#! by the binding power `token_powers` gives it. Prefix and postfix operators,
|
||||
#! casts, `is` tests, ternaries, `else` fallbacks, calls, indexes, and members
|
||||
#! are each parsed here.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! How tightly each operator binds, loosest first. An operator continues an
|
||||
#! expression only where it binds tighter than what the expression began under.
|
||||
enum parser::bp : u32 {
|
||||
none, #! Nothing has begun.
|
||||
assign, #! `=`, `+=`, and the rest, which group to the right.
|
||||
fallback, #! `x else y`, which groups to the right.
|
||||
ternary, #! `c ? a : b`, which groups to the right.
|
||||
range, #! `a..b` and `a..=b`.
|
||||
logor, #! `||`
|
||||
logand, #! `&&`
|
||||
bitor, #! `|`
|
||||
bitxor, #! `^`
|
||||
bitand, #! `&`
|
||||
equality, #! `==` and `!=`
|
||||
compare, #! `<`, `<=`, `>`, and `>=`
|
||||
shift, #! `<<` and `>>`
|
||||
sum, #! `+` and `-`
|
||||
product, #! `*`, `/`, and `%`
|
||||
cast, #! `as` and `is`, after a prefix operator's operand, so `-x as u8` is `(-x) as u8`.
|
||||
prefix, #! What a prefix operator applies to.
|
||||
postfix, #! Calls, indexing, members, `++`, and `--`.
|
||||
}
|
||||
|
||||
#! An expression, where struct literals are allowed.
|
||||
#! @param this The parser.
|
||||
#! @returns The expression's node, or an `error` node.
|
||||
def parser::expression(&mut this): u32 {
|
||||
return this.pratt(parser::bp::none, true);
|
||||
}
|
||||
|
||||
#! The expression of a condition, or of what a `for` loop or `match` takes,
|
||||
#! where `{` begins the block after it rather than a struct literal.
|
||||
#! @param this The parser.
|
||||
#! @returns The expression's node, or an `error` node.
|
||||
def parser::condition_expr(&mut this): u32 {
|
||||
return this.pratt(parser::bp::none, false);
|
||||
}
|
||||
|
||||
#! Parses an expression by precedence climbing: an operand, then each operator
|
||||
#! binding tighter than `min` with what it applies to.
|
||||
#! @param this The parser.
|
||||
#! @param min The power an operator must bind tighter than to be taken.
|
||||
#! @param structs Whether a name followed by `{` is a struct literal, which it
|
||||
#! is not in conditions, so that `if x {` opens the block. It
|
||||
#! is passed down rather than kept on the parser, so nothing
|
||||
#! has to put it back.
|
||||
#! @returns The expression's node, or an `error` node.
|
||||
def parser::pratt(&mut this, min: parser::bp, structs: bool): u32 {
|
||||
return this.error_here() if !this.enter();
|
||||
|
||||
var left := this.prefix(structs);
|
||||
while true {
|
||||
val power := this.power(left);
|
||||
break if power as u32 <= min as u32;
|
||||
left = this.infix(left, power, structs);
|
||||
}
|
||||
|
||||
this.leave();
|
||||
return left;
|
||||
}
|
||||
|
||||
#! How tightly the current token binds as an operator after `left`, or `none`
|
||||
#! where it ends the expression.
|
||||
#! @param this The parser.
|
||||
#! @param left The operand before the token.
|
||||
#! @returns The power.
|
||||
def parser::power(&this, left: u32): parser::bp {
|
||||
val power := token_powers[this.kind as u64];
|
||||
|
||||
# `else =>` is the last arm of a match, not a fallback, and `::<` gives type
|
||||
# arguments only to what a call gives, as `value_of(d)::<i64>`.
|
||||
return parser::bp::none if this.check(tk::kw_else) && this.peek(1) == tk::arrow;
|
||||
# Within type arguments, `>` closes them, and nothing is assigned.
|
||||
if this.angled {
|
||||
val kind := this.kind;
|
||||
return parser::bp::none if kind == tk::more || kind == tk::moreeq || kind == tk::rshift || kind == tk::rshifteq
|
||||
|| power == parser::bp::assign;
|
||||
}
|
||||
return parser::bp::none if this.check(tk::scope) && (this.syntax.node_kinds[left] != nk::call || this.peek(1) != tk::less);
|
||||
return power;
|
||||
}
|
||||
|
||||
#! An operand: a prefix operator and what it applies to, or a primary.
|
||||
#! @param this The parser.
|
||||
#! @param structs Whether a name followed by `{` is a struct literal.
|
||||
#! @returns The operand's node, or an `error` node.
|
||||
def parser::prefix(&mut this, structs: bool): u32 {
|
||||
val token := this.index;
|
||||
match this.kind {
|
||||
tk::minus, tk::negate, tk::bitnot, tk::increment, tk::decrement, tk::star => {
|
||||
this.advance();
|
||||
return this.make_node(nk::unary, token, this.pratt(parser::bp::prefix, structs));
|
||||
}
|
||||
tk::bitand => {
|
||||
this.advance();
|
||||
val mutable := this.accept(tk::kw_mut);
|
||||
val operand := this.pratt(parser::bp::prefix, structs);
|
||||
return this.make_node(nk::reference, token, operand, parser::bit(mutable, nf::mutable));
|
||||
}
|
||||
else => return this.primary(structs);
|
||||
}
|
||||
|
||||
return this.primary(structs);
|
||||
}
|
||||
|
||||
#! The operator at the current token applied to `left`, which binds as tightly
|
||||
#! as `power`. What follows an operator grouping to the right is parsed under
|
||||
#! the power just below its own, so another of it continues there.
|
||||
#! @param this The parser.
|
||||
#! @param left The operand before the operator.
|
||||
#! @param power How tightly the operator binds.
|
||||
#! @param structs Whether a name followed by `{` is a struct literal.
|
||||
#! @returns The node of the operator applied.
|
||||
def parser::infix(&mut this, left: u32, power: parser::bp, structs: bool): u32 {
|
||||
val token := this.index;
|
||||
match power {
|
||||
parser::bp::assign => {
|
||||
this.advance();
|
||||
return this.make_node(nk::assign, token, left, this.pratt(parser::bp::none, structs));
|
||||
}
|
||||
parser::bp::fallback => return this.fallback(left, structs);
|
||||
parser::bp::ternary => return this.ternary(left, structs);
|
||||
parser::bp::cast => return this.check(tk::kw_as) ? this.cast_to(left) : this.is_test(left);
|
||||
parser::bp::postfix => return this.postfix(left);
|
||||
parser::bp::range => {
|
||||
this.advance();
|
||||
return this.make_node(nk::range, token, left, this.pratt(power, structs));
|
||||
}
|
||||
else => {
|
||||
this.advance();
|
||||
return this.make_node(nk::binary, token, left, this.pratt(power, structs));
|
||||
}
|
||||
}
|
||||
|
||||
return left;
|
||||
}
|
||||
|
||||
#! `value else fallback`, which takes what a result or a maybe holds, or else
|
||||
#! what stands in for it: `else (e)` names the error, and a block standing in
|
||||
#! must leave, where an expression gives the value instead.
|
||||
#! @param this The parser.
|
||||
#! @param value The node of the value before `else`.
|
||||
#! @param structs Whether a name followed by `{` is a struct literal.
|
||||
#! @returns The `fallback` node.
|
||||
def parser::fallback(&mut this, value: u32, structs: bool): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
|
||||
# `(e)` names the error only before the block standing in, so `else (x)`
|
||||
# anywhere else is the value `x`.
|
||||
var error: u32 = 0;
|
||||
if this.check(tk::lparen) && this.peek(1) == tk::name && this.peek(2) == tk::rparen && this.peek(3) == tk::lbrace {
|
||||
this.advance();
|
||||
error = this.name_node("Expected the name of the error.");
|
||||
this.advance();
|
||||
}
|
||||
|
||||
val other := this.check(tk::lbrace)
|
||||
? this.block()
|
||||
: this.pratt(parser::bp::assign, structs);
|
||||
return this.make_node(nk::fallback, token, value, this.make_record(error, other));
|
||||
}
|
||||
|
||||
#! `cond ? then : else`. The branch taken where the condition holds ends at
|
||||
#! `:`, so it may be a fallback, as `ok ? parse(text) else 0 : 1`.
|
||||
#! @param this The parser.
|
||||
#! @param condition The condition's node.
|
||||
#! @param structs Whether a name followed by `{` is a struct literal.
|
||||
#! @returns The `ternary` node.
|
||||
def parser::ternary(&mut this, condition: u32, structs: bool): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
|
||||
val then := this.pratt(parser::bp::assign, structs);
|
||||
this.expect(tk::colon, "Expected `:` between the ternary branches.");
|
||||
val other := this.pratt(parser::bp::fallback, structs);
|
||||
return this.make_node(nk::ternary, token, condition, this.make_record(then, other));
|
||||
}
|
||||
|
||||
#! `x as T`.
|
||||
#! @param this The parser.
|
||||
#! @param value The node of the value converted.
|
||||
#! @returns The `cast` node.
|
||||
def parser::cast_to(&mut this, value: u32): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
if this.check(tk::kw_not) {
|
||||
this.fail(ec::token,
|
||||
"`not` follows `is`, which it denies; `as` converts a value and has nothing to deny.");
|
||||
}
|
||||
|
||||
this.plain_type = true;
|
||||
val target := this.type_expr();
|
||||
return this.make_node(nk::cast, token, value, target);
|
||||
}
|
||||
|
||||
#! `x is T`, `x is not field(value)`, and `x is (d)`.
|
||||
#! @param this The parser.
|
||||
#! @param value The node of what is tested.
|
||||
#! @returns The `is_test` node.
|
||||
def parser::is_test(&mut this, value: u32): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
|
||||
# `x is not T` denies the test, which saves writing `!(x is T)`.
|
||||
var flags := parser::bit(this.accept(tk::kw_not), nf::negated);
|
||||
|
||||
# `x is (d)` names the field of a union a declaration known while compiling
|
||||
# describes, as `x is field` would.
|
||||
if this.accept(tk::lparen) {
|
||||
val named := this.expression();
|
||||
this.expect(tk::rparen, "Expected `)` after the declaration naming the field.");
|
||||
flags |= nf::computed as u32;
|
||||
return this.make_node(nk::is_test, token, value, this.make_record(named, 0, flags));
|
||||
}
|
||||
|
||||
this.plain_type = true;
|
||||
val target := this.type_expr();
|
||||
|
||||
# `x is field(value)` names what the field holds, as an arm of a match does.
|
||||
var binding: u32 = 0;
|
||||
if this.accept(tk::lparen) {
|
||||
binding = this.binding();
|
||||
this.expect(tk::rparen, "Expected `)` after the name of the value.");
|
||||
}
|
||||
|
||||
return this.make_node(nk::is_test, token, value, this.make_record(target, binding, flags));
|
||||
}
|
||||
|
||||
#! The name given what a field holds, as `value` of `is field(value)`. `&name`
|
||||
#! and `&mut name` refer to the field where the union holds it, rather than
|
||||
#! naming a copy of what it holds.
|
||||
#! @param this The parser.
|
||||
#! @returns The `name` or `reference` node, or an `error` node.
|
||||
def parser::binding(&mut this): u32 {
|
||||
val detail := "Expected the name to give the value the field holds, as `is field(value)`.";
|
||||
return this.name_node(detail) if !this.check(tk::bitand);
|
||||
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
val mutable := this.accept(tk::kw_mut);
|
||||
return this.make_node(nk::reference, token, this.name_node(detail), parser::bit(mutable, nf::mutable));
|
||||
}
|
||||
|
||||
#! One postfix operator applied to `left`: a call, indexing or slicing, a
|
||||
#! member, type arguments, `++`, or `--`.
|
||||
#! @param this The parser.
|
||||
#! @param left The operand.
|
||||
#! @returns The node of the operator applied.
|
||||
def parser::postfix(&mut this, left: u32): u32 {
|
||||
val token := this.index;
|
||||
match this.kind {
|
||||
tk::lparen => {
|
||||
this.advance();
|
||||
val args := this.list(parser::item::argument, tk::rparen, "Expected `)` to close the arguments.");
|
||||
return this.make_node(nk::call, token, left, args);
|
||||
}
|
||||
tk::lbracket => return this.subscript(left);
|
||||
tk::dot => return this.member(left);
|
||||
tk::scope => {
|
||||
this.advance();
|
||||
return this.make_node(nk::type_args, token, left, this.type_args());
|
||||
}
|
||||
else => {
|
||||
this.advance();
|
||||
return this.make_node(nk::postfix, token, left);
|
||||
}
|
||||
}
|
||||
|
||||
return left;
|
||||
}
|
||||
|
||||
#! `xs[i]`, or a slice, `xs[a:n]`, either of whose bounds may be left out.
|
||||
#! @param this The parser.
|
||||
#! @param object The node of what is indexed.
|
||||
#! @returns The `index` or `slice` node.
|
||||
def parser::subscript(&mut this, object: u32): u32 {
|
||||
val token := this.index;
|
||||
val angled := this.angled;
|
||||
this.angled = false;
|
||||
this.advance();
|
||||
|
||||
val start := this.check(tk::colon) ? 0 : this.expression();
|
||||
if !this.accept(tk::colon) {
|
||||
this.expect(tk::rbracket, "Expected `]` to close the index.");
|
||||
this.angled = angled;
|
||||
return this.make_node(nk::index, token, object, start);
|
||||
}
|
||||
|
||||
val count := this.check(tk::rbracket) ? 0 : this.expression();
|
||||
this.expect(tk::rbracket, "Expected `]` to close the slice.");
|
||||
this.angled = angled;
|
||||
return this.make_node(nk::slice, token, object, this.make_record(start, count));
|
||||
}
|
||||
|
||||
#! `x.name`, `x.name::<T>`, or `x.(d)`, which names the member a declaration
|
||||
#! known while compiling describes.
|
||||
#! @param this The parser.
|
||||
#! @param object The node of the value.
|
||||
#! @returns The `member` or `member_of` node.
|
||||
def parser::member(&mut this, object: u32): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
if this.accept(tk::lparen) {
|
||||
val named := this.expression();
|
||||
this.expect(tk::rparen, "Expected `)` after the declaration naming the member.");
|
||||
return this.make_node(nk::member_of, token, object, named);
|
||||
}
|
||||
|
||||
if !this.check(tk::name) {
|
||||
this.fail(ec::ident, "Expected a member name after `.`.");
|
||||
return object;
|
||||
}
|
||||
|
||||
val name := this.index;
|
||||
this.advance();
|
||||
var types: u32 = 0;
|
||||
if this.at_value_args() {
|
||||
this.advance();
|
||||
types = this.type_args();
|
||||
}
|
||||
|
||||
return this.make_node(nk::member, name, object, types);
|
||||
}
|
||||
|
||||
#! An argument of a call. `...xs` spreads a view or a pack into the arguments,
|
||||
#! and is only an argument.
|
||||
#! @param this The parser.
|
||||
#! @returns The argument's node.
|
||||
def parser::argument(&mut this): u32 {
|
||||
return this.expression() if !this.check(tk::spread);
|
||||
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
return this.make_node(nk::unary, token, this.expression());
|
||||
}
|
||||
@@ -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,637 @@
|
||||
#! @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(this.scratch[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.
|
||||
const_arm, #! Of a `match const` used as a value, whose patterns are traits or types.
|
||||
type_arm, #! Of a `match const` that is a type, whose bodies are types too.
|
||||
}
|
||||
|
||||
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),
|
||||
parser::item::const_arm => this.arm(true, true),
|
||||
parser::item::type_arm => this.arm(true, true, 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,389 @@
|
||||
#! @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. `match const T` chooses by a type while compiling, its arms' patterns
|
||||
#! naming traits or types, and its node's token is the `const`.
|
||||
#! @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;
|
||||
var token := this.index;
|
||||
this.advance();
|
||||
val chosen := this.check(tk::kw_const);
|
||||
if chosen {
|
||||
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(chosen ? parser::item::const_arm : parser::item::value_arm, tk::rbrace,
|
||||
"Expected `,` between the arms, or `}` to close the match.")
|
||||
: this.arms(chosen);
|
||||
this.leave();
|
||||
return this.make_node(kind, token, subject, arms);
|
||||
}
|
||||
|
||||
#! Whether a value written in place begins here, as `4`, `-1`, `'a'`, `"a"`, or
|
||||
#! `true`, which a `match const` choosing by a constant takes as a pattern.
|
||||
#! @param this The parser.
|
||||
#! @returns Whether one does.
|
||||
def parser::written_value(&this): bool {
|
||||
val kind := this.peek(0);
|
||||
if kind == tk::minus {
|
||||
val next := this.peek(1);
|
||||
return next == tk::signed || next == tk::unsigned || next == tk::float;
|
||||
}
|
||||
return kind == tk::kw_true || kind == tk::kw_false || kind == tk::signed || kind == tk::unsigned
|
||||
|| kind == tk::float || kind == tk::char || kind == tk::string;
|
||||
}
|
||||
|
||||
#! The arms of a match statement, through its `}`.
|
||||
#! @param this The parser.
|
||||
#! @param chosen Whether it is a `match const`, whose patterns are traits or
|
||||
#! types.
|
||||
#! @returns The run of `match_arm` nodes.
|
||||
def parser::arms(&mut this, chosen: bool): u32 {
|
||||
val mark := this.mark;
|
||||
while !this.check(tk::rbrace) && !this.check(tk::eof) {
|
||||
this.push(this.arm(false, chosen));
|
||||
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)`. A `match const`'s
|
||||
#! patterns are types instead, as `integer` or `&strview`, or values written in
|
||||
#! place, as `4` or `true`, where it chooses by a constant, and where it is a
|
||||
#! type, so is what each arm gives.
|
||||
#! @param this The parser.
|
||||
#! @param value Whether the match is used as a value.
|
||||
#! @param chosen Whether it is a `match const`.
|
||||
#! @param typed Whether it is a type, whose arms give types.
|
||||
#! @returns The `match_arm` node, or an `error` node.
|
||||
def parser::arm(&mut this, value: bool, chosen: bool = false, typed: bool = false): u32 {
|
||||
val token := this.index;
|
||||
var patterns: u32 = 0;
|
||||
if !this.accept(tk::kw_else) {
|
||||
if chosen {
|
||||
val mark := this.mark;
|
||||
while true {
|
||||
this.push(this.written_value() ? this.condition_expr() : this.type_expr());
|
||||
break if !this.accept(tk::comma);
|
||||
}
|
||||
patterns = this.make_run(mark);
|
||||
} 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 typed {
|
||||
body = this.type_expr();
|
||||
} else 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,627 @@
|
||||
#! @file types.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the parsing of types: names and paths with their type arguments,
|
||||
#! references, arrays, `type_of`, and the type parameters of declarations.
|
||||
|
||||
module sakura::analyzer;
|
||||
|
||||
|
||||
#! What may follow the segments of a path as type arguments.
|
||||
enum parser::args {
|
||||
plain, #! Nothing, as in imports.
|
||||
types, #! Type arguments after `<`, as in `box<i64>`.
|
||||
values, #! Type arguments after `::<`, as in `box::<i64>`.
|
||||
}
|
||||
|
||||
#! A type, as `&mut T`, `*u8`, `T[4]`, `def(T): U`, or `std::list<T>`, which
|
||||
#! is also what follows `as` and `is`, so `x as i32 | y` remains a bitwise or.
|
||||
#! @param this The parser.
|
||||
#! @returns The type's node, or an `error` node.
|
||||
def parser::type_expr(&mut this): u32 {
|
||||
return this.error_here() if !this.enter();
|
||||
# What `as` and `is` take goes on with the expression's `?`, not a type's.
|
||||
val chooses := !this.plain_type;
|
||||
this.plain_type = false;
|
||||
val argument := this.type_argument;
|
||||
this.type_argument = false;
|
||||
|
||||
# `C ? A : B` chooses by a constant: a name or a path, which `!` may deny, a
|
||||
# call, or an expression in parentheses, as `(N > 4) ? A : B`.
|
||||
var condition: u32 = 0;
|
||||
var made: u32 = 0;
|
||||
if chooses && this.check(tk::negate) {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
condition = this.make_node(nk::unary, token, this.condition_name(this.type_name()));
|
||||
if !this.check(tk::quest) {
|
||||
this.fail(ec::token, "Expected `?`: a type is chosen by a constant, as `!MUTABLE ? &T : &mut T`.");
|
||||
}
|
||||
made = condition;
|
||||
} else if chooses && this.check(tk::lparen) && this.chooses_type(0) {
|
||||
val angled := this.angled;
|
||||
this.angled = false;
|
||||
condition = this.pratt(parser::bp::ternary, true);
|
||||
this.angled = angled;
|
||||
made = condition;
|
||||
} else if chooses && this.check(tk::name) && this.call_chooses_type() {
|
||||
# A call is a condition too, as `small(N) ? A : B`.
|
||||
val angled := this.angled;
|
||||
this.angled = false;
|
||||
condition = this.pratt(parser::bp::ternary, true);
|
||||
this.angled = angled;
|
||||
made = condition;
|
||||
} else if this.check(tk::star) || this.check(tk::bitand) {
|
||||
val kind := this.check(tk::star) ? nk::type_ptr : nk::type_ref;
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
val mutable := this.accept(tk::kw_mut);
|
||||
# What `as` and `is` take stays plain within it, as `x as *T != null`.
|
||||
this.plain_type = !chooses;
|
||||
made = this.make_node(kind, token, this.type_expr(), parser::bit(mutable, nf::mutable));
|
||||
} else {
|
||||
made = this.type_postfix();
|
||||
if chooses && this.check(tk::quest) && this.syntax.node_kinds[made] == nk::type_name && parser::begins_type(this.peek(1)) {
|
||||
condition = this.condition_name(made);
|
||||
} else if chooses && this.syntax.node_kinds[made] == nk::type_name && parser::continues_condition(this.kind)
|
||||
&& (!argument || this.condition_chooses_type()) {
|
||||
# A test of a type is a condition too, as `T is reference ? T::target : T`,
|
||||
# and so is a name compared, as `N == 4`, or joined, as `M && N == 4`.
|
||||
condition = this.condition_after(this.condition_name(made));
|
||||
if !this.check(tk::quest) {
|
||||
this.fail(ec::token, "Expected `?`: a condition chooses a type, as `T is reference ? T::target : T`.");
|
||||
}
|
||||
made = condition;
|
||||
}
|
||||
}
|
||||
if condition != 0 && this.check(tk::quest) {
|
||||
made = this.type_cond(condition);
|
||||
}
|
||||
|
||||
this.leave();
|
||||
return made;
|
||||
}
|
||||
|
||||
#! `C ? A : B`, from the `?`: the type `A` where the constant `C` holds, and `B`
|
||||
#! where it does not, as `MUTABLE ? &mut T : &T`.
|
||||
#! @param this The parser.
|
||||
#! @param condition The condition's node.
|
||||
#! @returns The `type_cond` node.
|
||||
def parser::type_cond(&mut this, condition: u32): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
val then := this.type_expr();
|
||||
this.expect(tk::colon, "Expected `:` between the types `?` chooses from, as `MUTABLE ? &mut T : &T`.");
|
||||
val other := this.type_expr();
|
||||
return this.make_node(nk::type_cond, token, condition, this.make_record(then, other));
|
||||
}
|
||||
|
||||
#! A name read as a type that is a type's condition instead, as `MUTABLE` of
|
||||
#! `MUTABLE ? &mut T : &T`: the name or path of a constant, as an expression.
|
||||
#! @param this The parser.
|
||||
#! @param made The `type_name` node.
|
||||
#! @returns The node, now a `name` or `path`.
|
||||
def parser::condition_name(&mut this, made: u32): u32 {
|
||||
if this.syntax.node_kinds[made] == nk::type_name {
|
||||
this.syntax.node_kinds[made] = this.syntax.node_lefts[made] == 0 ? nk::name : nk::path;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The rest of a condition a type is chosen by that begins with a name read as
|
||||
#! a type, as `T is pointer && T::target is integer` of `T is pointer &&
|
||||
#! T::target is integer ? T::target : u8`: what operators follow it, up to its
|
||||
#! `?`.
|
||||
#! @param this The parser.
|
||||
#! @param left The name's node, now a `name` or `path`.
|
||||
#! @returns The condition's node.
|
||||
def parser::condition_after(&mut this, left: u32): u32 {
|
||||
val angled := this.angled;
|
||||
this.angled = false;
|
||||
var made := left;
|
||||
while true {
|
||||
val power := this.power(made);
|
||||
break if power as u32 <= parser::bp::ternary as u32;
|
||||
made = this.infix(made, power, true);
|
||||
}
|
||||
this.angled = angled;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Whether a token after a name read as a type goes on with a condition a
|
||||
#! type is chosen by, which nothing a type is goes on with: `is`, `==`, `!=`,
|
||||
#! `&&`, or `||`. A comparison by `<` or `>` is written in parentheses, as
|
||||
#! `(N > 4) ? A : B`, since those are a type's arguments.
|
||||
#! @param kind The token's kind.
|
||||
#! @returns Whether it does.
|
||||
def parser::continues_condition(kind: tk): bool {
|
||||
return kind == tk::kw_is || kind == tk::equals || kind == tk::noteq || kind == tk::logand || kind == tk::logor;
|
||||
}
|
||||
|
||||
#! Whether what follows a name read as a type among type arguments goes on
|
||||
#! with a condition a type is chosen by, up to a `?` a type follows, as `is
|
||||
#! reference ? T::target : T`, where `T is integer ? 4 : 8` is a constant. The
|
||||
#! condition compares by no `<` or `>`, so those are brackets.
|
||||
#! @param this The parser.
|
||||
#! @returns Whether it does.
|
||||
def parser::condition_chooses_type(&this): bool {
|
||||
var depth: u32 = 0;
|
||||
var ahead: u32 = 0;
|
||||
while ahead < 1024 {
|
||||
val kind := this.peek(ahead);
|
||||
return false if kind == tk::eof || kind == tk::semicolon || kind == tk::lbrace || kind == tk::rbrace;
|
||||
if kind == tk::lparen || kind == tk::lbracket || kind == tk::less {
|
||||
depth++;
|
||||
} else if kind == tk::rparen || kind == tk::rbracket || kind == tk::more {
|
||||
return false if depth == 0;
|
||||
depth--;
|
||||
} else if kind == tk::rshift {
|
||||
return false if depth < 2;
|
||||
depth -= 2;
|
||||
} else if depth == 0 && (kind == tk::comma || kind == tk::assign) {
|
||||
return false;
|
||||
} else if depth == 0 && kind == tk::quest {
|
||||
return parser::begins_type(this.peek(ahead + 1));
|
||||
}
|
||||
ahead++;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Whether a token begins a type, so a `?` before it chooses between types.
|
||||
#! @param kind The token's kind.
|
||||
#! @returns Whether it does.
|
||||
def parser::begins_type(kind: tk): bool {
|
||||
return kind == tk::name || kind == tk::star || kind == tk::bitand || kind == tk::kw_def
|
||||
|| kind == tk::lparen || kind == tk::kw_match || kind == tk::negate;
|
||||
}
|
||||
|
||||
#! Whether what begins with the `(` a number of tokens ahead is the condition
|
||||
#! a type is chosen by: a `?` a type follows comes after it, outside any
|
||||
#! parentheses, before anything ends a type, as `(N > 4) ? A : B`, where `(N >
|
||||
#! 4) ? 8 : 4` is a value. The condition may go on past it, as `(A || B) && (C
|
||||
#! || D) ? X : Y`, or `small(N) && M ? A : B` from a call's `(`, but compares by
|
||||
#! `<` or `>` only within parentheses, since `>` ends type arguments.
|
||||
#! @param this The parser.
|
||||
#! @param start How many tokens ahead the `(` is.
|
||||
#! @returns Whether it does.
|
||||
def parser::chooses_type(&this, start: u32): bool {
|
||||
var depth: u32 = 0;
|
||||
var ahead := start;
|
||||
while ahead < start + 1024 {
|
||||
val kind := this.peek(ahead);
|
||||
return false if kind == tk::eof || kind == tk::semicolon || kind == tk::lbrace || kind == tk::rbrace;
|
||||
if kind == tk::lparen {
|
||||
depth++;
|
||||
} else if kind == tk::rparen {
|
||||
return false if depth == 0;
|
||||
depth--;
|
||||
} else if depth == 0 {
|
||||
return parser::begins_type(this.peek(ahead + 1)) if kind == tk::quest;
|
||||
return false if kind == tk::comma || kind == tk::assign || kind == tk::colon || kind == tk::more
|
||||
|| kind == tk::moreeq || kind == tk::rshift || kind == tk::arrow || kind == tk::rbracket;
|
||||
}
|
||||
ahead++;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! Whether the name at the current token begins a call that is the condition
|
||||
#! a type is chosen by, or begins it, as `small(N) ? u32 : u64`: a name or a
|
||||
#! path, which may give type arguments after `::<`, then its arguments in
|
||||
#! parentheses, as `chooses_type` reads them.
|
||||
#! @param this The parser.
|
||||
#! @returns Whether it does.
|
||||
def parser::call_chooses_type(&this): bool {
|
||||
var ahead: u32 = 1;
|
||||
while this.peek(ahead) == tk::scope {
|
||||
if this.peek(ahead + 1) == tk::name {
|
||||
ahead += 2;
|
||||
continue;
|
||||
}
|
||||
return false if this.peek(ahead + 1) != tk::less;
|
||||
ahead += 2;
|
||||
var depth: u32 = 1;
|
||||
while depth != 0 && ahead < 256 {
|
||||
val kind := this.peek(ahead);
|
||||
return false if kind == tk::eof || kind == tk::semicolon || kind == tk::lbrace || kind == tk::rbrace;
|
||||
if kind == tk::less {
|
||||
depth++;
|
||||
} else if kind == tk::more {
|
||||
depth--;
|
||||
} else if kind == tk::rshift {
|
||||
return false if depth < 2;
|
||||
depth -= 2;
|
||||
}
|
||||
ahead++;
|
||||
}
|
||||
}
|
||||
return this.peek(ahead) == tk::lparen && this.chooses_type(ahead);
|
||||
}
|
||||
|
||||
#! A type followed by the lengths of fixed arrays of it, as `T[4][2]`, or a
|
||||
#! pack followed by the index of one of its types, as `Ts...[0]`, a `type_fixed`
|
||||
#! node whose token is the `...`.
|
||||
#! @param this The parser.
|
||||
#! @returns The type's node, a `type_fixed` node where lengths follow.
|
||||
def parser::type_postfix(&mut this): u32 {
|
||||
var made := this.type_primary();
|
||||
while this.check(tk::lbracket) || (this.check(tk::spread) && this.peek(1) == tk::lbracket) {
|
||||
val token := this.index;
|
||||
if this.check(tk::spread) {
|
||||
this.advance();
|
||||
this.advance();
|
||||
val index := this.expression();
|
||||
this.expect(tk::rbracket, "Expected `]` after the index of the pack's type.");
|
||||
made = this.make_node(nk::type_fixed, token, made, index);
|
||||
continue;
|
||||
}
|
||||
this.advance();
|
||||
if this.check(tk::rbracket) {
|
||||
this.report(ec::token,
|
||||
"Expected the number of elements, as `T[4]`: a run of elements whose number is not known is a `std::list<T>`, and a view of one a `slice<T>`.");
|
||||
}
|
||||
|
||||
val length := this.expression();
|
||||
this.expect(tk::rbracket, "Expected `]` after the number of elements.");
|
||||
made = this.make_node(nk::type_fixed, token, made, length);
|
||||
}
|
||||
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A type that `...` may follow: a function type's last parameter, which takes
|
||||
#! any number of arguments, as `def(i64...): i64`, or is a pack, as `def(Ts...):
|
||||
#! R`, and a pack passed on among type arguments, as `box<i64, Ts...>`.
|
||||
#! @param this The parser.
|
||||
#! @returns The type's node, or a `type_spread` of it.
|
||||
def parser::spread_type(&mut this): u32 {
|
||||
val made := this.type_expr();
|
||||
return made if !this.check(tk::spread);
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
return this.make_node(nk::type_spread, token, made);
|
||||
}
|
||||
|
||||
def parser::type_primary(&mut this): u32 {
|
||||
# A function type, as `def(int, str): bool`, whose result takes everything
|
||||
# after it.
|
||||
if this.check(tk::kw_def) {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
this.expect(tk::lparen, "Expected `(` to begin the parameter types.");
|
||||
|
||||
val params := this.list(parser::item::param_type, tk::rparen, "Expected `)` to close the parameter types.");
|
||||
this.expect(tk::colon, "Expected `:` followed by the return type.");
|
||||
return this.make_node(nk::type_func, token, params, this.type_expr());
|
||||
}
|
||||
|
||||
if this.accept(tk::lparen) {
|
||||
val made := this.type_expr();
|
||||
this.expect(tk::rparen, "Expected `)` to close the type.");
|
||||
return made;
|
||||
}
|
||||
|
||||
# `match const T { pointer => T::target, else => T }` is the type its first arm
|
||||
# whose trait or type `T` fits gives.
|
||||
if this.check(tk::kw_match) {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
this.expect(tk::kw_const, "Expected `const` after `match`: a type is chosen by `match const T { ... }`.");
|
||||
val subject := this.type_expr();
|
||||
if !this.accept(tk::lbrace) {
|
||||
this.fail(ec::token, "Expected `{` to begin the arms of the match.");
|
||||
return this.make_node(nk::type_match, token, subject);
|
||||
}
|
||||
val arms := this.list(parser::item::type_arm, tk::rbrace, "Expected `,` between the arms, or `}` to close the match.");
|
||||
return this.make_node(nk::type_match, token, subject, arms);
|
||||
}
|
||||
|
||||
# `type_of(d)` is the type of what a declaration known while compiling declares.
|
||||
if this.check_word(names::type_of_id) && this.peek(1) == tk::lparen {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
this.advance();
|
||||
|
||||
val declaration := this.expression();
|
||||
this.expect(tk::rparen, "Expected `)` after the declaration whose type it is.");
|
||||
return this.make_node(nk::type_of, token, declaration);
|
||||
}
|
||||
|
||||
return this.type_name();
|
||||
}
|
||||
|
||||
#! A named type, as `std::list<T>`, made of its segments. One of a single
|
||||
#! segment without type arguments, as `u8`, holds no run: its token names it.
|
||||
#! @param this The parser.
|
||||
#! @returns The `type_name` node.
|
||||
def parser::type_name(&mut this): u32 {
|
||||
if !this.check(tk::name) {
|
||||
this.fail(ec::kind, "Expected a type name.");
|
||||
return this.error_here();
|
||||
}
|
||||
|
||||
val token := this.index;
|
||||
if this.peek(1) != tk::less && this.peek(1) != tk::scope {
|
||||
this.advance();
|
||||
return this.make_node(nk::type_name, token);
|
||||
}
|
||||
return this.make_node(nk::type_name, token, this.segments(parser::args::types));
|
||||
}
|
||||
|
||||
#! A path, as `std::io`, of segments without type arguments. One of a single
|
||||
#! segment holds no run: its token names it.
|
||||
#! @param this The parser.
|
||||
#! @returns The `path` node.
|
||||
def parser::path(&mut this): u32 {
|
||||
val token := this.index;
|
||||
if this.check(tk::name) && this.peek(1) != tk::scope {
|
||||
this.advance();
|
||||
return this.make_node(nk::path, token);
|
||||
}
|
||||
return this.make_node(nk::path, token, this.segments(parser::args::plain));
|
||||
}
|
||||
|
||||
#! The segments of a path, as `a::b::c`, each of which may take type arguments,
|
||||
#! as `res<i64>::ok` in a type, or `res::<i64>::ok` in an expression.
|
||||
#! @param this The parser.
|
||||
#! @param args How type arguments are written after each segment, if at all.
|
||||
#! @returns The run of `segment` nodes.
|
||||
def parser::segments(&mut this, args: parser::args): u32 {
|
||||
val mark := this.mark;
|
||||
while true {
|
||||
if !this.check(tk::name) {
|
||||
this.fail(ec::ident, "Expected an identifier in the path.");
|
||||
break;
|
||||
}
|
||||
|
||||
val token := this.index;
|
||||
var types: u32 = 0;
|
||||
this.advance();
|
||||
if args == parser::args::types && this.check(tk::less) {
|
||||
types = this.type_args();
|
||||
} else if args == parser::args::values && this.at_value_args() {
|
||||
this.advance();
|
||||
types = this.type_args();
|
||||
}
|
||||
|
||||
this.push(this.make_node(nk::segment, token, types));
|
||||
break if !this.accept(tk::scope);
|
||||
}
|
||||
|
||||
return this.make_run(mark);
|
||||
}
|
||||
|
||||
#! Whether type arguments follow a name in an expression, written `::<` so that
|
||||
#! a `<` alone always compares.
|
||||
#! @param this The parser.
|
||||
#! @returns Whether they do.
|
||||
def parser::at_value_args(&this): bool {
|
||||
return this.check(tk::scope) && this.peek(1) == tk::less;
|
||||
}
|
||||
|
||||
#! The type arguments `<T, U>`, from the current `<`. After `as` and `is`, a `<`
|
||||
#! always begins type arguments, so a comparison there needs parentheses.
|
||||
#! @param this The parser.
|
||||
#! @returns The run of types.
|
||||
def parser::type_args(&mut this): u32 {
|
||||
val open := this.index;
|
||||
val angled := this.angled;
|
||||
this.angled = false;
|
||||
this.advance();
|
||||
|
||||
val mark := this.mark;
|
||||
while true {
|
||||
this.push(this.type_arg());
|
||||
break if !this.accept(tk::comma);
|
||||
}
|
||||
this.angled = angled;
|
||||
|
||||
val types := this.make_run(mark);
|
||||
this.close_angle(this.follows_cast(open)
|
||||
? "Expected `>` to close the type arguments. A `<` after the type of `as` or `is` begins type arguments, so put a comparison in parentheses, as `(n as i64) < limit`."
|
||||
: "Expected `>` to close the type arguments.");
|
||||
return types;
|
||||
}
|
||||
|
||||
#! Whether the name at the current token begins what is given type arguments
|
||||
#! after `::<`, as `size_of::<T>()`, which no type is.
|
||||
#! @param this The parser.
|
||||
#! @returns Whether it does.
|
||||
def parser::names_generic_call(&this): bool {
|
||||
var ahead: u32 = 1;
|
||||
while this.peek(ahead) == tk::scope {
|
||||
return true if this.peek(ahead + 1) == tk::less;
|
||||
return false if this.peek(ahead + 1) != tk::name;
|
||||
ahead += 2;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#! A type argument: a type, or the value a constant parameter is given, a
|
||||
#! literal, a name, or an expression of them, as `buffer<u8, 64>` or
|
||||
#! `grid<N * 2>`. A name alone is read as a type, which the checker takes as the
|
||||
#! constant it names where the parameter is one. `(` begins a value, unless a
|
||||
#! type that needs one does, and so does a name given type arguments after
|
||||
#! `::<`, as `buffer<u8, size_of::<T>()>`.
|
||||
#! @param this The parser.
|
||||
#! @returns The type's or the value's node.
|
||||
def parser::type_arg(&mut this): u32 {
|
||||
val next := this.peek(1);
|
||||
val value := match this.kind {
|
||||
tk::signed, tk::unsigned, tk::float, tk::char, tk::string, tk::istring, tk::istring_beg,
|
||||
tk::kw_true, tk::kw_false, tk::kw_null, tk::minus, tk::negate, tk::bitnot, tk::lbracket => true,
|
||||
tk::lparen => next != tk::star && next != tk::bitand && next != tk::kw_def && !this.chooses_type(0),
|
||||
tk::name => this.names_generic_call(),
|
||||
else => false
|
||||
};
|
||||
return this.constant_arg(0) if value;
|
||||
|
||||
this.type_argument = true;
|
||||
val made := this.spread_type();
|
||||
return made if this.syntax.node_kinds[made] != nk::type_name || !this.continues_value();
|
||||
|
||||
# The name is the expression's first operand: a name of one segment, or a path.
|
||||
this.syntax.node_kinds[made] = this.syntax.node_lefts[made] == 0 ? nk::name : nk::path;
|
||||
return this.constant_arg(made);
|
||||
}
|
||||
|
||||
#! Whether what follows a name read as a type goes on with an expression, so the
|
||||
#! name began a constant argument, as `N` does in `grid<N * 2>`. `>` closes the
|
||||
#! arguments, so a comparison is put in parentheses.
|
||||
#! @param this The parser.
|
||||
#! @returns Whether it does.
|
||||
def parser::continues_value(&this): bool {
|
||||
return match this.kind {
|
||||
tk::lparen, tk::lbrace, tk::dot, tk::quest, tk::kw_as, tk::kw_is => true,
|
||||
tk::more, tk::moreeq, tk::rshift, tk::rshifteq, tk::comma => false,
|
||||
else => token_powers[this.kind as u64] as u32 > parser::bp::assign as u32
|
||||
};
|
||||
}
|
||||
|
||||
#! A constant argument, which is an expression, going on from the name already
|
||||
#! read as a type where one was.
|
||||
#! @param this The parser.
|
||||
#! @param primed The `name` or `path` the expression begins with, or 0.
|
||||
#! @returns The expression's node.
|
||||
def parser::constant_arg(&mut this, primed: u32): u32 {
|
||||
val angled := this.angled;
|
||||
this.angled = true;
|
||||
var made: u32 = 0;
|
||||
if primed == 0 {
|
||||
made = this.expression();
|
||||
} else {
|
||||
made = primed;
|
||||
# A struct literal of the name, as `point { x = 1 }`.
|
||||
if this.check(tk::lbrace) {
|
||||
this.syntax.node_kinds[made] = nk::type_name;
|
||||
made = this.make_node(nk::construct, this.index, made, this.field_list());
|
||||
}
|
||||
while true {
|
||||
val power := this.power(made);
|
||||
break if power == parser::bp::none;
|
||||
made = this.infix(made, power, true);
|
||||
}
|
||||
}
|
||||
this.angled = angled;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! A pattern parameter, `def(A, Ts...): R`, from the current `def`: a type
|
||||
#! parameter for each of the parameter types it names, the last of which may be
|
||||
#! a pack, and one for its result.
|
||||
#! @param this The parser.
|
||||
#! @returns The `type_pattern` node.
|
||||
def parser::type_pattern(&mut this): u32 {
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
this.expect(tk::lparen, "Expected `(` to begin the pattern's parameter types, as `def(Ts...): R`.");
|
||||
|
||||
val mark := this.mark;
|
||||
while !this.check(tk::rparen) && !this.check(tk::eof) {
|
||||
if !this.check(tk::name) {
|
||||
this.fail(ec::ident, "Expected the name of a type parameter the pattern's parameter type is, as `T` of `def(T): R`.");
|
||||
break;
|
||||
}
|
||||
val name := this.index;
|
||||
this.advance();
|
||||
val packed := this.accept(tk::spread);
|
||||
if packed && !this.check(tk::rparen) {
|
||||
this.report_at(name, ec::token, "A pack takes every parameter type after those before it, so it is the last.");
|
||||
}
|
||||
this.push(this.make_node(nk::type_param, name, 0, parser::bit(packed, nf::packed)));
|
||||
break if !this.accept(tk::comma);
|
||||
}
|
||||
val params := this.make_run(mark);
|
||||
this.expect(tk::rparen, "Expected `)` to close the pattern's parameter types.");
|
||||
this.expect(tk::colon, "Expected `:` followed by the name of the type parameter the result is, as `R` of `def(Ts...): R`.");
|
||||
|
||||
var result: u32 = 0;
|
||||
if this.check(tk::name) {
|
||||
result = this.make_node(nk::type_param, this.index, 0, 0);
|
||||
this.advance();
|
||||
} else {
|
||||
this.fail(ec::ident, "Expected the name of the type parameter the result is, as `R` of `def(Ts...): R`.");
|
||||
}
|
||||
return this.make_node(nk::type_pattern, token, params, result);
|
||||
}
|
||||
|
||||
#! A pattern parameter, `L[N]`, from the current `[` after the name of its
|
||||
#! element's type parameter: that, and a constant parameter for its length.
|
||||
#! @param this The parser.
|
||||
#! @param token The name of the element's type parameter.
|
||||
#! @returns The `array_pattern` node.
|
||||
def parser::array_pattern(&mut this, token: u32): u32 {
|
||||
val element := this.make_node(nk::type_param, token, 0, 0);
|
||||
this.advance();
|
||||
var length: u32 = 0;
|
||||
if this.check(tk::name) {
|
||||
length = this.make_node(nk::const_param, this.index, 0, 0);
|
||||
this.advance();
|
||||
} else {
|
||||
this.fail(ec::ident, "Expected the name of the constant parameter the length is, as `N` of `L[N]`.");
|
||||
}
|
||||
this.expect(tk::rbracket, "Expected `]` to close the pattern, as `L[N]`.");
|
||||
return this.make_node(nk::array_pattern, token, element, length);
|
||||
}
|
||||
|
||||
#! The type parameters `<T, Us...>` of a declaration, from the current `<`,
|
||||
#! whose bounds are given in a `where` clause after its signature, which gives
|
||||
#! them to the `type_param` nodes.
|
||||
#! @param this The parser.
|
||||
#! @returns The run of `type_param` nodes.
|
||||
def parser::type_params(&mut this): u32 {
|
||||
this.advance();
|
||||
|
||||
val mark := this.mark;
|
||||
while true {
|
||||
# `def(Ts...): R` is given a function type, and names its parameters' types
|
||||
# and its result's.
|
||||
if this.check(tk::kw_def) {
|
||||
this.push(this.type_pattern());
|
||||
break if !this.accept(tk::comma);
|
||||
continue;
|
||||
}
|
||||
|
||||
# `const N: u64` stands for a value each instance is given, of the type written.
|
||||
val valued := this.accept(tk::kw_const);
|
||||
if !this.check(tk::name) {
|
||||
this.fail(ec::ident, valued ? "Expected the name of a constant parameter, as `const N: u64`." : "Expected the name of a type parameter.");
|
||||
break;
|
||||
}
|
||||
|
||||
val token := this.index;
|
||||
this.advance();
|
||||
# `L[N]` is given a fixed array, and names its element's type and its length.
|
||||
if !valued && this.check(tk::lbracket) {
|
||||
this.push(this.array_pattern(token));
|
||||
break if !this.accept(tk::comma);
|
||||
continue;
|
||||
}
|
||||
if valued {
|
||||
if this.accept(tk::spread) {
|
||||
this.report_at(token, ec::token, "A constant parameter stands for one value, so it is not a pack.");
|
||||
}
|
||||
this.expect(tk::colon, "Expected `:` followed by the type of the constant, as `const N: u64`.");
|
||||
this.push(this.make_node(nk::const_param, token, 0, this.type_expr()));
|
||||
break if !this.accept(tk::comma);
|
||||
continue;
|
||||
}
|
||||
|
||||
# `Ts...` is a pack, standing for any number of types, which comes last.
|
||||
val packed := this.accept(tk::spread);
|
||||
if packed && !this.at(tt::angle) {
|
||||
this.report_at(token, ec::token,
|
||||
"A pack takes every type argument after the type parameters before it, so it is the last.");
|
||||
}
|
||||
|
||||
this.push(this.make_node(nk::type_param, token, 0, parser::bit(packed, nf::packed)));
|
||||
break if !this.accept(tk::comma);
|
||||
}
|
||||
|
||||
val params := this.make_run(mark);
|
||||
this.close_angle("Expected `>` to close the type parameters.");
|
||||
return params;
|
||||
}
|
||||
@@ -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", "type_match", "type_cond",
|
||||
"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.span);
|
||||
val contract := this.contract_of(decl);
|
||||
if contract.length != 0 {
|
||||
signature.append("\n");
|
||||
signature.append(contract.span);
|
||||
}
|
||||
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.record(node, function_slot::body);
|
||||
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 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.table_node_of(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.table_node_of(callee)) is some(found) {
|
||||
made = found;
|
||||
}
|
||||
if made == 0 && callee != node {
|
||||
if this.called.get(&this.table_node_of(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].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(node, function_slot::receiver) == 0 {
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
nk::when_block => {
|
||||
# Each branch is a block of declarations, or another `when`.
|
||||
var branch := this.record(node, if_slot::then);
|
||||
var other := this.record(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(other, if_slot::then);
|
||||
other = this.record(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(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(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(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.span);
|
||||
}
|
||||
|
||||
#! 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.span);
|
||||
}
|
||||
|
||||
#! 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 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];
|
||||
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(parts[count - own:own as u64], out);
|
||||
out.append(">");
|
||||
}
|
||||
} else {
|
||||
this.generics_text(file, syntax.record(node, function_slot::type_params), out);
|
||||
}
|
||||
|
||||
out.append("(");
|
||||
val params := syntax.record(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(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(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.span);
|
||||
} 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.span);
|
||||
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.span);
|
||||
}
|
||||
}
|
||||
|
||||
#! 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(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.span);
|
||||
}
|
||||
}
|
||||
|
||||
#! 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(node, aggregate_slot::type_params), out);
|
||||
this.traits_text(decl, out);
|
||||
this.where_text(file, syntax.record(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(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(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.span);
|
||||
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.span, 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(owner, function_slot::params), node)
|
||||
|| this.run_holds(syntax, syntax.record(owner, function_slot::type_params), node)
|
||||
|| this.receiver_holds(syntax, syntax.record(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(owner, decl_slot::type_params), node);
|
||||
}
|
||||
nk::variable, nk::property => {
|
||||
return owner if this.receiver_holds(syntax, syntax.record(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,603 @@
|
||||
#! @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.span.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 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.quiet++;
|
||||
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.quiet--;
|
||||
this.checker.owned_names = this.checker.quiet != 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.span, &mut ids);
|
||||
syntaxes.at(j).rename(ids.span);
|
||||
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,459 @@
|
||||
#! @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`.
|
||||
slot::run, #! Attributes.
|
||||
];
|
||||
|
||||
#! The slots of a parameter's record, by their positions, as `record` takes
|
||||
#! them.
|
||||
pub enum parameter_slot : u32 {
|
||||
value, #! Default value.
|
||||
flags, #! Flags.
|
||||
attributes, #! Attributes.
|
||||
}
|
||||
|
||||
#! 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
|
||||
shape { left = slot::node, right = slot::run, record = no_record }, # type_match: subject, arms
|
||||
shape { left = slot::node, right = slot::extra, record = if_record }, # type_cond: condition, [then, else]
|
||||
|
||||
# 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,233 @@
|
||||
#! @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.
|
||||
#! @param keep How many bytes of the file are its text, as a resolver's
|
||||
#! `cut_of` says, or 0 for all of them.
|
||||
#! @returns The source object containing the file contents read.
|
||||
pub def source::open(path: strview, keep: u64 = 0): source {
|
||||
var text := source::read(path);
|
||||
if keep != 0 && keep < text.length {
|
||||
text.resize(keep);
|
||||
}
|
||||
var result := source {
|
||||
path = path,
|
||||
text = without_mark(move(&mut text)),
|
||||
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.span;
|
||||
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.span;
|
||||
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.span.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.span.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,393 @@
|
||||
#! @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.span.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.span);
|
||||
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.span.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 };
|
||||
}
|
||||
|
||||
#! A slot of a node's record, in whichever slot its shape keeps the record, by
|
||||
#! its position, as the kind's slots name it, as `function_slot::body`. A
|
||||
#! checked program checks that the kind's record has the slot.
|
||||
#! @param this The syntax tree.
|
||||
#! @param node The node.
|
||||
#! @param slot The slot's position in the record.
|
||||
#! @returns What the slot holds, or 0 where the node has no record.
|
||||
pub def syntax::record(&this, node: u32, slot: u32): u32 {
|
||||
val shape := this.node_kinds[node].shape;
|
||||
asserts(slot < shape.record.length, "The node's record has the slot.");
|
||||
val at: u32 = shape.left == slot::extra ? this.node_lefts[node] : this.node_rights[node];
|
||||
return this.extras[at as u64 + slot 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.
|
||||
pub 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(node, i as u32) if shape.record[i] == slot::flags;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -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 this.extras[run as u64 + 1:this.extras[run] as u64];
|
||||
}
|
||||
Reference in new issue
Block a user