From 4a133f609bf2a6e51c1610fe25b3c1a4dba9a5c8 Mon Sep 17 00:00:00 2001 From: itsfuad Date: Tue, 17 Nov 2026 20:56:58 +0600 Subject: [PATCH 01/24] Hand each function only the facts of its own text The checker kept one list of facts per module, and the compile handed "the facts found so far" to the next function it built. A fact naming a local was then read against another function's body. A `where` that names a parameter is checked whenever the signature is first asked for, often during an earlier function, so the editor showed the wrong local (`main`'s `const Ratio` for `Pick`'s `N`) or panicked when that body had no such local, as `negative_where_conditions.peep` did. The checker now keeps facts by the declaration they were found in and owns the rule for handing them on: `function_facts` gives a function the facts of its own signature and body, whose locals that body declares, and a copy none; `other_facts` gives the rest of a module in declaration order, without names of locals, as no body declares those of a function never handed on. The driver only calls the two. A new LSP test opens every test program in the editor's check and fails on any panic, which no other test exercised. --- Cargo.lock | 1 + crates/driver/compile/src/lib.rs | 23 ++++----- crates/driver/compile/src/tests.rs | 26 +++++----- crates/driver/lsp/Cargo.toml | 3 ++ crates/driver/lsp/src/tests.rs | 78 ++++++++++++++++++++++++++++++ crates/middle/check/src/lib.rs | 54 +++++++++++++++++---- 6 files changed, 150 insertions(+), 35 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 94fd9c4c..7c2c65e0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -486,6 +486,7 @@ dependencies = [ "serde_json", "source", "syntax", + "test_programs", ] [[package]] diff --git a/crates/driver/compile/src/lib.rs b/crates/driver/compile/src/lib.rs index 31259c31..1c053312 100644 --- a/crates/driver/compile/src/lib.rs +++ b/crates/driver/compile/src/lib.rs @@ -116,9 +116,8 @@ pub enum Output<'c> { constant: Option<&'c Constant>, types: &'c Types, // the program's types so far, which `constant` names }, - /// The facts of `module` found after its last function was handed on; - /// none unless the compile records facts (`ModuleChecks::facts`), and - /// no name among them stands for a local. + /// The facts of `module` no function was handed on with + /// (`Checker::other_facts`); none unless the compile records facts. Facts { module: ModuleId, facts: &'c [thir::Fact], @@ -135,10 +134,8 @@ pub struct CheckedFunction<'c> { /// that first called it. pub module: ModuleId, pub thir: &'c thir::Body, - /// The facts of its module found since the last function was handed on: - /// those of its text, and of the declarations checked meanwhile, when - /// the compile records facts (as for an editor); otherwise none. Only - /// this function's locals are among their names, explained by `thir`. + /// Its facts (`Checker::function_facts`), whose locals `thir` declares, + /// when the compile records facts (as for an editor); otherwise none. pub facts: &'c [thir::Fact], /// Its path-checked MIR, `None` when checking it found an error, and /// for the own body of a function with `const` parameters, which an @@ -232,7 +229,7 @@ pub struct Options { /// whose imports' interfaces are unchanged keeps its diagnostics, and its /// bodies are not checked again. What it checks goes to `use_output` in /// declaration order, module by module: each function with a body as soon as -/// it is built, with the facts found so far when `options.record_facts`, then +/// it is built, with its own facts when `options.record_facts`, then /// dropped except its MIR, which is `use_output`'s: nothing here holds every /// function's bodies at once. Each module constant goes once checked, with /// its type and value, and last the module's remaining facts, none unless @@ -422,7 +419,7 @@ fn find_entry_point( } /// Checks each function and constant of `module` where it is declared, used -/// or not, and gives each, with its MIR and the facts found so far for a +/// or not, and gives each, with its MIR and its own facts for a /// function, then the module's remaining facts, to `use_output`. fn compile_module( checker: &mut Checker, @@ -453,7 +450,7 @@ fn compile_module( arguments: ConstArguments::NONE, }; if checker.check_body(function, name, thir, true) && record_facts { - let facts = std::mem::take(&mut checker.module_checks[module.index()].facts); + let facts = checker.function_facts(function); use_output(Output::Function(CheckedFunction { function, module, @@ -487,7 +484,7 @@ fn compile_module( while let Some(copy) = checker.next_copy() { build_function(checker, module, copy, thir, use_output); } - let facts = std::mem::take(&mut checker.module_checks[module.index()].facts); + let facts = checker.other_facts(module); use_output(Output::Facts { module, facts: &facts, @@ -496,7 +493,7 @@ fn compile_module( } /// Builds `function`, in the compile of `module`, and gives it with its MIR -/// and the facts found so far to `use_output`; nothing when it has no body +/// and its facts to `use_output`; nothing when it has no body /// or its signature has an error. fn build_function( checker: &mut Checker, @@ -511,7 +508,7 @@ fn build_function( let Some(mir) = checker.build_function(function, span, thir, true) else { return; }; - let facts = std::mem::take(&mut checker.module_checks[module.index()].facts); + let facts = checker.function_facts(function); use_output(Output::Function(CheckedFunction { function, module, diff --git a/crates/driver/compile/src/tests.rs b/crates/driver/compile/src/tests.rs index cec74d64..e9a41937 100644 --- a/crates/driver/compile/src/tests.rs +++ b/crates/driver/compile/src/tests.rs @@ -1060,9 +1060,9 @@ fn a_reused_module_reports_its_errors_once() { } /// A function run at compile time and then compiled records its facts -/// once, each with the function that explains its locals; a declaration -/// first checked while such a function is built (`inner`'s signature) -/// records its facts too. +/// once, each with the declaration it is found in, so a function's locals +/// go with its body; a declaration first checked while another is +/// (`inner`'s signature, in `twice`'s body) keeps its own. #[test] fn a_function_run_at_compile_time_records_its_facts_once() { let program = load(&[( @@ -1095,13 +1095,9 @@ fn a_function_run_at_compile_time_records_its_facts_once() { found.extend(facts.iter().map(|fact| (tree.file.slice(fact.span), owner))); }, ); - // `twice` gets the facts found until it is handed on: `BIG`'s value, - // both signatures, its body; `inner` its body. + // Each function gets its signature and body; `BIG`'s value, which no + // function is handed on with, comes last. let expected = [ - ("twice", "twice"), - ("i32", "twice"), - ("i32", "twice"), - ("2", "twice"), ("i32", "twice"), ("i32", "twice"), ("n", "twice"), @@ -1110,8 +1106,12 @@ fn a_function_run_at_compile_time_records_its_facts_once() { ("2", "twice"), ("doubled", "twice"), ("doubled", "twice"), + ("i32", "inner"), + ("i32", "inner"), ("n", "inner"), ("n", "inner"), + ("twice", "module"), + ("2", "module"), ]; assert_eq!(found, expected); } @@ -1374,10 +1374,10 @@ fn a_function_with_const_parameters_records_its_signature_once() { found.extend(facts.iter().map(|fact| tree.file.slice(fact.span))); }, ); - // Checked at the first call, before its arguments. - let expected = ["Pick", "i64", "T", "T", "i32", "2", "3", "x"]; - assert_eq!(found[..expected.len()], expected); - assert_eq!(found.iter().filter(|&&text| text == "i64").count(), 1); + // Its signature, checked at the first call, goes with its own body. + let main = ["Pick", "i32", "2", "3", "x", "Pick", "i32", "4", "5", "y"]; + let pick = ["i64", "T", "T", "n", "x", "x"]; + assert_eq!(found, [&main[..], &pick[..]].concat()); } /// The own body of a function with `const` parameters, which no call diff --git a/crates/driver/lsp/Cargo.toml b/crates/driver/lsp/Cargo.toml index 9058e93e..25978f07 100644 --- a/crates/driver/lsp/Cargo.toml +++ b/crates/driver/lsp/Cargo.toml @@ -20,5 +20,8 @@ lsp-server.workspace = true lsp-types.workspace = true serde_json.workspace = true +[dev-dependencies] +test_programs.workspace = true + [lints] workspace = true diff --git a/crates/driver/lsp/src/tests.rs b/crates/driver/lsp/src/tests.rs index b98a57e0..1f12bcd8 100644 --- a/crates/driver/lsp/src/tests.rs +++ b/crates/driver/lsp/src/tests.rs @@ -1200,3 +1200,81 @@ fn answers_only_from_the_current_text() { "not loaded" ); } + +/// Each test program is checked as an editor opens it, file by file, with +/// no panic: only the editor's compile records facts, so nothing else +/// checks what it does with them. +#[test] +fn checks_every_test_program() { + let projects = std::env::temp_dir().join(format!("peeper-lsp-programs-{}", std::process::id())); + let libraries = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../_builtin_library"); + let (connection, _client) = Connection::memory(); + let mut panicked = Vec::new(); + for program in test_programs::all() { + let folder = projects.join(&program.name); + program.write_project(&folder); + let check = || { + let mut server = Server::new(&connection, &libraries, true); + for (file, text) in &program.sources { + let uri = Url::from_file_path(folder.join("src").join(file)).unwrap(); + let document = + json!({ "uri": uri, "languageId": "peeper", "version": 1, "text": text }); + let open = Notification::new( + "textDocument/didOpen".to_string(), + json!({ "textDocument": document }), + ); + server.apply_notification(open).unwrap(); + server.check_pending().unwrap(); + } + }; + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(check)).is_err() { + panicked.push(program.name); + } + } + _ = std::fs::remove_dir_all(&projects); + assert!( + panicked.is_empty(), + "the editor's check panicked on {panicked:?}" + ); +} + +/// A name after `where` is a local of its own function, though another +/// function's body asks for its signature first. +#[test] +fn names_after_where_are_of_their_own_function() { + let folder = std::env::temp_dir().join(format!("peeper-lsp-where-{}", std::process::id())); + _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + let file = folder.join("main.peep"); + std::fs::write(&file, "fn main() {}\n").unwrap(); + let uri = Url::from_file_path(&file).unwrap(); + let (connection, _client) = Connection::memory(); + let mut server = Server::new(&connection, Path::new("no-libraries"), true); + let text = "fn Positive(const N: i32) -> bool { return N > 0; } +fn main() { + const Ratio = 1.5; + let total = Pick(3, 4); +} +fn Pick(const N: i32, value: i32) -> i32 +where + N: Positive +{ + return N + value; +} +"; + let document = json!({ "uri": uri, "languageId": "peeper", "version": 1, "text": text }); + let open = Notification::new( + "textDocument/didOpen".to_string(), + json!({ "textDocument": document }), + ); + server.apply_notification(open).unwrap(); + server.check_pending().unwrap(); + let params = place(&uri, text, "N: Positive", 0); + let request = Request::new(RequestId::from(1), "textDocument/hover".to_string(), params); + let Response { result, error, .. } = server.answer_request(request); + assert!(error.is_none(), "{error:?}"); + assert_eq!( + result.unwrap()["contents"]["value"], + "```peeper\nconst N: i32\n```\n\n---\n\n*in* `main` *ยท line 6*\n" + ); +} diff --git a/crates/middle/check/src/lib.rs b/crates/middle/check/src/lib.rs index f5f8a084..76666af2 100644 --- a/crates/middle/check/src/lib.rs +++ b/crates/middle/check/src/lib.rs @@ -197,10 +197,9 @@ pub struct ModuleChecks<'p> { /// (`evaluate_call`), so a constant's value depends on their bodies, /// which no interface holds. pub ran_modules: Vec, - /// The facts found in it (`Checker::record`), when they are recorded. - /// Declarations are checked as they are asked for, in any order, so the - /// facts wait here until the compile hands them over. - pub facts: Vec, + /// The facts found in it (`Checker::record`), by the declaration being + /// checked. + facts: FxHashMap>, /// What checking it reported, in order. pub diagnostics: Vec, } @@ -232,7 +231,7 @@ impl<'p, L: Checked> Checker<'p, L> { declared_types: vec![State::NotStarted; declarations], constants: vec![State::NotStarted; declarations], ran_modules: Vec::new(), - facts: Vec::new(), + facts: FxHashMap::default(), diagnostics, } }) @@ -522,8 +521,12 @@ impl<'p, L: Checked> Checker<'p, L> { return; }; if checking.records_facts && !self.in_copy() { - let module = checking.definition.module.index(); - self.module_checks[module].facts.push(Fact { span, kind }); + let definition = checking.definition; + let facts = &mut self.module_checks[definition.module.index()].facts; + facts + .entry(definition) + .or_default() + .push(Fact { span, kind }); } } @@ -541,15 +544,48 @@ impl<'p, L: Checked> Checker<'p, L> { if checking.arguments != ConstArguments::NONE { return; } - let module = self.current_module().index(); + let definition = checking.definition; let names_it = |kind| matches!(kind, FactKind::Name(Symbol::Function(named)) if named == copy.definition); - let mut facts = self.module_checks[module].facts.iter_mut().rev(); + let facts = &mut self.module_checks[definition.module.index()].facts; + let Some(facts) = facts.get_mut(&definition) else { + return; // none are recorded + }; + let mut facts = facts.iter_mut().rev(); // The facts of the call's arguments were recorded after its name's. if let Some(fact) = facts.find(|fact| fact.span.end == name_end && names_it(fact.kind)) { fact.kind = FactKind::Copy { function: copy, ty }; } } + /// The facts found in the text of `function`, its signature's and its + /// body's, which declares each local they name, as its `where` does + /// (`constraints_hold`); none for a copy, which records none and whose + /// body is not the one they name. + pub fn function_facts(&mut self, function: FunctionCopy) -> Vec { + let definition = function.definition; + let facts = &mut self.module_checks[definition.module.index()].facts; + (function.arguments == ConstArguments::NONE) + .then(|| facts.remove(&definition)) + .flatten() + .unwrap_or_default() + } + + /// The facts of `module` no function took (`function_facts`), by + /// declaration: of its types and constants, and of functions with no + /// body or an error in their signature, whose locals no body declares, + /// so no name among them stands for a local. + pub fn other_facts(&mut self, module: ModuleId) -> Vec { + let mut rest: Vec<(DefId, Vec)> = + std::mem::take(&mut self.module_checks[module.index()].facts) + .into_iter() + .collect(); + rest.sort_unstable_by_key(|(definition, _)| definition.index); + (rest.into_iter()) + .flat_map(|(_, facts)| facts) + .filter(|fact| !matches!(fact.kind, FactKind::Name(Symbol::Local(_)))) + .collect() + } + /// What `name` stands for at the top level: a `const T: type` parameter /// of the function being checked, the type it is given /// (`Checking::arguments`; a `const` value is a local of the body); From 399e00f8d935f95cad5dfa7eefd3a12396b1d79b Mon Sep 17 00:00:00 2001 From: itsfuad Date: Tue, 17 Nov 2026 23:15:41 +0600 Subject: [PATCH 02/24] Let structs take type parameters A struct can now declare ``: `struct Box { value: T }`, named as `Box`. Each list of type arguments makes its own copy of the struct, checked once and kept, so phases after the checker see only ordinary struct types. Copies of functions and of types now share one table and one `copy_type` (check/src/copies.rs): it makes each copy once, finds a copy that depends on itself, limits how deep copies nest, and moves a copy's errors to its use. `FunctionCopy` is renamed `DeclarationCopy` to match. A function copy then queues its body; a type copy runs its declaration's check. One list gives the type parameters of any declaration (`declaration_copy_parameters`), read for binding `T`, counting the arguments of `Box`, and refusing a bare `Box`. A type's own check, with no type for `T`, keeps which declaration a field names when an argument names `T` (`named_without_types`), and makes the copies its fields hold. So a struct that holds a new copy of itself by value, `struct Two { a: Box> }`, is reported once at its declaration as holding itself, instead of making copies without end; a pointer only names its target, so `*Node` stays fine. A generic function's own check still makes no copy. When a copy's error already marks the use, no second label is added there. Hashing a type for an importer's rebuild moves from the driver into `Types::hash`, which now also hashes a copy's arguments; the driver only says how to name a declaration. The shared copy messages now say "the copy made here" and "makes a new copy of itself", as a type's copy is not made by a call. Functions of generic types are refused for now. --- crates/backend/llvm/src/body.rs | 12 +- crates/backend/llvm/src/write.rs | 12 +- crates/driver/compile/src/lib.rs | 84 ++---- crates/driver/compile/src/tests.rs | 2 +- .../compile/tests/checks_through_features.rs | 4 +- crates/driver/lsp/src/checked.rs | 4 +- crates/driver/peeper/src/dump.rs | 4 +- crates/driver/peeper/src/lib.rs | 4 +- crates/features/src/interfaces.rs | 2 +- crates/features/src/printing.rs | 4 +- crates/features/src/structs.rs | 11 +- crates/features/src/testing.rs | 4 +- crates/features/src/text/tests.rs | 4 +- crates/middle/check/src/builtin.rs | 4 +- crates/middle/check/src/constraints.rs | 14 +- crates/middle/check/src/copies.rs | 258 ++++++++++++++++++ crates/middle/check/src/declaration.rs | 147 ++++++---- crates/middle/check/src/expression.rs | 2 +- crates/middle/check/src/expression/calls.rs | 12 +- crates/middle/check/src/expression/places.rs | 12 +- crates/middle/check/src/function.rs | 153 +---------- crates/middle/check/src/lib.rs | 118 ++++---- crates/middle/check/src/statement.rs | 15 +- crates/middle/check/src/statement/tests.rs | 6 +- crates/middle/eval/src/interpreter.rs | 20 +- crates/middle/eval/src/interpreter/program.rs | 6 +- crates/middle/lower/src/expression.rs | 4 +- crates/middle/lower/src/lib.rs | 9 +- crates/middle/lower/src/tests.rs | 6 +- crates/middle/model/src/layout.rs | 2 +- crates/middle/model/src/lib.rs | 10 +- crates/middle/model/src/mir.rs | 12 +- crates/middle/model/src/program.rs | 31 ++- crates/middle/model/src/semantic_types.rs | 142 +++++++++- .../middle/model/src/semantic_types/tests.rs | 35 ++- crates/middle/model/src/thir.rs | 7 +- docs/feature-front.md | 2 +- .../negative_const_parameters.peep | 2 +- .../negative_where_conditions.peep | 10 +- .../generic_types/negative_generic_types.peep | 50 ++++ .../generic_types/run_generic_types.out | 4 + .../generic_types/run_generic_types.peep | 62 +++++ .../generic_types/run_i686_generic_types.out | 3 + .../generic_types/run_i686_generic_types.peep | 44 +++ .../negative_check_struct_not_supported.peep | 6 +- .../types/negative_check_type_alias.peep | 2 +- 46 files changed, 912 insertions(+), 449 deletions(-) create mode 100644 crates/middle/check/src/copies.rs create mode 100644 test_programs/generic_types/negative_generic_types.peep create mode 100644 test_programs/generic_types/run_generic_types.out create mode 100644 test_programs/generic_types/run_generic_types.peep create mode 100644 test_programs/generic_types/run_i686_generic_types.out create mode 100644 test_programs/generic_types/run_i686_generic_types.peep diff --git a/crates/backend/llvm/src/body.rs b/crates/backend/llvm/src/body.rs index 22ba8bbb..2551dd26 100644 --- a/crates/backend/llvm/src/body.rs +++ b/crates/backend/llvm/src/body.rs @@ -10,7 +10,7 @@ use std::fmt::Display; use std::fmt::Write; use arena::Id; -use model::FunctionCopy; +use model::DeclarationCopy; use model::mir::Block; use model::mir::Body; use model::mir::CPassing; @@ -56,7 +56,7 @@ const MEMCPY: &str = "llvm.memcpy.p0.p0.i64"; /// A function the compile checked, for a worker to write. pub(crate) struct Defined { - pub(crate) copy: FunctionCopy, + pub(crate) copy: DeclarationCopy, /// As a debugger shows it, `const` arguments too; empty in a release /// build. pub(crate) shown_name: String, @@ -75,7 +75,7 @@ impl Module<'_> { &mut self, defined: &Defined, file: &SourceFile, - symbols: &FxHashMap, + symbols: &FxHashMap, debug_types: &DebugTypes, ) { let Defined { @@ -172,8 +172,8 @@ impl Module<'_> { /// per module, with a `declare` of each. fn add_table( &mut self, - entries: &[(FunctionCopy, Signature)], - symbols: &FxHashMap, + entries: &[(DeclarationCopy, Signature)], + symbols: &FxHashMap, ) -> String { let mut constant = format!("[{} x ptr] [", entries.len()); for (index, (copy, signature)) in entries.iter().enumerate() { @@ -392,7 +392,7 @@ struct Writer<'m, 'p, 'b> { module: &'m mut Module<'p>, body: &'b Body, file: &'b SourceFile, // the function's own, which a copy's module may not be - symbols: &'b FxHashMap, + symbols: &'b FxHashMap, globals: Vec, // each global's address scopes: Vec, // by debug scope, its metadata; none in a release build locations: FxHashMap<(usize, u32), usize>, // each scope and offset's DILocation diff --git a/crates/backend/llvm/src/write.rs b/crates/backend/llvm/src/write.rs index 903e89fa..69505358 100644 --- a/crates/backend/llvm/src/write.rs +++ b/crates/backend/llvm/src/write.rs @@ -9,7 +9,7 @@ use std::sync::Arc; use std::sync::Mutex; use std::sync::mpsc; -use model::FunctionCopy; +use model::DeclarationCopy; use model::ModuleId; use model::machine::Machine; use model::mir; @@ -29,7 +29,7 @@ struct Batch { functions: Vec, /// Made on the compile's thread, not by a worker: a copy's symbol names /// its `const` arguments, which only the program's types tell. - symbols: FxHashMap, + symbols: FxHashMap, debug_types: DebugTypes, } @@ -41,7 +41,7 @@ pub struct FunctionQueue { /// those so far, with the symbols they need (`Batch`). module: Option, functions: Vec, - symbols: FxHashMap, + symbols: FxHashMap, sent: Vec, // by module: whether its functions went to a worker batches: mpsc::Sender, /// In a debug build, a copy of the program's debug types so far, sent @@ -61,9 +61,9 @@ impl FunctionQueue { pub fn add( &mut self, module: ModuleId, - copy: FunctionCopy, + copy: DeclarationCopy, body: mir::Body, - symbol_of: impl Fn(FunctionCopy) -> String, + symbol_of: impl Fn(DeclarationCopy) -> String, debug_name: impl FnOnce() -> (String, Span), debug_types: &DebugTypes, ) { @@ -76,7 +76,7 @@ impl FunctionQueue { self.module = Some(module); } let symbols = &mut self.symbols; - let mut name = |copy: FunctionCopy| { + let mut name = |copy: DeclarationCopy| { symbols.entry(copy).or_insert_with(|| symbol_of(copy)); }; name(copy); diff --git a/crates/driver/compile/src/lib.rs b/crates/driver/compile/src/lib.rs index 1c053312..2e332d7f 100644 --- a/crates/driver/compile/src/lib.rs +++ b/crates/driver/compile/src/lib.rs @@ -22,8 +22,8 @@ use eval::interpreter::Failure; use eval::interpreter::program::Stream; use eval::interpreter::program::Written; use model::ConstArguments; +use model::DeclarationCopy; use model::DefId; -use model::FunctionCopy; use model::ModuleId; use model::machine::Machine; use model::mir; @@ -129,7 +129,7 @@ pub enum Output<'c> { /// parameters, as a compile hands it on: built, used once, and dropped /// after. pub struct CheckedFunction<'c> { - pub function: FunctionCopy, + pub function: DeclarationCopy, /// The module whose compile built it: its own, or, for a copy, the one /// that first called it. pub module: ModuleId, @@ -181,7 +181,7 @@ pub fn interpret( let Some((main, _)) = results.entry_point() else { return (results, None); }; - let main_function = FunctionCopy { + let main_function = DeclarationCopy { definition: main, arguments: ConstArguments::NONE, }; @@ -445,7 +445,7 @@ fn compile_module( { let name = function.name.span; checker.function_type(definition, name); - let function = FunctionCopy { + let function = DeclarationCopy { definition, arguments: ConstArguments::NONE, }; @@ -463,7 +463,7 @@ fn compile_module( } } ast::Decl::Function(_) => { - let function = FunctionCopy { + let function = DeclarationCopy { definition, arguments: ConstArguments::NONE, }; @@ -498,7 +498,7 @@ fn compile_module( fn build_function( checker: &mut Checker, module: ModuleId, - function: FunctionCopy, + function: DeclarationCopy, thir: &mut thir::Body, use_output: &mut dyn FnMut(Output), ) { @@ -520,68 +520,16 @@ fn build_function( })); } -/// Feeds `ty` to `hasher` by what it is, not by its id, which differs between -/// compiles: a named type by its module's path and its name. What it holds -/// is in the interface of the module declaring it (`interface`). -fn hash_type(checker: &Checker, id: TypeId, hasher: &mut DefaultHasher) { - let ty = &checker.types[id]; - std::mem::discriminant(ty).hash(hasher); - match ty { - Type::Integer(integer) => integer.hash(hasher), - Type::Float(float) => float.hash(hasher), - Type::Function { - parameters, - result, - origins, - variadic, - } => { - parameters.len().hash(hasher); - for ¶meter in parameters { - hash_type(checker, parameter, hasher); - } - hash_type(checker, *result, hasher); - origins.hash(hasher); - variadic.hash(hasher); - } - Type::Named(definition) - | Type::Struct { definition, .. } - | Type::Interface { definition, .. } => { - checker.modules[definition.module.index()].path.hash(hasher); - let (name, file) = model::program::declared_name(checker.modules, *definition); - name.text(file).hash(hasher); - } - Type::Array { internals, .. } => { - // Lengths are any number: the count keeps one from reading as - // the type after it. - checker.types.array_lengths(id).count().hash(hasher); - for length in checker.types.array_lengths(id) { - length.hash(hasher); - } - hash_type(checker, internals.base, hasher); - } - Type::Range { element, .. } => hash_type(checker, *element, hasher), // `step` follows - Type::Reference { mutable, target } - | Type::Slice { - mutable, - element: target, - } - | Type::InterfaceReference { - mutable, - interface: target, - } => { - mutable.hash(hasher); - // References and pointers nest as deep as the source does. - source::grow_stack(|| hash_type(checker, *target, hasher)); - } - Type::RawPointer { target } => { - target.is_some().hash(hasher); - if let Some(target) = target { - source::grow_stack(|| hash_type(checker, *target, hasher)); - } - } - Type::Invalid | Type::Void | Type::Bool | Type::CString | Type::Str => {} - Type::Alias { .. } => unreachable!("indexing looks through aliases"), - } +/// Feeds `ty` to `hasher` by what it is (`Types::hash`): a declared type +/// by its module's path and its name. What it holds is in the interface of +/// the module declaring it (`interface`). +fn hash_type(checker: &Checker, ty: TypeId, hasher: &mut DefaultHasher) { + let modules = checker.modules; + checker.types.hash(ty, hasher, |definition, hasher| { + modules[definition.module.index()].path.hash(hasher); + let (name, file) = model::program::declared_name(modules, definition); + name.text(file).hash(hasher); + }); } /// A hash of what other modules see of `module`, once its declarations are diff --git a/crates/driver/compile/src/tests.rs b/crates/driver/compile/src/tests.rs index e9a41937..395734d3 100644 --- a/crates/driver/compile/src/tests.rs +++ b/crates/driver/compile/src/tests.rs @@ -1260,7 +1260,7 @@ fn copies_report_once_to_the_calling_module() { "operator `+` cannot be applied to `bool`".to_string(), vec![ "x + x ".to_string(), - "add(T, x) in `add`, the copy made for this call".to_string(), + "add(T, x) in `add`, the copy made here".to_string(), ] ),] ); diff --git a/crates/driver/compile/tests/checks_through_features.rs b/crates/driver/compile/tests/checks_through_features.rs index be496f52..45f28d8d 100644 --- a/crates/driver/compile/tests/checks_through_features.rs +++ b/crates/driver/compile/tests/checks_through_features.rs @@ -9,8 +9,8 @@ use check::Checker; use check::scope::collect; use features::Peeper; use model::ConstArguments; +use model::DeclarationCopy; use model::DefId; -use model::FunctionCopy; use model::ModuleId; use model::machine::Machine; use model::program::Import; @@ -313,7 +313,7 @@ fn body_reports(text: &str) -> Vec { index: index as u32, }; checker.check_body( - FunctionCopy { + DeclarationCopy { definition, arguments: ConstArguments::NONE, }, diff --git a/crates/driver/lsp/src/checked.rs b/crates/driver/lsp/src/checked.rs index 57ee89ec..691c2550 100644 --- a/crates/driver/lsp/src/checked.rs +++ b/crates/driver/lsp/src/checked.rs @@ -8,7 +8,7 @@ use std::path::Path; use std::path::PathBuf; use lsp_types::CodeAction; -use model::FunctionCopy; +use model::DeclarationCopy; use model::ModuleId; use model::semantic_types::ConstArgument; use model::semantic_types::Constant; @@ -222,7 +222,7 @@ impl CachedFact { /// type parameters. fn copy_signature( program: &model::program::Program, - copy: FunctionCopy, + copy: DeclarationCopy, ty: TypeId, types: &Types, ) -> String { diff --git a/crates/driver/peeper/src/dump.rs b/crates/driver/peeper/src/dump.rs index 6800be6e..bb9cf147 100644 --- a/crates/driver/peeper/src/dump.rs +++ b/crates/driver/peeper/src/dump.rs @@ -6,8 +6,8 @@ use features::Peeper; use std::io::Write; use std::path::Path; +use model::DeclarationCopy; use model::DefId; -use model::FunctionCopy; use model::mir; use model::semantic_types::Types; use model::thir; @@ -60,7 +60,7 @@ impl<'p> Dumps<'p> { /// the dumps of the module that declares it. pub fn add( &mut self, - function: FunctionCopy, + function: DeclarationCopy, thir: &thir::Body, mir: &mir::Body, types: &Types, diff --git a/crates/driver/peeper/src/lib.rs b/crates/driver/peeper/src/lib.rs index 23503b9d..ff830e2c 100644 --- a/crates/driver/peeper/src/lib.rs +++ b/crates/driver/peeper/src/lib.rs @@ -4,7 +4,7 @@ use features::Peeper; use llvm::BuildMode; -use model::FunctionCopy; +use model::DeclarationCopy; use model::machine::Machine; use model::mir; use model::program::Program; @@ -23,7 +23,7 @@ pub fn write_program<'p>( target: &'static Machine, mode: BuildMode, require_main: bool, - mut each_function: impl FnMut(FunctionCopy, &thir::Body, &mir::Body, &Types), + mut each_function: impl FnMut(DeclarationCopy, &thir::Body, &mir::Body, &Types), ) -> (Vec>, compile::Results) { let files: Vec<_> = (program.modules.iter()) .map(|module| module.ast.file.clone()) diff --git a/crates/features/src/interfaces.rs b/crates/features/src/interfaces.rs index 7d62db0b..d408b168 100644 --- a/crates/features/src/interfaces.rs +++ b/crates/features/src/interfaces.rs @@ -125,7 +125,7 @@ impl TypeNode for InterfaceType { if methods.iter().any(|&method| invalid(method)) { return TypeId::INVALID; } - let named = checker.types.intern(Type::Named(definition)); + let named = checker.declared_name(definition); checker.types.define_interface(named, methods.into()); named } diff --git a/crates/features/src/printing.rs b/crates/features/src/printing.rs index 89ccab5c..d863d9ac 100644 --- a/crates/features/src/printing.rs +++ b/crates/features/src/printing.rs @@ -10,7 +10,7 @@ use bigint::Limbs; use check::builder::ThirBuilder; use model::Callee; use model::ConstArguments; -use model::FunctionCopy; +use model::DeclarationCopy; use model::constant::Value; use model::semantic_types::Conversion; use model::semantic_types::Float; @@ -370,7 +370,7 @@ fn library_call( } return None; }; - let function = FunctionCopy { + let function = DeclarationCopy { definition, arguments: ConstArguments::NONE, }; diff --git a/crates/features/src/structs.rs b/crates/features/src/structs.rs index 9f0ba7d1..ae9ecea6 100644 --- a/crates/features/src/structs.rs +++ b/crates/features/src/structs.rs @@ -183,7 +183,7 @@ impl TypeNode for StructType { return TypeId::INVALID; } let (offsets, size, align) = struct_layout(&checker.types, &field_types, checker.target); - let named = checker.types.intern(Type::Named(definition)); + let named = checker.declared_name(definition); let mut ty = checker.fits_target(named, size, written.name.span); let holders = checker.types.holders_in_fields(&field_types); if checker.reports_too_many_holders(named, holders, written.name.span) { @@ -225,6 +225,9 @@ impl ExprNode for StructLiteral { { expected } + // Reported where it was written, or a `T` only a copy knows: + // `let b: Box = .{ ... }` in a generic function's own body. + (None, Some(TypeId::INVALID)) => TypeId::INVALID, (None, _) => { let message = "this struct literal needs its type: write it before `.{`"; builder @@ -248,8 +251,10 @@ impl ExprNode for StructLiteral { .checker .error(diagnostics::TYPE_MISMATCH, message, span); } + // For their own errors; what each field's type is, is not known. for field in tree.children.lists.items(fields) { - builder.add_expr(tree.children.field_values[field].value, None); // for its own errors + let value = tree.children.field_values[field].value; + builder.add_expr(value, Some(TypeId::INVALID)); } return thir::Expr::INVALID; }; @@ -260,7 +265,7 @@ impl ExprNode for StructLiteral { for field in tree.children.lists.items(fields) { let ast::FieldValue { name, value } = tree.children.field_values[field]; let Some((index, field_type)) = builder.field_index(ty, name) else { - builder.add_expr(value, None); // for its own errors + builder.add_expr(value, Some(TypeId::INVALID)); // for its own errors continue; }; if let Some(first) = set[index] { diff --git a/crates/features/src/testing.rs b/crates/features/src/testing.rs index 14b94919..30b862b5 100644 --- a/crates/features/src/testing.rs +++ b/crates/features/src/testing.rs @@ -7,8 +7,8 @@ use arena::Id; use check::Checker; use diagnostics::Diagnostic; use model::ConstArguments; +use model::DeclarationCopy; use model::DefId; -use model::FunctionCopy; use model::ModuleId; use model::machine::Machine; use model::thir::Body; @@ -101,7 +101,7 @@ pub(crate) fn bodies(text: &str) -> (Vec, Vec) { let name = |function: DefId| names[function.index as usize].as_str(); (functions.iter()) .map(|&(definition, span)| { - let copy = FunctionCopy { + let copy = DeclarationCopy { definition, arguments: ConstArguments::NONE, }; diff --git a/crates/features/src/text/tests.rs b/crates/features/src/text/tests.rs index 7228c048..f399e67f 100644 --- a/crates/features/src/text/tests.rs +++ b/crates/features/src/text/tests.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use model::ConstArguments; -use model::FunctionCopy; +use model::DeclarationCopy; use model::semantic_types::TypeId; use model::thir::Body; use source::SourceFile; @@ -72,7 +72,7 @@ fn a_run_gives_back_a_c_string_without_its_end() { let (built, reported) = with_checker(text, |checker, functions| { let (definition, name) = functions[1]; let mut body = Body::default(); - let copy = FunctionCopy { + let copy = DeclarationCopy { definition, arguments: ConstArguments::NONE, }; diff --git a/crates/middle/check/src/builtin.rs b/crates/middle/check/src/builtin.rs index 4cefc4f5..6b489d03 100644 --- a/crates/middle/check/src/builtin.rs +++ b/crates/middle/check/src/builtin.rs @@ -3,7 +3,7 @@ //! `model::semantic_types` (`Types::builtin`). use bigint::Limbs; -use model::FunctionCopy; +use model::DeclarationCopy; use model::constant::Value; use model::layout::layout; use model::semantic_types::ConstArgument; @@ -70,7 +70,7 @@ impl Checker<'_, L> { /// is given, answers when its call at `span` runs (`evaluate_call`): the /// fact of that type its name asks for. `None` for a type the fact is /// not of, reported. - pub(crate) fn builtin_value(&mut self, function: FunctionCopy, span: Span) -> Option { + pub(crate) fn builtin_value(&mut self, function: DeclarationCopy, span: Span) -> Option { let &[ConstArgument::Type(ty)] = self.types.arguments(function.arguments) else { unreachable!("a `#[builtin]` function takes one type") }; diff --git a/crates/middle/check/src/constraints.rs b/crates/middle/check/src/constraints.rs index 4a4a8031..51952479 100644 --- a/crates/middle/check/src/constraints.rs +++ b/crates/middle/check/src/constraints.rs @@ -61,9 +61,9 @@ impl Checker<'_, L> { } } } - let call = (self.internals.function_copies.get(©)) - .map(|copied| (copied.called_in, copied.called_at)); - let made = call.map_or(String::new(), |_| { + let used = + (self.internals.copies.get(©)).map(|copied| (copied.used_in, copied.used_at)); + let made = used.map_or(String::new(), |_| { let name = model::program::copy_name(self.modules, &self.types, copy); format!(" for `{name}`") }); @@ -74,11 +74,11 @@ impl Checker<'_, L> { let text = tree.file.slice(span); let message = format!("`{text}` is false{made}"); let mut diagnostic = Diagnostic::new(diagnostics::INVALID_OPERATION, message); - if let Some((called_in, called_at)) = call { - let file = &self.modules[called_in.index()].ast.file; - diagnostic = diagnostic.label(file, called_at, ""); + if let Some((used_in, used_at)) = used { + let file = &self.modules[used_in.index()].ast.file; + diagnostic = diagnostic.label(file, used_at, ""); } - // A copy's is moved to the call's module (`report_from_copy`). + // A copy's is moved to the use's module (`report_from_copy`). self.report(diagnostic.label(&tree.file, span, "")); } holds diff --git a/crates/middle/check/src/copies.rs b/crates/middle/check/src/copies.rs new file mode 100644 index 00000000..1c20c5e9 --- /dev/null +++ b/crates/middle/check/src/copies.rs @@ -0,0 +1,258 @@ +//! Copies of a declaration with type or `const` parameters, a function's +//! (`fn Max`) or a type's (`struct Box`): each list of arguments +//! makes its own copy, checked once, with what its parameters are given. +//! What a copy is, each kind of declaration checks itself: a function its +//! signature, then its body (`next_copy`); a type its declaration. + +use std::sync::Arc; + +use arena::Id; +use arena::List; +use diagnostics::Diagnostic; +use model::ConstArguments; +use model::DeclarationCopy; +use model::DefId; +use model::ModuleId; +use model::semantic_types::ConstArgument; +use model::semantic_types::Type; +use model::semantic_types::TypeId; +use source::Span; +use syntax::ast; + +use crate::COPY_DEPTH_LIMIT; +use crate::Checked; +use crate::Checker; +use crate::Checking; +use crate::Copied; +use crate::expression::calls; + +impl Checker<'_, L> { + /// The type of `copy`, asked for at `used_at`: given nothing, its + /// declaration's own (`function_type`, `declared_type`); else the type + /// of its copy for what it is given, made the first time it is asked + /// for, and for a function kept for the compile to build its body + /// (`next_copy`). Invalid when the declaration's own check, or the + /// copy's, has an error, or when copies are made inside each other too + /// deep (`COPY_DEPTH_LIMIT`), reported at `used_at`. + pub fn copy_type(&mut self, copy: DeclarationCopy, used_at: Span) -> TypeId { + let has_body = matches!( + model::program::declaration(self.modules, copy.definition), + ast::Decl::Function(_) + ); + let check = if has_body { + Checker::check_function + } else { + Checker::check_type_declaration + }; + let own = self.check_once( + copy.definition, + used_at, + |module| &mut module.declared_types, + TypeId::INVALID, + check, + ); + if copy.arguments == ConstArguments::NONE || own == TypeId::INVALID { + return own; + } + // Named in a type's own check by what names `T` + // (`named_without_types`): its own check's name, which no value has. + if copy.arguments == self.own_arguments(copy.definition) { + return TypeId::INVALID; + } + if let Some(&Copied { ty, .. }) = self.internals.copies.get(©) { + // Invalid only while it is checked, as one with an error is not + // kept: asked for again there, as a `where` or a field can. + if ty == TypeId::INVALID { + let mut checking = self.internals.declarations_being_checked.iter(); + let start = (checking.position(|checking| checking.copy() == copy)) + .expect("a copy without a type is being checked"); + self.report_cycle(start, used_at); + } + return ty; + } + let made_inside = self + .internals + .declarations_being_checked + .last() + .expect("a use is being checked") + .copy(); + // A function's own signature and body, with no type for its `T`, + // are checked for their names only, so they make no copy. A type's + // own check does: it finds what its fields hold. + let made_by_function = matches!( + model::program::declaration(self.modules, made_inside.definition), + ast::Decl::Function(_) + ); + if made_by_function + && made_inside.arguments != ConstArguments::NONE + && !self.internals.copies.contains_key(&made_inside) + { + return TypeId::INVALID; + } + let (depth, reported_in) = match self.internals.copies.get(&made_inside) { + Some(inside) => (inside.depth + 1, inside.reported_in), + None => (1, self.current_module()), + }; + if depth > COPY_DEPTH_LIMIT { + // Reported once: the declaration that made the copy has the error. + if std::mem::replace(&mut self.internals.copies_too_deep, true) { + return TypeId::INVALID; + } + let name = model::program::declared_path(self.modules, copy.definition); + let message = format!( + "`{name}` makes a new copy of itself inside each copy, without end: \ + copies nest {COPY_DEPTH_LIMIT} deep here" + ); + return self.error(diagnostics::CIRCULAR_DEPENDENCY, message, used_at); + } + self.internals.copies.insert( + copy, + Copied { + ty: TypeId::INVALID, + depth, + reported_in, + used_in: self.current_module(), + used_at, + }, + ); + let module = copy.definition.module.index(); + let reported = self.module_checks[module].diagnostics.len(); + let checking = Checking { + definition: copy.definition, + arguments: copy.arguments, + used_at, + records_facts: true, + }; + // A type's copies are checked inside each other's fields. + let ty = source::grow_stack(|| { + self.checking_in(checking, |checker| check(checker, copy.definition)) + }); + let user = self.current_module(); + self.report_from_copy(copy, reported, user); + if ty == TypeId::INVALID { + // Not kept: another use that asks for it is told why as well. + self.internals.copies.remove(©); + return ty; + } + let copied = (self.internals.copies.get_mut(©)).expect("the copy was just made"); + copied.ty = ty; + if has_body { + self.internals.copies_to_build.push(copy); + } + ty + } + + /// What `definition` named with an argument that has no type stands + /// for: one reported, or one that names a `T` no copy gives yet. + /// Invalid, but in a type's own check, which keeps the declaration + /// named, as in its own check: what holds it by value checks it + /// (`copy_type`), so a type that holds itself, as `Two<[2]T>` in `Two`, + /// is found once, whatever `T` is. + pub(crate) fn named_without_types(&mut self, definition: DefId) -> TypeId { + let checking = (self.internals.declarations_being_checked.last()) + .expect("a declaration is being checked"); + let in_own_type_check = checking.arguments != ConstArguments::NONE + && !self.in_copy() + && matches!( + model::program::declaration(self.modules, checking.definition), + ast::Decl::Type(_) + ); + if !in_own_type_check { + return TypeId::INVALID; + } + let arguments = self.own_arguments(definition); + self.types.intern(Type::Named { + definition, + arguments, + }) + } + + /// A copy of a function whose body the compile has not built + /// (`build_function`), the newest first; building one may make more. + /// None once copies nested too deep. + pub fn next_copy(&mut self) -> Option { + self.internals + .copies_to_build + .pop() + .filter(|_| !self.internals.copies_too_deep) + } + + /// What the declaration `definition` is checked with outside any copy: + /// an invalid type for each of its type and `const` parameters + /// (`declaration_copy_parameters`), so only a type one is read as one + /// (`resolve_global`) and reports nothing; nothing when it has none. + pub(crate) fn own_arguments(&mut self, definition: DefId) -> ConstArguments { + let count = model::program::declaration_copy_parameters(self.modules, definition).count(); + if count == 0 { + return ConstArguments::NONE; + } + let invalid = ConstArgument::Type(TypeId::INVALID); + self.types.const_arguments(&vec![invalid; count]) + } + + /// The types `written` at `span` after `name`, the type declaration + /// `definition`: `Box`, or none, as a bare `Box` is written. `None` + /// after reporting that their count is not its type parameters' count + /// (`declaration_copy_parameters`). + pub(crate) fn written_type_arguments( + &mut self, + definition: DefId, + name: &str, + written: List>, + span: Span, + ) -> Option>>> { + let count = model::program::declaration_copy_parameters(self.modules, definition).count(); + let written: Vec>> = + self.module().ast.children.lists.items(written).collect(); + if written.len() == count { + return Some(written); + } + let message = if count == 0 { + format!("`{name}` takes no type arguments") + } else { + calls::argument_count_message(name, "type argument", count, false, written.len()) + }; + self.error(diagnostics::WRONG_ARGUMENT_COUNT, message, span); + None + } + + /// Moves what checking `copy` reported in its declaration's module, + /// past the first `reported` diagnostics, to the module `into`, each + /// marking the use it was made for. Another copy's check may find the + /// same in the declaration's text: the module keeps the first. + pub(crate) fn report_from_copy( + &mut self, + copy: DeclarationCopy, + reported: usize, + into: ModuleId, + ) { + let modules = self.modules; + let definition = copy.definition; + let found = &mut self.module_checks[definition.module.index()].diagnostics; + if found.len() == reported { + return; + } + let found: Vec = found.drain(reported..).collect(); + let Copied { + used_in, used_at, .. + } = self.internals.copies[©]; + let name = model::program::copy_name(modules, &self.types, copy); + let file = &modules[used_in.index()].ast.file; + let into = &mut self.module_checks[into.index()].diagnostics; + for diagnostic in found { + if into.iter().any(|earlier| earlier.reports_same(&diagnostic)) { + continue; + } + // One that marks the use already, as one about the use itself + // (`constraints_hold`) or a cycle through the copy, says where. + let at_use = (diagnostic.labels.iter()) + .any(|label| Arc::ptr_eq(&label.file, file) && label.span == used_at); + into.push(if at_use { + diagnostic + } else { + let message = format!("in `{name}`, the copy made here"); + diagnostic.label(file, used_at, message) + }); + } + } +} diff --git a/crates/middle/check/src/declaration.rs b/crates/middle/check/src/declaration.rs index 5ba637e8..485af6f0 100644 --- a/crates/middle/check/src/declaration.rs +++ b/crates/middle/check/src/declaration.rs @@ -3,8 +3,10 @@ //! value. use arena::Id; +use arena::List; use diagnostics::Diagnostic; use model::ConstArguments; +use model::DeclarationCopy; use model::DefId; use model::layout::layout; use model::program::BUILTIN_ATTRIBUTE; @@ -104,8 +106,12 @@ impl FunctionKind { impl Checker<'_, L> { /// The type the module's type declaration or alias `definition` declares: - /// a feature's (`declare_type`), or the type an alias names. Type - /// parameters are not supported yet. + /// a feature's (`declare_type`), or the type an alias names. One with + /// type parameters, `struct Box`, declares a type in each copy + /// (`copy_type`); its own check, with no type for its `T` + /// (`own_arguments`), reports what is wrong whatever its types are and + /// gives its name given nothing (`Type::Named`), which no value has; + /// invalid when that check reported an error. pub(crate) fn check_type_declaration(&mut self, definition: DefId) -> TypeId { let tree = &self.module().ast; let (written, is_alias) = match tree.decls[tree.declaration(definition.index)] { @@ -113,16 +119,30 @@ impl Checker<'_, L> { ast::Decl::Alias(written) => (written, true), _ => unreachable!("`{definition:?}` is a type declaration"), }; - if !written.type_parameters.is_empty() { - return self.not_supported(written.name.span, "generic types"); - } if is_alias { + if !written.type_parameters.is_empty() { + return self.not_supported(written.name.span, "generic aliases"); + } return self.resolve_value_type(written.ty); } let ast::Type::Feature(ty) = tree.types[written.ty] else { unreachable!("the parser gives a type declaration only a feature's type") }; - L::declare_type(self, definition, written, ty) + if written.type_parameters.is_empty() || self.in_copy() { + return L::declare_type(self, definition, written, ty); + } + let module = definition.module.index(); + let reported = self.module_checks[module].diagnostics.len(); + // Invalid whenever a field is of a type `T` names, which reports nothing. + L::declare_type(self, definition, written, ty); + let found = &self.module_checks[module].diagnostics[reported..]; + if found.iter().any(Diagnostic::is_error) { + return TypeId::INVALID; + } + self.types.intern(Type::Named { + definition, + arguments: ConstArguments::NONE, + }) } /// Reports each attribute of the declaration `definition` but an @@ -150,21 +170,6 @@ impl Checker<'_, L> { } } - /// What the function of `signature`, in `tree`, is checked with outside - /// any copy: an invalid type for each type parameter, ``, which come - /// first, then for each `const` parameter. Only a type one - /// is read as one (`resolve_global`), and an invalid type reports - /// nothing. - pub(crate) fn own_arguments( - &mut self, - tree: &ast::Tree, - signature: ast::Signature, - ) -> ConstArguments { - let count = model::program::copy_parameters(tree, signature).count(); - let invalid = ConstArgument::Type(TypeId::INVALID); - self.types.const_arguments(&vec![invalid; count]) - } - /// The type of the `const` value parameter written `ty` of the function /// `definition`, for its call at `used_at`. The function's own signature /// read it with no error and no type parameter (`signature_type`), so @@ -176,11 +181,9 @@ impl Checker<'_, L> { ty: Id>, used_at: Span, ) -> TypeId { - let tree = &self.modules[definition.module.index()].ast; - let signature = function_declaration(self.modules, definition).signature; let checking = Checking { definition, - arguments: self.own_arguments(tree, signature), + arguments: self.own_arguments(definition), used_at, records_facts: false, }; @@ -197,6 +200,14 @@ impl Checker<'_, L> { body, .. } = function_declaration(self.modules, definition); + // shortcut: a generic struct's functions are refused until a copy of + // one takes its owner's type arguments. + if let Some(written) = owner + && let Some(owner) = (self.scope()).struct_named(self.modules, written.text(&tree.file)) + && (model::program::declaration_copy_parameters(self.modules, owner).next()).is_some() + { + return self.not_supported(written.span, "functions of generic types"); + } let symbol = model::program::extern_symbol(self.modules, definition); if let Err(span) = symbol { let message = "write `#[extern(\"name\")]` once, with the C function's name"; @@ -215,19 +226,6 @@ impl Checker<'_, L> { let first_const = first_copy_parameter(tree, signature); let module = definition.module.index(); let reported = self.module_checks[module].diagnostics.len(); - let checking = self - .internals - .declarations_being_checked - .last() - .expect("the function is being checked"); - if first_const.is_some() && checking.arguments == ConstArguments::NONE { - let own = self.own_arguments(tree, signature); - self.internals - .declarations_being_checked - .last_mut() - .expect("the function is being checked") - .arguments = own; - } let ty = self.signature_type(name, signature, owner.is_some(), kind); // A copy's signature differs only by what it is given: an error in // the function's own is in each copy's. @@ -460,7 +458,8 @@ impl Checker<'_, L> { "only a reference to a type with members converts to an interface reference" ) }; - let (Type::Named(definition) | Type::Interface { definition, .. }) = self.types[interface] + let (Type::Named { definition, .. } | Type::Interface { definition, .. }) = + self.types[interface] else { unreachable!("an interface reference refers to an interface") }; @@ -708,11 +707,20 @@ impl Checker<'_, L> { self.value_type_at(resolved, span) } - /// `resolved`, written at `span`, as a value's type: a named type is - /// checked. - fn value_type_at(&mut self, resolved: TypeId, span: Span) -> TypeId { + /// `resolved`, written at `span`, as a value's type: a named type, or + /// copy of one, is checked (`copy_type`). + pub(crate) fn value_type_at(&mut self, resolved: TypeId, span: Span) -> TypeId { match self.types[resolved] { - Type::Named(definition) => self.declared_type(definition, span), + Type::Named { + definition, + arguments, + } => self.copy_type( + DeclarationCopy { + definition, + arguments, + }, + span, + ), _ => resolved, } } @@ -721,7 +729,7 @@ impl Checker<'_, L> { pub(crate) fn is_interface(&self, ty: TypeId) -> bool { match self.types[ty] { Type::Interface { .. } => true, - Type::Named(definition) => { + Type::Named { definition, .. } => { model::program::interface_methods(self.modules, definition).is_some() } _ => false, @@ -912,11 +920,18 @@ impl Checker<'_, L> { /// The type `symbol`, written at `span`, stands for, however it was /// reached: every kind of type declaration is `Symbol::Type`, in this - /// module or another. An error when it is not a type. + /// module or another. An error when it is not a type, or a generic + /// struct named without what it is given (`resolve_type` reads `Box`). pub(crate) fn type_named_by(&mut self, symbol: Symbol, span: Span) -> TypeId { let what = match symbol { Symbol::Builtin(ty) | Symbol::TypeArgument { ty, .. } => return ty, - Symbol::Type(definition) => return self.named_type(definition, span), + Symbol::Type(definition) => { + let name = self.module().ast.file.slice(span); + return match self.written_type_arguments(definition, name, List::EMPTY, span) { + Some(_) => self.named_type(definition, span), + None => TypeId::INVALID, // reported + }; + } Symbol::Function(_) | Symbol::Constant(_) | Symbol::Local(_) => "a value", Symbol::Module(_) => "a module", }; @@ -1100,7 +1115,10 @@ impl Checker<'_, L> { }) => owner, // An interface's method: `self` is the interface. ast::Decl::Type(_) => { - return self.types.intern(Type::Named(checking.definition)); + return self.types.intern(Type::Named { + definition: checking.definition, + arguments: ConstArguments::NONE, + }); } _ => unreachable!("only a type's function and an interface name `self`"), }; @@ -1121,7 +1139,42 @@ impl Checker<'_, L> { None => TypeId::INVALID, // reported }; } - ast::Type::Generic { .. } => "generic types", + // A generic struct's copy, only named, as any struct is: its + // arguments are named too, so `*Box` in `Node` is no + // cycle. A named struct's id becomes its type's once + // checked, so the copy is the same however it is reached. + ast::Type::Generic { name, arguments } => { + let text = name.text(&tree.file); + let definition = match self.resolve_global(text) { + Some(Symbol::Type(definition)) => definition, + None => return self.named_type_at(name.span), // reports it + Some(_) => { + let message = format!("`{text}` takes no type arguments"); + return self.error(diagnostics::WRONG_ARGUMENT_COUNT, message, span); + } + }; + self.record(name.span, FactKind::Name(Symbol::Type(definition))); + let Some(written) = + self.written_type_arguments(definition, text, arguments, span) + else { + return TypeId::INVALID; // reported + }; + let mut given = Vec::with_capacity(written.len()); + for argument in written { + let resolved = self.resolve_type(argument); + let span = self.module().ast.types.span(argument); + let resolved = self.type_argument(resolved, span); + given.push(ConstArgument::Type(self.types.real(resolved))); + } + if given.contains(&ConstArgument::Type(TypeId::INVALID)) { + return self.named_without_types(definition); + } + let arguments = self.types.const_arguments(&given); + return self.types.intern(Type::Named { + definition, + arguments, + }); + } ast::Type::Bracketed { name, inner } => { let written = tree.file.slice(name.span); if written != semantic_types::RANGE { diff --git a/crates/middle/check/src/expression.rs b/crates/middle/check/src/expression.rs index 5af63b81..1793cbff 100644 --- a/crates/middle/check/src/expression.rs +++ b/crates/middle/check/src/expression.rs @@ -2,7 +2,7 @@ //! operation on values known at compile time is folded to its value. mod borrows; -mod calls; +pub(crate) mod calls; mod literals; mod operators; mod places; diff --git a/crates/middle/check/src/expression/calls.rs b/crates/middle/check/src/expression/calls.rs index 37091b71..e695fbc4 100644 --- a/crates/middle/check/src/expression/calls.rs +++ b/crates/middle/check/src/expression/calls.rs @@ -7,8 +7,8 @@ use arena::Id; use arena::List; use model::Callee; use model::ConstArguments; +use model::DeclarationCopy; use model::DefId; -use model::FunctionCopy; use model::constant::Value; use model::semantic_types::ConstArgument; use model::semantic_types::Constant; @@ -347,7 +347,7 @@ impl ThirBuilder<'_, '_, L> { match symbol { Some(Symbol::Function(definition)) => { let ty = self.checker.function_type(definition, span); - let function = FunctionCopy { + let function = DeclarationCopy { definition, arguments: ConstArguments::NONE, }; @@ -458,7 +458,7 @@ impl ThirBuilder<'_, '_, L> { }) .count(); if arguments.len() < required { - let function = FunctionCopy { + let function = DeclarationCopy { definition, arguments: ConstArguments::NONE, }; @@ -574,7 +574,7 @@ impl ThirBuilder<'_, '_, L> { if failed { return None; } - let copy = FunctionCopy { + let copy = DeclarationCopy { definition, arguments: self.checker.types.const_arguments(&given), }; @@ -592,7 +592,7 @@ impl ThirBuilder<'_, '_, L> { interface: TypeId, name: Ident, ) -> Option<(Id, Callee, TypeId)> { - let (Type::Named(definition) | Type::Interface { definition, .. }) = + let (Type::Named { definition, .. } | Type::Interface { definition, .. }) = self.checker.types[interface] else { unreachable!("an interface reference refers to an interface") @@ -678,7 +678,7 @@ fn constant_expr(constant: Option) -> Expr { /// Why a call of `callee` with `given` arguments is wrong, when it takes /// `fixed` of them, or at least that many when `variadic`. -fn argument_count_message( +pub(crate) fn argument_count_message( callee: &str, what: &str, fixed: usize, diff --git a/crates/middle/check/src/expression/places.rs b/crates/middle/check/src/expression/places.rs index c81bc337..a2aa8b38 100644 --- a/crates/middle/check/src/expression/places.rs +++ b/crates/middle/check/src/expression/places.rs @@ -378,11 +378,13 @@ impl ThirBuilder<'_, '_, L> { /// What `reference`, whose type refers to `target`, refers to: a place. pub(super) fn dereference(&mut self, reference: Id, target: TypeId) -> Expr { let pointer = self.body.exprs[reference].ty; - let ty = match (&self.checker.types[pointer], &self.checker.types[target]) { - // Only a struct with an error stays a name; lowering stops at this. - (_, Type::Named(_)) => TypeId::INVALID, - (Type::RawPointer { .. }, _) => { - let span = self.body.exprs.span(reference); + let span = self.body.exprs.span(reference); + // A pointer only names its target, which may hold it (`*Node` in + // `Node`): reaching through it uses the target as a value, invalid + // for a struct with an error, where lowering stops. + let target = self.checker.value_type_at(target, span); + let ty = match self.checker.types[pointer] { + Type::RawPointer { .. } if target != TypeId::INVALID => { let held = self.checker.reached_through_pointer(target, span); held.unwrap_or(TypeId::INVALID) } diff --git a/crates/middle/check/src/function.rs b/crates/middle/check/src/function.rs index d70cb6a9..c688686b 100644 --- a/crates/middle/check/src/function.rs +++ b/crates/middle/check/src/function.rs @@ -1,16 +1,13 @@ //! A function's body built to checked MIR (THIR, lowering, the path checks), //! and calls run at compile time on it (`evaluate_call`). -use std::sync::Arc; - use diagnostics::Diagnostic; use eval::interpreter::ADDRESS_NOT_KNOWN; use eval::interpreter::ConstantShape; use eval::interpreter::Failure; use model::ConstArguments; +use model::DeclarationCopy; use model::DefId; -use model::FunctionCopy; -use model::ModuleId; use model::constant::Value; use model::mir; use model::semantic_types::Type; @@ -21,11 +18,8 @@ use source::Span; use syntax::ast; use syntax::ast::Language; -use crate::COPY_DEPTH_LIMIT; use crate::Checked; use crate::Checker; -use crate::Checking; -use crate::Copied; /// How far the body of a function is built (`Checker::build_function`), /// once it is. @@ -49,7 +43,7 @@ impl Checker<'_, L> { /// way round) finds the same and drops it. pub fn build_function( &mut self, - copy: FunctionCopy, + copy: DeclarationCopy, used_at: Span, thir: &mut thir::Body, records_facts: bool, @@ -69,149 +63,12 @@ impl Checker<'_, L> { if !first { found.truncate(reported); } else if copy.arguments != ConstArguments::NONE { - let into = self.internals.function_copies[©].reported_in; + let into = self.internals.copies[©].reported_in; self.report_from_copy(copy, reported, into); } mir.map(|mir| mir.filter(|_| !failed)) } - /// The type of `copy`, asked for at `used_at`: a plain function's - /// (`function_type`), or, for a function with `const T: type` - /// parameters, the type of its copy for the types it is given, made the - /// first time a call asks for it and kept for the compile to build its - /// body (`next_copy`). Invalid when the function's own signature, or - /// the copy's, has an error, or when copies are made inside each other - /// too deep (`COPY_DEPTH_LIMIT`), reported at `used_at`. - pub fn copy_type(&mut self, copy: FunctionCopy, used_at: Span) -> TypeId { - let pattern = self.function_type(copy.definition, used_at); - if copy.arguments == ConstArguments::NONE || pattern == TypeId::INVALID { - return pattern; - } - if let Some(&Copied { signature, .. }) = self.internals.function_copies.get(©) { - // Invalid only while its signature is checked, as one with an - // error is not kept: asked for again there, as a `where` can. - if signature == TypeId::INVALID { - let mut checking = self.internals.declarations_being_checked.iter(); - let start = (checking.position(|checking| checking.copy() == copy)) - .expect("a copy without a signature is being checked"); - self.report_cycle(start, used_at); - } - return signature; - } - let made_inside = self - .internals - .declarations_being_checked - .last() - .expect("a call is being checked") - .copy(); - // A function's own body (`check_body`) is checked for its names - // only, so it makes no copy. - if made_inside.arguments != ConstArguments::NONE - && !self.internals.function_copies.contains_key(&made_inside) - { - return TypeId::INVALID; - } - let (depth, reported_in) = match self.internals.function_copies.get(&made_inside) { - Some(inside) => (inside.depth + 1, inside.reported_in), - None => (1, self.current_module()), - }; - if depth > COPY_DEPTH_LIMIT { - // Reported once: the body that made the copy has the error. - if std::mem::replace(&mut self.internals.copies_too_deep, true) { - return TypeId::INVALID; - } - let name = model::program::declared_path(self.modules, copy.definition); - let message = format!( - "`{name}` makes a new copy of itself inside each copy, without end: \ - copies nest {COPY_DEPTH_LIMIT} deep here" - ); - return self.error(diagnostics::CIRCULAR_DEPENDENCY, message, used_at); - } - self.internals.function_copies.insert( - copy, - Copied { - signature: TypeId::INVALID, - depth, - reported_in, - called_in: self.current_module(), - called_at: used_at, - }, - ); - let module = copy.definition.module.index(); - let reported = self.module_checks[module].diagnostics.len(); - let checking = Checking { - definition: copy.definition, - arguments: copy.arguments, - used_at, - records_facts: true, - }; - let signature = - self.checking_in(checking, |checker| checker.check_function(copy.definition)); - let caller = self.current_module(); - self.report_from_copy(copy, reported, caller); - if signature == TypeId::INVALID { - // Not kept: another call that asks for it is told why as well. - self.internals.function_copies.remove(©); - return signature; - } - let copied = self - .internals - .function_copies - .get_mut(©) - .expect("the copy was just made"); - copied.signature = signature; - self.internals.copies_to_build.push(copy); - signature - } - - /// A copy of a function with `const T: type` parameters whose body the - /// compile has not built (`build_function`), the newest first; building - /// one may make more. None once copies nested too deep. - pub fn next_copy(&mut self) -> Option { - self.internals - .copies_to_build - .pop() - .filter(|_| !self.internals.copies_too_deep) - } - - /// Moves what checking `copy` reported in its function's module, past - /// the first `reported` diagnostics, to the module `into`, each marking - /// the call it was made for. Another copy's check may find the same in - /// the function's text: the module keeps the first. - fn report_from_copy(&mut self, copy: FunctionCopy, reported: usize, into: ModuleId) { - let modules = self.modules; - let definition = copy.definition; - let found = &mut self.module_checks[definition.module.index()].diagnostics; - if found.len() == reported { - return; - } - let found: Vec = found.drain(reported..).collect(); - let Copied { - called_in, - called_at, - .. - } = self.internals.function_copies[©]; - let name = model::program::copy_name(modules, &self.types, copy); - let file = &modules[called_in.index()].ast.file; - let into = &mut self.module_checks[into.index()].diagnostics; - for diagnostic in found { - if into.iter().any(|earlier| earlier.reports_same(&diagnostic)) { - continue; - } - // One about the call itself (`constraints_hold`) already marks it. - let at_call = diagnostic - .labels - .first() - .is_some_and(|label| Arc::ptr_eq(&label.file, file) && label.span == called_at); - into.push(if at_call { - diagnostic - } else { - let message = format!("in `{name}`, the copy made for this call"); - diagnostic.label(file, called_at, message) - }); - } - } - /// The MIR of the checked THIR `thir` of the function `definition`, of /// type `ty`, path-checked; `None` when it has an error. fn lower_function( @@ -252,7 +109,7 @@ impl Checker<'_, L> { /// error, which was. pub(crate) fn evaluate_call( &mut self, - function: FunctionCopy, + function: DeclarationCopy, arguments: &[Value], span: Span, ) -> Option { @@ -322,7 +179,7 @@ impl Checker<'_, L> { .map(|(argument, &ty)| (argument, shape(ty))) .collect(); let result = shape(*result); - let mir_of = |copy: FunctionCopy| match self.internals.built_bodies.get(©) { + let mir_of = |copy: DeclarationCopy| match self.internals.built_bodies.get(©) { Some(Built::Kept(mir)) => mir.as_deref(), None | Some(Built::Reported) => None, }; diff --git a/crates/middle/check/src/lib.rs b/crates/middle/check/src/lib.rs index 76666af2..7af75875 100644 --- a/crates/middle/check/src/lib.rs +++ b/crates/middle/check/src/lib.rs @@ -5,6 +5,7 @@ pub mod builder; pub mod builtin; mod constraints; +mod copies; pub mod declaration; mod expression; pub mod fold; @@ -23,11 +24,10 @@ use diagnostics::Code; use diagnostics::Diagnostic; use diagnostics::fix::Fix; use function::Built; -use function::function_declaration; use lower::ProgramDebugTypes; use model::ConstArguments; +use model::DeclarationCopy; use model::DefId; -use model::FunctionCopy; use model::ModuleId; use model::machine::Machine; use model::semantic_types::ConstArgument; @@ -112,47 +112,50 @@ struct CheckerInternals { declarations_being_checked: Vec, /// How far the body of each function, or each copy of one, is built /// (`build_function`). - built_bodies: FxHashMap, - /// Each copy of a function with `const T: type` parameters made so far - /// (`copy_type`). - function_copies: FxHashMap, + built_bodies: FxHashMap, + /// Each copy of a function or type with type or `const` parameters + /// made so far (`copy_type`). + copies: FxHashMap, /// The copies made whose bodies the compile has not built yet, in the /// order made; it takes them (`next_copy`). - copies_to_build: Vec, + copies_to_build: Vec, /// Whether copies nested too deep (`COPY_DEPTH_LIMIT`): then no copy's /// body is built any more, as a function that makes two copies inside /// each would make twice as many at each depth. copies_too_deep: bool, } -/// A copy of a function with `const T: type` parameters (`CheckerInternals::function_copies`). +/// A copy of a declaration with type or `const` parameters +/// (`CheckerInternals::copies`). struct Copied { - /// Its function type; invalid while it is checked, as one with an error - /// is removed (`copy_type`). - signature: TypeId, - /// The copies it is made inside, each in the body of the one before, - /// counting itself: 1 for one a plain function's body makes. + /// A function copy's function type, or a type copy's type; invalid + /// while it is checked, as one with an error is removed (`copy_type`). + ty: TypeId, + /// The copies it is made inside, each in the one before, counting + /// itself: 1 for one a declaration given nothing makes. depth: u32, /// The module whose check made it, or the copy it is made inside: what - /// the check of its body finds is reported there. Its signature's - /// errors go to the call's module, as the call's. + /// the check of a function copy's body finds is reported there. Its own + /// check's errors go to the use's module, as the use's. reported_in: ModuleId, - /// The call it was made for, in the module `called_in`. - called_in: ModuleId, - called_at: Span, + /// The use it was made for, a call or a type, in the module `used_in`. + used_in: ModuleId, + used_at: Span, } -/// How deep copies may be made inside each other's bodies (`Copied::depth`): -/// a function whose copy calls a copy for a new type each time would make -/// copies without end. +/// How deep copies may be made inside each other (`Copied::depth`): a +/// function whose copy calls a copy for a new type each time would make +/// copies without end. A type cannot: one that holds a new copy of itself, +/// `struct S { next: S<[2]T> }`, holds itself, found in its own check +/// (`resolve_type`). const COPY_DEPTH_LIMIT: u32 = 64; /// A declaration being checked (`CheckerInternals::declarations_being_checked`). struct Checking { definition: DefId, - /// What its `const` parameters are given, when it is a function that - /// has them: a copy's, or invalid types in its own signature - /// (`own_arguments`); else `ConstArguments::NONE`. + /// What its type and `const` parameters are given, when it is a + /// function or a struct that has them: a copy's, or invalid types in + /// its own check (`own_arguments`); else `ConstArguments::NONE`. arguments: ConstArguments, /// Where its asker wrote its name (its own name, when checked for its /// own sake). @@ -168,10 +171,9 @@ struct Checking { } impl Checking { - /// The function, or copy of one, it is; a declaration of another kind - /// with no arguments. - fn copy(&self) -> FunctionCopy { - FunctionCopy { + /// The declaration, or copy of one, it is. + fn copy(&self) -> DeclarationCopy { + DeclarationCopy { definition: self.definition, arguments: self.arguments, } @@ -247,7 +249,7 @@ impl<'p, L: Checked> Checker<'p, L> { records_editor_facts: record_facts, declarations_being_checked: Vec::new(), built_bodies: FxHashMap::default(), - function_copies: FxHashMap::default(), + copies: FxHashMap::default(), copies_to_build: Vec::new(), copies_too_deep: false, }, @@ -266,13 +268,30 @@ impl<'p, L: Checked> Checker<'p, L> { ) } + /// The name the type declaration `definition`, being checked, gives its + /// type: with what its copy is given, for a type with type parameters + /// (`copy_type`). + pub fn declared_name(&mut self, definition: DefId) -> TypeId { + let checking = (self.internals.declarations_being_checked.last()) + .expect("a declaration is being checked"); + debug_assert_eq!(checking.definition, definition); + let arguments = checking.arguments; + self.types.intern(Type::Named { + definition, + arguments, + }) + } + /// The type the name of the type declaration or alias `definition` stands /// for, named at `used_at`. A type declaration makes its type /// (`Type::Named`, a struct's once checked), so naming it checks nothing; /// an alias names its declared type (`Type::Alias`). pub fn named_type(&mut self, definition: DefId, used_at: Span) -> TypeId { if let ast::Decl::Type(_) = model::program::declaration(self.modules, definition) { - return self.types.intern(Type::Named(definition)); + return self.types.intern(Type::Named { + definition, + arguments: ConstArguments::NONE, + }); } let target = self.declared_type(definition, used_at); if target == TypeId::INVALID { @@ -331,7 +350,7 @@ impl<'p, L: Checked> Checker<'p, L> { } let checking = Checking { definition, - arguments: ConstArguments::NONE, + arguments: self.own_arguments(definition), used_at, records_facts: true, }; @@ -356,9 +375,8 @@ impl<'p, L: Checked> Checker<'p, L> { result } - /// Whether the declaration being checked is a copy of a function with - /// `const T: type` parameters (`copy_type`). A function's own signature - /// and its own body, checked with invalid types (`own_arguments`), are + /// Whether the declaration being checked is a copy (`copy_type`). A + /// declaration's own check, with invalid types (`own_arguments`), is /// none. pub(crate) fn in_copy(&self) -> bool { let checking = self @@ -366,9 +384,7 @@ impl<'p, L: Checked> Checker<'p, L> { .declarations_being_checked .last() .expect("a declaration is being checked"); - self.internals - .function_copies - .contains_key(&checking.copy()) + self.internals.copies.contains_key(&checking.copy()) } /// The type `ty` as a message names it (`Types::text`). @@ -535,7 +551,7 @@ impl<'p, L: Checked> Checker<'p, L> { /// `ty`. Only a body checked once has it: a copy has no facts, and a /// function's own body (`check_body`) makes no copy, so it would have /// only those that other calls happened to make. - pub(crate) fn record_copy(&mut self, name_end: u32, copy: FunctionCopy, ty: TypeId) { + pub(crate) fn record_copy(&mut self, name_end: u32, copy: DeclarationCopy, ty: TypeId) { let checking = self .internals .declarations_being_checked @@ -561,7 +577,7 @@ impl<'p, L: Checked> Checker<'p, L> { /// body's, which declares each local they name, as its `where` does /// (`constraints_hold`); none for a copy, which records none and whose /// body is not the one they name. - pub fn function_facts(&mut self, function: FunctionCopy) -> Vec { + pub fn function_facts(&mut self, function: DeclarationCopy) -> Vec { let definition = function.definition; let facts = &mut self.module_checks[definition.module.index()].facts; (function.arguments == ConstArguments::NONE) @@ -586,10 +602,10 @@ impl<'p, L: Checked> Checker<'p, L> { .collect() } - /// What `name` stands for at the top level: a `const T: type` parameter - /// of the function being checked, the type it is given - /// (`Checking::arguments`; a `const` value is a local of the body); - /// else a built-in type, which no declaration + /// What `name` stands for at the top level: a type parameter of the + /// function or struct being checked, `` or `const T: type`, the type + /// it is given (`Checking::arguments`; a `const` value is a local of the + /// body); else a built-in type, which no declaration /// hides; else a name in the module's scope; else an exported name of /// the prelude. pub(crate) fn resolve_global(&mut self, name: &str) -> Option { @@ -599,14 +615,14 @@ impl<'p, L: Checked> Checker<'p, L> { .last() .expect("a declaration is being checked"); if checking.arguments != ConstArguments::NONE { - // Only a function is given `const` arguments. - let function = function_declaration(self.modules, checking.definition); - let tree = &self.module().ast; - let parameters = model::program::copy_parameters(tree, function.signature); - let names_it = |(_, parameter): &(usize, Option)| { - parameter.is_some_and(|written| tree.file.slice(written) == name) - }; - if let Some((place, Some(declared))) = parameters.enumerate().find(names_it) + let file = &self.module().ast.file; + let found = + model::program::declaration_copy_parameters(self.modules, checking.definition) + .enumerate() + .find(|(_, parameter)| { + parameter.is_some_and(|written| file.slice(written) == name) + }); + if let Some((place, Some(declared))) = found && let ConstArgument::Type(ty) = self.types.arguments(checking.arguments)[place] { return Some(Symbol::TypeArgument { ty, declared }); diff --git a/crates/middle/check/src/statement.rs b/crates/middle/check/src/statement.rs index 56eedeba..37b87f80 100644 --- a/crates/middle/check/src/statement.rs +++ b/crates/middle/check/src/statement.rs @@ -11,7 +11,7 @@ use arena::Id; use arena::List; use diagnostics::Diagnostic; use model::ConstArguments; -use model::FunctionCopy; +use model::DeclarationCopy; use model::constant::Value; use model::semantic_types::ConstArgument; use model::semantic_types::Type; @@ -33,7 +33,6 @@ use crate::Checker; use crate::Checking; use crate::builder::Declared; use crate::builder::ThirBuilder; -use crate::declaration::first_copy_parameter; use crate::function::function_declaration; use crate::scope::report_redeclared; @@ -49,12 +48,12 @@ impl Checker<'_, L> { /// and it reports what is wrong whatever those are. pub fn check_body( &mut self, - copy: FunctionCopy, + copy: DeclarationCopy, used_at: Span, body: &mut Body, records_facts: bool, ) -> bool { - let FunctionCopy { + let DeclarationCopy { definition, arguments, } = copy; @@ -73,11 +72,9 @@ impl Checker<'_, L> { }; let (parameters, result) = (parameters.clone(), *result); let tree = &self.modules[module].ast; - let arguments = match first_copy_parameter(tree, function.signature) { - Some(_) if arguments == ConstArguments::NONE => { - self.own_arguments(tree, function.signature) - } - _ => arguments, + let arguments = match arguments { + ConstArguments::NONE => self.own_arguments(definition), + copy => copy, }; let checking = Checking { definition, diff --git a/crates/middle/check/src/statement/tests.rs b/crates/middle/check/src/statement/tests.rs index 08db9239..9f6353f7 100644 --- a/crates/middle/check/src/statement/tests.rs +++ b/crates/middle/check/src/statement/tests.rs @@ -1,6 +1,6 @@ use model::ConstArguments; +use model::DeclarationCopy; use model::DefId; -use model::FunctionCopy; use model::thir::Body; use source::SourceFile; use syntax::ast; @@ -27,7 +27,7 @@ fn bodies(text: &str) -> (Vec, Vec) { }; let mut body = Body::default(); let checked = checker.check_body( - FunctionCopy { + DeclarationCopy { definition, arguments: ConstArguments::NONE, }, @@ -378,7 +378,7 @@ fn notes(text: &str) -> Vec<(String, Option)> { index: 0, }; checker.check_body( - FunctionCopy { + DeclarationCopy { definition, arguments: ConstArguments::NONE, }, diff --git a/crates/middle/eval/src/interpreter.rs b/crates/middle/eval/src/interpreter.rs index 6ebf8327..8401fb64 100644 --- a/crates/middle/eval/src/interpreter.rs +++ b/crates/middle/eval/src/interpreter.rs @@ -22,8 +22,8 @@ use std::rc::Rc; use arena::Id; use bigint::Limbs; +use model::DeclarationCopy; use model::DefId; -use model::FunctionCopy; use model::constant::Value; use model::machine::Machine; use model::mir::Block; @@ -108,7 +108,7 @@ pub enum Failure { /// It called `callee`, a function or one of its copies, for which /// `mir_of` gave no MIR: the caller of `run_function` knows why. NoMir { - callee: FunctionCopy, + callee: DeclarationCopy, function: DefId, span: Span, }, @@ -137,7 +137,7 @@ pub fn run_function<'b>( arguments: &[(&Value, ConstantShape)], result: ConstantShape, target: &Machine, - mir_of: &dyn Fn(FunctionCopy) -> Option<&'b Body>, + mir_of: &dyn Fn(DeclarationCopy) -> Option<&'b Body>, ) -> Result, Failure> { let mut run = Interpreter::new(target, mir_of, Memory::for_constant()); let span = body.blocks.span(Id::from_index(0)); @@ -208,16 +208,16 @@ struct Frame<'b> { struct Interpreter<'b, 'f> { target: &'f Machine, - mir_of: &'f dyn Fn(FunctionCopy) -> Option<&'b Body>, + mir_of: &'f dyn Fn(DeclarationCopy) -> Option<&'b Body>, steps: u64, // run so far, by every call; past the limit the run stops, so it cannot wrap host: Host, // what a program printed; a constant's call prints nothing memory: Memory, /// Each function called so far: its body and layout, or `None` when /// `mir_of` gives it no body; asked once each. - called: FxHashMap)>>, + called: FxHashMap)>>, /// The functions whose addresses a table holds, in the order of their /// addresses from `FUNCTIONS_START`. - functions: Vec, + functions: Vec, frames: Vec>, /// Of every frame, the running one last. A register holds an integer /// of up to 128 bits, a float's bits or an address, with the bits above @@ -234,7 +234,7 @@ struct Interpreter<'b, 'f> { impl<'b, 'f> Interpreter<'b, 'f> { fn new( target: &'f Machine, - mir_of: &'f dyn Fn(FunctionCopy) -> Option<&'b Body>, + mir_of: &'f dyn Fn(DeclarationCopy) -> Option<&'b Body>, memory: Memory, ) -> Self { Interpreter { @@ -317,7 +317,7 @@ impl<'b, 'f> Interpreter<'b, 'f> { /// The body and layout of `function`, the first time it is called /// worked out and kept; `None` when it has no body. - fn called(&mut self, function: FunctionCopy) -> Option<(&'b Body, Rc)> { + fn called(&mut self, function: DeclarationCopy) -> Option<(&'b Body, Rc)> { if let Some(called) = self.called.get(&function) { return called.clone(); } @@ -360,7 +360,7 @@ impl<'b, 'f> Interpreter<'b, 'f> { } /// The address of `function`, given it the first time. - fn function_address(&mut self, function: FunctionCopy) -> u64 { + fn function_address(&mut self, function: DeclarationCopy) -> u64 { let known = self.functions.iter().position(|&known| known == function); let index = known.unwrap_or_else(|| { self.functions.push(function); @@ -551,7 +551,7 @@ impl<'b, 'f> Interpreter<'b, 'f> { pointer: Operand, signature: u32, id: Id, - ) -> Result { + ) -> Result { let address = self.operand(pointer) as u64; let index = (address.checked_sub(FUNCTIONS_START)) .filter(|offset| offset % FUNCTION_STRIDE == 0) diff --git a/crates/middle/eval/src/interpreter/program.rs b/crates/middle/eval/src/interpreter/program.rs index d497d05d..d84033d9 100644 --- a/crates/middle/eval/src/interpreter/program.rs +++ b/crates/middle/eval/src/interpreter/program.rs @@ -6,8 +6,8 @@ //! runs on. use arena::Id; +use model::DeclarationCopy; use model::DefId; -use model::FunctionCopy; use model::machine::Machine; use model::mir::Body; use model::mir::Instruction; @@ -72,7 +72,7 @@ pub fn run<'b>( main: DefId, body: &'b Body, target: &Machine, - mir_of: &dyn Fn(FunctionCopy) -> Option<&'b Body>, + mir_of: &dyn Fn(DeclarationCopy) -> Option<&'b Body>, ) -> Outcome { let mut run = Interpreter::new(target, mir_of, Memory::for_program()); let ending = match run.run_from(main, body) { @@ -225,7 +225,7 @@ impl<'f> Interpreter<'_, 'f> { pub(super) fn call_outside( &mut self, id: Id, - callee: FunctionCopy, + callee: DeclarationCopy, signature: u32, arguments: &[Operand], ) -> Result<(), Halt> { diff --git a/crates/middle/lower/src/expression.rs b/crates/middle/lower/src/expression.rs index 213bfc22..d5e21a14 100644 --- a/crates/middle/lower/src/expression.rs +++ b/crates/middle/lower/src/expression.rs @@ -5,7 +5,7 @@ use arena::Id; use bigint::Limbs; use model::Callee; use model::ConstArguments; -use model::FunctionCopy; +use model::DeclarationCopy; use model::constant::Value as Constant; use model::layout::layout; use model::mir::Callee as MirCallee; @@ -959,7 +959,7 @@ impl Lowering<'_, L> { // `Shape`; both pass an address, as a call through the table does. let table = (methods.iter().zip(signatures)) .map(|(&definition, &signature)| { - let copy = FunctionCopy { + let copy = DeclarationCopy { definition, arguments: ConstArguments::NONE, }; diff --git a/crates/middle/lower/src/lib.rs b/crates/middle/lower/src/lib.rs index 4578227a..a9108300 100644 --- a/crates/middle/lower/src/lib.rs +++ b/crates/middle/lower/src/lib.rs @@ -537,7 +537,7 @@ impl Lowering<'_, L> { | Type::Struct { .. } | Type::Array { .. } | Type::Range { .. } => None, - Type::Invalid | Type::Void | Type::Function { .. } | Type::Named(_) => { + Type::Invalid | Type::Void | Type::Function { .. } | Type::Named { .. } => { unreachable!("no value has this type") } Type::Alias { .. } => unreachable!("indexing looks through aliases"), @@ -667,7 +667,7 @@ impl Lowering<'_, L> { Type::Reference { .. } | Type::RawPointer { .. } => { let to = match self.types[ty].pointee() { // A struct with an error: this output is never linked. - Some(pointee) if matches!(self.types[pointee], Type::Named(_)) => None, + Some(pointee) if matches!(self.types[pointee], Type::Named { .. }) => None, // shortcut: past `DEEPEST_DEBUG_TYPE` a debugger sees an // untyped pointer, or a struct with no fields. Some(_) if depth == DEEPEST_DEBUG_TYPE => None, @@ -762,7 +762,8 @@ impl Lowering<'_, L> { Type::Struct { definition, fields, .. } => { - let name = model::program::declared_text(self.modules, *definition).to_string(); + // A generic struct's copy as written: `Box`. + let name = model::program::type_text(self.modules, self.types, ty); let names = model::program::field_names(self.modules, *definition); let fields: Vec<(String, TypeId)> = (names.map(str::to_string).zip(fields.iter().copied())).collect(); @@ -778,7 +779,7 @@ impl Lowering<'_, L> { .into(); return self.debug_struct(ty, &name, &fields, depth); } - Type::Invalid | Type::Void | Type::Function { .. } | Type::Named(_) => { + Type::Invalid | Type::Void | Type::Function { .. } | Type::Named { .. } => { unreachable!("no value has this type") } Type::Alias { .. } => unreachable!("indexing looks through aliases"), diff --git a/crates/middle/lower/src/tests.rs b/crates/middle/lower/src/tests.rs index d3311828..5b93d4ad 100644 --- a/crates/middle/lower/src/tests.rs +++ b/crates/middle/lower/src/tests.rs @@ -6,8 +6,8 @@ use std::sync::Arc; use check::Checker; use features::Peeper; use model::ConstArguments; +use model::DeclarationCopy; use model::DefId; -use model::FunctionCopy; use model::ModuleId; use model::machine::Machine; use model::mir; @@ -47,7 +47,7 @@ fn lower_main(text: &str, target: &str) -> (String, mir::Body, DebugTypes) { _ => None, }) .expect("the program has a `main`"); - let main = FunctionCopy { + let main = DeclarationCopy { definition: DefId { module: ModuleId::from_index(0), index: index as u32, @@ -73,7 +73,7 @@ fn lower_main(text: &str, target: &str) -> (String, mir::Body, DebugTypes) { ) .expect("the body lowers"); let name_of = - |function: FunctionCopy| model::program::declared_path(&modules, function.definition); + |function: DeclarationCopy| model::program::declared_path(&modules, function.definition); (mir.text(&file, name_of), mir, debug_types.table) } diff --git a/crates/middle/model/src/layout.rs b/crates/middle/model/src/layout.rs index 1e2f4f4d..9defb4d1 100644 --- a/crates/middle/model/src/layout.rs +++ b/crates/middle/model/src/layout.rs @@ -56,7 +56,7 @@ pub fn layout(types: &Types, ty: TypeId, target: &Machine) -> (u64, u64) { let (size, align) = layout(types, internals.base, target); (size.saturating_mul(internals.count), align) } - Type::Invalid | Type::Void | Type::Function { .. } | Type::Named(_) => { + Type::Invalid | Type::Void | Type::Function { .. } | Type::Named { .. } => { unreachable!("no value is laid out with this type") } Type::Alias { .. } => unreachable!("indexing looks through aliases"), diff --git a/crates/middle/model/src/lib.rs b/crates/middle/model/src/lib.rs index de9194ea..d2dfb5de 100644 --- a/crates/middle/model/src/lib.rs +++ b/crates/middle/model/src/lib.rs @@ -50,11 +50,11 @@ impl ConstArguments { pub const NONE: ConstArguments = ConstArguments(0); } -/// A function as a call names it: its declaration, and what its `const` -/// parameters are given, which makes this copy of it -/// (`ConstArguments::NONE` for a function without them). +/// A declaration as it is named: a function at a call, or a type, with +/// what its type and `const` parameters are given, which makes this copy +/// of it (`ConstArguments::NONE` for one without them). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct FunctionCopy { +pub struct DeclarationCopy { pub definition: DefId, pub arguments: ConstArguments, } @@ -64,6 +64,6 @@ pub struct FunctionCopy { /// argument, which the call gives as its `self` (THIR's and MIR's `Call`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Callee { - Function(FunctionCopy), + Function(DeclarationCopy), Method(u32), } diff --git a/crates/middle/model/src/mir.rs b/crates/middle/model/src/mir.rs index 4b4ff8ec..22f9f018 100644 --- a/crates/middle/model/src/mir.rs +++ b/crates/middle/model/src/mir.rs @@ -10,7 +10,7 @@ use std::fmt::Write; -use crate::FunctionCopy; +use crate::DeclarationCopy; use arena::Arena; use arena::Id; use arena::List; @@ -276,7 +276,7 @@ pub enum Global { Bytes(Box<[u8]>), /// A table of function addresses, in order, each with how it is called: /// a module may hold a table of functions it never calls. - Functions(Box<[(FunctionCopy, Signature)]>), + Functions(Box<[(DeclarationCopy, Signature)]>), } /// How a function takes its parameters and gives its result. @@ -741,7 +741,7 @@ pub enum InstructionKind { pub enum Callee { /// A function of the program, or a copy of one; an `extern` function /// has no body. - Function(FunctionCopy), + Function(DeclarationCopy), /// The function whose address the operand gives. Pointer(Operand), } @@ -956,7 +956,7 @@ impl Body { /// Each function the body may run: those it calls, and those in its /// tables, which a method call reaches through an interface value. - pub fn named_functions(&self) -> impl Iterator { + pub fn named_functions(&self) -> impl Iterator { let called = self .instructions .ids() @@ -1025,7 +1025,7 @@ impl Body { /// temporary), a place as its root then `[+8]`, `[*]` or `[%3 * 4]`. /// The globals follow the blocks: bytes as text, a table by its /// functions' names. - pub fn text(&self, file: &SourceFile, name_of: impl Fn(FunctionCopy) -> String) -> String { + pub fn text(&self, file: &SourceFile, name_of: impl Fn(DeclarationCopy) -> String) -> String { let mut printer = Printer { body: self, file, @@ -1066,7 +1066,7 @@ impl Body { struct Printer<'b> { body: &'b Body, file: &'b SourceFile, - name_of: &'b dyn Fn(FunctionCopy) -> String, + name_of: &'b dyn Fn(DeclarationCopy) -> String, out: String, } diff --git a/crates/middle/model/src/program.rs b/crates/middle/model/src/program.rs index 5aee3de1..7a19eeaf 100644 --- a/crates/middle/model/src/program.rs +++ b/crates/middle/model/src/program.rs @@ -6,12 +6,13 @@ use std::path::Path; use std::path::PathBuf; use std::sync::Arc; +use arena::List; use diagnostics::Diagnostic; use source::SourceFile; use source::Span; +use crate::DeclarationCopy; use crate::DefId; -use crate::FunctionCopy; use crate::ModuleId; use crate::constant::Value; use crate::semantic_types::ConstArgument; @@ -127,6 +128,26 @@ pub fn extern_symbol( Ok(symbol) } +/// What a copy of the declaration `definition` of `modules` is made for, as +/// `copy_parameters` says: a function's from its signature, a type's its +/// ``, as in `struct Box`; none for any other declaration. +pub fn declaration_copy_parameters( + modules: &[Module], + definition: DefId, +) -> impl Iterator> { + let tree = &modules[definition.module.index()].ast; + let (signature, type_parameters) = match declaration(modules, definition) { + ast::Decl::Function(function) => (Some(function.signature), List::EMPTY), + ast::Decl::Type(written) | ast::Decl::Alias(written) => (None, written.type_parameters), + _ => (None, List::EMPTY), + }; + let declared_type = (tree.children.lists.items(type_parameters)) + .map(|parameter| Some(tree.children.names.span(parameter))); + (signature.into_iter()) + .flat_map(|signature| copy_parameters(tree, signature)) + .chain(declared_type) +} + /// What a copy of the function with `signature`, in `tree`, is made for, in /// the order its `ConstArguments` hold them: each type parameter, ``, /// then each `const` parameter. `Some` is where one that stands for a type @@ -193,7 +214,7 @@ pub fn symbol(modules: &[Module], definition: DefId) -> String { pub fn copy_symbol( modules: &[Module], types: &Types, - copy: FunctionCopy, + copy: DeclarationCopy, ) -> String { let qualified = |definition: DefId| { let path = &modules[definition.module.index()].path; @@ -218,7 +239,11 @@ pub fn copy_symbol( /// The copy `copy` as a program names it: its declared path, with its /// `const` arguments as Peeper text (`Stack.New`); what messages, /// dumps and a debugger show. -pub fn copy_name(modules: &[Module], types: &Types, copy: FunctionCopy) -> String { +pub fn copy_name( + modules: &[Module], + types: &Types, + copy: DeclarationCopy, +) -> String { let declared = declared_path(modules, copy.definition); types.copy_text(declared, copy.arguments, |definition| { declared_text(modules, definition) diff --git a/crates/middle/model/src/semantic_types.rs b/crates/middle/model/src/semantic_types.rs index d3d787c4..c5484ae7 100644 --- a/crates/middle/model/src/semantic_types.rs +++ b/crates/middle/model/src/semantic_types.rs @@ -4,6 +4,8 @@ use std::fmt; use std::fmt::Display; use std::fmt::Write as _; +use std::hash::Hash; +use std::hash::Hasher; use std::ops::Index; use bigint::Limbs; @@ -212,16 +214,23 @@ pub enum Type { /// declares is checked: naming a type checks nothing. No value has it: a /// value's type is the declaration's own (`Type::Struct`), which takes /// over this id (`define_struct`); only a raw pointer's target can stay - /// this, when its declaration has an error. - Named(DefId), - /// The type a struct declaration makes, with its fields' types in order. - /// The declaration is its identity, so two structs with the same fields - /// differ; the field names stay in the declaration. A field held by value - /// has its own struct's type, so the type is complete. A raw pointer in a - /// field can reach the struct again, so a walk over types stops at - /// pointers or remembers the structs it met. + /// this, when its declaration has an error. `arguments`: the types a + /// generic struct is given, `Box`, which make its own copy; + /// `ConstArguments::NONE` for any other. + Named { + definition: DefId, + arguments: ConstArguments, + }, + /// The type a struct declaration makes, or a copy of a generic one for + /// its `arguments` (`Type::Named`), with its fields' types in order. + /// The declaration and the arguments are its identity, so two structs + /// with the same fields differ; the field names stay in the declaration. + /// A field held by value has its own struct's type, so the type is + /// complete. A raw pointer in a field can reach the struct again, so a + /// walk over types stops at pointers or remembers the structs it met. Struct { definition: DefId, + arguments: ConstArguments, fields: Box<[TypeId]>, internals: StructInternals, }, @@ -341,7 +350,7 @@ impl Type { /// an interface, or a declared name not checked yet. pub fn definition(&self) -> Option { match *self { - Type::Named(definition) + Type::Named { definition, .. } | Type::Struct { definition, .. } | Type::Interface { definition, .. } => Some(definition), _ => None, @@ -357,6 +366,7 @@ impl Type { definition, fields, internals, + .. } => Some(Members { definition: *definition, fields, @@ -751,11 +761,16 @@ impl Types { mutable_holder: (fields.iter()).any(|&field| self.holds_loans(field) == Some(true)), }; let slot = &mut self.types[named.0 as usize]; - let Type::Named(definition) = *slot else { + let Type::Named { + definition, + arguments, + } = *slot + else { unreachable!("only a declared name becomes a struct"); }; *slot = Type::Struct { definition, + arguments, fields, internals, }; @@ -767,7 +782,7 @@ impl Types { /// `&Shape` of after. pub fn define_interface(&mut self, named: TypeId, methods: Box<[TypeId]>) { let slot = &mut self.types[named.0 as usize]; - let Type::Named(definition) = *slot else { + let Type::Named { definition, .. } = *slot else { unreachable!("only a declared name becomes an interface"); }; *slot = Type::Interface { @@ -964,7 +979,7 @@ impl Types { Type::Struct { .. } | Type::Interface { .. } => false, // No value of these is moved: an error, nothing, or not yet a value. Type::Invalid | Type::Void | Type::Function { .. } => true, - Type::Alias { .. } | Type::Named(_) => { + Type::Alias { .. } | Type::Named { .. } => { unreachable!("indexing `Types` looks through aliases; no value is named") } } @@ -978,6 +993,92 @@ impl Types { } } + /// Feeds the type `id` to `hasher` by what it is, not by its id, which + /// differs between compiles: a declared type by what `declaration` + /// feeds for it, then what a copy of it is given. A struct's fields and + /// an interface's methods are not fed: its declaration holds them. + pub fn hash( + &self, + id: TypeId, + hasher: &mut H, + declaration: impl Fn(DefId, &mut H) + Copy, + ) { + let ty = &self[id]; + std::mem::discriminant(ty).hash(hasher); + match ty { + Type::Integer(integer) => integer.hash(hasher), + Type::Float(float) => float.hash(hasher), + Type::Function { + parameters, + result, + origins, + variadic, + } => { + parameters.len().hash(hasher); + for ¶meter in parameters { + self.hash(parameter, hasher, declaration); + } + self.hash(*result, hasher, declaration); + origins.hash(hasher); + variadic.hash(hasher); + } + Type::Named { + definition, + arguments, + } + | Type::Struct { + definition, + arguments, + .. + } => { + declaration(*definition, hasher); + let given = self.arguments(*arguments); + given.len().hash(hasher); + for argument in given { + match argument { + ConstArgument::Type(ty) => self.hash(*ty, hasher, declaration), + ConstArgument::Value(constant) => { + self.hash(constant.ty, hasher, declaration); + constant.value.hash(hasher); + } + } + } + } + Type::Interface { definition, .. } => declaration(*definition, hasher), + Type::Array { internals, .. } => { + // Lengths are any number: the count keeps one from reading as + // the type after it. + self.array_lengths(id).count().hash(hasher); + for length in self.array_lengths(id) { + length.hash(hasher); + } + self.hash(internals.base, hasher, declaration); + } + Type::Range { element, .. } => self.hash(*element, hasher, declaration), // `step` follows + Type::Reference { mutable, target } + | Type::Slice { + mutable, + element: target, + } + | Type::InterfaceReference { + mutable, + interface: target, + } => { + mutable.hash(hasher); + // References and pointers nest as deep as the source does. + source::grow_stack(|| self.hash(*target, hasher, declaration)); + } + Type::RawPointer { target } => { + target.is_some().hash(hasher); + if let Some(target) = target { + source::grow_stack(|| self.hash(*target, hasher, declaration)); + } + } + Type::Invalid | Type::Void | Type::Bool | Type::CString | Type::Str => {} + Type::Alias { .. } => unreachable!("indexing looks through aliases"), + } + } + /// The type `id` as a program writes it, a declared type or an alias by its name, /// which `name_of` gives for its declaration: an alias is followed by the /// type itself (`Meters (aka i64)`). @@ -1034,9 +1135,20 @@ impl Types { self.write_real_text(out, *result, name_of); } } - Type::Named(definition) - | Type::Struct { definition, .. } - | Type::Interface { definition, .. } => _ = write!(out, "{}", name_of(*definition)), + // A generic struct's copy as written: `Box`. + Type::Named { + definition, + arguments, + } + | Type::Struct { + definition, + arguments, + .. + } => { + let name = name_of(*definition).to_string(); + out.push_str(&self.copy_text(name, *arguments, name_of)); + } + Type::Interface { definition, .. } => _ = write!(out, "{}", name_of(*definition)), Type::Array { internals, .. } => { for length in self.array_lengths(id) { _ = write!(out, "[{length}]"); diff --git a/crates/middle/model/src/semantic_types/tests.rs b/crates/middle/model/src/semantic_types/tests.rs index 73f9df5d..cc6c29cb 100644 --- a/crates/middle/model/src/semantic_types/tests.rs +++ b/crates/middle/model/src/semantic_types/tests.rs @@ -1,3 +1,4 @@ +use super::ConstArgument; use super::Conversion; use super::FIXED; use super::Float; @@ -8,6 +9,7 @@ use super::TypeId; use super::Types; use super::builtin_doc; use super::integer; +use crate::ConstArguments; use crate::DefId; use crate::ModuleId; use crate::layout::layout; @@ -174,7 +176,10 @@ fn interface_references() { module: ModuleId::from_index(0), index, }; - let shape = types.intern(Type::Named(declaration(0))); + let shape = types.intern(Type::Named { + definition: declaration(0), + arguments: ConstArguments::NONE, + }); let view = types.intern(Type::InterfaceReference { mutable: false, interface: shape, @@ -191,8 +196,17 @@ fn interface_references() { }); types.define_interface(shape, [area].into()); assert!(matches!(types[shape], Type::Interface { .. })); - assert_eq!(types.intern(Type::Named(declaration(0))), shape); - let square = types.intern(Type::Named(declaration(1))); + assert_eq!( + types.intern(Type::Named { + definition: declaration(0), + arguments: ConstArguments::NONE, + }), + shape + ); + let square = types.intern(Type::Named { + definition: declaration(1), + arguments: ConstArguments::NONE, + }); types.define_struct(square, [TypeId::F64].into(), (vec![0], 8, 8)); let reference = |types: &mut Types, mutable, target| types.intern(Type::Reference { mutable, target }); @@ -296,13 +310,17 @@ fn type_text() { module: ModuleId::from_index(0), index, }; - let point = types.intern(Type::Named(declaration(0))); + let point = types.intern(Type::Named { + definition: declaration(0), + arguments: ConstArguments::NONE, + }); let place = types.intern(Type::Alias { definition: declaration(1), real: point, }); let complete = types.intern(Type::Struct { definition: declaration(0), + arguments: ConstArguments::NONE, fields: [TypeId::I32, TypeId::I32].into(), internals: StructInternals { offsets: [0, 4].into(), @@ -314,6 +332,13 @@ fn type_text() { }); let raw = TypeId::RAWPTR; let typed = types.intern(Type::RawPointer { target: Some(raw) }); + // A generic struct's copy names what it is given. + let given = [ConstArgument::Type(TypeId::I32), ConstArgument::Type(point)]; + let arguments = types.const_arguments(&given); + let copy = types.intern(Type::Named { + definition: declaration(0), + arguments, + }); let text = |ty| { types.text(ty, |definition| { ["Point", "Place"][definition.index as usize] @@ -327,6 +352,7 @@ fn type_text() { assert_eq!(text(point), "Point"); assert_eq!(text(place), "Place (aka Point)"); assert_eq!(text(complete), "Point"); + assert_eq!(text(copy), "Point"); assert_eq!(text(raw), "rawptr"); assert_eq!(text(typed), "*rawptr"); } @@ -402,6 +428,7 @@ fn arrays_hold_each_elements_holders() { module: ModuleId::from_index(0), index: 0, }, + arguments: ConstArguments::NONE, fields: [shared, shared].into(), internals: StructInternals { offsets: [0, 8].into(), diff --git a/crates/middle/model/src/thir.rs b/crates/middle/model/src/thir.rs index ee70603d..44890e0a 100644 --- a/crates/middle/model/src/thir.rs +++ b/crates/middle/model/src/thir.rs @@ -7,8 +7,8 @@ use std::fmt::Display; use std::fmt::Write; use crate::Callee; +use crate::DeclarationCopy; use crate::DefId; -use crate::FunctionCopy; use crate::ModuleId; use crate::constant::Value; use crate::semantic_types::Constant; @@ -117,7 +117,10 @@ pub enum FactKind { Literal(TypeId), /// The name of a function with type or `const` parameters, where it is /// called: the copy the call made, and that copy's function type. - Copy { function: FunctionCopy, ty: TypeId }, + Copy { + function: DeclarationCopy, + ty: TypeId, + }, } /// A parameter or a `let` binding, or one the checker makes. diff --git a/docs/feature-front.md b/docs/feature-front.md index 944d0f37..d19f781f 100644 --- a/docs/feature-front.md +++ b/docs/feature-front.md @@ -443,7 +443,7 @@ read the front's types. They move before any feature moves (step 18a): The core of `model` those crates read (`mir`, `machine`, `constant::Value` and the ids in `lib.rs`) reached the checker's types too, so three more -moved: `ConstArguments` (the id in `FunctionCopy`) to `lib.rs`, the widest +moved: `ConstArguments` (the id in `DeclarationCopy`) to `lib.rs`, the widest integer to `machine::MAX_INTEGER_BITS`, and `Constant` and `value_text`, which read a `Type`, to `semantic_types`. diff --git a/test_programs/const_parameters/negative_const_parameters.peep b/test_programs/const_parameters/negative_const_parameters.peep index 717df63a..fc2486d2 100644 --- a/test_programs/const_parameters/negative_const_parameters.peep +++ b/test_programs/const_parameters/negative_const_parameters.peep @@ -57,7 +57,7 @@ fn main() { let f = Size; //~ error[T0043]: functions as values are not supported yet let b = Box.{ x = 1 }; let n: &Named = &b; //~ error[T0001]: `Box` does not implement `Named`: its `Name` takes a `const` parameter, so it is not one function an interface reference can call - println(Double(i32, 2), Double(bool, true)); //~ label: in `Double`, the copy made for this call + println(Double(i32, 2), Double(bool, true)); //~ label: in `Double`, the copy made here println(Value(i32)); let x: i64 = 3; //~ label: `x` gets its value only when the program runs println(Scaled(x, 1)); //~ error[T0004]: the value of a constant must be known at compile time diff --git a/test_programs/generic_functions/negative_where_conditions.peep b/test_programs/generic_functions/negative_where_conditions.peep index 66874e54..2fd36b6b 100644 --- a/test_programs/generic_functions/negative_where_conditions.peep +++ b/test_programs/generic_functions/negative_where_conditions.peep @@ -154,21 +154,21 @@ where } fn main() { - Loop(1); //~ label: in `Loop`, the copy made for this call + Loop(1); //~ label: in `Loop`, the copy made here Max(true, false); //~ error[T0004]: `T: Number` is false for `Max` Whole(Point.{ x = 1 }); //~ error[T0004]: `T: is_int` is false for `Whole` Eight(1); //~ error[T0004]: `T: Sized(8)` is false for `Eight` Times(0, 5); //~ error[T0004]: `N: Positive` is false for `Times` Area(&5); //~ error[T0004]: `T: Shape` is false for `Area` - Area(&Circle.{ radius = 1 }); //~ label: in `Area`, the copy made for this call + Area(&Circle.{ radius = 1 }); //~ label: in `Area`, the copy made here println(Max(1, 2), Eight(2.5), Times(2, 5)); // The same types again are refused again. Max(false, true); //~ error[T0004]: `T: Number` is false for `Max` // Types written at the call are asked about too. Max::(true, false); //~ error[T0004]: `T: Number` is false for `Max` - NotBool(1); //~ label: in `NotBool`, the copy made for this call - Twice(true); //~ label: in `Twice`, the copy made for this call - Negate(2.5); //~ label: in `Negate`, the copy made for this call + NotBool(1); //~ label: in `NotBool`, the copy made here + Twice(true); //~ label: in `Twice`, the copy made here + Negate(2.5); //~ label: in `Negate`, the copy made here } // A call in a copy is refused too, with the call the copy was made for. diff --git a/test_programs/generic_types/negative_generic_types.peep b/test_programs/generic_types/negative_generic_types.peep new file mode 100644 index 00000000..b8a220ac --- /dev/null +++ b/test_programs/generic_types/negative_generic_types.peep @@ -0,0 +1,50 @@ +struct Box { + value: T, +} + +struct Plain { + x: i32, +} + +// Each copy's field is a new, bigger copy: wrong whatever `T` is, so +// reported once, at the struct. +struct Grow { //~ error[T0013]: `Grow` holds itself + inner: Grow>, +} + +// Through another struct's field too, and with two fields growing. +struct Two { //~ error[T0013]: `Two` holds itself + first: Box>, + second: Box>, +} + +struct Holds { //~ error[T0013]: `Holds` holds itself + again: Holds, +} + +// Wrong whatever `T` is: reported once, not at each copy. +struct Wrong { + value: T, + other: Missing, //~ error[T0002]: unknown type `Missing` +} + +fn Box::Get(&self) -> T { //~ error[T0043]: functions of generic types are not supported yet + return self.value; +} + +fn Bare(b: Box) {} //~ error[T0006]: `Box` takes 1 type argument, but 0 were given + +fn TooMany(b: Box) {} //~ error[T0006]: `Box` takes 1 type argument, but 2 were given + +fn NotGeneric(p: Plain) {} //~ error[T0006]: `Plain` takes no type arguments + +fn Uses(g: *Grow, h: Holds, w: Wrong) { + let grown = g.*; +} + +fn main() { + let b: Box = .{ value = true }; //~ error[T0001]: mismatched types: expected `i32`, found `bool` + let e: Box = .{}; //~ error[T0029]: missing field `value` in `Box` + // The literal inside reports nothing more. + let u: Box = .{ value = .{ x = 1 } }; //~ error[T0002]: unknown type `Unknown` +} diff --git a/test_programs/generic_types/run_generic_types.out b/test_programs/generic_types/run_generic_types.out new file mode 100644 index 00000000..ceb9085c --- /dev/null +++ b/test_programs/generic_types/run_generic_types.out @@ -0,0 +1,4 @@ +1 2.5 7 true 9 +1 8 16 +3 1 6 +4 5 16 diff --git a/test_programs/generic_types/run_generic_types.peep b/test_programs/generic_types/run_generic_types.peep new file mode 100644 index 00000000..63a8b4ff --- /dev/null +++ b/test_programs/generic_types/run_generic_types.peep @@ -0,0 +1,62 @@ +//@ run + +// A generic struct, `Box`: each list of types it is given makes its own +// copy of the struct, with its own fields and layout. + +struct Box { + value: T, +} + +struct Pair { + first: A, + second: B, +} + +// A copy points to another of its kind: a pointer only names it. +struct Node { + value: T, + next: *Node, +} + +// A pointer to a struct that holds a bigger copy of this one: only named, +// so no copy grows. +struct Ptr { + to: *T, +} + +struct Chain { + value: T, + next: Ptr>, +} + +// A generic struct that holds a copy of another inside a third. +struct Deep { + inner: Box>, +} + +fn Unwrap(b: Box) -> i32 { + return b.value; +} + +// A generic function names a copy with its own `T`. +fn Nest(value: T) -> Box> { + let made: Box> = .{ value = .{ value = value } }; + return made; +} + +fn main() { + // The type comes from where the value goes, or is written after `::`. + let a: Box = .{ value = 1 }; + let b = Box::.{ value = 2.5 }; + let nested: Box> = .{ value = .{ value = 7 } }; + let pair: Pair = .{ first = true, second = 9 }; + println(a.value, b.value, nested.value.value, pair.first, pair.second); + // In an expression, a type with arguments is written after `::`. + println(size_of(Box::), size_of(Box::), size_of(Node::)); + let mut last: Node = .{ value = 2, next = none }; + let first: Node = .{ value = 1, next = @last }; + println(first.value + first.next.*.value, Unwrap(a), Nest::(6).value.value); + let chain: Chain = .{ value = 4, next = .{ to = none } }; + let deep: Deep = .{ inner = .{ value = .{ value = 5 } } }; + println(chain.value, deep.inner.value.value, size_of(Chain::)); +} diff --git a/test_programs/generic_types/run_i686_generic_types.out b/test_programs/generic_types/run_i686_generic_types.out new file mode 100644 index 00000000..58676f54 --- /dev/null +++ b/test_programs/generic_types/run_i686_generic_types.out @@ -0,0 +1,3 @@ +1 2.5 7 true 9 +1 8 8 +3 1 6 diff --git a/test_programs/generic_types/run_i686_generic_types.peep b/test_programs/generic_types/run_i686_generic_types.peep new file mode 100644 index 00000000..926039e9 --- /dev/null +++ b/test_programs/generic_types/run_i686_generic_types.peep @@ -0,0 +1,44 @@ +//@ run +//@ target: i686-linux + +// A generic struct, `Box`: each list of types it is given makes its own +// copy of the struct, with its own fields and layout. + +struct Box { + value: T, +} + +struct Pair { + first: A, + second: B, +} + +// A copy points to another of its kind: a pointer only names it. +struct Node { + value: T, + next: *Node, +} + +fn Unwrap(b: Box) -> i32 { + return b.value; +} + +// A generic function names a copy with its own `T`. +fn Nest(value: T) -> Box> { + let made: Box> = .{ value = .{ value = value } }; + return made; +} + +fn main() { + // The type comes from where the value goes, or is written after `::`. + let a: Box = .{ value = 1 }; + let b = Box::.{ value = 2.5 }; + let nested: Box> = .{ value = .{ value = 7 } }; + let pair: Pair = .{ first = true, second = 9 }; + println(a.value, b.value, nested.value.value, pair.first, pair.second); + // In an expression, a type with arguments is written after `::`. + println(size_of(Box::), size_of(Box::), size_of(Node::)); + let mut last: Node = .{ value = 2, next = none }; + let first: Node = .{ value = 1, next = @last }; + println(first.value + first.next.*.value, Unwrap(a), Nest::(6).value.value); +} diff --git a/test_programs/structs/negative_check_struct_not_supported.peep b/test_programs/structs/negative_check_struct_not_supported.peep index 33fcb601..63894108 100644 --- a/test_programs/structs/negative_check_struct_not_supported.peep +++ b/test_programs/structs/negative_check_struct_not_supported.peep @@ -1,15 +1,11 @@ // C functions do not take or give structs until the C ABI's struct rules are -// written; generic structs and enums come later. +// written; enums come later. struct Point { x: i32, } type Place = Point; -struct Pair { //~ error[T0043]: generic types are not supported yet - first: T, -} - enum Shape { //~ error[T0043]: enum declarations are not supported yet Circle, } diff --git a/test_programs/types/negative_check_type_alias.peep b/test_programs/types/negative_check_type_alias.peep index 6f56bbab..567caae3 100644 --- a/test_programs/types/negative_check_type_alias.peep +++ b/test_programs/types/negative_check_type_alias.peep @@ -1,7 +1,7 @@ const Limit = 3; type Bound = Limit; //~ error[T0021]: `Limit` is a value, not a type -type Same = T; //~ error[T0043]: generic types are not supported yet +type Same = T; //~ error[T0043]: generic aliases are not supported yet type Lost = Missing; //~ error[T0002]: unknown type `Missing` fn main() {} From 3c3d74b49a77d691ba2b0804eaa5d17030674487 Mon Sep 17 00:00:00 2001 From: itsfuad Date: Tue, 17 Nov 2026 23:16:28 +0600 Subject: [PATCH 03/24] Let any declared type have functions `fn Owner::name` was allowed only on a struct. Any type a module declares can now have functions: a struct, an interface, later an enum. An alias still cannot, as it names a type declared elsewhere. A call with a dot finds the function by the type's declaration rather than its fields. On an interface or an interface reference, the interface's own function (`fn Shape::Twice(&self)`) is found before its methods; inside it, `self.Area()` still goes through the method table, so it runs for every type that implements the interface. A function that shares a name with one of the interface's methods is refused as declared twice, so a call never means both. An unknown name on an interface now suggests its functions too, not another module's private ones. The refusal of an owner now reads "is not a type declared in this module". `Status::Ready` on a refused enum reads as an unknown name in the type, as the type can have functions. --- .../compile/tests/checks_through_features.rs | 8 ++-- crates/middle/check/src/declaration.rs | 4 +- crates/middle/check/src/expression/calls.rs | 38 +++++++++++----- crates/middle/check/src/scope.rs | 43 +++++++++++------- .../middle/model/src/semantic_types/tests.rs | 2 +- .../interfaces/negative_interfaces.peep | 6 +++ .../interfaces/run_interface_functions.out | 2 + .../interfaces/run_interface_functions.peep | 45 +++++++++++++++++++ .../types/negative_type_functions/main.peep | 14 +++--- 9 files changed, 119 insertions(+), 43 deletions(-) create mode 100644 test_programs/interfaces/run_interface_functions.out create mode 100644 test_programs/interfaces/run_interface_functions.peep diff --git a/crates/driver/compile/tests/checks_through_features.rs b/crates/driver/compile/tests/checks_through_features.rs index 45f28d8d..18ac7313 100644 --- a/crates/driver/compile/tests/checks_through_features.rs +++ b/crates/driver/compile/tests/checks_through_features.rs @@ -290,10 +290,10 @@ fn a_type_function_needs_a_struct_of_its_module() { messages, [ "`a` is already declared in this type", - "`Limit` is not a struct declared in this module", - "`Missing` is not a struct declared in this module", - "`Other` is not a struct declared in this module", - "`i32` is not a struct declared in this module", + "`Limit` is not a type declared in this module", + "`Missing` is not a type declared in this module", + "`Other` is not a type declared in this module", + "`i32` is not a type declared in this module", ] ); } diff --git a/crates/middle/check/src/declaration.rs b/crates/middle/check/src/declaration.rs index 485af6f0..590ab423 100644 --- a/crates/middle/check/src/declaration.rs +++ b/crates/middle/check/src/declaration.rs @@ -203,7 +203,7 @@ impl Checker<'_, L> { // shortcut: a generic struct's functions are refused until a copy of // one takes its owner's type arguments. if let Some(written) = owner - && let Some(owner) = (self.scope()).struct_named(self.modules, written.text(&tree.file)) + && let Some(owner) = (self.scope()).owner_named(self.modules, written.text(&tree.file)) && (model::program::declaration_copy_parameters(self.modules, owner).next()).is_some() { return self.not_supported(written.span, "functions of generic types"); @@ -1124,7 +1124,7 @@ impl Checker<'_, L> { }; let owner = self .scope() - .struct_named(self.modules, owner.text(&tree.file)); + .owner_named(self.modules, owner.text(&tree.file)); return owner.map_or(TypeId::INVALID, |owner| self.named_type(owner, span)); } ast::Type::Name => return self.named_type_at(span), diff --git a/crates/middle/check/src/expression/calls.rs b/crates/middle/check/src/expression/calls.rs index e695fbc4..d6c70c93 100644 --- a/crates/middle/check/src/expression/calls.rs +++ b/crates/middle/check/src/expression/calls.rs @@ -12,7 +12,6 @@ use model::DefId; use model::constant::Value; use model::semantic_types::ConstArgument; use model::semantic_types::Constant; -use model::semantic_types::Members; use model::semantic_types::Type; use model::semantic_types::TypeId; use model::thir::Expr; @@ -363,11 +362,13 @@ impl ThirBuilder<'_, '_, L> { } } - /// The function `name` of the struct `value` is or points to, or the + /// The function `name` of the type `value` is or points to, or the /// method `name` of the interface or interface reference `value` is, - /// called with a dot written at `span`: the place of the struct, of the + /// called with a dot written at `span`: the place of the value, of the /// interface, or of what the interface reference views, which the call - /// gives as `self`, the callee, and its type. + /// gives as `self`, the callee, and its type. An interface's own + /// function (`fn Shape::name`) is found before its methods; a name + /// cannot be both (`scope::collect`). fn method( &mut self, value: Id>, @@ -376,16 +377,23 @@ impl ThirBuilder<'_, '_, L> { ) -> Option<(Id, Callee, TypeId)> { let value = self.add_expr(value, None); let ty = self.body.exprs[value].ty; - match self.checker.types[ty] { - Type::InterfaceReference { interface, .. } => { - return self.interface_method(value, interface, name); - } - Type::Interface { .. } => return self.interface_method(value, ty, name), - _ => {} + let interface = match self.checker.types[ty] { + Type::InterfaceReference { interface, .. } => Some(interface), + Type::Interface { .. } => Some(ty), + _ => None, + }; + if let Some(interface) = interface + && let Some(definition) = self.checker.types[interface].definition() + && let text = name.text(&self.checker.module().ast.file) + && (self.checker.module_checks[definition.module.index()].scope) + .get(Some(definition), text) + .is_none() + { + return self.interface_method(value, interface, name); } let place = self.through_pointer(value, self.body.exprs.span(value)); let ty = self.body.exprs[place].ty; - let Some(Members { definition, .. }) = self.checker.types[ty].members() else { + let Some(definition) = self.checker.types[ty].definition() else { if ty != TypeId::INVALID { let message = format!("`{}` has no functions", self.checker.type_text(ty)); self.checker @@ -611,7 +619,13 @@ impl ThirBuilder<'_, '_, L> { }; let head = self.checker.type_text(interface); let Some(slot) = names().position(|method| method == text) else { - let meant = scope::nearest(text, std::iter::empty(), names()); + // Another module's private ones cannot be called from here. + let elsewhere = definition.module != self.checker.current_module(); + let functions = (self.checker.module_checks[definition.module.index()].scope) + .symbols(Some(definition)) + .map(|(function, _)| function) + .filter(|function| !elsewhere || model::program::is_exported(function)); + let meant = scope::nearest(text, names(), functions); let message = format!("unknown name `{text}` in interface `{head}`"); self.checker .report_unknown(diagnostics::UNDEFINED_NAME, name.span, message, meant); diff --git a/crates/middle/check/src/scope.rs b/crates/middle/check/src/scope.rs index ffa24391..d14d87ae 100644 --- a/crates/middle/check/src/scope.rs +++ b/crates/middle/check/src/scope.rs @@ -47,11 +47,11 @@ impl<'p> Scope<'p> { self.names.get(&(owner, name)).map(|&(symbol, _)| symbol) } - /// The struct this module declares as `name`, the only type that can - /// have functions (`fn Point::name`); `None` for any other name. A type + /// The type this module declares as `name`, which can have functions + /// (`fn Point::name`, `has_functions`); `None` for any other name. A type /// here is always this module's: imports bring in modules, and the /// prelude is not copied in. - pub(crate) fn struct_named( + pub(crate) fn owner_named( &self, modules: &[model::program::Module], name: &str, @@ -89,20 +89,17 @@ impl<'p> Scope<'p> { } } -/// Whether the type declaration `definition` can have functions -/// (`fn Point::name`): only a struct can. +/// Whether the declaration `definition` can have functions +/// (`fn Point::name`): any type it declares, not an alias, which names a +/// type declared elsewhere. pub(crate) fn has_functions( modules: &[model::program::Module], definition: DefId, ) -> bool { - let tree = &modules[definition.module.index()].ast; - match model::program::declaration(modules, definition) { - ast::Decl::Type(declaration) => match tree.types[declaration.ty] { - ast::Type::Feature(ty) => L::fields(&ty).is_some(), - _ => false, - }, - _ => false, - } + matches!( + model::program::declaration(modules, definition), + ast::Decl::Type(_) + ) } /// The name nearest to `name` (`nearest_name`): one of `first`, else one of @@ -141,7 +138,7 @@ pub fn report_redeclared( /// The scope of the module `id` of `modules`. A name declared twice keeps /// its first meaning and is reported. A type's functions come after the /// top-level names, since a type may be declared below its functions; the -/// type must be a struct of this module, so it has the same functions +/// type must be one this module declares, so it has the same functions /// everywhere. pub fn collect<'p, L: Language>( id: ModuleId, @@ -209,9 +206,9 @@ pub fn collect<'p, L: Language>( else { continue; }; - let Some(owner_struct) = scope.struct_named(modules, owner.text(file)) else { + let Some(owner_type) = scope.owner_named(modules, owner.text(file)) else { let message = format!( - "`{}` is not a struct declared in this module", + "`{}` is not a type declared in this module", owner.text(file) ); diagnostics.push( @@ -221,10 +218,22 @@ pub fn collect<'p, L: Language>( ); continue; }; + // An interface's own methods are its names too: a call through it + // must mean one. + let text = name.text(file); + let methods = model::program::interface_methods(modules, owner_type).into_iter(); + if let Some(method) = methods + .flatten() + .find(|method| method.name.text(file) == text) + { + let diagnostic = report_redeclared(file, text, "type", name.span, method.name.span); + diagnostics.push(diagnostic); + continue; + } let symbol = Symbol::Function(definition(index)); diagnostics.extend(declare( &mut scope, - Some(owner_struct), + Some(owner_type), name.text(file), symbol, name.span, diff --git a/crates/middle/model/src/semantic_types/tests.rs b/crates/middle/model/src/semantic_types/tests.rs index cc6c29cb..74e238a2 100644 --- a/crates/middle/model/src/semantic_types/tests.rs +++ b/crates/middle/model/src/semantic_types/tests.rs @@ -218,7 +218,7 @@ fn interface_references() { (to_mutable_square, view, Conversion::ToInterface), (to_mutable_square, edit, Conversion::ToInterface), (to_square, edit, Conversion::Never), - (to_number, view, Conversion::Never), // only a struct has methods + (to_number, view, Conversion::Never), // only a declared type has methods (edit, view, Conversion::Reborrow), (view, edit, Conversion::Never), (view, to_square, Conversion::Never), diff --git a/test_programs/interfaces/negative_interfaces.peep b/test_programs/interfaces/negative_interfaces.peep index a03370ce..f15f17ec 100644 --- a/test_programs/interfaces/negative_interfaces.peep +++ b/test_programs/interfaces/negative_interfaces.peep @@ -12,6 +12,10 @@ iface Bad { fn generic(&self, value: T) //~ error[P0005]: an interface method takes no type or `const` parameter: each type that implements it gives one function for every call } +// An interface's own functions share its methods' names. +fn Shape::area(&self) -> f64 { return 0.0; } //~ error[T0003]: `area` is already declared in this type +fn Shape::double(&self) -> f64 { return self.area() * 2.0; } + struct Square { side: f64 } fn Square::area(&self) -> f64 { return self.side * self.side; } fn Square::grow(&mut self, by: f64) { self.side = self.side + by; } @@ -29,6 +33,8 @@ fn show(s: &Shape) { s.grow(1.0); //~ error[T0007]: cannot mutably borrow `s` through shared reference `s` println(s.aera()); //~ error[T0002]: unknown name `aera` in interface `Shape` s.parts(); //~ error[T0004]: `parts` takes `self` whole, so it cannot be called through `&Shape` + println(s.doubel()); //~ error[T0002]: unknown name `doubel` in interface `Shape` + //~ help: did you mean `double`? } fn pointer(p: *Shape) -> f64 { return p.*.area(); } //~ error[T0043]: raw pointers to owned interfaces are not supported yet diff --git a/test_programs/interfaces/run_interface_functions.out b/test_programs/interfaces/run_interface_functions.out new file mode 100644 index 00000000..30ab3386 --- /dev/null +++ b/test_programs/interfaces/run_interface_functions.out @@ -0,0 +1,2 @@ +18 20 1 +18 diff --git a/test_programs/interfaces/run_interface_functions.peep b/test_programs/interfaces/run_interface_functions.peep new file mode 100644 index 00000000..8f046694 --- /dev/null +++ b/test_programs/interfaces/run_interface_functions.peep @@ -0,0 +1,45 @@ +//@ run + +// Any type a module declares can have functions, an interface too: one +// called through a reference to the interface runs once for every type +// that implements it, and reaches the type's methods through the table. + +iface Shape { + fn Area(&self) -> i32, +} + +struct Square { + side: i32, +} + +fn Square::Area(&self) -> i32 { + return self.side * self.side; +} + +struct Rectangle { + width: i32, + height: i32, +} + +fn Rectangle::Area(&self) -> i32 { + return self.width * self.height; +} + +fn Shape::Twice(&self) -> i32 { + return self.Area() * 2; +} + +// One that takes no `self` is called by its path. +fn Shape::Unit() -> i32 { + return 1; +} + +fn main() { + let square: Square = .{ side = 3 }; + let rectangle: Rectangle = .{ width = 2, height = 5 }; + let first: &Shape = □ + let second: &Shape = &rectangle; + println(first.Twice(), second.Twice(), Shape::Unit()); + let owned: Shape = square; + println(owned.Twice()); +} diff --git a/test_programs/types/negative_type_functions/main.peep b/test_programs/types/negative_type_functions/main.peep index bacc3100..894e5022 100644 --- a/test_programs/types/negative_type_functions/main.peep +++ b/test_programs/types/negative_type_functions/main.peep @@ -6,18 +6,18 @@ const Limit: i32 = 1; struct Local { x: i32 } enum Status { Ready } //~ error[T0043]: enum declarations are not supported yet -// Only the module that declares a struct declares its functions. -fn P::Extra() {} //~ error[P0005]: `P` is not a struct declared in this module +// Only the module that declares a type declares its functions. +fn P::Extra() {} //~ error[P0005]: `P` is not a type declared in this module //~ note: a type's functions are declared in the module of the type -fn Limit::f() {} //~ error[P0005]: `Limit` is not a struct declared in this module -fn Missing::f() {} //~ error[P0005]: `Missing` is not a struct declared in this module +fn Limit::f() {} //~ error[P0005]: `Limit` is not a type declared in this module +fn Missing::f() {} //~ error[P0005]: `Missing` is not a type declared in this module fn Local::f() {} fn Local::f() {} //~ error[T0003]: `f` is already declared in this type // `self` is the first parameter of a type's function. fn plain(&self) {} //~ error[P0005]: only a type's function takes `self`: `fn Point::name(&self)` fn Local::late(step: i32, &self) {} //~ error[P0005]: `self` must be the first parameter -fn Missing::get(&self) -> i32 { //~ error[P0005]: `Missing` is not a struct declared in this module +fn Missing::get(&self) -> i32 { //~ error[P0005]: `Missing` is not a type declared in this module return self.x; } fn Local::get(&self) -> i32 { @@ -34,8 +34,8 @@ fn main() { let c = i32::f(); //~ error[T0004]: `i32` has no functions let d = Limit::f(); //~ error[T0004]: `Limit` is not a module or a type let e = Local::g(); //~ error[T0002]: unknown name `g` in type `Local` - // Only a struct has functions; an enum's variants are not supported yet. - let f = Status::Ready; //~ error[T0004]: `Status` has no functions + // An enum's variants are not supported yet, so `Ready` names no function. + let f = Status::Ready; //~ error[T0002]: unknown name `Ready` in type `Status` // `&self` takes a reference; the call does not borrow by itself. let local = Local.{ x = 1 }; let g = Local::get(local); //~ error[T0001]: mismatched types: expected `&Local`, found `Local` From 4c358bc1ed272f06a6000bbd8776375d1160f878 Mon Sep 17 00:00:00 2001 From: itsfuad Date: Wed, 18 Nov 2026 01:27:01 +0600 Subject: [PATCH 04/24] Move the phase crates under crates/kernel The front and middle crates move to one kernel folder, as agreed in docs/structure-mapping.md (step 1): token, lexer, syntax (in tree/) and parser under kernel/syntax/; check (in semantic/), model, lower, flow and eval under kernel/. project moves to driver/, since it gathers a compile's input. Package names stay, so no Rust file changes. The feature-boundary check in check.sh still reads the same 17 crate manifests, project among them. --- Cargo.toml | 29 ++-- .../{frontend => driver}/project/Cargo.toml | 0 .../{frontend => driver}/project/src/lib.rs | 0 .../project/src/loading.rs | 0 .../project/src/manifest.rs | 0 .../{frontend => driver}/project/src/order.rs | 0 .../project/src/packages.rs | 0 .../{frontend => driver}/project/src/tests.rs | 0 crates/{middle => kernel}/eval/Cargo.toml | 0 .../eval/src/interpreter.rs | 0 .../eval/src/interpreter/instructions.rs | 0 .../eval/src/interpreter/memory.rs | 0 .../eval/src/interpreter/program.rs | 0 crates/{middle => kernel}/eval/src/lib.rs | 0 .../{middle => kernel}/eval/src/operations.rs | 0 crates/{middle => kernel}/flow/Cargo.toml | 0 crates/{middle => kernel}/flow/src/lib.rs | 0 .../flow/src/loans/errors.rs | 0 .../flow/src/loans/holders.rs | 0 .../{middle => kernel}/flow/src/loans/mod.rs | 0 .../flow/src/loans/passes.rs | 0 .../flow/src/loans/places.rs | 0 .../flow/src/loans/two_phase.rs | 0 .../flow/src/missing_return.rs | 0 .../flow/src/unreachable.rs | 0 .../flow/src/variable_state.rs | 0 crates/{middle => kernel}/lower/Cargo.toml | 0 .../lower/src/aggregates.rs | 0 .../lower/src/arithmetic.rs | 0 crates/{middle => kernel}/lower/src/c_abi.rs | 0 .../lower/src/expression.rs | 0 crates/{middle => kernel}/lower/src/lib.rs | 0 .../{middle => kernel}/lower/src/statement.rs | 0 crates/{middle => kernel}/lower/src/tests.rs | 0 crates/{middle => kernel}/model/Cargo.toml | 0 .../{middle => kernel}/model/src/constant.rs | 0 crates/{middle => kernel}/model/src/layout.rs | 0 .../model/src/layout/tests.rs | 0 crates/{middle => kernel}/model/src/lib.rs | 0 .../{middle => kernel}/model/src/machine.rs | 0 crates/{middle => kernel}/model/src/mir.rs | 0 .../{middle => kernel}/model/src/program.rs | 0 .../model/src/semantic_types.rs | 0 .../model/src/semantic_types/tests.rs | 0 crates/{middle => kernel}/model/src/thir.rs | 0 .../check => kernel/semantic}/Cargo.toml | 0 .../check => kernel/semantic}/src/builder.rs | 0 .../check => kernel/semantic}/src/builtin.rs | 0 .../semantic}/src/constraints.rs | 0 .../check => kernel/semantic}/src/copies.rs | 0 .../semantic}/src/declaration.rs | 0 .../semantic}/src/expression.rs | 0 .../semantic}/src/expression/borrows.rs | 0 .../semantic}/src/expression/calls.rs | 0 .../semantic}/src/expression/literals.rs | 0 .../semantic}/src/expression/operators.rs | 0 .../semantic}/src/expression/places.rs | 0 .../check => kernel/semantic}/src/fold.rs | 0 .../semantic}/src/fold/conversions.rs | 0 .../semantic}/src/fold/operators.rs | 0 .../semantic}/src/fold/tests.rs | 0 .../check => kernel/semantic}/src/function.rs | 0 .../check => kernel/semantic}/src/lib.rs | 0 .../check => kernel/semantic}/src/scope.rs | 0 .../semantic}/src/statement.rs | 0 .../semantic}/src/statement/assignments.rs | 0 .../semantic}/src/statement/declarations.rs | 0 .../semantic}/src/statement/loops.rs | 0 .../semantic}/src/statement/tests.rs | 0 .../check => kernel/semantic}/src/testing.rs | 0 .../semantic}/tests/llvm_parity.rs | 0 .../syntax}/lexer/Cargo.toml | 0 .../syntax}/lexer/src/lib.rs | 0 .../syntax}/lexer/src/tests.rs | 0 .../syntax}/parser/Cargo.toml | 0 .../syntax}/parser/src/decl.rs | 0 .../syntax}/parser/src/decl/tests.rs | 0 .../syntax}/parser/src/dump.rs | 0 .../syntax}/parser/src/expr.rs | 0 .../syntax}/parser/src/expr/tests.rs | 0 .../syntax}/parser/src/lib.rs | 0 .../syntax}/parser/src/literals.rs | 0 .../syntax}/parser/src/pattern.rs | 0 .../syntax}/parser/src/stmt.rs | 0 .../syntax}/parser/src/stmt/tests.rs | 0 .../syntax}/parser/src/tests.rs | 0 .../syntax}/parser/src/types.rs | 0 .../syntax}/token/Cargo.toml | 0 .../syntax}/token/src/lib.rs | 0 .../syntax => kernel/syntax/tree}/Cargo.toml | 0 .../syntax => kernel/syntax/tree}/src/ast.rs | 0 .../syntax => kernel/syntax/tree}/src/lib.rs | 0 .../syntax/tree}/src/operators.rs | 0 docs/feature-free-mir.md | 3 + docs/feature-front.md | 18 ++- docs/flow-crate.md | 3 + docs/ir-design.md | 3 + docs/structure-mapping.md | 143 ++++++++++++++++++ scripts/check.sh | 13 +- 99 files changed, 188 insertions(+), 24 deletions(-) rename crates/{frontend => driver}/project/Cargo.toml (100%) rename crates/{frontend => driver}/project/src/lib.rs (100%) rename crates/{frontend => driver}/project/src/loading.rs (100%) rename crates/{frontend => driver}/project/src/manifest.rs (100%) rename crates/{frontend => driver}/project/src/order.rs (100%) rename crates/{frontend => driver}/project/src/packages.rs (100%) rename crates/{frontend => driver}/project/src/tests.rs (100%) rename crates/{middle => kernel}/eval/Cargo.toml (100%) rename crates/{middle => kernel}/eval/src/interpreter.rs (100%) rename crates/{middle => kernel}/eval/src/interpreter/instructions.rs (100%) rename crates/{middle => kernel}/eval/src/interpreter/memory.rs (100%) rename crates/{middle => kernel}/eval/src/interpreter/program.rs (100%) rename crates/{middle => kernel}/eval/src/lib.rs (100%) rename crates/{middle => kernel}/eval/src/operations.rs (100%) rename crates/{middle => kernel}/flow/Cargo.toml (100%) rename crates/{middle => kernel}/flow/src/lib.rs (100%) rename crates/{middle => kernel}/flow/src/loans/errors.rs (100%) rename crates/{middle => kernel}/flow/src/loans/holders.rs (100%) rename crates/{middle => kernel}/flow/src/loans/mod.rs (100%) rename crates/{middle => kernel}/flow/src/loans/passes.rs (100%) rename crates/{middle => kernel}/flow/src/loans/places.rs (100%) rename crates/{middle => kernel}/flow/src/loans/two_phase.rs (100%) rename crates/{middle => kernel}/flow/src/missing_return.rs (100%) rename crates/{middle => kernel}/flow/src/unreachable.rs (100%) rename crates/{middle => kernel}/flow/src/variable_state.rs (100%) rename crates/{middle => kernel}/lower/Cargo.toml (100%) rename crates/{middle => kernel}/lower/src/aggregates.rs (100%) rename crates/{middle => kernel}/lower/src/arithmetic.rs (100%) rename crates/{middle => kernel}/lower/src/c_abi.rs (100%) rename crates/{middle => kernel}/lower/src/expression.rs (100%) rename crates/{middle => kernel}/lower/src/lib.rs (100%) rename crates/{middle => kernel}/lower/src/statement.rs (100%) rename crates/{middle => kernel}/lower/src/tests.rs (100%) rename crates/{middle => kernel}/model/Cargo.toml (100%) rename crates/{middle => kernel}/model/src/constant.rs (100%) rename crates/{middle => kernel}/model/src/layout.rs (100%) rename crates/{middle => kernel}/model/src/layout/tests.rs (100%) rename crates/{middle => kernel}/model/src/lib.rs (100%) rename crates/{middle => kernel}/model/src/machine.rs (100%) rename crates/{middle => kernel}/model/src/mir.rs (100%) rename crates/{middle => kernel}/model/src/program.rs (100%) rename crates/{middle => kernel}/model/src/semantic_types.rs (100%) rename crates/{middle => kernel}/model/src/semantic_types/tests.rs (100%) rename crates/{middle => kernel}/model/src/thir.rs (100%) rename crates/{middle/check => kernel/semantic}/Cargo.toml (100%) rename crates/{middle/check => kernel/semantic}/src/builder.rs (100%) rename crates/{middle/check => kernel/semantic}/src/builtin.rs (100%) rename crates/{middle/check => kernel/semantic}/src/constraints.rs (100%) rename crates/{middle/check => kernel/semantic}/src/copies.rs (100%) rename crates/{middle/check => kernel/semantic}/src/declaration.rs (100%) rename crates/{middle/check => kernel/semantic}/src/expression.rs (100%) rename crates/{middle/check => kernel/semantic}/src/expression/borrows.rs (100%) rename crates/{middle/check => kernel/semantic}/src/expression/calls.rs (100%) rename crates/{middle/check => kernel/semantic}/src/expression/literals.rs (100%) rename crates/{middle/check => kernel/semantic}/src/expression/operators.rs (100%) rename crates/{middle/check => kernel/semantic}/src/expression/places.rs (100%) rename crates/{middle/check => kernel/semantic}/src/fold.rs (100%) rename crates/{middle/check => kernel/semantic}/src/fold/conversions.rs (100%) rename crates/{middle/check => kernel/semantic}/src/fold/operators.rs (100%) rename crates/{middle/check => kernel/semantic}/src/fold/tests.rs (100%) rename crates/{middle/check => kernel/semantic}/src/function.rs (100%) rename crates/{middle/check => kernel/semantic}/src/lib.rs (100%) rename crates/{middle/check => kernel/semantic}/src/scope.rs (100%) rename crates/{middle/check => kernel/semantic}/src/statement.rs (100%) rename crates/{middle/check => kernel/semantic}/src/statement/assignments.rs (100%) rename crates/{middle/check => kernel/semantic}/src/statement/declarations.rs (100%) rename crates/{middle/check => kernel/semantic}/src/statement/loops.rs (100%) rename crates/{middle/check => kernel/semantic}/src/statement/tests.rs (100%) rename crates/{middle/check => kernel/semantic}/src/testing.rs (100%) rename crates/{middle/check => kernel/semantic}/tests/llvm_parity.rs (100%) rename crates/{frontend => kernel/syntax}/lexer/Cargo.toml (100%) rename crates/{frontend => kernel/syntax}/lexer/src/lib.rs (100%) rename crates/{frontend => kernel/syntax}/lexer/src/tests.rs (100%) rename crates/{frontend => kernel/syntax}/parser/Cargo.toml (100%) rename crates/{frontend => kernel/syntax}/parser/src/decl.rs (100%) rename crates/{frontend => kernel/syntax}/parser/src/decl/tests.rs (100%) rename crates/{frontend => kernel/syntax}/parser/src/dump.rs (100%) rename crates/{frontend => kernel/syntax}/parser/src/expr.rs (100%) rename crates/{frontend => kernel/syntax}/parser/src/expr/tests.rs (100%) rename crates/{frontend => kernel/syntax}/parser/src/lib.rs (100%) rename crates/{frontend => kernel/syntax}/parser/src/literals.rs (100%) rename crates/{frontend => kernel/syntax}/parser/src/pattern.rs (100%) rename crates/{frontend => kernel/syntax}/parser/src/stmt.rs (100%) rename crates/{frontend => kernel/syntax}/parser/src/stmt/tests.rs (100%) rename crates/{frontend => kernel/syntax}/parser/src/tests.rs (100%) rename crates/{frontend => kernel/syntax}/parser/src/types.rs (100%) rename crates/{frontend => kernel/syntax}/token/Cargo.toml (100%) rename crates/{frontend => kernel/syntax}/token/src/lib.rs (100%) rename crates/{core/syntax => kernel/syntax/tree}/Cargo.toml (100%) rename crates/{core/syntax => kernel/syntax/tree}/src/ast.rs (100%) rename crates/{core/syntax => kernel/syntax/tree}/src/lib.rs (100%) rename crates/{core/syntax => kernel/syntax/tree}/src/operators.rs (100%) create mode 100644 docs/structure-mapping.md diff --git a/Cargo.toml b/Cargo.toml index c7590ead..368a29e2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,10 +1,13 @@ [workspace] members = [ "crates/base/*", - "crates/core/*", + "crates/kernel/syntax/*", + "crates/kernel/semantic", + "crates/kernel/model", + "crates/kernel/lower", + "crates/kernel/flow", + "crates/kernel/eval", "crates/features", - "crates/frontend/*", - "crates/middle/*", "crates/backend/*", "crates/driver/*", "crates/tools/*", @@ -20,24 +23,24 @@ publish = false [workspace.dependencies] source = { path = "crates/base/source" } diagnostics = { path = "crates/base/diagnostics" } -token = { path = "crates/frontend/token" } -lexer = { path = "crates/frontend/lexer" } +token = { path = "crates/kernel/syntax/token" } +lexer = { path = "crates/kernel/syntax/lexer" } arena = { path = "crates/base/arena" } bigint = { path = "crates/base/bigint" } runtime_abi = { path = "crates/base/runtime_abi" } -parser = { path = "crates/frontend/parser" } +parser = { path = "crates/kernel/syntax/parser" } literal = { path = "crates/base/literal" } -syntax = { path = "crates/core/syntax" } +syntax = { path = "crates/kernel/syntax/tree" } test_programs = { path = "crates/driver/test_programs" } -model = { path = "crates/middle/model" } -eval = { path = "crates/middle/eval" } -check = { path = "crates/middle/check" } -lower = { path = "crates/middle/lower" } -flow = { path = "crates/middle/flow" } +model = { path = "crates/kernel/model" } +eval = { path = "crates/kernel/eval" } +check = { path = "crates/kernel/semantic" } +lower = { path = "crates/kernel/lower" } +flow = { path = "crates/kernel/flow" } llvm = { path = "crates/backend/llvm" } compile = { path = "crates/driver/compile" } features = { path = "crates/features" } -project = { path = "crates/frontend/project" } +project = { path = "crates/driver/project" } lsp = { path = "crates/driver/lsp" } unicode-general-category = "1.1.0" stacker = "0.1.25" diff --git a/crates/frontend/project/Cargo.toml b/crates/driver/project/Cargo.toml similarity index 100% rename from crates/frontend/project/Cargo.toml rename to crates/driver/project/Cargo.toml diff --git a/crates/frontend/project/src/lib.rs b/crates/driver/project/src/lib.rs similarity index 100% rename from crates/frontend/project/src/lib.rs rename to crates/driver/project/src/lib.rs diff --git a/crates/frontend/project/src/loading.rs b/crates/driver/project/src/loading.rs similarity index 100% rename from crates/frontend/project/src/loading.rs rename to crates/driver/project/src/loading.rs diff --git a/crates/frontend/project/src/manifest.rs b/crates/driver/project/src/manifest.rs similarity index 100% rename from crates/frontend/project/src/manifest.rs rename to crates/driver/project/src/manifest.rs diff --git a/crates/frontend/project/src/order.rs b/crates/driver/project/src/order.rs similarity index 100% rename from crates/frontend/project/src/order.rs rename to crates/driver/project/src/order.rs diff --git a/crates/frontend/project/src/packages.rs b/crates/driver/project/src/packages.rs similarity index 100% rename from crates/frontend/project/src/packages.rs rename to crates/driver/project/src/packages.rs diff --git a/crates/frontend/project/src/tests.rs b/crates/driver/project/src/tests.rs similarity index 100% rename from crates/frontend/project/src/tests.rs rename to crates/driver/project/src/tests.rs diff --git a/crates/middle/eval/Cargo.toml b/crates/kernel/eval/Cargo.toml similarity index 100% rename from crates/middle/eval/Cargo.toml rename to crates/kernel/eval/Cargo.toml diff --git a/crates/middle/eval/src/interpreter.rs b/crates/kernel/eval/src/interpreter.rs similarity index 100% rename from crates/middle/eval/src/interpreter.rs rename to crates/kernel/eval/src/interpreter.rs diff --git a/crates/middle/eval/src/interpreter/instructions.rs b/crates/kernel/eval/src/interpreter/instructions.rs similarity index 100% rename from crates/middle/eval/src/interpreter/instructions.rs rename to crates/kernel/eval/src/interpreter/instructions.rs diff --git a/crates/middle/eval/src/interpreter/memory.rs b/crates/kernel/eval/src/interpreter/memory.rs similarity index 100% rename from crates/middle/eval/src/interpreter/memory.rs rename to crates/kernel/eval/src/interpreter/memory.rs diff --git a/crates/middle/eval/src/interpreter/program.rs b/crates/kernel/eval/src/interpreter/program.rs similarity index 100% rename from crates/middle/eval/src/interpreter/program.rs rename to crates/kernel/eval/src/interpreter/program.rs diff --git a/crates/middle/eval/src/lib.rs b/crates/kernel/eval/src/lib.rs similarity index 100% rename from crates/middle/eval/src/lib.rs rename to crates/kernel/eval/src/lib.rs diff --git a/crates/middle/eval/src/operations.rs b/crates/kernel/eval/src/operations.rs similarity index 100% rename from crates/middle/eval/src/operations.rs rename to crates/kernel/eval/src/operations.rs diff --git a/crates/middle/flow/Cargo.toml b/crates/kernel/flow/Cargo.toml similarity index 100% rename from crates/middle/flow/Cargo.toml rename to crates/kernel/flow/Cargo.toml diff --git a/crates/middle/flow/src/lib.rs b/crates/kernel/flow/src/lib.rs similarity index 100% rename from crates/middle/flow/src/lib.rs rename to crates/kernel/flow/src/lib.rs diff --git a/crates/middle/flow/src/loans/errors.rs b/crates/kernel/flow/src/loans/errors.rs similarity index 100% rename from crates/middle/flow/src/loans/errors.rs rename to crates/kernel/flow/src/loans/errors.rs diff --git a/crates/middle/flow/src/loans/holders.rs b/crates/kernel/flow/src/loans/holders.rs similarity index 100% rename from crates/middle/flow/src/loans/holders.rs rename to crates/kernel/flow/src/loans/holders.rs diff --git a/crates/middle/flow/src/loans/mod.rs b/crates/kernel/flow/src/loans/mod.rs similarity index 100% rename from crates/middle/flow/src/loans/mod.rs rename to crates/kernel/flow/src/loans/mod.rs diff --git a/crates/middle/flow/src/loans/passes.rs b/crates/kernel/flow/src/loans/passes.rs similarity index 100% rename from crates/middle/flow/src/loans/passes.rs rename to crates/kernel/flow/src/loans/passes.rs diff --git a/crates/middle/flow/src/loans/places.rs b/crates/kernel/flow/src/loans/places.rs similarity index 100% rename from crates/middle/flow/src/loans/places.rs rename to crates/kernel/flow/src/loans/places.rs diff --git a/crates/middle/flow/src/loans/two_phase.rs b/crates/kernel/flow/src/loans/two_phase.rs similarity index 100% rename from crates/middle/flow/src/loans/two_phase.rs rename to crates/kernel/flow/src/loans/two_phase.rs diff --git a/crates/middle/flow/src/missing_return.rs b/crates/kernel/flow/src/missing_return.rs similarity index 100% rename from crates/middle/flow/src/missing_return.rs rename to crates/kernel/flow/src/missing_return.rs diff --git a/crates/middle/flow/src/unreachable.rs b/crates/kernel/flow/src/unreachable.rs similarity index 100% rename from crates/middle/flow/src/unreachable.rs rename to crates/kernel/flow/src/unreachable.rs diff --git a/crates/middle/flow/src/variable_state.rs b/crates/kernel/flow/src/variable_state.rs similarity index 100% rename from crates/middle/flow/src/variable_state.rs rename to crates/kernel/flow/src/variable_state.rs diff --git a/crates/middle/lower/Cargo.toml b/crates/kernel/lower/Cargo.toml similarity index 100% rename from crates/middle/lower/Cargo.toml rename to crates/kernel/lower/Cargo.toml diff --git a/crates/middle/lower/src/aggregates.rs b/crates/kernel/lower/src/aggregates.rs similarity index 100% rename from crates/middle/lower/src/aggregates.rs rename to crates/kernel/lower/src/aggregates.rs diff --git a/crates/middle/lower/src/arithmetic.rs b/crates/kernel/lower/src/arithmetic.rs similarity index 100% rename from crates/middle/lower/src/arithmetic.rs rename to crates/kernel/lower/src/arithmetic.rs diff --git a/crates/middle/lower/src/c_abi.rs b/crates/kernel/lower/src/c_abi.rs similarity index 100% rename from crates/middle/lower/src/c_abi.rs rename to crates/kernel/lower/src/c_abi.rs diff --git a/crates/middle/lower/src/expression.rs b/crates/kernel/lower/src/expression.rs similarity index 100% rename from crates/middle/lower/src/expression.rs rename to crates/kernel/lower/src/expression.rs diff --git a/crates/middle/lower/src/lib.rs b/crates/kernel/lower/src/lib.rs similarity index 100% rename from crates/middle/lower/src/lib.rs rename to crates/kernel/lower/src/lib.rs diff --git a/crates/middle/lower/src/statement.rs b/crates/kernel/lower/src/statement.rs similarity index 100% rename from crates/middle/lower/src/statement.rs rename to crates/kernel/lower/src/statement.rs diff --git a/crates/middle/lower/src/tests.rs b/crates/kernel/lower/src/tests.rs similarity index 100% rename from crates/middle/lower/src/tests.rs rename to crates/kernel/lower/src/tests.rs diff --git a/crates/middle/model/Cargo.toml b/crates/kernel/model/Cargo.toml similarity index 100% rename from crates/middle/model/Cargo.toml rename to crates/kernel/model/Cargo.toml diff --git a/crates/middle/model/src/constant.rs b/crates/kernel/model/src/constant.rs similarity index 100% rename from crates/middle/model/src/constant.rs rename to crates/kernel/model/src/constant.rs diff --git a/crates/middle/model/src/layout.rs b/crates/kernel/model/src/layout.rs similarity index 100% rename from crates/middle/model/src/layout.rs rename to crates/kernel/model/src/layout.rs diff --git a/crates/middle/model/src/layout/tests.rs b/crates/kernel/model/src/layout/tests.rs similarity index 100% rename from crates/middle/model/src/layout/tests.rs rename to crates/kernel/model/src/layout/tests.rs diff --git a/crates/middle/model/src/lib.rs b/crates/kernel/model/src/lib.rs similarity index 100% rename from crates/middle/model/src/lib.rs rename to crates/kernel/model/src/lib.rs diff --git a/crates/middle/model/src/machine.rs b/crates/kernel/model/src/machine.rs similarity index 100% rename from crates/middle/model/src/machine.rs rename to crates/kernel/model/src/machine.rs diff --git a/crates/middle/model/src/mir.rs b/crates/kernel/model/src/mir.rs similarity index 100% rename from crates/middle/model/src/mir.rs rename to crates/kernel/model/src/mir.rs diff --git a/crates/middle/model/src/program.rs b/crates/kernel/model/src/program.rs similarity index 100% rename from crates/middle/model/src/program.rs rename to crates/kernel/model/src/program.rs diff --git a/crates/middle/model/src/semantic_types.rs b/crates/kernel/model/src/semantic_types.rs similarity index 100% rename from crates/middle/model/src/semantic_types.rs rename to crates/kernel/model/src/semantic_types.rs diff --git a/crates/middle/model/src/semantic_types/tests.rs b/crates/kernel/model/src/semantic_types/tests.rs similarity index 100% rename from crates/middle/model/src/semantic_types/tests.rs rename to crates/kernel/model/src/semantic_types/tests.rs diff --git a/crates/middle/model/src/thir.rs b/crates/kernel/model/src/thir.rs similarity index 100% rename from crates/middle/model/src/thir.rs rename to crates/kernel/model/src/thir.rs diff --git a/crates/middle/check/Cargo.toml b/crates/kernel/semantic/Cargo.toml similarity index 100% rename from crates/middle/check/Cargo.toml rename to crates/kernel/semantic/Cargo.toml diff --git a/crates/middle/check/src/builder.rs b/crates/kernel/semantic/src/builder.rs similarity index 100% rename from crates/middle/check/src/builder.rs rename to crates/kernel/semantic/src/builder.rs diff --git a/crates/middle/check/src/builtin.rs b/crates/kernel/semantic/src/builtin.rs similarity index 100% rename from crates/middle/check/src/builtin.rs rename to crates/kernel/semantic/src/builtin.rs diff --git a/crates/middle/check/src/constraints.rs b/crates/kernel/semantic/src/constraints.rs similarity index 100% rename from crates/middle/check/src/constraints.rs rename to crates/kernel/semantic/src/constraints.rs diff --git a/crates/middle/check/src/copies.rs b/crates/kernel/semantic/src/copies.rs similarity index 100% rename from crates/middle/check/src/copies.rs rename to crates/kernel/semantic/src/copies.rs diff --git a/crates/middle/check/src/declaration.rs b/crates/kernel/semantic/src/declaration.rs similarity index 100% rename from crates/middle/check/src/declaration.rs rename to crates/kernel/semantic/src/declaration.rs diff --git a/crates/middle/check/src/expression.rs b/crates/kernel/semantic/src/expression.rs similarity index 100% rename from crates/middle/check/src/expression.rs rename to crates/kernel/semantic/src/expression.rs diff --git a/crates/middle/check/src/expression/borrows.rs b/crates/kernel/semantic/src/expression/borrows.rs similarity index 100% rename from crates/middle/check/src/expression/borrows.rs rename to crates/kernel/semantic/src/expression/borrows.rs diff --git a/crates/middle/check/src/expression/calls.rs b/crates/kernel/semantic/src/expression/calls.rs similarity index 100% rename from crates/middle/check/src/expression/calls.rs rename to crates/kernel/semantic/src/expression/calls.rs diff --git a/crates/middle/check/src/expression/literals.rs b/crates/kernel/semantic/src/expression/literals.rs similarity index 100% rename from crates/middle/check/src/expression/literals.rs rename to crates/kernel/semantic/src/expression/literals.rs diff --git a/crates/middle/check/src/expression/operators.rs b/crates/kernel/semantic/src/expression/operators.rs similarity index 100% rename from crates/middle/check/src/expression/operators.rs rename to crates/kernel/semantic/src/expression/operators.rs diff --git a/crates/middle/check/src/expression/places.rs b/crates/kernel/semantic/src/expression/places.rs similarity index 100% rename from crates/middle/check/src/expression/places.rs rename to crates/kernel/semantic/src/expression/places.rs diff --git a/crates/middle/check/src/fold.rs b/crates/kernel/semantic/src/fold.rs similarity index 100% rename from crates/middle/check/src/fold.rs rename to crates/kernel/semantic/src/fold.rs diff --git a/crates/middle/check/src/fold/conversions.rs b/crates/kernel/semantic/src/fold/conversions.rs similarity index 100% rename from crates/middle/check/src/fold/conversions.rs rename to crates/kernel/semantic/src/fold/conversions.rs diff --git a/crates/middle/check/src/fold/operators.rs b/crates/kernel/semantic/src/fold/operators.rs similarity index 100% rename from crates/middle/check/src/fold/operators.rs rename to crates/kernel/semantic/src/fold/operators.rs diff --git a/crates/middle/check/src/fold/tests.rs b/crates/kernel/semantic/src/fold/tests.rs similarity index 100% rename from crates/middle/check/src/fold/tests.rs rename to crates/kernel/semantic/src/fold/tests.rs diff --git a/crates/middle/check/src/function.rs b/crates/kernel/semantic/src/function.rs similarity index 100% rename from crates/middle/check/src/function.rs rename to crates/kernel/semantic/src/function.rs diff --git a/crates/middle/check/src/lib.rs b/crates/kernel/semantic/src/lib.rs similarity index 100% rename from crates/middle/check/src/lib.rs rename to crates/kernel/semantic/src/lib.rs diff --git a/crates/middle/check/src/scope.rs b/crates/kernel/semantic/src/scope.rs similarity index 100% rename from crates/middle/check/src/scope.rs rename to crates/kernel/semantic/src/scope.rs diff --git a/crates/middle/check/src/statement.rs b/crates/kernel/semantic/src/statement.rs similarity index 100% rename from crates/middle/check/src/statement.rs rename to crates/kernel/semantic/src/statement.rs diff --git a/crates/middle/check/src/statement/assignments.rs b/crates/kernel/semantic/src/statement/assignments.rs similarity index 100% rename from crates/middle/check/src/statement/assignments.rs rename to crates/kernel/semantic/src/statement/assignments.rs diff --git a/crates/middle/check/src/statement/declarations.rs b/crates/kernel/semantic/src/statement/declarations.rs similarity index 100% rename from crates/middle/check/src/statement/declarations.rs rename to crates/kernel/semantic/src/statement/declarations.rs diff --git a/crates/middle/check/src/statement/loops.rs b/crates/kernel/semantic/src/statement/loops.rs similarity index 100% rename from crates/middle/check/src/statement/loops.rs rename to crates/kernel/semantic/src/statement/loops.rs diff --git a/crates/middle/check/src/statement/tests.rs b/crates/kernel/semantic/src/statement/tests.rs similarity index 100% rename from crates/middle/check/src/statement/tests.rs rename to crates/kernel/semantic/src/statement/tests.rs diff --git a/crates/middle/check/src/testing.rs b/crates/kernel/semantic/src/testing.rs similarity index 100% rename from crates/middle/check/src/testing.rs rename to crates/kernel/semantic/src/testing.rs diff --git a/crates/middle/check/tests/llvm_parity.rs b/crates/kernel/semantic/tests/llvm_parity.rs similarity index 100% rename from crates/middle/check/tests/llvm_parity.rs rename to crates/kernel/semantic/tests/llvm_parity.rs diff --git a/crates/frontend/lexer/Cargo.toml b/crates/kernel/syntax/lexer/Cargo.toml similarity index 100% rename from crates/frontend/lexer/Cargo.toml rename to crates/kernel/syntax/lexer/Cargo.toml diff --git a/crates/frontend/lexer/src/lib.rs b/crates/kernel/syntax/lexer/src/lib.rs similarity index 100% rename from crates/frontend/lexer/src/lib.rs rename to crates/kernel/syntax/lexer/src/lib.rs diff --git a/crates/frontend/lexer/src/tests.rs b/crates/kernel/syntax/lexer/src/tests.rs similarity index 100% rename from crates/frontend/lexer/src/tests.rs rename to crates/kernel/syntax/lexer/src/tests.rs diff --git a/crates/frontend/parser/Cargo.toml b/crates/kernel/syntax/parser/Cargo.toml similarity index 100% rename from crates/frontend/parser/Cargo.toml rename to crates/kernel/syntax/parser/Cargo.toml diff --git a/crates/frontend/parser/src/decl.rs b/crates/kernel/syntax/parser/src/decl.rs similarity index 100% rename from crates/frontend/parser/src/decl.rs rename to crates/kernel/syntax/parser/src/decl.rs diff --git a/crates/frontend/parser/src/decl/tests.rs b/crates/kernel/syntax/parser/src/decl/tests.rs similarity index 100% rename from crates/frontend/parser/src/decl/tests.rs rename to crates/kernel/syntax/parser/src/decl/tests.rs diff --git a/crates/frontend/parser/src/dump.rs b/crates/kernel/syntax/parser/src/dump.rs similarity index 100% rename from crates/frontend/parser/src/dump.rs rename to crates/kernel/syntax/parser/src/dump.rs diff --git a/crates/frontend/parser/src/expr.rs b/crates/kernel/syntax/parser/src/expr.rs similarity index 100% rename from crates/frontend/parser/src/expr.rs rename to crates/kernel/syntax/parser/src/expr.rs diff --git a/crates/frontend/parser/src/expr/tests.rs b/crates/kernel/syntax/parser/src/expr/tests.rs similarity index 100% rename from crates/frontend/parser/src/expr/tests.rs rename to crates/kernel/syntax/parser/src/expr/tests.rs diff --git a/crates/frontend/parser/src/lib.rs b/crates/kernel/syntax/parser/src/lib.rs similarity index 100% rename from crates/frontend/parser/src/lib.rs rename to crates/kernel/syntax/parser/src/lib.rs diff --git a/crates/frontend/parser/src/literals.rs b/crates/kernel/syntax/parser/src/literals.rs similarity index 100% rename from crates/frontend/parser/src/literals.rs rename to crates/kernel/syntax/parser/src/literals.rs diff --git a/crates/frontend/parser/src/pattern.rs b/crates/kernel/syntax/parser/src/pattern.rs similarity index 100% rename from crates/frontend/parser/src/pattern.rs rename to crates/kernel/syntax/parser/src/pattern.rs diff --git a/crates/frontend/parser/src/stmt.rs b/crates/kernel/syntax/parser/src/stmt.rs similarity index 100% rename from crates/frontend/parser/src/stmt.rs rename to crates/kernel/syntax/parser/src/stmt.rs diff --git a/crates/frontend/parser/src/stmt/tests.rs b/crates/kernel/syntax/parser/src/stmt/tests.rs similarity index 100% rename from crates/frontend/parser/src/stmt/tests.rs rename to crates/kernel/syntax/parser/src/stmt/tests.rs diff --git a/crates/frontend/parser/src/tests.rs b/crates/kernel/syntax/parser/src/tests.rs similarity index 100% rename from crates/frontend/parser/src/tests.rs rename to crates/kernel/syntax/parser/src/tests.rs diff --git a/crates/frontend/parser/src/types.rs b/crates/kernel/syntax/parser/src/types.rs similarity index 100% rename from crates/frontend/parser/src/types.rs rename to crates/kernel/syntax/parser/src/types.rs diff --git a/crates/frontend/token/Cargo.toml b/crates/kernel/syntax/token/Cargo.toml similarity index 100% rename from crates/frontend/token/Cargo.toml rename to crates/kernel/syntax/token/Cargo.toml diff --git a/crates/frontend/token/src/lib.rs b/crates/kernel/syntax/token/src/lib.rs similarity index 100% rename from crates/frontend/token/src/lib.rs rename to crates/kernel/syntax/token/src/lib.rs diff --git a/crates/core/syntax/Cargo.toml b/crates/kernel/syntax/tree/Cargo.toml similarity index 100% rename from crates/core/syntax/Cargo.toml rename to crates/kernel/syntax/tree/Cargo.toml diff --git a/crates/core/syntax/src/ast.rs b/crates/kernel/syntax/tree/src/ast.rs similarity index 100% rename from crates/core/syntax/src/ast.rs rename to crates/kernel/syntax/tree/src/ast.rs diff --git a/crates/core/syntax/src/lib.rs b/crates/kernel/syntax/tree/src/lib.rs similarity index 100% rename from crates/core/syntax/src/lib.rs rename to crates/kernel/syntax/tree/src/lib.rs diff --git a/crates/core/syntax/src/operators.rs b/crates/kernel/syntax/tree/src/operators.rs similarity index 100% rename from crates/core/syntax/src/operators.rs rename to crates/kernel/syntax/tree/src/operators.rs diff --git a/docs/feature-free-mir.md b/docs/feature-free-mir.md index 68aadd9c..e7f02eec 100644 --- a/docs/feature-free-mir.md +++ b/docs/feature-free-mir.md @@ -1,5 +1,8 @@ # Design page: a MIR of core concepts only +> The crates have moved since this was written: `middle/*` and +> `core/syntax` are now under `crates/kernel/` (docs/structure-mapping.md). + Status: **done 2026-11-11.** Agreed 2026-11-10 (section 9) and built in order B; the old MIR, its lowering and `flow::cleanup` are deleted, and the MIR of core concepts is `model::mir`. diff --git a/docs/feature-front.md b/docs/feature-front.md index d19f781f..d8d402ad 100644 --- a/docs/feature-front.md +++ b/docs/feature-front.md @@ -462,14 +462,21 @@ crate (step 19): with none, it cannot fail. ```text crates/ base/ arena, bigint, diagnostics, literal, source, runtime_abi - core/ syntax: the tree and the `Language` trait - frontend/ token, lexer, parser (the engine and its rule table), project - middle/ check, lower, flow, eval, and model (THIR, MIR, layout, machine) + kernel/ + syntax/ token, lexer, tree (the `syntax` crate: the tree and the + `Language` trait), parser (the engine and its rule table) + semantic the `check` crate + model THIR, MIR, layout, machine + lower, flow, eval features/ one crate: `src/lib.rs` lists the features, one file each backend/ llvm - driver/ compile, peeper, lsp, browser, test_programs + driver/ compile, peeper, lsp, browser, test_programs, project ``` +Until 2026-11-18 the kernel crates were `core/` (syntax), `frontend/` +(token, lexer, parser, project) and `middle/` (check, lower, flow, eval, +model); docs/structure-mapping.md has the move. + One crate per feature lets Cargo refuse a dependency between features for free; one file per feature in a single crate needs a grep check instead. A crate per feature was decided first and then replaced, the same day @@ -478,7 +485,8 @@ build and link, and the grep check ("feature boundary" in `scripts/check.sh`) keeps a feature file from naming another. This also answers plan item 10: the syntax tree leaves `model`; its core -part goes to `core/syntax`, each feature's nodes to the feature. +part goes to the `syntax` crate (`kernel/syntax/tree`), each feature's +nodes to the feature. A consequence for tests: a crate's own tests cannot use a crate that depends on it, so the core's tests cannot write a feature's syntax. Each diff --git a/docs/flow-crate.md b/docs/flow-crate.md index f662837f..51f26115 100644 --- a/docs/flow-crate.md +++ b/docs/flow-crate.md @@ -1,5 +1,8 @@ # The `flow` crate +> The crates have moved since this was written: `middle/*` and +> `core/syntax` are now under `crates/kernel/` (docs/structure-mapping.md). + The path checks: errors that depend on which routes execution can take through one function. Source: `crates/middle/flow/src/`: `lib.rs` (the shared engine), `missing_return.rs`, `unreachable.rs`, `variable_state.rs`, diff --git a/docs/ir-design.md b/docs/ir-design.md index bf4c1b66..a03c2525 100644 --- a/docs/ir-design.md +++ b/docs/ir-design.md @@ -1,5 +1,8 @@ # Semantic design: check, THIR, MIR, LLVM +> The crates have moved since this was written: `middle/*` and +> `core/syntax` are now under `crates/kernel/` (docs/structure-mapping.md). + Status: PROPOSAL. Decided by the owner (2026-10-17): the points marked **decided**. Open points are listed at the end. diff --git a/docs/structure-mapping.md b/docs/structure-mapping.md new file mode 100644 index 00000000..6f424142 --- /dev/null +++ b/docs/structure-mapping.md @@ -0,0 +1,143 @@ +# Structure mapping: from today's crates to `kernel/` and `features/` + +Status: final, agreed by Fuad, GPT and Claude. Nothing has moved yet. + +Each line says what kind of change it is: + +- **move**: a file or folder changes path; its content does not change. +- **extract**: code leaves a file for another; behavior does not change. +- **API**: a type, node or trait changes shape; callers change with it. +- **later**: not part of this restructuring; listed so its place is known. + +## Rules + +1. No feature depends on another; a feature depends only on the kernel. +2. A concept used by many features lives in the kernel once, never in the + kernel and in a feature. +3. The kernel owns shared machinery, the operations on the closed checked + type shapes, and anything that only wraps an operation the core already + owns. A feature parses and validates its own syntax and builds a core + shape. +4. Phase crates stay separate. Cargo package names do not change. +5. Production dependencies follow the phase direction. A test may use a + higher crate (through `[dev-dependencies]`) to build a real program. +6. No new feature hooks, iteration-plan services, extra crates or + duplicated machinery come with this restructuring. + +## Step 1: crates (move only) + +| Today | New | Package | +| --- | --- | --- | +| `crates/frontend/token` | `crates/kernel/syntax/token` | `token` | +| `crates/frontend/lexer` | `crates/kernel/syntax/lexer` | `lexer` | +| `crates/core/syntax` | `crates/kernel/syntax/tree` | `syntax` | +| `crates/frontend/parser` | `crates/kernel/syntax/parser` | `parser` | +| `crates/middle/check` | `crates/kernel/semantic` | `check` | +| `crates/middle/model` | `crates/kernel/model` | `model` | +| `crates/middle/lower` | `crates/kernel/lower` | `lower` | +| `crates/middle/flow` | `crates/kernel/flow` | `flow` | +| `crates/middle/eval` | `crates/kernel/eval` | `eval` | +| `crates/frontend/project` | `crates/driver/project` | `project` | + +Unchanged: `crates/base/*`, `crates/features`, `crates/backend/llvm`, +`crates/driver/{compile, lsp, browser, peeper, test_programs}`, +`crates/tools/toolchain`. `crates/frontend`, `crates/core` and +`crates/middle` are empty afterwards and go. + +What step 1 edits besides `git mv` (found by searching every file for the +old paths): + +- `Cargo.toml`: the `members` list and the 11 `path =` entries of + `[workspace.dependencies]`. Crates name each other with + `workspace = true`, so no crate manifest changes. +- `scripts/check.sh` lines 39-55: the model, eval, flow and feature-boundary + checks name `crates/middle/...`. +- `docs/feature-front.md` (lines 466-481, the crate list) and + `docs/architecture.md`: current architecture, updated. +- `docs/feature-free-mir.md`, `docs/flow-crate.md`, `docs/ir-design.md`: + design notes of their time; their old paths stay, with one line saying + where the crates are now. +- No Rust file names these paths. Every `CARGO_MANIFEST_DIR` and `#[path]` + that climbs folders is in a crate that does not move or moves at the same + depth (`check` and `project` stay three deep), so none changes. +- CI workflows name only `crates/tools/toolchain` and + `crates/driver/browser`, which do not move. + +Done when: the build and the full `scripts/check.sh` pass, with no change in +behavior or in who owns what. + +## Step 2: four features into the kernel (API + extract) + +| From | Syntax becomes (API) | Parser rule goes to | Checking goes to | +| --- | --- | --- | --- | +| `features/src/bools.rs` | `ast::Expr::Bool(bool)` | `parser/src/literals.rs` | `check/src/expression/literals.rs` | +| `features/src/text.rs` | `ast::Expr::String(StringKind)` | `parser/src/literals.rs` | `check/src/expression/literals.rs` | +| `features/src/casts.rs` | `ast::Expr::Cast { value, ty }` | `parser/src/expr.rs` (infix `as`) | `check/src/expression/operators.rs` | +| `features/src/panics.rs` | `ast::Stmt::Panic(Id)` | `parser/src/stmt.rs` | `check/src/statement.rs` (THIR `Stmt::Panic` exists) | + +Each feature's `tests.rs` moves with its code. Each feature's node, its +registration and its `ExprNode`/`StmtNode` impl leave `features/src/lib.rs`. + +API: `Language::string_kind` is removed. Its places: +`syntax/src/ast.rs:56` (the trait method), `features/src/lib.rs:52` and +`:197` (the impls), `check/src/testing.rs:58` and `parser/src/tests.rs:42` +(test stubs). Its two users match `ast::Expr::String` instead: +`model/src/program.rs:116` (an `extern`'s name) and the panic message check. + +## Step 3: inside the checker (`kernel/semantic/src`) + +| Today | Kind | New | What | +| --- | --- | --- | --- | +| `lib.rs` | stays | `lib.rs` | `Checker`, `check_once`, name resolution, reporting | +| `lib.rs`: `record_copy` | extract | `generics/copies.rs` | records a copy in the copy table | +| `builder.rs`, `scope.rs`, `fold.rs`, `fold/*`, `testing.rs` | stay | same | | +| `function.rs` | move | `functions/bodies.rs` | a body to checked MIR, `evaluate_call` | +| `builtin.rs` | move | `functions/builtin.rs` | `#[builtin]` functions | +| `declaration.rs`: `check_function`, `is_builtin_declared`, `signature_type`, `result_origins`, `resolve_signature_type` | extract | `functions/signatures.rs` | a function's type | +| `declaration.rs`: `implementation`, `method_type` | extract | `conformance.rs` | whether a type implements an interface; receiver substitution; the cached `ImplementationId` | +| `declaration.rs`: `resolve_type_argument`, `type_argument`, `first_copy_parameter`, `written_inside`, `find_type_argument`, `names_type_parameter` | extract | `generics/arguments.rs` | finding and writing type arguments | +| `declaration.rs`: the rest (`check_attributes` for every declaration, type declarations, constants, resolving written types, `is_interface`, `reference_type`, `array_type`, `range_type`, ...) | stays | `declaration.rs` | about 670 of its 1382 lines leave | +| `copies.rs` | move | `generics/copies.rs` | the one copy table | +| `constraints.rs` | move | `generics/constraints.rs` | `where`: both interface constraints (through `conformance.rs`) and predicate functions run at compile time; neither form changes | +| `expression.rs`, `expression/{borrows, literals, operators, places}.rs` | stay | same | | +| `expression/calls.rs`: `check_call`, `call_found`, `function_called`, `method`, `takes_self`, `interface_method`, `argument_count_message` | move (file renamed) | `functions/calls.rs` | function, method and interface method calls | +| `expression/calls.rs`: `check_symbol_value`, `constant_expr` | extract | `expression/names.rs` | a name or path used as a value | +| `expression/calls.rs`: `written_type_argument`, `copy_called` | extract | `generics/arguments.rs` | type arguments at a call, the copy a call makes | +| `statement.rs`, `statement/assignments.rs`, `statement/loops.rs` | stay | same | blocks, `if`, `for`, `return`, `break`, `continue`, `panic` | +| `statement/declarations.rs` | move | `locals.rs` | `let`, `const` in a body, `let .{ }`; `statement.rs` declares the module and calls it as before | + +`interface_method`, interface conversions (`expression.rs`) and `where` stay +in the kernel and call `conformance.rs`; none imports `features`. +`conformance.rs` still reads some source declarations as well as checked +types; that stays as it is for this restructuring. + +Done when: the full `scripts/check.sh` passes and no fixture output +changes. `conformance.rs` gets its own unit tests: a type that implements, +one that lacks a function, one with a wrong signature. + +## Step 4: the feature-boundary check (`scripts/check.sh`) + +The check that a feature's file names no other feature also refuses +`super::` and paths into another feature's nested module. + +## Step 5 (later, with enums): patterns + +| Today | Kind | New | +| --- | --- | --- | +| `features/src/enums.rs`: `match_statement`, `match_arm` | later | `parser/src/stmt.rs`; checked in `check/src/statement/` | +| `features/src/enums.rs`: `case_test` (`is`) | later | `parser/src/expr.rs`; checked in `check/src/expression/` | +| `features/src/enums.rs`: `case_pattern`, `payload_pattern` | later | stay in `features/enums` | +| `parser/src/pattern.rs`: `struct_pattern` | later | a general `parse_pattern` in the parser; the `.{ }` field pattern moves to `features/structs` through a small parser API, not by opening parser internals | +| (new) | later | `check/src/patterns/{checked, coverage, decision}.rs`: the pattern engine | + +## Step 6 (separate job) + +`TypeId::INVALID` today means "error reported", "no type for `T` yet" and +"copy being checked". The last two become explicit states; `INVALID` stays +for real errors. + +## Features after the restructuring + +`features/src`: `arrays`, `chars`, `enums`, `interfaces`, `optionals`, +`pipes`, `printing`, `ranges`, `raw_pointers`, `structs`, each one +`name.rs` and `name/tests.rs`, plus `lib.rs` (the list) and `testing.rs`. diff --git a/scripts/check.sh b/scripts/check.sh index 5b21899b..d8f46382 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -36,19 +36,20 @@ check "runtime clippy" clippy-driver --edition=2024 -Cpanic=abort --crate-type=s # which Cargo checks. front='semantic_types|thir|program|layout' check "middle boundary" bash -c " - ! grep -rnE 'crate::($front)' crates/middle/model/src/{mir,machine,constant}.rs && - ! grep -nE '^use crate::' crates/middle/model/src/lib.rs && - ! grep -rnE 'model::($front)' crates/middle/eval crates/middle/flow && + ! grep -rnE 'crate::($front)' crates/kernel/model/src/{mir,machine,constant}.rs && + ! grep -nE '^use crate::' crates/kernel/model/src/lib.rs && + ! grep -rnE 'model::($front)' crates/kernel/eval crates/kernel/flow && ! grep -rnE --exclude=tests.rs 'model::($front)' crates/backend/llvm && - ! grep -rnE '\bsyntax::' crates/middle/model/src/{mir,machine,constant,lib}.rs \ - crates/middle/{eval,flow} crates/backend/llvm" + ! grep -rnE '\bsyntax::' crates/kernel/model/src/{mir,machine,constant,lib}.rs \ + crates/kernel/{eval,flow} crates/backend/llvm" # A phase names no feature: only its tests may use the `features` crate # (docs/feature-front.md section 7); Cargo refuses the cycle for the crates # `features` depends on, this the others. And a feature's file names no # other feature: of its own crate, only the list's `Peeper` and enums, so # no module's path (`crate::bools`). check "feature boundary" bash -c " - for manifest in crates/{base,core,frontend,middle,backend}/*/Cargo.toml; do + for manifest in crates/{base,backend}/*/Cargo.toml crates/kernel/syntax/*/Cargo.toml \\ + crates/kernel/{semantic,model,lower,flow,eval}/Cargo.toml crates/driver/project/Cargo.toml; do sed '/^\[dev-dependencies\]/,\$d' \$manifest | grep -H --label=\$manifest '^features\b' && exit 1 done ! grep -nE '\bcrate::[a-z_]' crates/features/src/*.rs crates/features/src/*/tests.rs | From d2c367a768c48fa4a9d0a2894db8a02adf5a9e0b Mon Sep 17 00:00:00 2001 From: itsfuad Date: Wed, 18 Nov 2026 01:41:33 +0600 Subject: [PATCH 05/24] Move bools, strings, casts and panic into the kernel Each of the four features only wrapped what the core already owned: a bool or str/cstr constant, the core's conversion, the THIR panic. They become plain tree nodes (Expr::Bool, Expr::String, Expr::Cast, Stmt::Panic), read by the core parser and checked by the core checker; the feature files go (docs/structure-mapping.md, step 2). Language::string_kind goes with them: it only let the core ask the text feature whether an expression was a string literal, for an extern's name and a panic message, which now match Expr::String directly. The features' tests move to the core crates and run in Bare; the cast cases join the parser's precedence table. --- crates/features/src/bools.rs | 66 -------------- crates/features/src/bools/tests.rs | 35 -------- crates/features/src/casts.rs | 86 ------------------- crates/features/src/casts/tests.rs | 58 ------------- crates/features/src/lib.rs | 18 ---- crates/features/src/panics.rs | 68 --------------- crates/features/src/panics/tests.rs | 47 ---------- crates/features/src/text.rs | 75 ---------------- crates/features/src/text/tests.rs | 85 ------------------ crates/kernel/model/src/program.rs | 5 +- crates/kernel/semantic/src/declaration.rs | 16 ++++ crates/kernel/semantic/src/expression.rs | 15 +++- .../semantic/src/expression/literals.rs | 2 +- .../semantic/src/expression/operators.rs | 37 ++++++++ crates/kernel/semantic/src/statement.rs | 23 +++++ crates/kernel/semantic/src/statement/tests.rs | 36 ++++++++ crates/kernel/semantic/src/testing.rs | 4 - crates/kernel/syntax/parser/src/dump.rs | 9 ++ crates/kernel/syntax/parser/src/expr.rs | 20 ++++- crates/kernel/syntax/parser/src/expr/tests.rs | 52 ++++++++++- crates/kernel/syntax/parser/src/literals.rs | 19 +++- crates/kernel/syntax/parser/src/stmt.rs | 9 ++ crates/kernel/syntax/parser/src/stmt/tests.rs | 18 ++++ crates/kernel/syntax/parser/src/tests.rs | 5 -- crates/kernel/syntax/tree/src/ast.rs | 16 +++- scripts/check.sh | 2 +- 26 files changed, 261 insertions(+), 565 deletions(-) delete mode 100644 crates/features/src/bools.rs delete mode 100644 crates/features/src/bools/tests.rs delete mode 100644 crates/features/src/casts.rs delete mode 100644 crates/features/src/casts/tests.rs delete mode 100644 crates/features/src/panics.rs delete mode 100644 crates/features/src/panics/tests.rs delete mode 100644 crates/features/src/text.rs delete mode 100644 crates/features/src/text/tests.rs diff --git a/crates/features/src/bools.rs b/crates/features/src/bools.rs deleted file mode 100644 index a6b8bf7e..00000000 --- a/crates/features/src/bools.rs +++ /dev/null @@ -1,66 +0,0 @@ -//! Bools: `true` and `false`. The checker gives the core's bool constant, -//! so the phases after it know nothing of them. The `bool` type and -//! its operations (`!`, `&&`, `==`) are the core's: they read the checked -//! type. - -use arena::Id; -use check::builder::ThirBuilder; -use model::constant::Value; -use model::semantic_types::TypeId; -use model::thir; -use parser::Parser; -use parser::Rules; -use source::Span; -use syntax::ast; -use syntax::operators::Precedence; -use token::TokenKind; - -use crate::ExprNode; -use crate::FeatureExpr; -use crate::Peeper; - -/// `true` or `false` -#[derive(Clone, Copy, Debug)] -pub struct BoolLiteral { - pub value: bool, -} - -impl BoolLiteral { - /// Adds the rules that read bools to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.prefix(TokenKind::True, bool_literal); - rules.prefix(TokenKind::False, bool_literal); - } -} - -/// Reads `true` or `false`. -fn bool_literal(p: &mut Parser) -> Id> { - let token = p.next(); - let value = token.kind == TokenKind::True; - p.add( - token.span.start, - ast::Expr::Feature(FeatureExpr::Bool(BoolLiteral { value })), - ) -} - -impl ExprNode for BoolLiteral { - fn precedence(&self) -> Precedence { - Precedence::Call - } - - /// The constant `literal` is. - fn check( - &self, - _builder: &mut ThirBuilder<'_, '_, Peeper>, - _span: Span, - _expected: Option, - ) -> thir::Expr { - thir::Expr { - ty: TypeId::BOOL, - kind: thir::ExprKind::Constant(Value::Bool(self.value)), - } - } -} - -#[cfg(test)] -mod tests; diff --git a/crates/features/src/bools/tests.rs b/crates/features/src/bools/tests.rs deleted file mode 100644 index c226121b..00000000 --- a/crates/features/src/bools/tests.rs +++ /dev/null @@ -1,35 +0,0 @@ -//! Reading bools. The parser's tree dump is its own tests', so these look -//! at the tree. - -use std::sync::Arc; - -use source::SourceFile; -use syntax::ast; - -use super::*; - -/// `true` and `false` are bool literals, each spanning its word, and an -/// operand like any value. -#[test] -fn parses_literals() { - let text = "fn f() { true; false; !true == false; }"; - let (tree, errors) = parser::parse::(&Arc::new(SourceFile::new("t.peep", text))); - assert!(errors.is_empty(), "{errors:?}"); - let literals: Vec<(bool, &str)> = (tree.exprs.ids()) - .filter_map(|id| match tree.exprs[id] { - ast::Expr::Feature(FeatureExpr::Bool(BoolLiteral { value })) => { - Some((value, tree.file.slice(tree.exprs.span(id)))) - } - _ => None, - }) - .collect(); - assert_eq!( - literals, - [ - (true, "true"), - (false, "false"), - (true, "true"), - (false, "false") - ] - ); -} diff --git a/crates/features/src/casts.rs b/crates/features/src/casts.rs deleted file mode 100644 index edc4401b..00000000 --- a/crates/features/src/casts.rs +++ /dev/null @@ -1,86 +0,0 @@ -//! Casts: `value as T`, read and checked into the core's conversion of the -//! value (`Types::conversion`), so the phases after checking know nothing -//! of them. - -use arena::Id; -use check::builder::ThirBuilder; -use model::semantic_types::Conversion; -use model::semantic_types::TypeId; -use model::thir; -use parser::Parser; -use parser::Rules; -use source::Span; -use syntax::ast; -use syntax::operators::Precedence; -use token::TokenKind; - -use crate::ExprNode; -use crate::FeatureExpr; -use crate::Peeper; - -/// `value as ty` -#[derive(Clone, Copy, Debug)] -pub struct Cast { - pub value: Id>, - pub ty: Id>, -} - -impl Cast { - /// Adds the rule that reads casts to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.infix(TokenKind::As, Precedence::Cast, cast); - } -} - -/// Reads `as Type` after `value`. -fn cast(p: &mut Parser, value: Id>) -> Id> { - p.next(); - let ty = p.type_expr(); - let cast = FeatureExpr::Cast(Cast { value, ty }); - p.add(p.start_of(value), ast::Expr::Feature(cast)) -} - -impl ExprNode for Cast { - fn precedence(&self) -> Precedence { - Precedence::Cast - } - - /// `value as ty`: `value` as a value of the type `ty`, which its type - /// converts to with `as` or without it (`Types::conversion`). A number - /// literal takes the type `ty` if it can, so `300 as u8` is an error. - fn check( - &self, - builder: &mut ThirBuilder<'_, '_, Peeper>, - span: Span, - _expected: Option, - ) -> thir::Expr { - let Cast { value, ty } = *self; - let to = builder.checker.resolve_value_type(ty); - let checked = builder.check_expr(value, Some(to)); - if checked.ty == TypeId::INVALID || to == TypeId::INVALID { - return thir::Expr::INVALID; - } - let value_span = builder.checker.module().ast.exprs.span(value); - let found = checked.ty; - let conversion = builder.checker.types.conversion(found, to); - if let Some(converted) = builder.convert(checked, value_span, to, conversion) { - return converted; - } - let (found_text, to_text) = builder.checker.type_texts(found, to); - let message = format!("`{found_text}` cannot be converted to `{to_text}`"); - let types = &builder.checker.types; - let diagnostic = builder.type_error( - diagnostics::INVALID_CAST, - message, - span, - value, - found, - |ty| types.conversion(ty, to) != Conversion::Never, - ); - builder.checker.report(diagnostic); - thir::Expr::INVALID - } -} - -#[cfg(test)] -mod tests; diff --git a/crates/features/src/casts/tests.rs b/crates/features/src/casts/tests.rs deleted file mode 100644 index a68ddeee..00000000 --- a/crates/features/src/casts/tests.rs +++ /dev/null @@ -1,58 +0,0 @@ -//! Reading casts. The parser's tree dump is its own tests', so these look -//! at the tree. - -use std::sync::Arc; - -use arena::Id; -use source::SourceFile; -use syntax::ast; - -use super::*; -use crate::testing::Tree; - -/// The expression `id` with each cast and operation that holds a cast in -/// parentheses, and the rest as written. -fn grouped(tree: &Tree, id: Id>) -> String { - let text = |span| tree.file.slice(span).to_string(); - match tree.exprs[id] { - ast::Expr::Feature(FeatureExpr::Cast(Cast { value, ty })) => { - format!( - "({} as {})", - grouped(tree, value), - text(tree.types.span(ty)) - ) - } - ast::Expr::Binary { op, left, right } => { - format!( - "({} {} {})", - grouped(tree, left), - op.symbol(), - grouped(tree, right) - ) - } - _ => text(tree.exprs.span(id)), - } -} - -/// A cast binds tighter than every binary operator. -#[test] -fn precedence() { - for (text, want) in [ - ("a + b as i64", "(a + (b as i64))"), - ("a as i32 * b", "((a as i32) * b)"), - ] { - let source = Arc::new(SourceFile::new("t.peep", format!("fn f() {{ {text}; }}"))); - let (tree, errors) = parser::parse::(&source); - assert!(errors.is_empty(), "{text}: {errors:?}"); - let decl = tree.declarations().next().unwrap(); - let ast::Decl::Function(function) = tree.decls[decl] else { - panic!("not a function") - }; - let statements = tree.blocks[function.body.unwrap()].statements; - let statement = tree.children.lists.items(statements).next().unwrap(); - let ast::Stmt::Expression(expr) = tree.stmts[statement] else { - panic!("not an expression statement") - }; - assert_eq!(grouped(&tree, expr), want, "{text}"); - } -} diff --git a/crates/features/src/lib.rs b/crates/features/src/lib.rs index b269cf49..3b6248ad 100644 --- a/crates/features/src/lib.rs +++ b/crates/features/src/lib.rs @@ -17,24 +17,19 @@ use parser::Rules; use source::Span; use syntax::ast; use syntax::ast::Language; -use syntax::ast::StringKind; use syntax::ast::WrittenRange; use syntax::operators::Precedence; pub mod arrays; -pub mod bools; -pub mod casts; pub mod chars; pub mod enums; pub mod interfaces; pub mod optionals; -pub mod panics; pub mod pipes; pub mod printing; pub mod ranges; pub mod raw_pointers; pub mod structs; -pub mod text; #[cfg(test)] mod testing; @@ -48,11 +43,6 @@ pub(crate) trait ExprNode { /// The precedence the expression has where it is an operand. fn precedence(&self) -> Precedence; - /// What kind of string literal it is, if it is one. - fn string_kind(&self) -> Option { - None - } - /// The range it writes, if it is one. fn written_range(&self) -> Option> { None @@ -141,16 +131,13 @@ nodes! { /// An expression of a feature's, by feature. FeatureExpr: ExprNode { ArrayLiteral(arrays::ArrayLiteral), - Bool(bools::BoolLiteral), CaseTest(enums::CaseTest), - Cast(casts::Cast), Char(chars::CharLiteral), OrElse(optionals::OrElse), Pipe(pipes::Pipe), Print(printing::Print), Range(ranges::Range), RawAddress(raw_pointers::RawAddress), - String(text::StringLiteral), StructLiteral(structs::StructLiteral), VariantLiteral(enums::VariantLiteral), } @@ -160,7 +147,6 @@ nodes! { /// A statement of a feature's, by feature. FeatureStmt: StmtNode { Match(enums::Match), - Panic(panics::Panic), } } @@ -194,10 +180,6 @@ impl Language for Peeper { expr.node().precedence() } - fn string_kind(expr: &FeatureExpr) -> Option { - expr.node().string_kind() - } - fn written_range(expr: &FeatureExpr) -> Option> { expr.node().written_range() } diff --git a/crates/features/src/panics.rs b/crates/features/src/panics.rs deleted file mode 100644 index 21a03c71..00000000 --- a/crates/features/src/panics.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! Panics: `panic message;`, read and checked into the core's panic -//! statement (`thir::Stmt::Panic`), which stops the program. - -use arena::Id; -use check::builder::ThirBuilder; -use model::semantic_types::TypeId; -use model::thir; -use parser::Parser; -use parser::Rules; -use source::Span; -use syntax::ast; -use syntax::ast::Language; -use syntax::ast::StringKind; -use syntax::operators::Precedence; -use token::TokenKind; - -use crate::FeatureStmt; -use crate::Peeper; -use crate::StmtNode; - -/// `panic message;` -#[derive(Clone, Copy, Debug)] -pub struct Panic { - pub message: Id>, -} - -impl Panic { - /// Adds the rule that reads panics to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.statement(TokenKind::Panic, panic); - } -} - -/// Reads `panic message;`. -fn panic(p: &mut Parser) -> Id> { - let start = p.next().span.start; - let message = p.expr(Precedence::Lowest); - p.end(); - p.add( - start, - ast::Stmt::Feature(FeatureStmt::Panic(Panic { message })), - ) -} - -impl StmtNode for Panic { - /// `panic message;`: the message is a plain string literal. - fn check(&self, builder: &mut ThirBuilder<'_, '_, Peeper>, _span: Span) -> Option { - let tree = &builder.checker.module().ast; - let message = tree.unparenthesized(self.message); - let span = tree.exprs.span(message); - // shortcut: a plain string literal only, as there are no run-time - // strings; take a string value once there are. - let plain = |expr| Peeper::string_kind(&expr) == Some(StringKind::Plain); - if !matches!(tree.exprs[message], ast::Expr::Feature(expr) if plain(expr)) { - let checked = builder.add_expr(message, None); - if builder.body.exprs[checked].ty != TypeId::INVALID { - let what = "`panic` messages other than string literals"; - builder.checker.not_supported(span, what); - } - return None; - } - let message = builder.string_literal(span, TypeId::STR); - Some(thir::Stmt::Panic(builder.body.add(message, span))) - } -} - -#[cfg(test)] -mod tests; diff --git a/crates/features/src/panics/tests.rs b/crates/features/src/panics/tests.rs deleted file mode 100644 index 0d257543..00000000 --- a/crates/features/src/panics/tests.rs +++ /dev/null @@ -1,47 +0,0 @@ -//! Reading panics. What a panic does when it runs is the test programs' -//! to show. - -use syntax::ast; - -use super::*; -use crate::testing::bodies; -use crate::testing::messages; -use crate::testing::parse_text; - -/// `panic` takes one expression and ends with `;`. -#[test] -fn parses_panics() { - let (tree, errors) = parse_text("fn f() { panic \"stop\"; panic (message); }"); - assert!(errors.is_empty(), "{errors:?}"); - let found: Vec<&str> = (tree.stmts.ids()) - .filter_map(|id| match tree.stmts[id] { - ast::Stmt::Feature(FeatureStmt::Panic(Panic { message })) => { - Some(tree.file.slice(tree.exprs.span(message))) - } - _ => None, - }) - .collect(); - assert_eq!(found, ["\"stop\"", "(message)"]); - assert_eq!(messages("fn f() { panic ; }").len(), 1); -} - -/// The message is a plain string literal, in parentheses or not; any -/// other value is refused, once. -#[test] -fn message_is_a_string_literal() { - let (bodies, reported) = bodies( - "fn f(a: i32) { panic (\"stop\"); } - fn g(a: i32) { panic a; } - fn h() { panic c\"stop\"; } - fn i() { panic missing; }", - ); - assert_eq!(bodies[0], " panic \"stop\"\n"); - let found: Vec<(&str, &str)> = (reported.iter()) - .map(|(_, message, text)| (message.as_str(), text.as_str())) - .collect(); - let refused = "`panic` messages other than string literals are not supported yet"; - assert_eq!(found.len(), 3, "{found:?}"); - assert_eq!(found[0], (refused, "a")); - assert_eq!(found[1], (refused, "c\"stop\"")); - assert_eq!(found[2].1, "missing"); -} diff --git a/crates/features/src/text.rs b/crates/features/src/text.rs deleted file mode 100644 index 8bca4f7c..00000000 --- a/crates/features/src/text.rs +++ /dev/null @@ -1,75 +0,0 @@ -//! Text: string literals, `"..."` and `c"..."`. The checker gives the -//! core's `str` or `cstr` constant, so the phases after it know nothing of -//! them. The `str` and `cstr` types are the core's; the core reads a -//! literal's kind through `Language::string_kind`, which the list answers (an -//! `extern`'s name, a `panic` message). - -use arena::Id; -use check::builder::ThirBuilder; -use model::semantic_types::TypeId; -use model::thir; -use parser::Parser; -use parser::Rules; -use source::Span; -use syntax::ast; -use syntax::ast::StringKind; -use syntax::operators::Precedence; -use token::TokenKind; - -use crate::ExprNode; -use crate::FeatureExpr; -use crate::Peeper; - -/// `"..."`, or `c"..."`; `literal::value` decodes its text -#[derive(Clone, Copy, Debug)] -pub struct StringLiteral { - pub kind: StringKind, -} - -impl StringLiteral { - /// Adds the rules that read string literals to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.prefix(TokenKind::String, string_literal); - rules.prefix(TokenKind::CString, string_literal); - } -} - -/// Reads `"text"` or `c"text"`. -fn string_literal(p: &mut Parser) -> Id> { - let token = p.next(); - let kind = match token.kind { - TokenKind::CString => StringKind::C, - _ => StringKind::Plain, - }; - p.add( - token.span.start, - ast::Expr::Feature(FeatureExpr::String(StringLiteral { kind })), - ) -} - -impl ExprNode for StringLiteral { - fn precedence(&self) -> Precedence { - Precedence::Call - } - - fn string_kind(&self) -> Option { - Some(self.kind) - } - - /// The constant the string literal `literal`, written at `span`, is. - fn check( - &self, - builder: &mut ThirBuilder<'_, '_, Peeper>, - span: Span, - _expected: Option, - ) -> thir::Expr { - let ty = match self.kind { - StringKind::Plain => TypeId::STR, - StringKind::C => TypeId::CSTR, - }; - builder.string_literal(span, ty) - } -} - -#[cfg(test)] -mod tests; diff --git a/crates/features/src/text/tests.rs b/crates/features/src/text/tests.rs deleted file mode 100644 index f399e67f..00000000 --- a/crates/features/src/text/tests.rs +++ /dev/null @@ -1,85 +0,0 @@ -//! Reading and checking string literals. The parser's tree dump and the checker's -//! test program are those crates' own, so these build what they need. - -use std::sync::Arc; - -use model::ConstArguments; -use model::DeclarationCopy; -use model::semantic_types::TypeId; -use model::thir::Body; -use source::SourceFile; -use syntax::ast; -use syntax::ast::StringKind; - -use super::*; -use crate::testing::with_checker; - -/// `"..."` is a plain string literal and `c"..."` a C one, each spanning -/// its quotes. -#[test] -fn parses_literals() { - let text = r#"fn f() { g("a", c"b"); }"#; - let (tree, errors) = parser::parse::(&Arc::new(SourceFile::new("t.peep", text))); - assert!(errors.is_empty(), "{errors:?}"); - let literals: Vec<(StringKind, &str)> = (tree.exprs.ids()) - .filter_map(|id| match tree.exprs[id] { - ast::Expr::Feature(FeatureExpr::String(StringLiteral { kind })) => { - Some((kind, tree.file.slice(tree.exprs.span(id)))) - } - _ => None, - }) - .collect(); - assert_eq!( - literals, - [(StringKind::Plain, "\"a\""), (StringKind::C, "c\"b\"")] - ); -} - -/// An `extern` function is C's, so it has no body here, and any other -/// function has one; their calls are not lowered. -#[test] -fn only_an_extern_function_has_no_body() { - let text = "#[extern(\"f\")]\nfn f(a: i8) -> i8 { return a; }\nfn g();\n"; - let (found, reported) = with_checker(text, |checker, functions| { - (functions.iter()) - .map(|&(definition, name)| checker.function_type(definition, name)) - .collect::>() - }); - let body = "a function needs a body, or `#[extern(\"name\")]` when C defines it"; - assert_eq!( - reported, - [ - ( - "P0005", - "an `extern` function has no body: C gives its code".to_string(), - "f".to_string() - ), - ("P0005", body.to_string(), "g".to_string()), - ] - ); - assert_eq!(found, [TypeId::INVALID, TypeId::INVALID]); -} - -/// A C string a compile-time run gives back is its text, read up to the -/// zero byte that ends it, as C reads it. -#[test] -fn a_run_gives_back_a_c_string_without_its_end() { - let text = "fn hello() -> &cstr { return c\"hello\"; } - fn g() { - const Greeting = hello(); - let greeting = Greeting; - }"; - let (built, reported) = with_checker(text, |checker, functions| { - let (definition, name) = functions[1]; - let mut body = Body::default(); - let copy = DeclarationCopy { - definition, - arguments: ConstArguments::NONE, - }; - assert!(checker.check_body(copy, name, &mut body, true)); - let file = SourceFile::new("main.peep", text); - body.text(&checker.types, &file, |_| "hello") - }); - assert!(reported.is_empty(), "{reported:?}"); - assert_eq!(built, " let greeting.0 = c\"hello\"\n"); -} diff --git a/crates/kernel/model/src/program.rs b/crates/kernel/model/src/program.rs index 7a19eeaf..11b1cd23 100644 --- a/crates/kernel/model/src/program.rs +++ b/crates/kernel/model/src/program.rs @@ -110,12 +110,9 @@ pub fn extern_symbol( let (None, Some(argument), None) = (&symbol, arguments.next(), arguments.next()) else { return Err(span); }; - let ast::Expr::Feature(expr) = tree.exprs[argument] else { + let ast::Expr::String(_) = tree.exprs[argument] else { return Err(span); }; - if L::string_kind(&expr).is_none() { - return Err(span); - } let text = tree.file.slice(tree.exprs.span(argument)); let name = String::from_utf8_lossy(&literal::value(text)).into_owned(); // No symbol has an empty name or one with a zero byte, which ends a diff --git a/crates/kernel/semantic/src/declaration.rs b/crates/kernel/semantic/src/declaration.rs index 590ab423..4e2709f4 100644 --- a/crates/kernel/semantic/src/declaration.rs +++ b/crates/kernel/semantic/src/declaration.rs @@ -1379,4 +1379,20 @@ mod tests { assert_eq!(found[1], format!("fn[] -> {void}")); assert_eq!(found[2], format!("fn[{:?}] -> {void}", TypeId::CSTR)); } + + /// An `extern` function is C's, so it has no body here, and any other + /// function has one. + #[test] + fn only_an_extern_function_has_no_body() { + let (found, reported) = + declared_types("#[extern(\"f\")]\nfn f(a: i8) -> i8 { return a; }\nfn g();\n"); + let invalid = format!("{:?}", Type::Invalid); + assert_eq!(found, [invalid.clone(), invalid]); + let body = "a function needs a body, or `#[extern(\"name\")]` when C defines it"; + let extern_body = "an `extern` function has no body: C gives its code"; + assert_eq!( + reported, + crate::testing::reported(&[("P0005", extern_body, "f"), ("P0005", body, "g")]) + ); + } } diff --git a/crates/kernel/semantic/src/expression.rs b/crates/kernel/semantic/src/expression.rs index 1793cbff..b8cb2c65 100644 --- a/crates/kernel/semantic/src/expression.rs +++ b/crates/kernel/semantic/src/expression.rs @@ -11,6 +11,7 @@ use arena::Id; use diagnostics::Code; use diagnostics::Diagnostic; use diagnostics::fix::Fix; +use model::constant::Value; use model::semantic_types::Conversion; use model::semantic_types::Type; use model::semantic_types::TypeId; @@ -278,6 +279,18 @@ impl ThirBuilder<'_, '_, L> { self.check_reference(mutable, value, span, expected) } ast::Expr::None => self.check_none(span, expected), + ast::Expr::Bool(value) => Expr { + ty: TypeId::BOOL, + kind: ExprKind::Constant(Value::Bool(value)), + }, + ast::Expr::String(kind) => { + let ty = match kind { + ast::StringKind::Plain => TypeId::STR, + ast::StringKind::C => TypeId::CSTR, + }; + self.string_literal(span, ty) + } + ast::Expr::Cast { value, ty } => self.check_cast(value, ty, span), } }) } @@ -347,7 +360,7 @@ impl ThirBuilder<'_, '_, L> { /// reference to a value of a type `accepts` takes, it helps to read that /// value with `.*`. An error that a value's type is not one its place /// takes is made here, so each such error gets the same help. - pub fn type_error( + pub(crate) fn type_error( &self, code: Code, message: String, diff --git a/crates/kernel/semantic/src/expression/literals.rs b/crates/kernel/semantic/src/expression/literals.rs index 2881dfc3..60f1d889 100644 --- a/crates/kernel/semantic/src/expression/literals.rs +++ b/crates/kernel/semantic/src/expression/literals.rs @@ -24,7 +24,7 @@ use crate::expression::unsuffixed_literal; impl ThirBuilder<'_, '_, L> { /// The string literal at `span`, a `&str` or with its `c` a `&cstr` (`ty`): /// its bytes. - pub fn string_literal(&mut self, span: Span, ty: TypeId) -> Expr { + pub(crate) fn string_literal(&mut self, span: Span, ty: TypeId) -> Expr { self.checker.record(span, FactKind::Literal(ty)); let bytes = literal::value(self.checker.module().ast.file.slice(span)); Expr { diff --git a/crates/kernel/semantic/src/expression/operators.rs b/crates/kernel/semantic/src/expression/operators.rs index bd6bd7d6..5a3f3dcf 100644 --- a/crates/kernel/semantic/src/expression/operators.rs +++ b/crates/kernel/semantic/src/expression/operators.rs @@ -4,6 +4,7 @@ use arena::Id; use bigint::Limbs; use model::constant::Value; +use model::semantic_types::Conversion; use model::semantic_types::Float; use model::semantic_types::Type; use model::semantic_types::TypeId; @@ -331,6 +332,42 @@ impl ThirBuilder<'_, '_, L> { self.checker.report(diagnostic); Expr::INVALID } + + /// `value as ty`, written at `span`: `value` as a value of the type + /// `ty`, which its type converts to with `as` or without it + /// (`Types::conversion`). A number literal takes the type `ty` if it + /// can, so `300 as u8` is an error. + pub(super) fn check_cast( + &mut self, + value: Id>, + ty: Id>, + span: Span, + ) -> Expr { + let to = self.checker.resolve_value_type(ty); + let checked = self.check_expr(value, Some(to)); + if checked.ty == TypeId::INVALID || to == TypeId::INVALID { + return Expr::INVALID; + } + let value_span = self.checker.module().ast.exprs.span(value); + let found = checked.ty; + let conversion = self.checker.types.conversion(found, to); + if let Some(converted) = self.convert(checked, value_span, to, conversion) { + return converted; + } + let (found_text, to_text) = self.checker.type_texts(found, to); + let message = format!("`{found_text}` cannot be converted to `{to_text}`"); + let types = &self.checker.types; + let diagnostic = self.type_error( + diagnostics::INVALID_CAST, + message, + span, + value, + found, + |ty| types.conversion(ty, to) != Conversion::Never, + ); + self.checker.report(diagnostic); + Expr::INVALID + } } /// Whether a number literal without a suffix can have the type `ty`: an diff --git a/crates/kernel/semantic/src/statement.rs b/crates/kernel/semantic/src/statement.rs index 37b87f80..eca430bf 100644 --- a/crates/kernel/semantic/src/statement.rs +++ b/crates/kernel/semantic/src/statement.rs @@ -392,6 +392,7 @@ impl<'a, 'p, L: Checked> ThirBuilder<'a, 'p, L> { return None; } ast::Stmt::Return(value) => Stmt::Return(self.check_return_value(span, value)), + ast::Stmt::Panic(message) => self.check_panic(message)?, ast::Stmt::Feature(stmt) => L::check_stmt(self, stmt, span)?, ast::Stmt::Expression(value) => Stmt::Expression(self.add_expr(value, None)), ast::Stmt::Assign { target, value } => self.assign(target, value)?, @@ -500,6 +501,28 @@ impl<'a, 'p, L: Checked> ThirBuilder<'a, 'p, L> { Some(self.body.add(checked, span)) }) } + + /// `panic message;`: the message is a plain string literal. + fn check_panic(&mut self, message: Id>) -> Option { + let tree = &self.checker.module().ast; + let message = tree.unparenthesized(message); + let span = tree.exprs.span(message); + // shortcut: a plain string literal only, as there are no run-time + // strings; take a string value once there are. + if !matches!( + tree.exprs[message], + ast::Expr::String(ast::StringKind::Plain) + ) { + let checked = self.add_expr(message, None); + if self.body.exprs[checked].ty != TypeId::INVALID { + let what = "`panic` messages other than string literals"; + self.checker.not_supported(span, what); + } + return None; + } + let message = self.string_literal(span, TypeId::STR); + Some(Stmt::Panic(self.body.add(message, span))) + } } #[cfg(test)] diff --git a/crates/kernel/semantic/src/statement/tests.rs b/crates/kernel/semantic/src/statement/tests.rs index 9f6353f7..76f139ff 100644 --- a/crates/kernel/semantic/src/statement/tests.rs +++ b/crates/kernel/semantic/src/statement/tests.rs @@ -523,3 +523,39 @@ fn a_constant_cannot_be_lent_as_writable() { ]); assert_eq!(found, expected); } + +/// A `panic` message is a plain string literal, in parentheses or not; any +/// other value is refused, once. +#[test] +fn a_panic_message_is_a_string_literal() { + let (bodies, found) = bodies( + "fn f(a: i32) { panic (\"stop\"); } + fn g(a: i32) { panic a; } + fn h() { panic c\"stop\"; } + fn i() { panic missing; }", + ); + assert_eq!(bodies, [" panic \"stop\"\n"]); + let refused = "`panic` messages other than string literals are not supported yet"; + let found: Vec<(&str, &str)> = (found.iter()) + .map(|(_, message, text)| (message.as_str(), text.as_str())) + .collect(); + assert_eq!(found.len(), 3, "{found:?}"); + assert_eq!(found[0], (refused, "a")); + assert_eq!(found[1], (refused, "c\"stop\"")); + assert_eq!(found[2].1, "missing"); +} + +/// A C string a compile-time run gives back is its text, read up to the +/// zero byte that ends it, as C reads it. +#[test] +fn a_run_gives_back_a_c_string_without_its_end() { + let (bodies, found) = bodies( + "fn hello() -> &cstr { return c\"hello\"; } + fn g() { + const Greeting = hello(); + let greeting = Greeting; + }", + ); + assert!(found.is_empty(), "{found:?}"); + assert_eq!(bodies[1], " let greeting.0 = c\"hello\"\n"); +} diff --git a/crates/kernel/semantic/src/testing.rs b/crates/kernel/semantic/src/testing.rs index 59a0624a..40746dde 100644 --- a/crates/kernel/semantic/src/testing.rs +++ b/crates/kernel/semantic/src/testing.rs @@ -55,10 +55,6 @@ impl Language for Bare { match *ty {} } - fn string_kind(expr: &Infallible) -> Option { - match *expr {} - } - fn written_range(expr: &Infallible) -> Option> { match *expr {} } diff --git a/crates/kernel/syntax/parser/src/dump.rs b/crates/kernel/syntax/parser/src/dump.rs index 7caf0a77..afc575c2 100644 --- a/crates/kernel/syntax/parser/src/dump.rs +++ b/crates/kernel/syntax/parser/src/dump.rs @@ -21,6 +21,7 @@ use syntax::ast::Param; use syntax::ast::Pattern; use syntax::ast::Signature; use syntax::ast::Stmt; +use syntax::ast::StringKind; use syntax::ast::Tree; use syntax::ast::Type; @@ -322,6 +323,7 @@ impl<'t> Dumper<'t> { None, value.map(Item::Expr).into_iter().collect(), ), + Stmt::Panic(message) => ("panic statement", None, vec![Item::Expr(message)]), Stmt::Feature(feature) => match feature {}, Stmt::Expression(e) => ("expression statement", None, vec![Item::Expr(e)]), Stmt::Assign { target, value } => ( @@ -408,6 +410,13 @@ impl<'t> Dumper<'t> { Expr::Name => ("name reference", None, vec![]), Expr::Number => ("number literal", None, vec![]), Expr::None => ("none literal", None, vec![]), + Expr::Bool(_) => ("bool literal", None, vec![]), + Expr::String(kind) => ( + "string literal", + (kind == StringKind::C).then_some(TokenKind::CString.text()), + vec![], + ), + Expr::Cast { value, ty } => ("cast expression", None, two(value, Item::Type(ty))), Expr::Binary { op, left, right } => ( "binary expression", Some(op.symbol()), diff --git a/crates/kernel/syntax/parser/src/expr.rs b/crates/kernel/syntax/parser/src/expr.rs index c76e7747..866a52f6 100644 --- a/crates/kernel/syntax/parser/src/expr.rs +++ b/crates/kernel/syntax/parser/src/expr.rs @@ -19,8 +19,7 @@ use token::TokenKind; use crate::Grammar; use crate::Parser; use crate::Rules; -use crate::literals::none_literal; -use crate::literals::number_literal; +use crate::literals; /// Reads the expression the current token begins. pub type PrefixRule = fn(&mut Parser) -> Id>; @@ -67,8 +66,12 @@ pub(crate) const fn expression_rows(rules: &mut Rules) { // values rules.prefix(TokenKind::Ident, name_or_path); rules.prefix(TokenKind::SelfValue, self_name); - rules.prefix(TokenKind::Number, number_literal); - rules.prefix(TokenKind::None, none_literal); + rules.prefix(TokenKind::Number, literals::number_literal); + rules.prefix(TokenKind::None, literals::none_literal); + rules.prefix(TokenKind::True, literals::bool_literal); + rules.prefix(TokenKind::False, literals::bool_literal); + rules.prefix(TokenKind::String, literals::string_literal); + rules.prefix(TokenKind::CString, literals::string_literal); rules.prefix(TokenKind::LeftParen, parentheses); // prefix operators @@ -108,6 +111,8 @@ pub(crate) const fn expression_rows(rules: &mut Rules) { rules.infix(TokenKind::LeftParen, Precedence::Call, call); rules.infix(TokenKind::LeftBracket, Precedence::Call, index); rules.infix(TokenKind::Dot, Precedence::Call, selector); + + rules.infix(TokenKind::As, Precedence::Cast, cast); } /// Whether an expression can begin with `kind`. @@ -188,6 +193,13 @@ pub(crate) fn name_or_path(p: &mut Parser) -> Id> { p.add(start, Expr::Path(path)) } +/// Reads `as Type` after `value`. +fn cast(p: &mut Parser, value: Id>) -> Id> { + p.next(); + let ty = p.type_expr(); + p.add(p.start_of(value), Expr::Cast { value, ty }) +} + /// Reads `( expression )`. fn parentheses(p: &mut Parser) -> Id> { let open = p.next(); diff --git a/crates/kernel/syntax/parser/src/expr/tests.rs b/crates/kernel/syntax/parser/src/expr/tests.rs index 377c743d..6e7e0b03 100644 --- a/crates/kernel/syntax/parser/src/expr/tests.rs +++ b/crates/kernel/syntax/parser/src/expr/tests.rs @@ -1,5 +1,6 @@ use syntax::ast::Decl; use syntax::ast::Stmt; +use syntax::ast::StringKind; use syntax::ast::Tree; use super::*; @@ -70,10 +71,13 @@ fn first_expression(tree: &Tree) -> Id> { e } -/// An expression with each binary operation in parentheses. +/// An expression with each binary operation and cast in parentheses. fn grouped(t: &Tree, id: Id>) -> String { let text = |span| t.file.slice(span).to_string(); match t.exprs[id] { + Expr::Cast { value, ty } => { + format!("({} as {})", grouped(t, value), text(t.types.span(ty))) + } Expr::Binary { op, left, right } => { format!( "({} {} {})", @@ -115,7 +119,8 @@ fn grouped(t: &Tree, id: Id>) -> String { } /// How operators group, from loosest to tightest, and that operators of -/// one precedence group to the left. +/// one precedence group to the left. A cast binds tighter than every binary +/// operator. #[test] fn precedence() { for (text, want) in [ @@ -137,6 +142,8 @@ fn precedence() { ("x.y.z[0][i]", "x.y.z[0][i]"), ("-r.* * r.x.*", "(-r.* * r.x.*)"), ("&mut r.*.x", "&mut r.*.x"), + ("a + b as i64", "(a + (b as i64))"), + ("a as i32 * b", "((a as i32) * b)"), ] { let (tree, errors) = parse_text(&format!("fn f() {{ {text}; }}")); assert!(errors.is_empty(), "{text}: {errors:?}"); @@ -310,3 +317,44 @@ fn number_checks() { ); } } + +/// `true` and `false` are bool literals, each spanning its word, and an +/// operand like any value. +#[test] +fn bool_literals() { + let (tree, errors) = parse_text("fn f() { true; false; !true == false; }"); + assert!(errors.is_empty(), "{errors:?}"); + let literals: Vec<(bool, &str)> = (tree.exprs.ids()) + .filter_map(|id| match tree.exprs[id] { + Expr::Bool(value) => Some((value, tree.file.slice(tree.exprs.span(id)))), + _ => None, + }) + .collect(); + assert_eq!( + literals, + [ + (true, "true"), + (false, "false"), + (true, "true"), + (false, "false") + ] + ); +} + +/// `"..."` is a plain string literal and `c"..."` a C one, each spanning +/// its quotes. +#[test] +fn string_literals() { + let (tree, errors) = parse_text(r#"fn f() { g("a", c"b"); }"#); + assert!(errors.is_empty(), "{errors:?}"); + let literals: Vec<(StringKind, &str)> = (tree.exprs.ids()) + .filter_map(|id| match tree.exprs[id] { + Expr::String(kind) => Some((kind, tree.file.slice(tree.exprs.span(id)))), + _ => None, + }) + .collect(); + assert_eq!( + literals, + [(StringKind::Plain, "\"a\""), (StringKind::C, "c\"b\"")] + ); +} diff --git a/crates/kernel/syntax/parser/src/literals.rs b/crates/kernel/syntax/parser/src/literals.rs index 13b29cc3..6ed1042a 100644 --- a/crates/kernel/syntax/parser/src/literals.rs +++ b/crates/kernel/syntax/parser/src/literals.rs @@ -1,9 +1,11 @@ -//! Literals: numbers, characters and `none`. +//! Literals: numbers, characters, bools, strings and `none`. use arena::Id; use diagnostics::Diagnostic; use syntax::ast::Expr; +use syntax::ast::StringKind; use token::Token; +use token::TokenKind; use crate::Grammar; use crate::Parser; @@ -41,6 +43,21 @@ pub(crate) fn none_literal(p: &mut Parser) -> Id> { p.leaf(Expr::None) } +/// Reads `true` or `false`. +pub(crate) fn bool_literal(p: &mut Parser) -> Id> { + let value = p.tok().kind == TokenKind::True; + p.leaf(Expr::Bool(value)) +} + +/// Reads `"text"` or `c"text"`. +pub(crate) fn string_literal(p: &mut Parser) -> Id> { + let kind = match p.tok().kind { + TokenKind::CString => StringKind::C, + _ => StringKind::Plain, + }; + p.leaf(Expr::String(kind)) +} + /// Reads a number and checks its type suffix. pub(crate) fn number_literal(p: &mut Parser) -> Id> { p.check_number(p.tok()); diff --git a/crates/kernel/syntax/parser/src/stmt.rs b/crates/kernel/syntax/parser/src/stmt.rs index 44e29cc1..7c1d2066 100644 --- a/crates/kernel/syntax/parser/src/stmt.rs +++ b/crates/kernel/syntax/parser/src/stmt.rs @@ -31,6 +31,7 @@ pub(crate) const fn statement_rows(statements: &mut [Option(p: &mut Parser) -> Id> { p.add(start, Stmt::Return(value)) } +/// Reads `panic message;`. +fn panic_statement(p: &mut Parser) -> Id> { + let start = p.next().span.start; + let message = p.expr(Precedence::Lowest); + p.end(); + p.add(start, Stmt::Panic(message)) +} + #[cfg(test)] mod tests; diff --git a/crates/kernel/syntax/parser/src/stmt/tests.rs b/crates/kernel/syntax/parser/src/stmt/tests.rs index 4b100498..96d67a39 100644 --- a/crates/kernel/syntax/parser/src/stmt/tests.rs +++ b/crates/kernel/syntax/parser/src/stmt/tests.rs @@ -1,6 +1,9 @@ +use syntax::ast::Stmt; + use crate::tests::dump_of; use crate::tests::messages; use crate::tests::one_error; +use crate::tests::parse_text; /// A `return` without a value needs only its `;`: one missing at a line /// end is read past with a fix, one missing inside a line is reported. @@ -147,3 +150,18 @@ fn statement_errors() { one_error(&format!("fn f() {{ {text} }}"), message, fixed.as_deref()); } } + +/// `panic` takes one expression and ends with `;`. +#[test] +fn panics() { + let (tree, errors) = parse_text("fn f() { panic \"stop\"; panic (message); }"); + assert!(errors.is_empty(), "{errors:?}"); + let found: Vec<&str> = (tree.stmts.ids()) + .filter_map(|id| match tree.stmts[id] { + Stmt::Panic(message) => Some(tree.file.slice(tree.exprs.span(message))), + _ => None, + }) + .collect(); + assert_eq!(found, ["\"stop\"", "(message)"]); + assert_eq!(messages("fn f() { panic ; }").len(), 1); +} diff --git a/crates/kernel/syntax/parser/src/tests.rs b/crates/kernel/syntax/parser/src/tests.rs index 44332111..5c913d3c 100644 --- a/crates/kernel/syntax/parser/src/tests.rs +++ b/crates/kernel/syntax/parser/src/tests.rs @@ -2,7 +2,6 @@ use std::convert::Infallible; use syntax::ast::Decl; use syntax::ast::Field; -use syntax::ast::StringKind; use syntax::ast::Type; use syntax::ast::WrittenRange; use syntax::operators::Precedence; @@ -39,10 +38,6 @@ impl Language for Bare { match *ty {} } - fn string_kind(expr: &Infallible) -> Option { - match *expr {} - } - fn written_range(expr: &Infallible) -> Option> { match *expr {} } diff --git a/crates/kernel/syntax/tree/src/ast.rs b/crates/kernel/syntax/tree/src/ast.rs index ff7e0103..eb9af087 100644 --- a/crates/kernel/syntax/tree/src/ast.rs +++ b/crates/kernel/syntax/tree/src/ast.rs @@ -51,10 +51,6 @@ pub trait Language: Copy + Debug + 'static { /// array type (`[N]T`). fn element(ty: &Self::Type) -> Option>>; - /// The kind of string literal the feature expression `expr` is, if it - /// is one. - fn string_kind(expr: &Self::Expr) -> Option; - /// The parts of the feature expression `expr`, if it is a written range. fn written_range(expr: &Self::Expr) -> Option>; } @@ -420,6 +416,8 @@ pub enum Stmt { /// a `Decl::Const` Const(Id>), Return(Option>>), + /// `panic message;` + Panic(Id>), /// a feature's statement Feature(L::Stmt), /// an expression followed by `;` @@ -504,6 +502,13 @@ pub enum Expr { Number, /// `none` None, + /// `true` or `false` + Bool(bool), + /// `"..."` or `c"..."`; its text is its span, which `literal::value` + /// decodes + String(StringKind), + /// `value as ty` + Cast { value: Id>, ty: Id> }, /// `left op right` Binary { op: BinaryOp, @@ -553,10 +558,13 @@ impl Expr { match self { Expr::Binary { op, .. } => op.precedence(), Expr::Unary { .. } | Expr::Reference { .. } => Precedence::Prefix, + Expr::Cast { .. } => Precedence::Cast, Expr::Name | Expr::Path(_) | Expr::Number | Expr::None + | Expr::Bool(_) + | Expr::String(_) | Expr::Call { .. } | Expr::Selector { .. } | Expr::Dereference(_) diff --git a/scripts/check.sh b/scripts/check.sh index d8f46382..d2138663 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -46,7 +46,7 @@ check "middle boundary" bash -c " # (docs/feature-front.md section 7); Cargo refuses the cycle for the crates # `features` depends on, this the others. And a feature's file names no # other feature: of its own crate, only the list's `Peeper` and enums, so -# no module's path (`crate::bools`). +# no module's path (`crate::structs`). check "feature boundary" bash -c " for manifest in crates/{base,backend}/*/Cargo.toml crates/kernel/syntax/*/Cargo.toml \\ crates/kernel/{semantic,model,lower,flow,eval}/Cargo.toml crates/driver/project/Cargo.toml; do From d13e23c11528fd6dae2ed5f83591138b32850116 Mon Sep 17 00:00:00 2001 From: itsfuad Date: Wed, 18 Nov 2026 02:03:23 +0600 Subject: [PATCH 06/24] Group the checker's modules by concept Split declaration.rs and its neighbours into one module per concept: functions (signatures, bodies, calls, #[builtin] functions), generics (type arguments, copies, where), conformance, locals (let and const) and expression/names. No checking logic changed. function_declaration moves to model::program beside declaration, and argument_count_message to lib.rs, so generics needs nothing from functions and the two modules no longer depend on each other. unsupported_type moves next to the type-name lookup that reads it, and the signature tests move to functions.rs with the code they test. Imports in the new and moved files are at most two levels deep. --- crates/driver/compile/src/lib.rs | 4 +- crates/features/src/interfaces.rs | 4 +- crates/kernel/model/src/program.rs | 11 + crates/kernel/semantic/src/conformance.rs | 147 ++++ crates/kernel/semantic/src/declaration.rs | 814 +----------------- crates/kernel/semantic/src/expression.rs | 2 +- .../kernel/semantic/src/expression/borrows.rs | 2 +- .../semantic/src/expression/literals.rs | 2 +- .../kernel/semantic/src/expression/names.rs | 60 ++ crates/kernel/semantic/src/functions.rs | 568 ++++++++++++ .../src/{function.rs => functions/bodies.rs} | 73 +- .../semantic/src/{ => functions}/builtin.rs | 68 +- .../src/{expression => functions}/calls.rs | 383 ++------ crates/kernel/semantic/src/generics.rs | 363 ++++++++ .../src/{ => generics}/constraints.rs | 34 +- .../semantic/src/{ => generics}/copies.rs | 72 +- crates/kernel/semantic/src/lib.rs | 56 +- .../{statement/declarations.rs => locals.rs} | 59 +- crates/kernel/semantic/src/statement.rs | 6 +- docs/structure-mapping.md | 27 +- 20 files changed, 1440 insertions(+), 1315 deletions(-) create mode 100644 crates/kernel/semantic/src/conformance.rs create mode 100644 crates/kernel/semantic/src/expression/names.rs create mode 100644 crates/kernel/semantic/src/functions.rs rename crates/kernel/semantic/src/{function.rs => functions/bodies.rs} (82%) rename crates/kernel/semantic/src/{ => functions}/builtin.rs (60%) rename crates/kernel/semantic/src/{expression => functions}/calls.rs (52%) create mode 100644 crates/kernel/semantic/src/generics.rs rename crates/kernel/semantic/src/{ => generics}/constraints.rs (90%) rename crates/kernel/semantic/src/{ => generics}/copies.rs (80%) rename crates/kernel/semantic/src/{statement/declarations.rs => locals.rs} (82%) diff --git a/crates/driver/compile/src/lib.rs b/crates/driver/compile/src/lib.rs index 2e332d7f..c78477e8 100644 --- a/crates/driver/compile/src/lib.rs +++ b/crates/driver/compile/src/lib.rs @@ -441,7 +441,7 @@ fn compile_module( // its types are is reported here, once, though no call copies // it, and an editor asks about its text. ast::Decl::Function(function) - if check::declaration::first_copy_parameter(tree, function.signature).is_some() => + if check::generics::first_copy_parameter(tree, function.signature).is_some() => { let name = function.name.span; checker.function_type(definition, name); @@ -563,7 +563,7 @@ fn interface(checker: &Checker, module: ModuleId, done: &[ModuleResults] .hash(&mut hasher); // Another module's call builds a copy of its body, so the body // is what that module sees. - if check::declaration::first_copy_parameter(tree, function.signature).is_some() { + if check::generics::first_copy_parameter(tree, function.signature).is_some() { tree.file .slice(tree.decls.span(declaration)) .hash(&mut hasher); diff --git a/crates/features/src/interfaces.rs b/crates/features/src/interfaces.rs index d408b168..1cec2aee 100644 --- a/crates/features/src/interfaces.rs +++ b/crates/features/src/interfaces.rs @@ -6,7 +6,7 @@ use arena::Id; use arena::List; use check::Checker; -use check::declaration::FunctionKind; +use check::functions; use check::scope::report_redeclared; use model::DefId; use model::semantic_types::Type; @@ -113,7 +113,7 @@ impl TypeNode for InterfaceType { methods.push(TypeId::INVALID); continue; } - let kind = &FunctionKind::INTERFACE_METHOD; + let kind = &functions::FunctionKind::INTERFACE_METHOD; methods.push(checker.signature_type(method.name, method.signature, true, kind)); } let invalid = |ty: TypeId| match &checker.types[ty] { diff --git a/crates/kernel/model/src/program.rs b/crates/kernel/model/src/program.rs index 11b1cd23..631a03e3 100644 --- a/crates/kernel/model/src/program.rs +++ b/crates/kernel/model/src/program.rs @@ -39,6 +39,17 @@ pub fn declaration(modules: &[Module], definition: DefId) -> &as &tree.decls[tree.declaration(definition.index)] } +/// The function `definition`, as written. +pub fn function_declaration( + modules: &[Module], + definition: DefId, +) -> &ast::Function { + match declaration(modules, definition) { + ast::Decl::Function(function) => function, + _ => unreachable!("`{definition:?}` is a function"), + } +} + /// The text of the name the declaration `definition` of `modules` declares. pub fn declared_text(modules: &[Module], definition: DefId) -> &str { let (name, file) = declared_name(modules, definition); diff --git a/crates/kernel/semantic/src/conformance.rs b/crates/kernel/semantic/src/conformance.rs new file mode 100644 index 00000000..a0bda17f --- /dev/null +++ b/crates/kernel/semantic/src/conformance.rs @@ -0,0 +1,147 @@ +//! Interface conformance: whether a type has every function an interface +//! asks for, with the signature it asks for, its receiver the type's own; +//! each answer is kept as an `ImplementationId`. + +use model::DefId; +use model::semantic_types; +use model::thir; +use source::Span; + +use crate::Checked; +use crate::Checker; +use crate::generics; + +impl Checker<'_, L> { + /// The functions of the struct `structure` that are the methods of the + /// interface `interface`, for a reference to the struct used as a + /// reference to the interface at `span`: for each method, the struct's + /// function of its name and type, `self` being the struct; looked up + /// once for the pair. `None` after reporting the first method the struct + /// lacks or has with another type, or when the interface's error was + /// reported; such a pair is reported at each conversion. + pub(crate) fn implementation( + &mut self, + structure: semantic_types::TypeId, + interface: semantic_types::TypeId, + span: Span, + ) -> Option { + if let Some(&found) = self + .internals + .known_implementations + .get(&(structure, interface)) + { + return Some(found); + } + let modules = self.modules; + let Some(semantic_types::Members { + definition: owner, .. + }) = self.types[structure].members() + else { + unreachable!( + "only a reference to a type with members converts to an interface reference" + ) + }; + let (semantic_types::Type::Named { definition, .. } + | semantic_types::Type::Interface { definition, .. }) = self.types[interface] + else { + unreachable!("an interface reference refers to an interface") + }; + if self.declared_type(definition, span) == semantic_types::TypeId::INVALID { + return None; + } + let semantic_types::Type::Interface { methods, .. } = &self.types[interface] else { + unreachable!("a checked interface is `Type::Interface`") + }; + let signatures = methods.clone(); + let declared = model::program::interface_methods(modules, definition) + .expect("an interface declaration has methods"); + let file = &modules[definition.module.index()].ast.file; + let mut found = Vec::with_capacity(signatures.len()); + for (method, &signature) in declared.zip(&signatures) { + let name = method.name.text(file); + let function = match self.module_checks[owner.module.index()] + .scope + .get(Some(owner), name) + { + Some(thir::Symbol::Function(function)) => Some(function), + _ => None, + }; + let expected = self.method_type(signature, structure); + let ty = function.map(|function| (function, self.function_type(function, span))); + let generic = |function: DefId| { + let tree = &modules[function.module.index()].ast; + generics::first_copy_parameter( + tree, + model::program::function_declaration(modules, function).signature, + ) + .is_some() + }; + let message = match ty { + Some((function, _)) if generic(function) => { + format!( + "its `{name}` takes a `const` parameter, so it is not one function an interface reference can call" + ) + } + Some((_, semantic_types::TypeId::INVALID)) => return None, // reported + Some((function, ty)) if ty == expected => { + if model::program::is_extern(modules, function) { + self.not_supported(span, "C functions as interface methods"); + return None; + } + found.push(function); + continue; + } + Some((_, ty)) => format!( + "its `{name}` is `{}`, but `{}` needs `{}`", + self.type_text(ty), + self.type_text(interface), + self.type_text(expected) + ), + None => format!("it has no method `{name}`"), + }; + let (structure, interface) = self.type_texts(structure, interface); + let message = format!("`{structure}` does not implement `{interface}`: {message}"); + self.error(diagnostics::TYPE_MISMATCH, message, span); + return None; + } + let id = self.types.add_implementation(found.into()); + self.internals + .known_implementations + .insert((structure, interface), id); + Some(id) + } + + /// The type a function of the struct `structure` has when it is the + /// interface method of the type `signature`: the same, with `self` the + /// struct. + fn method_type( + &mut self, + signature: semantic_types::TypeId, + structure: semantic_types::TypeId, + ) -> semantic_types::TypeId { + let semantic_types::Type::Function { + mut parameters, + result, + origins, + variadic, + } = self.types[signature].clone() + else { + unreachable!("a method's type is a function type") + }; + parameters[0] = match self.types[parameters[0]] { + semantic_types::Type::InterfaceReference { mutable, .. } => { + self.types.intern(semantic_types::Type::Reference { + mutable, + target: structure, + }) + } + _ => structure, // `self` taken whole + }; + self.types.intern(semantic_types::Type::Function { + parameters, + result, + origins, + variadic, + }) + } +} diff --git a/crates/kernel/semantic/src/declaration.rs b/crates/kernel/semantic/src/declaration.rs index 4e2709f4..530448da 100644 --- a/crates/kernel/semantic/src/declaration.rs +++ b/crates/kernel/semantic/src/declaration.rs @@ -1,6 +1,6 @@ //! Module-scope declarations, without their bodies, one check per category: -//! a type declaration's type, a function's type and a constant's type and -//! value. +//! a type declaration's type and a constant's type and value. A function's +//! type is `functions`'s. use arena::Id; use arena::List; @@ -14,9 +14,7 @@ use model::program::EXTERN_ATTRIBUTE; use model::semantic_types; use model::semantic_types::ConstArgument; use model::semantic_types::Constant; -use model::semantic_types::ImplementationId; use model::semantic_types::Integer; -use model::semantic_types::Members; use model::semantic_types::Type; use model::semantic_types::TypeId; use model::semantic_types::Types; @@ -25,17 +23,11 @@ use model::thir::FactKind; use model::thir::Symbol; use source::Span; use syntax::ast; -use syntax::ast::Ident; -use syntax::ast::Language; use crate::Checked; use crate::Checker; use crate::Checking; use crate::builder::ThirBuilder; -use crate::builtin::TypeFact; -use crate::builtin::type_fact; -use crate::builtin::unsupported_type; -use crate::function::function_declaration; use crate::scope; /// The most references and slices a struct or an array holds, however deep. @@ -46,64 +38,6 @@ use crate::scope; // lifetime, as Rust does. const MOST_HOLDERS: usize = 4_096; -/// What a function's declaration may hold, from who gives its code: its -/// body, C, the compiler or each type that implements its interface. Each -/// rule reads it (`Checker::signature_type`, and `Checker::check_function` -/// for the body). -pub struct FunctionKind { - /// How a message names such a function. - pub name: &'static str, - /// Who gives its code, as a message says it. - pub coded_by: &'static str, - pub has_body: bool, - /// Whether it may take type or `const` parameters, which make a copy - /// for each call. - pub has_copies: bool, - pub takes_variadic: bool, - pub takes_self_first: bool, - /// Whether its parameters and result must be C types. - pub c_types: bool, -} - -impl FunctionKind { - pub const BODY: FunctionKind = FunctionKind { - name: "a function", - coded_by: "its body", - has_body: true, - has_copies: true, - takes_variadic: true, - takes_self_first: false, - c_types: false, - }; - pub const C: FunctionKind = FunctionKind { - name: "an `extern` function", - coded_by: "C", - has_body: false, - has_copies: false, - takes_variadic: false, - takes_self_first: false, - c_types: true, - }; - pub const COMPILER: FunctionKind = FunctionKind { - name: "a `#[builtin]` function", - coded_by: "the compiler", - has_body: false, - has_copies: true, - takes_variadic: true, - takes_self_first: false, - c_types: false, - }; - pub const INTERFACE_METHOD: FunctionKind = FunctionKind { - name: "an interface method", - coded_by: "each type that implements it", - has_body: false, - has_copies: false, - takes_variadic: true, - takes_self_first: true, - c_types: false, - }; -} - impl Checker<'_, L> { /// The type the module's type declaration or alias `definition` declares: /// a feature's (`declare_type`), or the type an alias names. One with @@ -190,492 +124,6 @@ impl Checker<'_, L> { self.checking_in(checking, |checker| checker.resolve_value_type(ty)) } - /// The type of the module's function or method `definition`. - pub(crate) fn check_function(&mut self, definition: DefId) -> TypeId { - let tree = &self.module().ast; - let &ast::Function { - owner, - name, - signature, - body, - .. - } = function_declaration(self.modules, definition); - // shortcut: a generic struct's functions are refused until a copy of - // one takes its owner's type arguments. - if let Some(written) = owner - && let Some(owner) = (self.scope()).owner_named(self.modules, written.text(&tree.file)) - && (model::program::declaration_copy_parameters(self.modules, owner).next()).is_some() - { - return self.not_supported(written.span, "functions of generic types"); - } - let symbol = model::program::extern_symbol(self.modules, definition); - if let Err(span) = symbol { - let message = "write `#[extern(\"name\")]` once, with the C function's name"; - self.error(diagnostics::INVALID_DECLARATION, message, span); - } - // A malformed `extern` is still read as one, so its signature gets - // the C rules. - let builtin = model::program::is_builtin(self.modules, definition); - let kind = if symbol != Ok(None) { - &FunctionKind::C - } else if builtin { - &FunctionKind::COMPILER - } else { - &FunctionKind::BODY - }; - let first_const = first_copy_parameter(tree, signature); - let module = definition.module.index(); - let reported = self.module_checks[module].diagnostics.len(); - let ty = self.signature_type(name, signature, owner.is_some(), kind); - // A copy's signature differs only by what it is given: an error in - // the function's own is in each copy's. - let failed = || { - let found = &self.module_checks[module].diagnostics[reported..]; - found.iter().any(Diagnostic::is_error) - }; - if ty == TypeId::INVALID || first_const.is_some() && failed() { - return TypeId::INVALID; - } - if builtin && !self.is_builtin_declared(definition, ty) { - return TypeId::INVALID; // reported - } - if kind.has_body != body.is_some() { - let message = if kind.has_body { - "a function needs a body, or `#[extern(\"name\")]` when C defines it".to_owned() - } else { - format!( - "{} has no body: {} gives its code", - kind.name, kind.coded_by - ) - }; - return self.error(diagnostics::INVALID_DECLARATION, message, name.span); - } - // Reported above; invalid, so no call of it is lowered. - if symbol.is_err() { - return TypeId::INVALID; - } - ty - } - - /// Whether the `#[builtin]` function `definition`, of the type `ty`, is - /// one the compiler has, declared as the compiler answers it: in the - /// prelude, taking one type and giving the fact's type. Reports it when - /// not. - fn is_builtin_declared(&mut self, definition: DefId, ty: TypeId) -> bool { - let tree = &self.module().ast; - let &ast::Function { - name, signature, .. - } = function_declaration(self.modules, definition); - let text = name.text(&tree.file); - let message = match type_fact(text) { - // A module with no prelude is one, as a test's is. - _ if self.prelude().is_some() => { - "only the `core` library's prelude declares a `#[builtin]` function".to_owned() - } - None => format!("the compiler has no built-in function `{text}`"), - Some(fact) => { - let (gives, written) = match fact { - TypeFact::Signed - | TypeFact::IsInteger - | TypeFact::IsFloat - | TypeFact::IsText - | TypeFact::IsBool - | TypeFact::IsPointer => (TypeId::BOOL, "bool"), - TypeFact::Size | TypeFact::Align | TypeFact::Bits => { - (self.types.usize, "usize") - } - }; - let mut parameters = (tree.children.lists.items(signature.parameters)) - .map(|parameter| tree.children.params[parameter]); - let takes_a_type = matches!( - (parameters.next(), parameters.next()), - (Some(parameter), None) - if parameter.constant && matches!(tree.types[parameter.ty], ast::Type::Type) - ); - let result = match &self.types[ty] { - Type::Function { result, .. } => *result, - _ => unreachable!("a function's type is a function type"), - }; - if takes_a_type && result == gives { - return true; - } - format!("the compiler's `{text}` is `fn {text}(const T: type) -> {written}`") - } - }; - self.error(diagnostics::INVALID_DECLARATION, message, name.span); - false - } - - /// The function type `signature` of the module's tree declares, for the - /// function `name`, of a type's function or an interface's method when - /// `has_owner` (only these take `self`), of the kind `kind`. - /// Invalid when the signature is reported; a parameter or result whose - /// type is reported is invalid inside it. A `const T: type` parameter is - /// not among its parameters: each call gives it a type, which makes its - /// own copy (`copy_type`). - pub fn signature_type( - &mut self, - name: Ident, - signature: ast::Signature, - has_owner: bool, - kind: &FunctionKind, - ) -> TypeId { - let tree = &self.module().ast; - let first = tree.children.lists.items(signature.parameters).next(); - if kind.takes_self_first - && !first.is_some_and(|first| tree.is_self(tree.children.params[first])) - { - let (what, text) = (kind.name, name.text(&tree.file)); - let message = format!("{what} takes `self` first: `fn {text}(&self)`"); - return self.error(diagnostics::INVALID_DECLARATION, message, name.span); - } - if !kind.has_copies - && let Some(span) = first_copy_parameter(tree, signature) - { - let message = format!( - "{} takes no type or `const` parameter: {} gives one function for every call", - kind.name, kind.coded_by - ); - return self.error(diagnostics::INVALID_DECLARATION, message, span); - } - // Each name that stands for a type, `` or `const T: type`, once. - let type_names: Vec = (model::program::copy_parameters(tree, signature)) - .flatten() - .collect(); - for (place, &again) in type_names.iter().enumerate() { - let name = tree.file.slice(again); - let mut earlier = type_names[..place].iter(); - if let Some(&first) = earlier.find(|&&first| tree.file.slice(first) == name) { - let file = &tree.file; - self.report(scope::report_redeclared( - file, name, "function", again, first, - )); - return TypeId::INVALID; - } - } - let tree = &self.module().ast; - let mut parameters = Vec::with_capacity(signature.parameters.len()); - let mut variadic = false; - for (position, parameter) in tree.children.lists.items(signature.parameters).enumerate() { - let parameter = tree.children.params[parameter]; - if let Some(default) = parameter.default { - return self.not_supported(tree.exprs.span(default), "default parameters"); - } - let span = tree.types.span(parameter.ty); - let is_variadic = matches!(tree.types[parameter.ty], ast::Type::Variadic { .. }); - if parameter.constant { - if parameter.mutable || is_variadic { - let message = "a `const` parameter is one value known when compiling, so it takes no `mut` or `...`"; - return self.error(diagnostics::INVALID_DECLARATION, message, span); - } - if let ast::Type::Type = tree.types[parameter.ty] { - continue; - } - if self.resolve_value_type(parameter.ty) != TypeId::INVALID { - continue; - } - // A value's type is read again at each call (`const_value_type`), - // which cannot know a type parameter yet: only the copy does. - // Any other error in it was reported. - let tree = &self.module().ast; - let type_parameters: Vec<&str> = (model::program::copy_parameters(tree, signature)) - .flatten() - .map(|name| tree.file.slice(name)) - .collect(); - if names_type_parameter(tree, parameter.ty, &type_parameters) { - return self - .not_supported(span, "`const` values whose type names a type parameter"); - } - return TypeId::INVALID; - } - if is_variadic && !kind.takes_variadic { - let message = format!("{} cannot have a `...` parameter", kind.name); - return self.error(diagnostics::INVALID_DECLARATION, message, span); - } - if is_variadic && position + 1 != signature.parameters.len() { - let message = "a `...` parameter must be the last one"; - return self.error(diagnostics::INVALID_DECLARATION, message, span); - } - if tree.is_self(parameter) { - let message = match (position, has_owner) { - (0, true) => None, - (0, false) => { - Some("only a type's function takes `self`: `fn Point::name(&self)`") - } - _ => Some("`self` must be the first parameter"), - }; - if let Some(message) = message { - return self.error(diagnostics::INVALID_DECLARATION, message, span); - } - } - variadic |= is_variadic; - parameters.push(self.resolve_signature_type(parameter.ty, kind.c_types)); - } - let result = signature.result.map_or(TypeId::VOID, |result| { - self.resolve_signature_type(result, kind.c_types) - }); - let Some(origins) = self.result_origins(&signature, ¶meters, result) else { - return TypeId::INVALID; - }; - if !signature.constraints.is_empty() && !self.constraints_hold(signature, ¶meters) { - return TypeId::INVALID; - } - let parameters = parameters.into(); - self.types.intern(Type::Function { - parameters, - result, - origins, - variadic, - }) - } - - /// The functions of the struct `structure` that are the methods of the - /// interface `interface`, for a reference to the struct used as a - /// reference to the interface at `span`: for each method, the struct's - /// function of its name and type, `self` being the struct; looked up - /// once for the pair. `None` after reporting the first method the struct - /// lacks or has with another type, or when the interface's error was - /// reported; such a pair is reported at each conversion. - pub(crate) fn implementation( - &mut self, - structure: TypeId, - interface: TypeId, - span: Span, - ) -> Option { - if let Some(&found) = self - .internals - .known_implementations - .get(&(structure, interface)) - { - return Some(found); - } - let modules = self.modules; - let Some(Members { - definition: owner, .. - }) = self.types[structure].members() - else { - unreachable!( - "only a reference to a type with members converts to an interface reference" - ) - }; - let (Type::Named { definition, .. } | Type::Interface { definition, .. }) = - self.types[interface] - else { - unreachable!("an interface reference refers to an interface") - }; - if self.declared_type(definition, span) == TypeId::INVALID { - return None; - } - let Type::Interface { methods, .. } = &self.types[interface] else { - unreachable!("a checked interface is `Type::Interface`") - }; - let signatures = methods.clone(); - let declared = model::program::interface_methods(modules, definition) - .expect("an interface declaration has methods"); - let file = &modules[definition.module.index()].ast.file; - let mut found = Vec::with_capacity(signatures.len()); - for (method, &signature) in declared.zip(&signatures) { - let name = method.name.text(file); - let function = match self.module_checks[owner.module.index()] - .scope - .get(Some(owner), name) - { - Some(Symbol::Function(function)) => Some(function), - _ => None, - }; - let expected = self.method_type(signature, structure); - let ty = function.map(|function| (function, self.function_type(function, span))); - let generic = |function: DefId| { - let tree = &modules[function.module.index()].ast; - first_copy_parameter(tree, function_declaration(modules, function).signature) - .is_some() - }; - let message = match ty { - Some((function, _)) if generic(function) => { - format!( - "its `{name}` takes a `const` parameter, so it is not one function an interface reference can call" - ) - } - Some((_, TypeId::INVALID)) => return None, // reported - Some((function, ty)) if ty == expected => { - if model::program::is_extern(modules, function) { - self.not_supported(span, "C functions as interface methods"); - return None; - } - found.push(function); - continue; - } - Some((_, ty)) => format!( - "its `{name}` is `{}`, but `{}` needs `{}`", - self.type_text(ty), - self.type_text(interface), - self.type_text(expected) - ), - None => format!("it has no method `{name}`"), - }; - let (structure, interface) = self.type_texts(structure, interface); - let message = format!("`{structure}` does not implement `{interface}`: {message}"); - self.error(diagnostics::TYPE_MISMATCH, message, span); - return None; - } - let id = self.types.add_implementation(found.into()); - self.internals - .known_implementations - .insert((structure, interface), id); - Some(id) - } - - /// The type a function of the struct `structure` has when it is the - /// interface method of the type `signature`: the same, with `self` the - /// struct. - fn method_type(&mut self, signature: TypeId, structure: TypeId) -> TypeId { - let Type::Function { - mut parameters, - result, - origins, - variadic, - } = self.types[signature].clone() - else { - unreachable!("a method's type is a function type") - }; - parameters[0] = match self.types[parameters[0]] { - Type::InterfaceReference { mutable, .. } => self.types.intern(Type::Reference { - mutable, - target: structure, - }), - _ => structure, // `self` taken whole - }; - self.types.intern(Type::Function { - parameters, - result, - origins, - variadic, - }) - } - - /// The positions of the parameters a `result` of `signature` holding - /// references may point into, in order: those `in` names, else every - /// parameter that holds one (every `&mut` one for a `&mut` result). - /// `None` when an error was reported. - fn result_origins( - &mut self, - signature: &ast::Signature, - parameters: &[TypeId], - result: TypeId, - ) -> Option> { - let tree = &self.module().ast; - let file = &tree.file; - let mut names = tree.children.lists.items(signature.origins); - // An invalid type was reported, or is a `const T: type` parameter's - // in the function's own signature, which no copy gives one. - if result == TypeId::INVALID { - return Some(Box::default()); - } - if self.types.holds_loans(result).is_none() { - if let Some(origin) = names.next() { - let span = tree.children.names.span(origin); - self.error( - diagnostics::INVALID_RETURN, - "`in` needs a reference or slice result", - span, - ); - return None; - } - return Some(Box::default()); - } - // A struct may hold shared references too, so any parameter may be - // where they come from; the body's returns are checked by the loans. - let mutable = self.types[result].borrows() == Some(true); - let mut origins: Vec = Vec::new(); - for origin in names { - let span = tree.children.names.span(origin); - let name = file.slice(span); - // A `const T: type` parameter is not among the function's. - let position = (tree.children.lists.items(signature.parameters)) - .map(|parameter| tree.children.params[parameter]) - .filter(|parameter| !parameter.constant) - .position(|parameter| { - parameter - .name - .is_some_and(|written| written.text(file) == name) - }); - let error = match position { - None => Some(( - diagnostics::UNDEFINED_NAME, - format!("`{name}` is not a parameter"), - )), - Some(position) if parameters[position] == TypeId::INVALID => None, - // `Some(whether it can lend mutably)` for a parameter that lends. - Some(position) => match self.types.holds_loans(parameters[position]) { - None => Some(( - diagnostics::INVALID_RETURN, - format!( - "`{name}` is not a reference or a slice, so a result cannot borrow from it" - ), - )), - Some(false) if mutable => Some(( - diagnostics::INVALID_RETURN, - if self.types[parameters[position]].borrows().is_some() { - format!("a `&mut` result cannot borrow from shared reference `{name}`") - } else { - format!( - "a `&mut` result cannot borrow from `{name}`, which holds only shared references" - ) - }, - )), - Some(_) if origins.contains(&(position as u32)) => Some(( - diagnostics::INVALID_RETURN, - format!("`{name}` is named twice in `in`"), - )), - Some(_) => { - origins.push(position as u32); - None - } - }, - }; - if let Some((code, message)) = error { - self.error(code, message, span); - return None; - } - } - if signature.origins.is_empty() { - origins = (0..parameters.len()) - .filter(|&position| { - self.types - .holds_loans(parameters[position]) - .is_some_and(|source| source || !mutable) - }) - .map(|position| position as u32) - .collect(); - if origins.is_empty() { - let kind = if mutable { - "`&mut` reference or slice" - } else { - "reference or slice" - }; - let message = if self.types[result].borrows().is_some() { - format!("a {kind} result needs a {kind} parameter to borrow from") - } else if self.is_interface(result) { - let ty = self.type_text(result); - format!( - "a `{ty}` result needs a parameter to come from: a struct the function moves into it is gone once it returns" - ) - } else { - "a result holding references needs a parameter that holds one".to_owned() - }; - let result = signature.result.expect("a reference result is written"); - self.error( - diagnostics::INVALID_RETURN, - message, - tree.types.span(result), - ); - return None; - } - } - origins.sort_unstable(); - Some(origins.into()) - } - /// The type and value of the module's constant `definition`; `None` when /// it had an error. Its value is checked as a body's `const` is, with no /// variables in scope. @@ -736,49 +184,6 @@ impl Checker<'_, L> { } } - /// The type of a parameter or result written `ty`, which must be a C - /// type when `c_types` (`FunctionKind::c_types`). - fn resolve_signature_type(&mut self, ty: Id>, c_types: bool) -> TypeId { - let resolved = self.resolve_value_type(ty); - if !c_types { - return resolved; - } - let span = self.module().ast.types.span(ty); - match self.types[resolved] { - // shortcut: structs, arrays, ranges, slices and `&str` pass as - // LLVM values, which the C ABI does not match; allow structs and - // arrays when its aggregate rules are written (a range, slice or - // `&str` has no C type). - Type::Struct { .. } - | Type::Array { .. } - | Type::Range { .. } - | Type::Slice { .. } - | Type::Str => { - let what = "struct, array, range, slice and `&str` parameters and results of `extern` functions"; - self.not_supported(span, what) - } - Type::InterfaceReference { .. } => { - self.not_supported(span, "interface references in `extern` functions") - } - Type::Interface { .. } => { - self.not_supported(span, "owned interfaces in `extern` functions") - } - // C could keep what the target holds, which no loan would follow. - Type::Reference { target, .. } if self.types.holds_loans(target).is_some() => { - let what = self.loan_holder_text(target); - self.not_supported(span, &format!("references to {what} in `extern` functions")) - } - Type::Integer(integer) if integer.bits > self.target.widest_c_integer() => { - let (target, widest) = (self.target.name, self.target.widest_c_integer()); - let message = format!( - "C has no `{integer}` on {target}, whose integers have at most {widest} bits" - ); - self.error(diagnostics::INVALID_TYPE, message, span) - } - _ => resolved, - } - } - /// The real type of `element`, for an array, slice, reference or raw /// pointer that holds or reaches it, so `[2]Meters` is `[2]f64` under an /// alias; `None` when it is invalid. @@ -821,7 +226,7 @@ impl Checker<'_, L> { } /// What `ty`, which holds loans, is, in a message: "slices". - fn loan_holder_text(&self, ty: TypeId) -> &'static str { + pub(crate) fn loan_holder_text(&self, ty: TypeId) -> &'static str { match self.types[ty] { Type::Reference { .. } => "references", Type::Slice { .. } => "slices", @@ -1026,29 +431,9 @@ impl Checker<'_, L> { self.reference_type(mutable, target) } - /// The value type the argument `argument` is read as where a parameter - /// takes a type: a type the parser read (`ast::Expr::Type`), or a value - /// spelled like a type, a name, a path, `&x`, `&mut x` or `range[x]`. - /// Anything else is reported as not a type. - pub(crate) fn resolve_type_argument(&mut self, argument: Id>) -> TypeId { - let resolved = self.expression_type(argument); - let span = self.module().ast.exprs.span(argument); - let resolved = self.type_argument(resolved, span); - self.value_type_at(resolved, span) - } - - /// `ty`, a type argument written or found at `span`, when a copy can be - /// made for it; an owned interface is reported. - pub(crate) fn type_argument(&mut self, ty: TypeId, span: Span) -> TypeId { - if self.is_interface(ty) { - return self.not_supported(span, "owned interfaces as type arguments"); - } - ty - } - /// `resolve_type_argument` before it is made a value's type, as /// `resolve_type` is. - fn expression_type(&mut self, expression: Id>) -> TypeId { + pub(crate) fn expression_type(&mut self, expression: Id>) -> TypeId { source::grow_stack(|| { let tree = &self.module().ast; let span = tree.exprs.span(expression); @@ -1210,189 +595,12 @@ impl Checker<'_, L> { } } -/// Where the first parameter of `signature`, in `tree`, that a copy is -/// made for is written, if it has one: a type parameter, ``, or a -/// `const` parameter. -pub fn first_copy_parameter( - tree: &ast::Tree, - signature: ast::Signature, -) -> Option { - if let Some(parameter) = tree.children.lists.items(signature.type_parameters).next() { - return Some(tree.children.names.span(parameter)); - } - let mut parameters = tree.children.lists.items(signature.parameters); - let parameter = parameters.find(|¶meter| tree.children.params[parameter].constant)?; - Some(tree.children.params.span(parameter)) -} - -/// The type written inside the type written `ty` in `tree`, where a type -/// parameter can be named: a reference's or a pointer's target, or the -/// element of a slice, a `...`, an array or a range. `None` for a name and -/// for a type not looked into: a path names another module's type, and a -/// type the checker refuses (`resolve_type`), such as `?T`, is reported. -fn written_inside( - tree: &ast::Tree, - ty: Id>, -) -> Option>> { - match tree.types[ty] { - ast::Type::Bracketed { inner: written, .. } - | ast::Type::Reference { - target: written, .. - } - | ast::Type::Slice { - element: written, .. - } - | ast::Type::Variadic { - element: written, .. - } => Some(written), - // shortcut: of a feature's types, only a pointer's target and an - // array's element are looked into; a struct's fields and an - // interface's methods are taken to name no type parameter, as a - // written one is not supported yet. - ast::Type::Feature(ty) => L::pointee(&ty).or_else(|| L::element(&ty)), - ast::Type::Name - | ast::Type::Path(_) - | ast::Type::Generic { .. } - | ast::Type::Function(_) - | ast::Type::Owner - | ast::Type::Type - | ast::Type::Invalid => None, - } -} - -/// Finds the type one of the type parameters `names` of a function in -/// `tree` stands for, from one argument: its parameter is written `written` -/// and the argument has the type `ty`. The type is put in `found`, at the -/// name's place, unless an earlier argument gave it one. Each type written -/// around the name (`written_inside`) takes the argument's type one step -/// in; an argument of another shape finds another type, or none, and the -/// call reports the mismatch. -pub(crate) fn find_type_argument( - tree: &ast::Tree, - types: &Types, - written: Id>, - ty: TypeId, - names: &[&str], - found: &mut [Option], -) { - let (mut written, mut ty) = (written, ty); - while let Some(inside) = written_inside(tree, written) { - ty = match (&tree.types[written], &types[ty]) { - // A `&[3]T` is given where a `&[]T` is taken. - (ast::Type::Slice { .. }, Type::Reference { target, .. }) => match &types[*target] { - Type::Array { element, .. } => *element, - _ => return, - }, - (_, Type::Reference { target, .. }) => *target, - ( - _, - Type::Slice { element, .. } - | Type::Range { element, .. } - | Type::Array { element, .. }, - ) => *element, - ( - _, - Type::RawPointer { - target: Some(target), - }, - ) => *target, - _ => return, - }; - written = inside; - } - let name = tree.file.slice(tree.types.span(written)); - if let ast::Type::Name = tree.types[written] - && let Some(place) = names.iter().position(|¶meter| parameter == name) - { - found[place].get_or_insert(types.real(ty)); - } -} - -/// Whether the type written `ty` in `tree` names one of `parameters`, the -/// names of a function's type parameters, `` or `const T: type`, which -/// only its copies know. -pub(crate) fn names_type_parameter( - tree: &ast::Tree, - ty: Id>, - parameters: &[&str], -) -> bool { - let mut ty = ty; - while let Some(inside) = written_inside(tree, ty) { - ty = inside; - } - matches!(tree.types[ty], ast::Type::Name) - && parameters.contains(&tree.file.slice(tree.types.span(ty))) -} - -#[cfg(test)] -mod tests { - use model::DefId; - use model::semantic_types::Type; - use model::semantic_types::TypeId; - use syntax::ast; - - use crate::testing::Reported; - use crate::testing::with_checker; - - /// The type of every function and type declaration of `text`, as type - /// text, and the diagnostics. - fn declared_types(text: &str) -> (Vec, Vec) { - let (found, types, reported) = with_checker(text, |checker, main| { - let tree = &checker.modules[main.index()].ast; - let found: Vec = tree - .declarations() - .enumerate() - .map(|(index, declaration)| { - let definition = DefId { - module: main, - index: index as u32, - }; - // As a compile asks, so a use does not report it again. - let written = tree.decls[declaration]; - let name_span = written.name().span; - match written { - ast::Decl::Function(_) => checker.function_type(definition, name_span), - _ => checker.declared_type(definition, name_span), - } - }) - .collect(); - found - }); - let text_of = |ty: TypeId| match &types[ty] { - Type::Function { - parameters, result, .. - } => format!("fn{parameters:?} -> {result:?}"), - other => format!("{other:?}"), - }; - (found.into_iter().map(text_of).collect(), reported) - } - - #[test] - fn functions_and_constants() { - let (found, reported) = declared_types( - "fn add(a: i32, b: i32) -> i32 { return a; }\nfn main() {}\nfn take(s: &cstr) {}\n", - ); - assert!(reported.is_empty(), "{reported:?}"); - let i32 = format!("{:?}", TypeId::I32); - let void = format!("{:?}", TypeId::VOID); - assert_eq!(found[0], format!("fn[{i32}, {i32}] -> {i32}")); - assert_eq!(found[1], format!("fn[] -> {void}")); - assert_eq!(found[2], format!("fn[{:?}] -> {void}", TypeId::CSTR)); - } - - /// An `extern` function is C's, so it has no body here, and any other - /// function has one. - #[test] - fn only_an_extern_function_has_no_body() { - let (found, reported) = - declared_types("#[extern(\"f\")]\nfn f(a: i8) -> i8 { return a; }\nfn g();\n"); - let invalid = format!("{:?}", Type::Invalid); - assert_eq!(found, [invalid.clone(), invalid]); - let body = "a function needs a body, or `#[extern(\"name\")]` when C defines it"; - let extern_body = "an `extern` function has no body: C gives its code"; - assert_eq!( - reported, - crate::testing::reported(&[("P0005", extern_body, "f"), ("P0005", body, "g")]) - ); +/// What to call the built-in type `name` in a "not supported yet" report, if +/// it is one the checker does not handle yet. +pub(crate) fn unsupported_type(name: &str) -> Option<&'static str> { + match name { + "string" => Some("string types"), + "byte" | "char" => Some("byte and char types"), + _ => None, } } diff --git a/crates/kernel/semantic/src/expression.rs b/crates/kernel/semantic/src/expression.rs index b8cb2c65..ee7d166c 100644 --- a/crates/kernel/semantic/src/expression.rs +++ b/crates/kernel/semantic/src/expression.rs @@ -2,8 +2,8 @@ //! operation on values known at compile time is folded to its value. mod borrows; -pub(crate) mod calls; mod literals; +mod names; mod operators; mod places; diff --git a/crates/kernel/semantic/src/expression/borrows.rs b/crates/kernel/semantic/src/expression/borrows.rs index 8b48c386..04d123c5 100644 --- a/crates/kernel/semantic/src/expression/borrows.rs +++ b/crates/kernel/semantic/src/expression/borrows.rs @@ -16,7 +16,7 @@ use crate::builder::ThirBuilder; impl ThirBuilder<'_, '_, L> { /// A `&place` or `&mut place` reference to the checked place `place`. /// `&mut` needs a place that can be written. - pub(super) fn check_borrow(&mut self, mutable: bool, place: Id) -> Expr { + pub(crate) fn check_borrow(&mut self, mutable: bool, place: Id) -> Expr { let target = self.body.exprs[place].ty; let ty = self.checker.reference_type(mutable, target); if ty == TypeId::INVALID { diff --git a/crates/kernel/semantic/src/expression/literals.rs b/crates/kernel/semantic/src/expression/literals.rs index 60f1d889..e6c6e907 100644 --- a/crates/kernel/semantic/src/expression/literals.rs +++ b/crates/kernel/semantic/src/expression/literals.rs @@ -189,7 +189,7 @@ impl ThirBuilder<'_, '_, L> { /// else a slice of an array made from them, as `[_]T{ values }` would be. /// That array holds what is listed, so writes through a `...mut T` never /// reach the variables named. - pub(super) fn check_variadic( + pub(crate) fn check_variadic( &mut self, values: &[Id>], parameter: TypeId, diff --git a/crates/kernel/semantic/src/expression/names.rs b/crates/kernel/semantic/src/expression/names.rs new file mode 100644 index 00000000..780de524 --- /dev/null +++ b/crates/kernel/semantic/src/expression/names.rs @@ -0,0 +1,60 @@ +//! Checking a name or a path used as a value: what it stands for. + +use model::semantic_types; +use model::thir; +use source::Span; + +use crate::Checked; +use crate::builder; + +impl builder::ThirBuilder<'_, '_, L> { + /// The name or path written at `span`, which stands for `symbol`, as a + /// value. `None` when finding the symbol reported an error. + pub(super) fn check_symbol_value( + &mut self, + symbol: Option, + span: Span, + ) -> thir::Expr { + let what = match symbol { + None => return thir::Expr::INVALID, // finding it reported the error + Some(thir::Symbol::Local(thir::Local::Variable(variable))) => { + return thir::Expr { + ty: self.body.variables[variable].ty, + kind: thir::ExprKind::Variable(variable), + }; + } + Some(thir::Symbol::Local(thir::Local::Constant(constant))) => { + return constant_expr(self.body.constants[constant].clone()); + } + Some(thir::Symbol::Constant(constant)) => { + return constant_expr(self.checker.constant(constant, span)); + } + Some(thir::Symbol::Function(_)) => { + self.checker.not_supported(span, "functions as values"); + return thir::Expr::INVALID; + } + Some( + thir::Symbol::Type(_) + | thir::Symbol::Builtin(_) + | thir::Symbol::TypeArgument { .. }, + ) => "a type", + Some(thir::Symbol::Module(_)) => "a module", + }; + let text = self.checker.module().ast.file.slice(span); + let message = format!("`{text}` is {what}, not a value"); + self.checker + .error(diagnostics::INVALID_OPERATION, message, span); + thir::Expr::INVALID + } +} + +/// The value of a constant (`Checker::constant`) as an expression. +fn constant_expr(constant: Option) -> thir::Expr { + match constant { + Some(semantic_types::Constant { ty, value }) => thir::Expr { + ty, + kind: thir::ExprKind::Constant(value), + }, + None => thir::Expr::INVALID, + } +} diff --git a/crates/kernel/semantic/src/functions.rs b/crates/kernel/semantic/src/functions.rs new file mode 100644 index 00000000..c9758749 --- /dev/null +++ b/crates/kernel/semantic/src/functions.rs @@ -0,0 +1,568 @@ +//! Functions: a function's type from its signature, what its declaration +//! may hold, its body (`bodies`), calls (`calls`) and the `#[builtin]` +//! functions (`builtin`). A method is a function with an owner. + +pub(crate) mod bodies; +pub(crate) mod builtin; +pub(crate) mod calls; + +use arena::Id; +use diagnostics::Diagnostic; +use model::DefId; +use model::semantic_types; +use source::Span; +use syntax::ast; + +use crate::Checked; +use crate::Checker; +use crate::generics; +use crate::scope; + +/// What a function's declaration may hold, from who gives its code: its +/// body, C, the compiler or each type that implements its interface. Each +/// rule reads it (`Checker::signature_type`, and `Checker::check_function` +/// for the body). +pub struct FunctionKind { + /// How a message names such a function. + pub name: &'static str, + /// Who gives its code, as a message says it. + pub coded_by: &'static str, + pub has_body: bool, + /// Whether it may take type or `const` parameters, which make a copy + /// for each call. + pub has_copies: bool, + pub takes_variadic: bool, + pub takes_self_first: bool, + /// Whether its parameters and result must be C types. + pub c_types: bool, +} + +impl FunctionKind { + pub const BODY: FunctionKind = FunctionKind { + name: "a function", + coded_by: "its body", + has_body: true, + has_copies: true, + takes_variadic: true, + takes_self_first: false, + c_types: false, + }; + pub const C: FunctionKind = FunctionKind { + name: "an `extern` function", + coded_by: "C", + has_body: false, + has_copies: false, + takes_variadic: false, + takes_self_first: false, + c_types: true, + }; + pub const COMPILER: FunctionKind = FunctionKind { + name: "a `#[builtin]` function", + coded_by: "the compiler", + has_body: false, + has_copies: true, + takes_variadic: true, + takes_self_first: false, + c_types: false, + }; + pub const INTERFACE_METHOD: FunctionKind = FunctionKind { + name: "an interface method", + coded_by: "each type that implements it", + has_body: false, + has_copies: false, + takes_variadic: true, + takes_self_first: true, + c_types: false, + }; +} + +impl Checker<'_, L> { + /// The type of the module's function or method `definition`. + pub(crate) fn check_function(&mut self, definition: DefId) -> semantic_types::TypeId { + let tree = &self.module().ast; + let &ast::Function { + owner, + name, + signature, + body, + .. + } = model::program::function_declaration(self.modules, definition); + // shortcut: a generic struct's functions are refused until a copy of + // one takes its owner's type arguments. + if let Some(written) = owner + && let Some(owner) = (self.scope()).owner_named(self.modules, written.text(&tree.file)) + && (model::program::declaration_copy_parameters(self.modules, owner).next()).is_some() + { + return self.not_supported(written.span, "functions of generic types"); + } + let symbol = model::program::extern_symbol(self.modules, definition); + if let Err(span) = symbol { + let message = "write `#[extern(\"name\")]` once, with the C function's name"; + self.error(diagnostics::INVALID_DECLARATION, message, span); + } + // A malformed `extern` is still read as one, so its signature gets + // the C rules. + let builtin = model::program::is_builtin(self.modules, definition); + let kind = if symbol != Ok(None) { + &FunctionKind::C + } else if builtin { + &FunctionKind::COMPILER + } else { + &FunctionKind::BODY + }; + let first_const = generics::first_copy_parameter(tree, signature); + let module = definition.module.index(); + let reported = self.module_checks[module].diagnostics.len(); + let ty = self.signature_type(name, signature, owner.is_some(), kind); + // A copy's signature differs only by what it is given: an error in + // the function's own is in each copy's. + let failed = || { + let found = &self.module_checks[module].diagnostics[reported..]; + found.iter().any(Diagnostic::is_error) + }; + if ty == semantic_types::TypeId::INVALID || first_const.is_some() && failed() { + return semantic_types::TypeId::INVALID; + } + if builtin && !self.is_builtin_declared(definition, ty) { + return semantic_types::TypeId::INVALID; // reported + } + if kind.has_body != body.is_some() { + let message = if kind.has_body { + "a function needs a body, or `#[extern(\"name\")]` when C defines it".to_owned() + } else { + format!( + "{} has no body: {} gives its code", + kind.name, kind.coded_by + ) + }; + return self.error(diagnostics::INVALID_DECLARATION, message, name.span); + } + // Reported above; invalid, so no call of it is lowered. + if symbol.is_err() { + return semantic_types::TypeId::INVALID; + } + ty + } + + /// Whether the `#[builtin]` function `definition`, of the type `ty`, is + /// one the compiler has, declared as the compiler answers it: in the + /// prelude, taking one type and giving the fact's type. Reports it when + /// not. + fn is_builtin_declared(&mut self, definition: DefId, ty: semantic_types::TypeId) -> bool { + let tree = &self.module().ast; + let &ast::Function { + name, signature, .. + } = model::program::function_declaration(self.modules, definition); + let text = name.text(&tree.file); + let message = match builtin::type_fact(text) { + // A module with no prelude is one, as a test's is. + _ if self.prelude().is_some() => { + "only the `core` library's prelude declares a `#[builtin]` function".to_owned() + } + None => format!("the compiler has no built-in function `{text}`"), + Some(fact) => { + let (gives, written) = match fact { + builtin::TypeFact::Signed + | builtin::TypeFact::IsInteger + | builtin::TypeFact::IsFloat + | builtin::TypeFact::IsText + | builtin::TypeFact::IsBool + | builtin::TypeFact::IsPointer => (semantic_types::TypeId::BOOL, "bool"), + builtin::TypeFact::Size + | builtin::TypeFact::Align + | builtin::TypeFact::Bits => (self.types.usize, "usize"), + }; + let mut parameters = (tree.children.lists.items(signature.parameters)) + .map(|parameter| tree.children.params[parameter]); + let takes_a_type = matches!( + (parameters.next(), parameters.next()), + (Some(parameter), None) + if parameter.constant && matches!(tree.types[parameter.ty], ast::Type::Type) + ); + let result = match &self.types[ty] { + semantic_types::Type::Function { result, .. } => *result, + _ => unreachable!("a function's type is a function type"), + }; + if takes_a_type && result == gives { + return true; + } + format!("the compiler's `{text}` is `fn {text}(const T: type) -> {written}`") + } + }; + self.error(diagnostics::INVALID_DECLARATION, message, name.span); + false + } + + /// The function type `signature` of the module's tree declares, for the + /// function `name`, of a type's function or an interface's method when + /// `has_owner` (only these take `self`), of the kind `kind`. + /// Invalid when the signature is reported; a parameter or result whose + /// type is reported is invalid inside it. A `const T: type` parameter is + /// not among its parameters: each call gives it a type, which makes its + /// own copy (`copy_type`). + pub fn signature_type( + &mut self, + name: ast::Ident, + signature: ast::Signature, + has_owner: bool, + kind: &FunctionKind, + ) -> semantic_types::TypeId { + let tree = &self.module().ast; + let first = tree.children.lists.items(signature.parameters).next(); + if kind.takes_self_first + && !first.is_some_and(|first| tree.is_self(tree.children.params[first])) + { + let (what, text) = (kind.name, name.text(&tree.file)); + let message = format!("{what} takes `self` first: `fn {text}(&self)`"); + return self.error(diagnostics::INVALID_DECLARATION, message, name.span); + } + if !kind.has_copies + && let Some(span) = generics::first_copy_parameter(tree, signature) + { + let message = format!( + "{} takes no type or `const` parameter: {} gives one function for every call", + kind.name, kind.coded_by + ); + return self.error(diagnostics::INVALID_DECLARATION, message, span); + } + // Each name that stands for a type, `` or `const T: type`, once. + let type_names: Vec = (model::program::copy_parameters(tree, signature)) + .flatten() + .collect(); + for (place, &again) in type_names.iter().enumerate() { + let name = tree.file.slice(again); + let mut earlier = type_names[..place].iter(); + if let Some(&first) = earlier.find(|&&first| tree.file.slice(first) == name) { + let file = &tree.file; + self.report(scope::report_redeclared( + file, name, "function", again, first, + )); + return semantic_types::TypeId::INVALID; + } + } + let tree = &self.module().ast; + let mut parameters = Vec::with_capacity(signature.parameters.len()); + let mut variadic = false; + for (position, parameter) in tree.children.lists.items(signature.parameters).enumerate() { + let parameter = tree.children.params[parameter]; + if let Some(default) = parameter.default { + return self.not_supported(tree.exprs.span(default), "default parameters"); + } + let span = tree.types.span(parameter.ty); + let is_variadic = matches!(tree.types[parameter.ty], ast::Type::Variadic { .. }); + if parameter.constant { + if parameter.mutable || is_variadic { + let message = "a `const` parameter is one value known when compiling, so it takes no `mut` or `...`"; + return self.error(diagnostics::INVALID_DECLARATION, message, span); + } + if let ast::Type::Type = tree.types[parameter.ty] { + continue; + } + if self.resolve_value_type(parameter.ty) != semantic_types::TypeId::INVALID { + continue; + } + // A value's type is read again at each call (`const_value_type`), + // which cannot know a type parameter yet: only the copy does. + // Any other error in it was reported. + let tree = &self.module().ast; + let type_parameters: Vec<&str> = (model::program::copy_parameters(tree, signature)) + .flatten() + .map(|name| tree.file.slice(name)) + .collect(); + if generics::names_type_parameter(tree, parameter.ty, &type_parameters) { + return self + .not_supported(span, "`const` values whose type names a type parameter"); + } + return semantic_types::TypeId::INVALID; + } + if is_variadic && !kind.takes_variadic { + let message = format!("{} cannot have a `...` parameter", kind.name); + return self.error(diagnostics::INVALID_DECLARATION, message, span); + } + if is_variadic && position + 1 != signature.parameters.len() { + let message = "a `...` parameter must be the last one"; + return self.error(diagnostics::INVALID_DECLARATION, message, span); + } + if tree.is_self(parameter) { + let message = match (position, has_owner) { + (0, true) => None, + (0, false) => { + Some("only a type's function takes `self`: `fn Point::name(&self)`") + } + _ => Some("`self` must be the first parameter"), + }; + if let Some(message) = message { + return self.error(diagnostics::INVALID_DECLARATION, message, span); + } + } + variadic |= is_variadic; + parameters.push(self.resolve_signature_type(parameter.ty, kind.c_types)); + } + let result = signature + .result + .map_or(semantic_types::TypeId::VOID, |result| { + self.resolve_signature_type(result, kind.c_types) + }); + let Some(origins) = self.result_origins(&signature, ¶meters, result) else { + return semantic_types::TypeId::INVALID; + }; + if !signature.constraints.is_empty() && !self.constraints_hold(signature, ¶meters) { + return semantic_types::TypeId::INVALID; + } + let parameters = parameters.into(); + self.types.intern(semantic_types::Type::Function { + parameters, + result, + origins, + variadic, + }) + } + + /// The positions of the parameters a `result` of `signature` holding + /// references may point into, in order: those `in` names, else every + /// parameter that holds one (every `&mut` one for a `&mut` result). + /// `None` when an error was reported. + fn result_origins( + &mut self, + signature: &ast::Signature, + parameters: &[semantic_types::TypeId], + result: semantic_types::TypeId, + ) -> Option> { + let tree = &self.module().ast; + let file = &tree.file; + let mut names = tree.children.lists.items(signature.origins); + // An invalid type was reported, or is a `const T: type` parameter's + // in the function's own signature, which no copy gives one. + if result == semantic_types::TypeId::INVALID { + return Some(Box::default()); + } + if self.types.holds_loans(result).is_none() { + if let Some(origin) = names.next() { + let span = tree.children.names.span(origin); + self.error( + diagnostics::INVALID_RETURN, + "`in` needs a reference or slice result", + span, + ); + return None; + } + return Some(Box::default()); + } + // A struct may hold shared references too, so any parameter may be + // where they come from; the body's returns are checked by the loans. + let mutable = self.types[result].borrows() == Some(true); + let mut origins: Vec = Vec::new(); + for origin in names { + let span = tree.children.names.span(origin); + let name = file.slice(span); + // A `const T: type` parameter is not among the function's. + let position = (tree.children.lists.items(signature.parameters)) + .map(|parameter| tree.children.params[parameter]) + .filter(|parameter| !parameter.constant) + .position(|parameter| { + parameter + .name + .is_some_and(|written| written.text(file) == name) + }); + let error = match position { + None => Some(( + diagnostics::UNDEFINED_NAME, + format!("`{name}` is not a parameter"), + )), + Some(position) if parameters[position] == semantic_types::TypeId::INVALID => None, + // `Some(whether it can lend mutably)` for a parameter that lends. + Some(position) => match self.types.holds_loans(parameters[position]) { + None => Some(( + diagnostics::INVALID_RETURN, + format!( + "`{name}` is not a reference or a slice, so a result cannot borrow from it" + ), + )), + Some(false) if mutable => Some(( + diagnostics::INVALID_RETURN, + if self.types[parameters[position]].borrows().is_some() { + format!("a `&mut` result cannot borrow from shared reference `{name}`") + } else { + format!( + "a `&mut` result cannot borrow from `{name}`, which holds only shared references" + ) + }, + )), + Some(_) if origins.contains(&(position as u32)) => Some(( + diagnostics::INVALID_RETURN, + format!("`{name}` is named twice in `in`"), + )), + Some(_) => { + origins.push(position as u32); + None + } + }, + }; + if let Some((code, message)) = error { + self.error(code, message, span); + return None; + } + } + if signature.origins.is_empty() { + origins = (0..parameters.len()) + .filter(|&position| { + self.types + .holds_loans(parameters[position]) + .is_some_and(|source| source || !mutable) + }) + .map(|position| position as u32) + .collect(); + if origins.is_empty() { + let kind = if mutable { + "`&mut` reference or slice" + } else { + "reference or slice" + }; + let message = if self.types[result].borrows().is_some() { + format!("a {kind} result needs a {kind} parameter to borrow from") + } else if self.is_interface(result) { + let ty = self.type_text(result); + format!( + "a `{ty}` result needs a parameter to come from: a struct the function moves into it is gone once it returns" + ) + } else { + "a result holding references needs a parameter that holds one".to_owned() + }; + let result = signature.result.expect("a reference result is written"); + self.error( + diagnostics::INVALID_RETURN, + message, + tree.types.span(result), + ); + return None; + } + } + origins.sort_unstable(); + Some(origins.into()) + } + + /// The type of a parameter or result written `ty`, which must be a C + /// type when `c_types` (`FunctionKind::c_types`). + fn resolve_signature_type( + &mut self, + ty: Id>, + c_types: bool, + ) -> semantic_types::TypeId { + let resolved = self.resolve_value_type(ty); + if !c_types { + return resolved; + } + let span = self.module().ast.types.span(ty); + match self.types[resolved] { + // shortcut: structs, arrays, ranges, slices and `&str` pass as + // LLVM values, which the C ABI does not match; allow structs and + // arrays when its aggregate rules are written (a range, slice or + // `&str` has no C type). + semantic_types::Type::Struct { .. } + | semantic_types::Type::Array { .. } + | semantic_types::Type::Range { .. } + | semantic_types::Type::Slice { .. } + | semantic_types::Type::Str => { + let what = "struct, array, range, slice and `&str` parameters and results of `extern` functions"; + self.not_supported(span, what) + } + semantic_types::Type::InterfaceReference { .. } => { + self.not_supported(span, "interface references in `extern` functions") + } + semantic_types::Type::Interface { .. } => { + self.not_supported(span, "owned interfaces in `extern` functions") + } + // C could keep what the target holds, which no loan would follow. + semantic_types::Type::Reference { target, .. } + if self.types.holds_loans(target).is_some() => + { + let what = self.loan_holder_text(target); + self.not_supported(span, &format!("references to {what} in `extern` functions")) + } + semantic_types::Type::Integer(integer) + if integer.bits > self.target.widest_c_integer() => + { + let (target, widest) = (self.target.name, self.target.widest_c_integer()); + let message = format!( + "C has no `{integer}` on {target}, whose integers have at most {widest} bits" + ); + self.error(diagnostics::INVALID_TYPE, message, span) + } + _ => resolved, + } + } +} + +#[cfg(test)] +mod tests { + use model::DefId; + use model::semantic_types; + use syntax::ast; + + use crate::testing; + + /// The type of every function and type declaration of `text`, as type + /// text, and the diagnostics. + fn declared_types(text: &str) -> (Vec, Vec) { + let (found, types, reported) = testing::with_checker(text, |checker, main| { + let tree = &checker.modules[main.index()].ast; + let found: Vec = tree + .declarations() + .enumerate() + .map(|(index, declaration)| { + let definition = DefId { + module: main, + index: index as u32, + }; + // As a compile asks, so a use does not report it again. + let written = tree.decls[declaration]; + let name_span = written.name().span; + match written { + ast::Decl::Function(_) => checker.function_type(definition, name_span), + _ => checker.declared_type(definition, name_span), + } + }) + .collect(); + found + }); + let text_of = |ty: semantic_types::TypeId| match &types[ty] { + semantic_types::Type::Function { + parameters, result, .. + } => format!("fn{parameters:?} -> {result:?}"), + other => format!("{other:?}"), + }; + (found.into_iter().map(text_of).collect(), reported) + } + + #[test] + fn function_types() { + let (found, reported) = declared_types( + "fn add(a: i32, b: i32) -> i32 { return a; }\nfn main() {}\nfn take(s: &cstr) {}\n", + ); + assert!(reported.is_empty(), "{reported:?}"); + let i32 = format!("{:?}", semantic_types::TypeId::I32); + let void = format!("{:?}", semantic_types::TypeId::VOID); + assert_eq!(found[0], format!("fn[{i32}, {i32}] -> {i32}")); + assert_eq!(found[1], format!("fn[] -> {void}")); + assert_eq!( + found[2], + format!("fn[{:?}] -> {void}", semantic_types::TypeId::CSTR) + ); + } + + /// An `extern` function is C's, so it has no body here, and any other + /// function has one. + #[test] + fn only_an_extern_function_has_no_body() { + let (found, reported) = + declared_types("#[extern(\"f\")]\nfn f(a: i8) -> i8 { return a; }\nfn g();\n"); + let invalid = format!("{:?}", semantic_types::Type::Invalid); + assert_eq!(found, [invalid.clone(), invalid]); + let body = "a function needs a body, or `#[extern(\"name\")]` when C defines it"; + let extern_body = "an `extern` function has no body: C gives its code"; + assert_eq!( + reported, + crate::testing::reported(&[("P0005", extern_body, "f"), ("P0005", body, "g")]) + ); + } +} diff --git a/crates/kernel/semantic/src/function.rs b/crates/kernel/semantic/src/functions/bodies.rs similarity index 82% rename from crates/kernel/semantic/src/function.rs rename to crates/kernel/semantic/src/functions/bodies.rs index c688686b..9e795854 100644 --- a/crates/kernel/semantic/src/function.rs +++ b/crates/kernel/semantic/src/functions/bodies.rs @@ -2,21 +2,16 @@ //! and calls run at compile time on it (`evaluate_call`). use diagnostics::Diagnostic; -use eval::interpreter::ADDRESS_NOT_KNOWN; -use eval::interpreter::ConstantShape; -use eval::interpreter::Failure; +use eval::interpreter; use model::ConstArguments; use model::DeclarationCopy; use model::DefId; -use model::constant::Value; +use model::constant; use model::mir; -use model::semantic_types::Type; -use model::semantic_types::TypeId; +use model::semantic_types; use model::thir; use rustc_hash::FxHashSet; use source::Span; -use syntax::ast; -use syntax::ast::Language; use crate::Checked; use crate::Checker; @@ -74,12 +69,12 @@ impl Checker<'_, L> { fn lower_function( &mut self, definition: DefId, - ty: TypeId, + ty: semantic_types::TypeId, thir: &thir::Body, ) -> Option { let modules = self.modules; let module = definition.module.index(); - let Type::Function { result, .. } = &self.types[ty] else { + let semantic_types::Type::Function { result, .. } = &self.types[ty] else { unreachable!("a checked body has a function type") }; let debug_types = &mut self.debug_types; @@ -110,9 +105,9 @@ impl Checker<'_, L> { pub(crate) fn evaluate_call( &mut self, function: DeclarationCopy, - arguments: &[Value], + arguments: &[constant::Value], span: Span, - ) -> Option { + ) -> Option { if model::program::is_builtin(self.modules, function.definition) { return self.builtin_value(function, span); } @@ -156,28 +151,29 @@ impl Checker<'_, L> { } } let ty = self.copy_type(function, span); - let Type::Function { + let semantic_types::Type::Function { parameters, result, .. } = &self.types[ty] else { unreachable!("a body is a function's") }; - let shape = |ty: TypeId| match &self.types[ty] { - Type::Bool => ConstantShape::Bool, - &Type::Integer(integer) => ConstantShape::Integer { + let shape = |ty: semantic_types::TypeId| match &self.types[ty] { + semantic_types::Type::Bool => interpreter::ConstantShape::Bool, + &semantic_types::Type::Integer(integer) => interpreter::ConstantShape::Integer { bits: integer.bits, signed: integer.signed, }, - &Type::Float(float) => ConstantShape::Float(float.class()), - Type::RawPointer { .. } => ConstantShape::RawPointer, - Type::CString => ConstantShape::CString, - Type::Str => ConstantShape::Str, - other => ConstantShape::Refused(constant_refusal(other)), + &semantic_types::Type::Float(float) => interpreter::ConstantShape::Float(float.class()), + semantic_types::Type::RawPointer { .. } => interpreter::ConstantShape::RawPointer, + semantic_types::Type::CString => interpreter::ConstantShape::CString, + semantic_types::Type::Str => interpreter::ConstantShape::Str, + other => interpreter::ConstantShape::Refused(constant_refusal(other)), }; - let shaped_arguments: Vec<(&Value, ConstantShape)> = (arguments.iter()) - .zip(parameters) - .map(|(argument, &ty)| (argument, shape(ty))) - .collect(); + let shaped_arguments: Vec<(&constant::Value, interpreter::ConstantShape)> = (arguments + .iter()) + .zip(parameters) + .map(|(argument, &ty)| (argument, shape(ty))) + .collect(); let result = shape(*result); let mir_of = |copy: DeclarationCopy| match self.internals.built_bodies.get(©) { Some(Built::Kept(mir)) => mir.as_deref(), @@ -196,12 +192,12 @@ impl Checker<'_, L> { &mir_of, ) { Ok(value) => return value, - Err(Failure::Stopped { + Err(interpreter::Failure::Stopped { message, function, span, }) => break 'failed (Some((function, span)), message), - Err(Failure::NoMir { + Err(interpreter::Failure::NoMir { callee, function, span, @@ -217,7 +213,7 @@ impl Checker<'_, L> { self.report_cycle(start, span); return None; } - if function_declaration(self.modules, callee.definition) + if model::program::function_declaration(self.modules, callee.definition) .body .is_some() { @@ -243,26 +239,15 @@ impl Checker<'_, L> { } } -/// The function `definition`, as written. -pub(crate) fn function_declaration( - modules: &[model::program::Module], - definition: DefId, -) -> &ast::Function { - match model::program::declaration(modules, definition) { - ast::Decl::Function(function) => function, - _ => unreachable!("`{definition:?}` is a function"), - } -} - /// Why a constant cannot hold a value of the type `ty`. -pub(crate) fn constant_refusal(ty: &Type) -> &'static str { +pub(crate) fn constant_refusal(ty: &semantic_types::Type) -> &'static str { match ty { - Type::Struct { .. } => "a constant cannot hold a struct yet", - Type::Array { .. } => "a constant cannot hold an array yet", - Type::Range { .. } => "a constant cannot hold a range yet", + semantic_types::Type::Struct { .. } => "a constant cannot hold a struct yet", + semantic_types::Type::Array { .. } => "a constant cannot hold an array yet", + semantic_types::Type::Range { .. } => "a constant cannot hold a range yet", _ if ty.borrows() == Some(true) => { "a constant cannot hold a mutable reference, as all its uses would share one value" } - _ => ADDRESS_NOT_KNOWN, + _ => interpreter::ADDRESS_NOT_KNOWN, } } diff --git a/crates/kernel/semantic/src/builtin.rs b/crates/kernel/semantic/src/functions/builtin.rs similarity index 60% rename from crates/kernel/semantic/src/builtin.rs rename to crates/kernel/semantic/src/functions/builtin.rs index 6b489d03..a27817e5 100644 --- a/crates/kernel/semantic/src/builtin.rs +++ b/crates/kernel/semantic/src/functions/builtin.rs @@ -1,29 +1,15 @@ -//! The `#[builtin]` functions the checker works out itself, and the built-in -//! types it does not handle yet. The types it does handle are named in -//! `model::semantic_types` (`Types::builtin`). +//! The `#[builtin]` functions the checker works out itself. use bigint::Limbs; use model::DeclarationCopy; -use model::constant::Value; -use model::layout::layout; -use model::semantic_types::ConstArgument; -use model::semantic_types::Float; -use model::semantic_types::Type; +use model::constant; +use model::layout; +use model::semantic_types; use source::Span; use crate::Checked; use crate::Checker; -/// What to call the built-in type `name` in a "not supported yet" report, if -/// it is one the checker does not handle yet. -pub(crate) fn unsupported_type(name: &str) -> Option<&'static str> { - match name { - "string" => Some("string types"), - "byte" | "char" => Some("byte and char types"), - _ => None, - } -} - /// What a `#[builtin]` function gives of the type it takes, on the target /// being built. #[derive(Clone, Copy)] @@ -70,27 +56,47 @@ impl Checker<'_, L> { /// is given, answers when its call at `span` runs (`evaluate_call`): the /// fact of that type its name asks for. `None` for a type the fact is /// not of, reported. - pub(crate) fn builtin_value(&mut self, function: DeclarationCopy, span: Span) -> Option { - let &[ConstArgument::Type(ty)] = self.types.arguments(function.arguments) else { + pub(crate) fn builtin_value( + &mut self, + function: DeclarationCopy, + span: Span, + ) -> Option { + let &[semantic_types::ConstArgument::Type(ty)] = self.types.arguments(function.arguments) + else { unreachable!("a `#[builtin]` function takes one type") }; let (name, file) = model::program::declared_name(self.modules, function.definition); let name = name.text(file); let fact = type_fact(name).expect("a `#[builtin]` function is one the compiler has"); - let (size, align) = layout(&self.types, ty, self.target); - let number = |value: u64| Value::Integer(Limbs::new(self.target.pointer_bits, &[value])); + let (size, align) = layout::layout(&self.types, ty, self.target); + let number = + |value: u64| constant::Value::Integer(Limbs::new(self.target.pointer_bits, &[value])); Some(match (fact, &self.types[ty]) { (TypeFact::Size, _) => number(size), (TypeFact::Align, _) => number(align), - (TypeFact::Bits, Type::Integer(integer)) => number(u64::from(integer.bits)), - (TypeFact::Bits, Type::Float(Float::F32)) => number(32), - (TypeFact::Bits, Type::Float(Float::F64)) => number(64), - (TypeFact::Signed, Type::Integer(integer)) => Value::Bool(integer.signed), - (TypeFact::IsInteger, kind) => Value::Bool(matches!(kind, Type::Integer(_))), - (TypeFact::IsFloat, kind) => Value::Bool(matches!(kind, Type::Float(_))), - (TypeFact::IsText, kind) => Value::Bool(matches!(kind, Type::Str)), - (TypeFact::IsBool, kind) => Value::Bool(matches!(kind, Type::Bool)), - (TypeFact::IsPointer, kind) => Value::Bool(matches!(kind, Type::RawPointer { .. })), + (TypeFact::Bits, semantic_types::Type::Integer(integer)) => { + number(u64::from(integer.bits)) + } + (TypeFact::Bits, semantic_types::Type::Float(semantic_types::Float::F32)) => number(32), + (TypeFact::Bits, semantic_types::Type::Float(semantic_types::Float::F64)) => number(64), + (TypeFact::Signed, semantic_types::Type::Integer(integer)) => { + constant::Value::Bool(integer.signed) + } + (TypeFact::IsInteger, kind) => { + constant::Value::Bool(matches!(kind, semantic_types::Type::Integer(_))) + } + (TypeFact::IsFloat, kind) => { + constant::Value::Bool(matches!(kind, semantic_types::Type::Float(_))) + } + (TypeFact::IsText, kind) => { + constant::Value::Bool(matches!(kind, semantic_types::Type::Str)) + } + (TypeFact::IsBool, kind) => { + constant::Value::Bool(matches!(kind, semantic_types::Type::Bool)) + } + (TypeFact::IsPointer, kind) => { + constant::Value::Bool(matches!(kind, semantic_types::Type::RawPointer { .. })) + } (TypeFact::Bits | TypeFact::Signed, _) => { let kinds = match fact { TypeFact::Bits => "an integer or a float", diff --git a/crates/kernel/semantic/src/expression/calls.rs b/crates/kernel/semantic/src/functions/calls.rs similarity index 52% rename from crates/kernel/semantic/src/expression/calls.rs rename to crates/kernel/semantic/src/functions/calls.rs index d6c70c93..357bc9d7 100644 --- a/crates/kernel/semantic/src/expression/calls.rs +++ b/crates/kernel/semantic/src/functions/calls.rs @@ -1,7 +1,7 @@ -//! Checking names, paths and calls: what a name stands for as a value, and -//! a call's arguments. +//! Checking calls: of a function, a method or an interface's method, and +//! their arguments. -use std::num::NonZeroU32; +use std::num; use arena::Id; use arena::List; @@ -9,59 +9,18 @@ use model::Callee; use model::ConstArguments; use model::DeclarationCopy; use model::DefId; -use model::constant::Value; -use model::semantic_types::ConstArgument; -use model::semantic_types::Constant; -use model::semantic_types::Type; -use model::semantic_types::TypeId; -use model::thir::Expr; -use model::thir::ExprKind; -use model::thir::Local; -use model::thir::Symbol; +use model::constant; +use model::semantic_types; +use model::thir; use source::Span; use syntax::ast; -use syntax::ast::Ident; use crate::Checked; -use crate::builder::ThirBuilder; -use crate::declaration::find_type_argument; -use crate::declaration::first_copy_parameter; -use crate::declaration::names_type_parameter; -use crate::function::function_declaration; +use crate::builder; +use crate::generics; use crate::scope; -impl ThirBuilder<'_, '_, L> { - /// The name or path written at `span`, which stands for `symbol`, as a - /// value. `None` when finding the symbol reported an error. - pub(super) fn check_symbol_value(&mut self, symbol: Option, span: Span) -> Expr { - let what = match symbol { - None => return Expr::INVALID, // finding it reported the error - Some(Symbol::Local(Local::Variable(variable))) => { - return Expr { - ty: self.body.variables[variable].ty, - kind: ExprKind::Variable(variable), - }; - } - Some(Symbol::Local(Local::Constant(constant))) => { - return constant_expr(self.body.constants[constant].clone()); - } - Some(Symbol::Constant(constant)) => { - return constant_expr(self.checker.constant(constant, span)); - } - Some(Symbol::Function(_)) => { - self.checker.not_supported(span, "functions as values"); - return Expr::INVALID; - } - Some(Symbol::Type(_) | Symbol::Builtin(_) | Symbol::TypeArgument { .. }) => "a type", - Some(Symbol::Module(_)) => "a module", - }; - let text = self.checker.module().ast.file.slice(span); - let message = format!("`{text}` is {what}, not a value"); - self.checker - .error(diagnostics::INVALID_OPERATION, message, span); - Expr::INVALID - } - +impl builder::ThirBuilder<'_, '_, L> { /// `callee(arguments)`, written at `span`; a pipe gives its value as the /// first of `arguments`. Only a module's function, by /// its name or its path, can be called, or with a dot, `x.name(arguments)`, @@ -76,7 +35,7 @@ impl ThirBuilder<'_, '_, L> { type_arguments: List>, arguments: &[Id>], span: Span, - ) -> Expr { + ) -> thir::Expr { let tree = &self.checker.module().ast; let callee_span = tree.exprs.span(callee); let mut receiver = None; @@ -84,13 +43,13 @@ impl ThirBuilder<'_, '_, L> { ast::Expr::Name => { let symbol = match self.resolve(callee_span) { // Their errors were reported. - Some(Symbol::Local(Local::Constant(constant))) + Some(thir::Symbol::Local(thir::Local::Constant(constant))) if self.body.constants[constant].is_none() => { None } - Some(Symbol::Local(Local::Variable(variable))) - if self.body.variables[variable].ty == TypeId::INVALID => + Some(thir::Symbol::Local(thir::Local::Variable(variable))) + if self.body.variables[variable].ty == semantic_types::TypeId::INVALID => { None } @@ -130,13 +89,13 @@ impl ThirBuilder<'_, '_, L> { /// after `receiver`'s for a method (`check_call`). `None` was reported. pub(crate) fn call_found( &mut self, - found: Option<(Callee, TypeId)>, - receiver: Option>, + found: Option<(Callee, semantic_types::TypeId)>, + receiver: Option>, callee_span: Span, type_arguments: List>, arguments: &[Id>], span: Span, - ) -> Expr { + ) -> thir::Expr { let tree = &self.checker.module().ast; let text = tree.file.slice(callee_span); // The written arguments come after the receiver's. @@ -144,10 +103,10 @@ impl ThirBuilder<'_, '_, L> { // The places among the written arguments of what a copy is for. let mut const_places = Vec::new(); // The written arguments checked to find a type parameter, by place. - let mut checked_early: Vec> = Vec::new(); + let mut checked_early: Vec> = Vec::new(); let type_parameters = match found { Some((Callee::Function(function), _)) => { - function_declaration(self.checker.modules, function.definition) + model::program::function_declaration(self.checker.modules, function.definition) .signature .type_parameters .len() @@ -164,9 +123,10 @@ impl ThirBuilder<'_, '_, L> { let found = match found { Some((Callee::Function(function), _)) if let definition = function.definition - && let declared = function_declaration(self.checker.modules, definition) + && let declared = + model::program::function_declaration(self.checker.modules, definition) && let tree = &self.checker.modules[definition.module.index()].ast - && first_copy_parameter(tree, declared.signature).is_some() => + && generics::first_copy_parameter(tree, declared.signature).is_some() => { let early = &mut checked_early; let copied = self.copy_called( @@ -182,7 +142,7 @@ impl ThirBuilder<'_, '_, L> { // few arguments, and a type with an error are of no copy. if let Some((Callee::Function(copy), ty)) = copied && copy.arguments != ConstArguments::NONE - && ty != TypeId::INVALID + && ty != semantic_types::TypeId::INVALID { self.checker.record_copy(callee_span.end, copy, ty); } @@ -195,7 +155,7 @@ impl ThirBuilder<'_, '_, L> { let Some(( callee, signature, - Type::Function { + semantic_types::Type::Function { parameters, result, variadic, @@ -214,7 +174,7 @@ impl ThirBuilder<'_, '_, L> { }; self.add_expr(argument, None); // for its own errors } - return Expr::INVALID; + return thir::Expr::INVALID; }; let fixed = parameters.len() - usize::from(variadic) - first; // A `const` parameter is not among the type's, but takes an argument. @@ -225,15 +185,17 @@ impl ThirBuilder<'_, '_, L> { arguments.len() == all }; if !arity_matches { - let message = argument_count_message(text, "argument", all, variadic, arguments.len()); + let message = + crate::argument_count_message(text, "argument", all, variadic, arguments.len()); self.checker .error(diagnostics::WRONG_ARGUMENT_COUNT, message, span); } - let mut checked: Vec = Vec::with_capacity(parameters.len()); + let mut checked: Vec = Vec::with_capacity(parameters.len()); if let Some(place) = receiver { // `self` takes the value itself; `&self` and `&mut self` borrow it. let argument = match self.checker.types[parameters[0]] { - Type::Reference { mutable, .. } | Type::InterfaceReference { mutable, .. } => { + semantic_types::Type::Reference { mutable, .. } + | semantic_types::Type::InterfaceReference { mutable, .. } => { let span = self.body.exprs.span(place); let borrowed = self.check_borrow(mutable, place); self.body.add(borrowed, span) @@ -268,49 +230,49 @@ impl ThirBuilder<'_, '_, L> { } } if !arity_matches { - return Expr::INVALID; + return thir::Expr::INVALID; } if let Callee::Function(function) = callee && model::program::is_builtin(self.checker.modules, function.definition) { // Its answer is known now, wherever the call is. let Some(value) = self.checker.evaluate_call(function, &[], span) else { - return Expr::INVALID; // reported + return thir::Expr::INVALID; // reported }; let ty = match value { - Value::Bool(_) => TypeId::BOOL, + constant::Value::Bool(_) => semantic_types::TypeId::BOOL, _ => self.checker.types.usize, }; - let kind = ExprKind::Constant(value); - return Expr { ty, kind }; + let kind = thir::ExprKind::Constant(value); + return thir::Expr { ty, kind }; } let arguments = self.body.children.lists.add(&checked); // In a constant's value, a call on constants runs now. let constant_arguments = || { let values = self.body.children.lists.items(arguments).map(|argument| { match &self.body.exprs[argument].kind { - ExprKind::Constant(value) => Some(value.clone()), + thir::ExprKind::Constant(value) => Some(value.clone()), _ => None, } }); - values.collect::>>() + values.collect::>>() }; if let Callee::Function(function) = callee && self.in_constant - && result != TypeId::VOID + && result != semantic_types::TypeId::VOID && let Some(values) = constant_arguments() { return match self.checker.evaluate_call(function, &values, span) { - Some(value) => Expr { + Some(value) => thir::Expr { ty: result, - kind: ExprKind::Constant(value), + kind: thir::ExprKind::Constant(value), }, - None => Expr::INVALID, + None => thir::Expr::INVALID, }; } - Expr { + thir::Expr { ty: result, - kind: ExprKind::Call { + kind: thir::ExprKind::Call { callee, signature, arguments, @@ -318,33 +280,16 @@ impl ThirBuilder<'_, '_, L> { } } - /// The type `argument`, written in the body for a type (a `const T: - /// type` argument, a constraint's subject), names. A local of its name - /// is a value, reported; a type of its name elsewhere is still the type. - pub(crate) fn written_type_argument(&mut self, argument: Id>) -> TypeId { - let tree = &self.checker.module().ast; - let written = tree.exprs.span(argument); - if let ast::Expr::Name = tree.exprs[argument] - && let name = tree.file.slice(written) - && let Some(&position) = self.innermost.get(name) - && self.checker.resolve_global(name).is_none() - { - let local = Symbol::Local(self.names[position].local); - return self.checker.type_named_by(local, written); - } - self.checker.resolve_type_argument(argument) - } - /// What the function `symbol`, called at `span`, is: its callee and /// type. `None` when it is not a function, reported, or when finding it /// reported an error. pub(crate) fn function_called( &mut self, - symbol: Option, + symbol: Option, span: Span, - ) -> Option<(Callee, TypeId)> { + ) -> Option<(Callee, semantic_types::TypeId)> { match symbol { - Some(Symbol::Function(definition)) => { + Some(thir::Symbol::Function(definition)) => { let ty = self.checker.function_type(definition, span); let function = DeclarationCopy { definition, @@ -372,14 +317,14 @@ impl ThirBuilder<'_, '_, L> { fn method( &mut self, value: Id>, - name: Ident, + name: ast::Ident, span: Span, - ) -> Option<(Id, Callee, TypeId)> { + ) -> Option<(Id, Callee, semantic_types::TypeId)> { let value = self.add_expr(value, None); let ty = self.body.exprs[value].ty; let interface = match self.checker.types[ty] { - Type::InterfaceReference { interface, .. } => Some(interface), - Type::Interface { .. } => Some(ty), + semantic_types::Type::InterfaceReference { interface, .. } => Some(interface), + semantic_types::Type::Interface { .. } => Some(ty), _ => None, }; if let Some(interface) = interface @@ -394,7 +339,7 @@ impl ThirBuilder<'_, '_, L> { let place = self.through_pointer(value, self.body.exprs.span(value)); let ty = self.body.exprs[place].ty; let Some(definition) = self.checker.types[ty].definition() else { - if ty != TypeId::INVALID { + if ty != semantic_types::TypeId::INVALID { let message = format!("`{}` has no functions", self.checker.type_text(ty)); self.checker .error(diagnostics::INVALID_OPERATION, message, name.span); @@ -417,196 +362,23 @@ impl ThirBuilder<'_, '_, L> { .then_some((place, callee, signature)) } - /// The copy of the function `definition` that its call at `span` with - /// the written `arguments`, after `first` of the receiver, asks for, - /// and its type. The argument in the place of each `const` parameter, - /// put in `const_places`, is what the copy is made for: a type for - /// `const T: type` (`resolve_type_argument`), else a value of the - /// parameter's type known when compiling. A type parameter, ``, - /// takes no argument: its type is written at the call, in - /// `type_arguments`, or found from the arguments of the parameters - /// whose types name it (`find_type_argument`), each checked here, once, - /// until every type parameter is found, and left in `checked_early` at - /// its place for `check_call` to take. When a `const` one is missing, the - /// function itself and its own type, for `check_call` to report the - /// count. `None` when one has an error, or the function's signature - /// has one, reported. - #[expect(clippy::too_many_arguments, reason = "each is one fact of the call")] - fn copy_called( - &mut self, - definition: DefId, - type_arguments: List>, - arguments: &[Id>], - first: usize, - const_places: &mut Vec, - checked_early: &mut Vec>, - span: Span, - ) -> Option<(Callee, TypeId)> { - let modules = self.checker.modules; - let tree = &modules[definition.module.index()].ast; - let declared = function_declaration(modules, definition); - let parameters = tree.children.lists.items(declared.signature.parameters); - // The parameters past the receiver, each with its written argument's place. - let written_parameters: Vec<(usize, ast::Param)> = (parameters.skip(first)) - .map(|parameter| tree.children.params[parameter]) - .enumerate() - .collect(); - let const_parameters = (written_parameters.iter().copied()) - .filter(|(_, parameter)| parameter.constant) - .collect::>(); - const_places.extend(const_parameters.iter().map(|&(place, _)| place)); - let pattern = self.checker.function_type(definition, span); - if pattern == TypeId::INVALID { - return None; // reported - } - // Too few arguments: `check_call` reports it, by the function's own type. - let required = (written_parameters.iter()) - .filter(|(_, parameter)| { - !matches!(tree.types[parameter.ty], ast::Type::Variadic { .. }) - }) - .count(); - if arguments.len() < required { - let function = DeclarationCopy { - definition, - arguments: ConstArguments::NONE, - }; - return Some((Callee::Function(function), pattern)); - } - // Its type parameters, ``, which take no argument of their own: - // the types written at the call, or else found from the arguments. - let names: Vec<&str> = (tree.children.lists) - .items(declared.signature.type_parameters) - .map(|parameter| tree.file.slice(tree.children.names.span(parameter))) - .collect(); - let calling = &self.checker.module().ast; - let written_types: Vec>> = - calling.children.lists.items(type_arguments).collect(); - let function = model::program::declared_path(modules, definition); - let mut failed = false; - let mut types_found = vec![None; names.len()]; - if !written_types.is_empty() { - if written_types.len() == names.len() { - for (found, &written) in types_found.iter_mut().zip(&written_types) { - *found = Some(self.checker.resolve_value_type(written)); - } - } else { - let (count, given) = (names.len(), written_types.len()); - let message = - argument_count_message(&function, "type argument", count, false, given); - self.checker - .error(diagnostics::WRONG_ARGUMENT_COUNT, message, span); - failed = true; - } - } else if !names.is_empty() { - checked_early.resize(arguments.len(), None); - for &(place, parameter) in &written_parameters { - // The rest are checked as the copy's parameters, so a - // literal takes the found type: `Max(small, 1)`. - if types_found.iter().all(Option::is_some) { - break; - } - // shortcut: the arguments of a `...T` do not say what `T` is, - // as `check_variadic` checks them; find it from them when a - // function needs it. - if parameter.constant - || place >= arguments.len() - || matches!(tree.types[parameter.ty], ast::Type::Variadic { .. }) - || !names_type_parameter(tree, parameter.ty, &names) - { - continue; - } - let checked = self.check_expr(arguments[place], None); - if checked.ty == TypeId::VOID { - let written = self.checker.module().ast.exprs.span(arguments[place]); - let message = "this expression has no value to pass"; - self.checker - .error(diagnostics::INVALID_OPERATION, message, written); - failed = true; - } - failed |= checked.ty == TypeId::INVALID; // reported - let types = &self.checker.types; - find_type_argument( - tree, - types, - parameter.ty, - checked.ty, - &names, - &mut types_found, - ); - checked_early[place] = Some(checked); - } - } - let mut given = Vec::with_capacity(names.len() + const_parameters.len()); - for (name, found) in names.iter().zip(types_found) { - match found { - Some(ty) => { - let ty = self.checker.type_argument(ty, span); - failed |= ty == TypeId::INVALID; - given.push(ConstArgument::Type(ty)); - } - None if failed => {} - None => { - // No parameter names it, so only the call can. - let named = (written_parameters.iter()) - .any(|(_, parameter)| names_type_parameter(tree, parameter.ty, &[name])); - let hint = if named { - String::new() - } else { - format!(": write it at the call, `{function}::<...>(...)`") - }; - let message = format!( - "the arguments of `{function}` do not say what its `{name}` is{hint}" - ); - self.checker - .error(diagnostics::INVALID_OPERATION, message, span); - failed = true; - } - } - } - for (place, parameter) in const_parameters { - let argument = arguments[place]; - if let ast::Type::Type = tree.types[parameter.ty] { - let ty = self.written_type_argument(argument); - failed |= ty == TypeId::INVALID; - given.push(ConstArgument::Type(self.checker.types.real(ty))); - continue; - } - let ty = self - .checker - .const_value_type(definition, parameter.ty, span); - match self.check_constant_value(argument, Some(ty)) { - Some(constant) => given.push(ConstArgument::Value(constant)), - None => failed = true, // reported - } - } - if failed { - return None; - } - let copy = DeclarationCopy { - definition, - arguments: self.checker.types.const_arguments(&given), - }; - let ty = self.checker.copy_type(copy, span); - Some((Callee::Function(copy), ty)) - } - /// The method `name` of `interface` that `value`, an interface or a /// reference to one, calls, as `method` gives it: its place in the /// interface's table. A method taking `self` whole is called only on an /// interface, which it takes. fn interface_method( &mut self, - value: Id, - interface: TypeId, - name: Ident, - ) -> Option<(Id, Callee, TypeId)> { - let (Type::Named { definition, .. } | Type::Interface { definition, .. }) = - self.checker.types[interface] + value: Id, + interface: semantic_types::TypeId, + name: ast::Ident, + ) -> Option<(Id, Callee, semantic_types::TypeId)> { + let (semantic_types::Type::Named { definition, .. } + | semantic_types::Type::Interface { definition, .. }) = self.checker.types[interface] else { unreachable!("an interface reference refers to an interface") }; // Checked first, so the place's type is the interface, not its name. - if self.checker.declared_type(definition, name.span) == TypeId::INVALID { + if self.checker.declared_type(definition, name.span) == semantic_types::TypeId::INVALID { return None; } let modules = self.checker.modules; @@ -631,20 +403,23 @@ impl ThirBuilder<'_, '_, L> { .report_unknown(diagnostics::UNDEFINED_NAME, name.span, message, meant); return None; }; - let Type::Interface { methods, .. } = &self.checker.types[interface] else { + let semantic_types::Type::Interface { methods, .. } = &self.checker.types[interface] else { unreachable!("a checked interface is `Type::Interface`") }; let signature = methods[slot]; - let Type::Function { parameters, .. } = &self.checker.types[signature] else { + let semantic_types::Type::Function { parameters, .. } = &self.checker.types[signature] + else { unreachable!("a method's type is a function type") }; let callee = Callee::Method(slot as u32); - let Type::InterfaceReference { .. } = self.checker.types[self.body.exprs[value].ty] else { + let semantic_types::Type::InterfaceReference { .. } = + self.checker.types[self.body.exprs[value].ty] + else { return Some((value, callee, signature)); // an interface, the place itself }; if !matches!( self.checker.types[parameters[0]], - Type::InterfaceReference { .. } + semantic_types::Type::InterfaceReference { .. } ) { let message = format!("`{text}` takes `self` whole, so it cannot be called through `&{head}`"); @@ -661,7 +436,7 @@ impl ThirBuilder<'_, '_, L> { fn takes_self(&mut self, function: DefId, span: Span) -> bool { let modules = self.checker.modules; let tree = &modules[function.module.index()].ast; - let declared = function_declaration(modules, function); + let declared = model::program::function_declaration(modules, function); let first = tree .children .lists @@ -678,31 +453,3 @@ impl ThirBuilder<'_, '_, L> { false } } - -/// The value of a constant (`Checker::constant`) as an expression. -fn constant_expr(constant: Option) -> Expr { - match constant { - Some(Constant { ty, value }) => Expr { - ty, - kind: ExprKind::Constant(value), - }, - None => Expr::INVALID, - } -} - -/// Why a call of `callee` with `given` arguments is wrong, when it takes -/// `fixed` of them, or at least that many when `variadic`. -pub(crate) fn argument_count_message( - callee: &str, - what: &str, - fixed: usize, - variadic: bool, - given: usize, -) -> String { - format!( - "`{callee}` takes {}{fixed} {what}{}, but {given} {} given", - if variadic { "at least " } else { "" }, - if fixed == 1 { "" } else { "s" }, - if given == 1 { "was" } else { "were" }, - ) -} diff --git a/crates/kernel/semantic/src/generics.rs b/crates/kernel/semantic/src/generics.rs new file mode 100644 index 00000000..ae6f3b0f --- /dev/null +++ b/crates/kernel/semantic/src/generics.rs @@ -0,0 +1,363 @@ +//! Type and `const` parameters: finding the types a copy is made for, from +//! what is written or from a call's arguments; the copies themselves +//! (`copies`) and the constraints after `where` (`constraints`). + +mod constraints; +mod copies; + +use arena::Id; +use arena::List; +use model::Callee; +use model::ConstArguments; +use model::DeclarationCopy; +use model::DefId; +use model::semantic_types; +use model::thir; +use source::Span; +use syntax::ast; + +use crate::Checked; +use crate::Checker; +use crate::builder; + +impl Checker<'_, L> { + /// The value type the argument `argument` is read as where a parameter + /// takes a type: a type the parser read (`ast::Expr::Type`), or a value + /// spelled like a type, a name, a path, `&x`, `&mut x` or `range[x]`. + /// Anything else is reported as not a type. + pub(crate) fn resolve_type_argument( + &mut self, + argument: Id>, + ) -> semantic_types::TypeId { + let resolved = self.expression_type(argument); + let span = self.module().ast.exprs.span(argument); + let resolved = self.type_argument(resolved, span); + self.value_type_at(resolved, span) + } + + /// `ty`, a type argument written or found at `span`, when a copy can be + /// made for it; an owned interface is reported. + pub(crate) fn type_argument( + &mut self, + ty: semantic_types::TypeId, + span: Span, + ) -> semantic_types::TypeId { + if self.is_interface(ty) { + return self.not_supported(span, "owned interfaces as type arguments"); + } + ty + } +} + +impl builder::ThirBuilder<'_, '_, L> { + /// The type `argument`, written in the body for a type (a `const T: + /// type` argument, a constraint's subject), names. A local of its name + /// is a value, reported; a type of its name elsewhere is still the type. + pub(crate) fn written_type_argument( + &mut self, + argument: Id>, + ) -> semantic_types::TypeId { + let tree = &self.checker.module().ast; + let written = tree.exprs.span(argument); + if let ast::Expr::Name = tree.exprs[argument] + && let name = tree.file.slice(written) + && let Some(&position) = self.innermost.get(name) + && self.checker.resolve_global(name).is_none() + { + let local = thir::Symbol::Local(self.names[position].local); + return self.checker.type_named_by(local, written); + } + self.checker.resolve_type_argument(argument) + } + + /// The copy of the function `definition` that its call at `span` with + /// the written `arguments`, after `first` of the receiver, asks for, + /// and its type. The argument in the place of each `const` parameter, + /// put in `const_places`, is what the copy is made for: a type for + /// `const T: type` (`resolve_type_argument`), else a value of the + /// parameter's type known when compiling. A type parameter, ``, + /// takes no argument: its type is written at the call, in + /// `type_arguments`, or found from the arguments of the parameters + /// whose types name it (`find_type_argument`), each checked here, once, + /// until every type parameter is found, and left in `checked_early` at + /// its place for `check_call` to take. When a `const` one is missing, the + /// function itself and its own type, for `check_call` to report the + /// count. `None` when one has an error, or the function's signature + /// has one, reported. + #[expect(clippy::too_many_arguments, reason = "each is one fact of the call")] + pub(crate) fn copy_called( + &mut self, + definition: DefId, + type_arguments: List>, + arguments: &[Id>], + first: usize, + const_places: &mut Vec, + checked_early: &mut Vec>, + span: Span, + ) -> Option<(Callee, semantic_types::TypeId)> { + let modules = self.checker.modules; + let tree = &modules[definition.module.index()].ast; + let declared = model::program::function_declaration(modules, definition); + let parameters = tree.children.lists.items(declared.signature.parameters); + // The parameters past the receiver, each with its written argument's place. + let written_parameters: Vec<(usize, ast::Param)> = (parameters.skip(first)) + .map(|parameter| tree.children.params[parameter]) + .enumerate() + .collect(); + let const_parameters = (written_parameters.iter().copied()) + .filter(|(_, parameter)| parameter.constant) + .collect::>(); + const_places.extend(const_parameters.iter().map(|&(place, _)| place)); + let pattern = self.checker.function_type(definition, span); + if pattern == semantic_types::TypeId::INVALID { + return None; // reported + } + // Too few arguments: `check_call` reports it, by the function's own type. + let required = (written_parameters.iter()) + .filter(|(_, parameter)| { + !matches!(tree.types[parameter.ty], ast::Type::Variadic { .. }) + }) + .count(); + if arguments.len() < required { + let function = DeclarationCopy { + definition, + arguments: ConstArguments::NONE, + }; + return Some((Callee::Function(function), pattern)); + } + // Its type parameters, ``, which take no argument of their own: + // the types written at the call, or else found from the arguments. + let names: Vec<&str> = (tree.children.lists) + .items(declared.signature.type_parameters) + .map(|parameter| tree.file.slice(tree.children.names.span(parameter))) + .collect(); + let calling = &self.checker.module().ast; + let written_types: Vec>> = + calling.children.lists.items(type_arguments).collect(); + let function = model::program::declared_path(modules, definition); + let mut failed = false; + let mut types_found = vec![None; names.len()]; + if !written_types.is_empty() { + if written_types.len() == names.len() { + for (found, &written) in types_found.iter_mut().zip(&written_types) { + *found = Some(self.checker.resolve_value_type(written)); + } + } else { + let (count, given) = (names.len(), written_types.len()); + let message = + crate::argument_count_message(&function, "type argument", count, false, given); + self.checker + .error(diagnostics::WRONG_ARGUMENT_COUNT, message, span); + failed = true; + } + } else if !names.is_empty() { + checked_early.resize(arguments.len(), None); + for &(place, parameter) in &written_parameters { + // The rest are checked as the copy's parameters, so a + // literal takes the found type: `Max(small, 1)`. + if types_found.iter().all(Option::is_some) { + break; + } + // shortcut: the arguments of a `...T` do not say what `T` is, + // as `check_variadic` checks them; find it from them when a + // function needs it. + if parameter.constant + || place >= arguments.len() + || matches!(tree.types[parameter.ty], ast::Type::Variadic { .. }) + || !names_type_parameter(tree, parameter.ty, &names) + { + continue; + } + let checked = self.check_expr(arguments[place], None); + if checked.ty == semantic_types::TypeId::VOID { + let written = self.checker.module().ast.exprs.span(arguments[place]); + let message = "this expression has no value to pass"; + self.checker + .error(diagnostics::INVALID_OPERATION, message, written); + failed = true; + } + failed |= checked.ty == semantic_types::TypeId::INVALID; // reported + let types = &self.checker.types; + find_type_argument( + tree, + types, + parameter.ty, + checked.ty, + &names, + &mut types_found, + ); + checked_early[place] = Some(checked); + } + } + let mut given = Vec::with_capacity(names.len() + const_parameters.len()); + for (name, found) in names.iter().zip(types_found) { + match found { + Some(ty) => { + let ty = self.checker.type_argument(ty, span); + failed |= ty == semantic_types::TypeId::INVALID; + given.push(semantic_types::ConstArgument::Type(ty)); + } + None if failed => {} + None => { + // No parameter names it, so only the call can. + let named = (written_parameters.iter()) + .any(|(_, parameter)| names_type_parameter(tree, parameter.ty, &[name])); + let hint = if named { + String::new() + } else { + format!(": write it at the call, `{function}::<...>(...)`") + }; + let message = format!( + "the arguments of `{function}` do not say what its `{name}` is{hint}" + ); + self.checker + .error(diagnostics::INVALID_OPERATION, message, span); + failed = true; + } + } + } + for (place, parameter) in const_parameters { + let argument = arguments[place]; + if let ast::Type::Type = tree.types[parameter.ty] { + let ty = self.written_type_argument(argument); + failed |= ty == semantic_types::TypeId::INVALID; + given.push(semantic_types::ConstArgument::Type( + self.checker.types.real(ty), + )); + continue; + } + let ty = self + .checker + .const_value_type(definition, parameter.ty, span); + match self.check_constant_value(argument, Some(ty)) { + Some(constant) => given.push(semantic_types::ConstArgument::Value(constant)), + None => failed = true, // reported + } + } + if failed { + return None; + } + let copy = DeclarationCopy { + definition, + arguments: self.checker.types.const_arguments(&given), + }; + let ty = self.checker.copy_type(copy, span); + Some((Callee::Function(copy), ty)) + } +} + +/// Where the first parameter of `signature`, in `tree`, that a copy is +/// made for is written, if it has one: a type parameter, ``, or a +/// `const` parameter. +pub fn first_copy_parameter( + tree: &ast::Tree, + signature: ast::Signature, +) -> Option { + if let Some(parameter) = tree.children.lists.items(signature.type_parameters).next() { + return Some(tree.children.names.span(parameter)); + } + let mut parameters = tree.children.lists.items(signature.parameters); + let parameter = parameters.find(|¶meter| tree.children.params[parameter].constant)?; + Some(tree.children.params.span(parameter)) +} + +/// The type written inside the type written `ty` in `tree`, where a type +/// parameter can be named: a reference's or a pointer's target, or the +/// element of a slice, a `...`, an array or a range. `None` for a name and +/// for a type not looked into: a path names another module's type, and a +/// type the checker refuses (`resolve_type`), such as `?T`, is reported. +fn written_inside( + tree: &ast::Tree, + ty: Id>, +) -> Option>> { + match tree.types[ty] { + ast::Type::Bracketed { inner: written, .. } + | ast::Type::Reference { + target: written, .. + } + | ast::Type::Slice { + element: written, .. + } + | ast::Type::Variadic { + element: written, .. + } => Some(written), + // shortcut: of a feature's types, only a pointer's target and an + // array's element are looked into; a struct's fields and an + // interface's methods are taken to name no type parameter, as a + // written one is not supported yet. + ast::Type::Feature(ty) => L::pointee(&ty).or_else(|| L::element(&ty)), + ast::Type::Name + | ast::Type::Path(_) + | ast::Type::Generic { .. } + | ast::Type::Function(_) + | ast::Type::Owner + | ast::Type::Type + | ast::Type::Invalid => None, + } +} + +/// Finds the type one of the type parameters `names` of a function in +/// `tree` stands for, from one argument: its parameter is written `written` +/// and the argument has the type `ty`. The type is put in `found`, at the +/// name's place, unless an earlier argument gave it one. Each type written +/// around the name (`written_inside`) takes the argument's type one step +/// in; an argument of another shape finds another type, or none, and the +/// call reports the mismatch. +pub(crate) fn find_type_argument( + tree: &ast::Tree, + types: &semantic_types::Types, + written: Id>, + ty: semantic_types::TypeId, + names: &[&str], + found: &mut [Option], +) { + let (mut written, mut ty) = (written, ty); + while let Some(inside) = written_inside(tree, written) { + ty = match (&tree.types[written], &types[ty]) { + // A `&[3]T` is given where a `&[]T` is taken. + (ast::Type::Slice { .. }, semantic_types::Type::Reference { target, .. }) => { + match &types[*target] { + semantic_types::Type::Array { element, .. } => *element, + _ => return, + } + } + (_, semantic_types::Type::Reference { target, .. }) => *target, + ( + _, + semantic_types::Type::Slice { element, .. } + | semantic_types::Type::Range { element, .. } + | semantic_types::Type::Array { element, .. }, + ) => *element, + ( + _, + semantic_types::Type::RawPointer { + target: Some(target), + }, + ) => *target, + _ => return, + }; + written = inside; + } + let name = tree.file.slice(tree.types.span(written)); + if let ast::Type::Name = tree.types[written] + && let Some(place) = names.iter().position(|¶meter| parameter == name) + { + found[place].get_or_insert(types.real(ty)); + } +} + +/// Whether the type written `ty` in `tree` names one of `parameters`, the +/// names of a function's type parameters, `` or `const T: type`, which +/// only its copies know. +pub(crate) fn names_type_parameter( + tree: &ast::Tree, + ty: Id>, + parameters: &[&str], +) -> bool { + let mut ty = ty; + while let Some(inside) = written_inside(tree, ty) { + ty = inside; + } + matches!(tree.types[ty], ast::Type::Name) + && parameters.contains(&tree.file.slice(tree.types.span(ty))) +} diff --git a/crates/kernel/semantic/src/constraints.rs b/crates/kernel/semantic/src/generics/constraints.rs similarity index 90% rename from crates/kernel/semantic/src/constraints.rs rename to crates/kernel/semantic/src/generics/constraints.rs index 51952479..999e5278 100644 --- a/crates/kernel/semantic/src/constraints.rs +++ b/crates/kernel/semantic/src/generics/constraints.rs @@ -7,16 +7,14 @@ use arena::Id; use arena::List; use diagnostics::Diagnostic; use model::ConstArguments; -use model::constant::Value; -use model::semantic_types::TypeId; -use model::thir::Block; -use model::thir::Body; -use model::thir::Symbol; +use model::constant; +use model::semantic_types; +use model::thir; use syntax::ast; use crate::Checked; use crate::Checker; -use crate::builder::ThirBuilder; +use crate::builder; impl Checker<'_, L> { /// Whether the constraints of `signature`, after `where`, hold for what @@ -28,7 +26,7 @@ impl Checker<'_, L> { pub(crate) fn constraints_hold( &mut self, signature: ast::Signature, - parameters: &[TypeId], + parameters: &[semantic_types::TypeId], ) -> bool { let checking = (self.internals.declarations_being_checked.last()) .expect("a declaration is being checked"); @@ -39,9 +37,9 @@ impl Checker<'_, L> { let constraints: Vec>> = tree.children.lists.items(signature.constraints).collect(); let span = tree.children.constraints.span(constraints[0]); - let mut body = Body::default(); - let mut builder = ThirBuilder::new(self, &mut body, TypeId::VOID); - let block = Block { + let mut body = thir::Body::default(); + let mut builder = builder::ThirBuilder::new(self, &mut body, semantic_types::TypeId::VOID); + let block = thir::Block { parent: None, statements: List::EMPTY, }; @@ -85,7 +83,7 @@ impl Checker<'_, L> { } } -impl ThirBuilder<'_, '_, L> { +impl builder::ThirBuilder<'_, '_, L> { /// Whether `constraint`, after a function's `where`, holds: its subject, /// a type, implements the interface its bound names, or the function its /// bound names gives `true` when called at compile time with the subject @@ -109,15 +107,15 @@ impl ThirBuilder<'_, '_, L> { _ => self.resolve(bound_span), }?; match symbol { - Symbol::Function(_) => { + thir::Symbol::Function(_) => { let outer = std::mem::replace(&mut self.in_constant, true); let found = self.function_called(Some(symbol), bound_span); let checked = self.call_found(found, None, bound_span, List::EMPTY, &given, span); self.in_constant = outer; - if checked.ty == TypeId::INVALID { + if checked.ty == semantic_types::TypeId::INVALID { return None; // reported, or only a copy knows it } - if checked.ty != TypeId::BOOL { + if checked.ty != semantic_types::TypeId::BOOL { let ty = self.checker.type_text(checked.ty); let message = format!("`{bound_text}` gives `{ty}`, but a constraint needs `bool`"); @@ -126,13 +124,13 @@ impl ThirBuilder<'_, '_, L> { return None; } match self.known_constant(checked, span)?.value { - Value::Bool(holds) => Some(holds), + constant::Value::Bool(holds) => Some(holds), _ => unreachable!("a `bool` constant is a `Value::Bool`"), } } - Symbol::Type(definition) => { + thir::Symbol::Type(definition) => { let interface = self.checker.declared_type(definition, bound_span); - if interface == TypeId::INVALID { + if interface == semantic_types::TypeId::INVALID { return None; // reported } if !self.checker.is_interface(interface) { @@ -149,7 +147,7 @@ impl ThirBuilder<'_, '_, L> { return None; } let ty = self.written_type_argument(subject); - if ty == TypeId::INVALID { + if ty == semantic_types::TypeId::INVALID { return None; // reported, or only a copy knows it } if self.checker.types[ty].members().is_none() { diff --git a/crates/kernel/semantic/src/copies.rs b/crates/kernel/semantic/src/generics/copies.rs similarity index 80% rename from crates/kernel/semantic/src/copies.rs rename to crates/kernel/semantic/src/generics/copies.rs index 1c20c5e9..8f79087a 100644 --- a/crates/kernel/semantic/src/copies.rs +++ b/crates/kernel/semantic/src/generics/copies.rs @@ -4,7 +4,7 @@ //! What a copy is, each kind of declaration checks itself: a function its //! signature, then its body (`next_copy`); a type its declaration. -use std::sync::Arc; +use std::sync; use arena::Id; use arena::List; @@ -13,9 +13,8 @@ use model::ConstArguments; use model::DeclarationCopy; use model::DefId; use model::ModuleId; -use model::semantic_types::ConstArgument; -use model::semantic_types::Type; -use model::semantic_types::TypeId; +use model::semantic_types; +use model::thir; use source::Span; use syntax::ast; @@ -24,7 +23,6 @@ use crate::Checked; use crate::Checker; use crate::Checking; use crate::Copied; -use crate::expression::calls; impl Checker<'_, L> { /// The type of `copy`, asked for at `used_at`: given nothing, its @@ -34,7 +32,7 @@ impl Checker<'_, L> { /// (`next_copy`). Invalid when the declaration's own check, or the /// copy's, has an error, or when copies are made inside each other too /// deep (`COPY_DEPTH_LIMIT`), reported at `used_at`. - pub fn copy_type(&mut self, copy: DeclarationCopy, used_at: Span) -> TypeId { + pub fn copy_type(&mut self, copy: DeclarationCopy, used_at: Span) -> semantic_types::TypeId { let has_body = matches!( model::program::declaration(self.modules, copy.definition), ast::Decl::Function(_) @@ -48,21 +46,21 @@ impl Checker<'_, L> { copy.definition, used_at, |module| &mut module.declared_types, - TypeId::INVALID, + semantic_types::TypeId::INVALID, check, ); - if copy.arguments == ConstArguments::NONE || own == TypeId::INVALID { + if copy.arguments == ConstArguments::NONE || own == semantic_types::TypeId::INVALID { return own; } // Named in a type's own check by what names `T` // (`named_without_types`): its own check's name, which no value has. if copy.arguments == self.own_arguments(copy.definition) { - return TypeId::INVALID; + return semantic_types::TypeId::INVALID; } if let Some(&Copied { ty, .. }) = self.internals.copies.get(©) { // Invalid only while it is checked, as one with an error is not // kept: asked for again there, as a `where` or a field can. - if ty == TypeId::INVALID { + if ty == semantic_types::TypeId::INVALID { let mut checking = self.internals.declarations_being_checked.iter(); let start = (checking.position(|checking| checking.copy() == copy)) .expect("a copy without a type is being checked"); @@ -87,7 +85,7 @@ impl Checker<'_, L> { && made_inside.arguments != ConstArguments::NONE && !self.internals.copies.contains_key(&made_inside) { - return TypeId::INVALID; + return semantic_types::TypeId::INVALID; } let (depth, reported_in) = match self.internals.copies.get(&made_inside) { Some(inside) => (inside.depth + 1, inside.reported_in), @@ -96,7 +94,7 @@ impl Checker<'_, L> { if depth > COPY_DEPTH_LIMIT { // Reported once: the declaration that made the copy has the error. if std::mem::replace(&mut self.internals.copies_too_deep, true) { - return TypeId::INVALID; + return semantic_types::TypeId::INVALID; } let name = model::program::declared_path(self.modules, copy.definition); let message = format!( @@ -108,7 +106,7 @@ impl Checker<'_, L> { self.internals.copies.insert( copy, Copied { - ty: TypeId::INVALID, + ty: semantic_types::TypeId::INVALID, depth, reported_in, used_in: self.current_module(), @@ -129,7 +127,7 @@ impl Checker<'_, L> { }); let user = self.current_module(); self.report_from_copy(copy, reported, user); - if ty == TypeId::INVALID { + if ty == semantic_types::TypeId::INVALID { // Not kept: another use that asks for it is told why as well. self.internals.copies.remove(©); return ty; @@ -148,7 +146,7 @@ impl Checker<'_, L> { /// named, as in its own check: what holds it by value checks it /// (`copy_type`), so a type that holds itself, as `Two<[2]T>` in `Two`, /// is found once, whatever `T` is. - pub(crate) fn named_without_types(&mut self, definition: DefId) -> TypeId { + pub(crate) fn named_without_types(&mut self, definition: DefId) -> semantic_types::TypeId { let checking = (self.internals.declarations_being_checked.last()) .expect("a declaration is being checked"); let in_own_type_check = checking.arguments != ConstArguments::NONE @@ -158,10 +156,10 @@ impl Checker<'_, L> { ast::Decl::Type(_) ); if !in_own_type_check { - return TypeId::INVALID; + return semantic_types::TypeId::INVALID; } let arguments = self.own_arguments(definition); - self.types.intern(Type::Named { + self.types.intern(semantic_types::Type::Named { definition, arguments, }) @@ -186,7 +184,7 @@ impl Checker<'_, L> { if count == 0 { return ConstArguments::NONE; } - let invalid = ConstArgument::Type(TypeId::INVALID); + let invalid = semantic_types::ConstArgument::Type(semantic_types::TypeId::INVALID); self.types.const_arguments(&vec![invalid; count]) } @@ -210,7 +208,7 @@ impl Checker<'_, L> { let message = if count == 0 { format!("`{name}` takes no type arguments") } else { - calls::argument_count_message(name, "type argument", count, false, written.len()) + crate::argument_count_message(name, "type argument", count, false, written.len()) }; self.error(diagnostics::WRONG_ARGUMENT_COUNT, message, span); None @@ -246,7 +244,7 @@ impl Checker<'_, L> { // One that marks the use already, as one about the use itself // (`constraints_hold`) or a cycle through the copy, says where. let at_use = (diagnostic.labels.iter()) - .any(|label| Arc::ptr_eq(&label.file, file) && label.span == used_at); + .any(|label| sync::Arc::ptr_eq(&label.file, file) && label.span == used_at); into.push(if at_use { diagnostic } else { @@ -256,3 +254,37 @@ impl Checker<'_, L> { } } } + +impl Checker<'_, L> { + /// Makes the fact that the name ending at `name_end` is a function + /// (`record`) the fact that its call there made `copy`, of the type + /// `ty`. Only a body checked once has it: a copy has no facts, and a + /// function's own body (`check_body`) makes no copy, so it would have + /// only those that other calls happened to make. + pub(crate) fn record_copy( + &mut self, + name_end: u32, + copy: DeclarationCopy, + ty: semantic_types::TypeId, + ) { + let checking = self + .internals + .declarations_being_checked + .last() + .expect("a declaration is being checked"); + if checking.arguments != ConstArguments::NONE { + return; + } + let definition = checking.definition; + let names_it = |kind| matches!(kind, thir::FactKind::Name(thir::Symbol::Function(named)) if named == copy.definition); + let facts = &mut self.module_checks[definition.module.index()].facts; + let Some(facts) = facts.get_mut(&definition) else { + return; // none are recorded + }; + let mut facts = facts.iter_mut().rev(); + // The facts of the call's arguments were recorded after its name's. + if let Some(fact) = facts.find(|fact| fact.span.end == name_end && names_it(fact.kind)) { + fact.kind = thir::FactKind::Copy { function: copy, ty }; + } + } +} diff --git a/crates/kernel/semantic/src/lib.rs b/crates/kernel/semantic/src/lib.rs index 7af75875..6276a762 100644 --- a/crates/kernel/semantic/src/lib.rs +++ b/crates/kernel/semantic/src/lib.rs @@ -3,15 +3,32 @@ //! (docs/ir-design.md). It starts with each module's scope. pub mod builder; -pub mod builtin; -mod constraints; -mod copies; +mod conformance; pub mod declaration; mod expression; pub mod fold; -mod function; +pub mod functions; +pub mod generics; +mod locals; pub mod scope; mod statement; +/// Why a call of `callee` with `given` arguments is wrong, when it takes +/// `fixed` of them, or at least that many when `variadic`. +pub(crate) fn argument_count_message( + callee: &str, + what: &str, + fixed: usize, + variadic: bool, + given: usize, +) -> String { + format!( + "`{callee}` takes {}{fixed} {what}{}, but {given} {} given", + if variadic { "at least " } else { "" }, + if fixed == 1 { "" } else { "s" }, + if given == 1 { "was" } else { "were" }, + ) +} + #[cfg(test)] mod testing; @@ -23,7 +40,7 @@ use builder::ThirBuilder; use diagnostics::Code; use diagnostics::Diagnostic; use diagnostics::fix::Fix; -use function::Built; +use functions::bodies; use lower::ProgramDebugTypes; use model::ConstArguments; use model::DeclarationCopy; @@ -112,7 +129,7 @@ struct CheckerInternals { declarations_being_checked: Vec, /// How far the body of each function, or each copy of one, is built /// (`build_function`). - built_bodies: FxHashMap, + built_bodies: FxHashMap, /// Each copy of a function or type with type or `const` parameters /// made so far (`copy_type`). copies: FxHashMap, @@ -546,33 +563,6 @@ impl<'p, L: Checked> Checker<'p, L> { } } - /// Makes the fact that the name ending at `name_end` is a function - /// (`record`) the fact that its call there made `copy`, of the type - /// `ty`. Only a body checked once has it: a copy has no facts, and a - /// function's own body (`check_body`) makes no copy, so it would have - /// only those that other calls happened to make. - pub(crate) fn record_copy(&mut self, name_end: u32, copy: DeclarationCopy, ty: TypeId) { - let checking = self - .internals - .declarations_being_checked - .last() - .expect("a declaration is being checked"); - if checking.arguments != ConstArguments::NONE { - return; - } - let definition = checking.definition; - let names_it = |kind| matches!(kind, FactKind::Name(Symbol::Function(named)) if named == copy.definition); - let facts = &mut self.module_checks[definition.module.index()].facts; - let Some(facts) = facts.get_mut(&definition) else { - return; // none are recorded - }; - let mut facts = facts.iter_mut().rev(); - // The facts of the call's arguments were recorded after its name's. - if let Some(fact) = facts.find(|fact| fact.span.end == name_end && names_it(fact.kind)) { - fact.kind = FactKind::Copy { function: copy, ty }; - } - } - /// The facts found in the text of `function`, its signature's and its /// body's, which declares each local they name, as its `where` does /// (`constraints_hold`); none for a copy, which records none and whose diff --git a/crates/kernel/semantic/src/statement/declarations.rs b/crates/kernel/semantic/src/locals.rs similarity index 82% rename from crates/kernel/semantic/src/statement/declarations.rs rename to crates/kernel/semantic/src/locals.rs index 422a2fb5..31bc07b1 100644 --- a/crates/kernel/semantic/src/statement/declarations.rs +++ b/crates/kernel/semantic/src/locals.rs @@ -3,33 +3,26 @@ use arena::Id; use diagnostics::Diagnostic; -use model::layout::in_memory; -use model::semantic_types::Constant; -use model::semantic_types::Type; -use model::semantic_types::TypeId; -use model::thir::Expr; -use model::thir::ExprKind; -use model::thir::Local; -use model::thir::Stmt; -use model::thir::Variable; +use model::layout; +use model::semantic_types; +use model::thir; use source::Span; use syntax::ast; -use syntax::ast::Ident; use crate::Checked; -use crate::builder::ThirBuilder; -use crate::function::constant_refusal; +use crate::builder; +use crate::functions; -impl ThirBuilder<'_, '_, L> { +impl builder::ThirBuilder<'_, '_, L> { /// `let mut name: ty = value;`. The variable is declared after its value is /// checked, so the value cannot use it. pub(super) fn check_let_statement( &mut self, mutable: bool, - name: Ident, + name: ast::Ident, ty: Option>>, value: Option>>, - ) -> Stmt { + ) -> thir::Stmt { let declared = ty.map(|ty| self.checker.resolve_value_type(ty)); let initialized = value.is_some(); let (ty, value) = match (declared, value) { @@ -37,12 +30,12 @@ impl ThirBuilder<'_, '_, L> { (None, Some(value)) => { let value = self.add_expr(value, None); let ty = self.body.exprs[value].ty; - if ty == TypeId::VOID { + if ty == semantic_types::TypeId::VOID { let span = self.body.exprs.span(value); let message = "this expression has no value to bind"; self.checker .error(diagnostics::INVALID_OPERATION, message, span); - (TypeId::INVALID, None) + (semantic_types::TypeId::INVALID, None) } else { (ty, Some(value)) } @@ -52,10 +45,10 @@ impl ThirBuilder<'_, '_, L> { let message = format!("`{text}` needs a type or a value"); self.checker .error(diagnostics::MISSING_TYPE, message, name.span); - (TypeId::INVALID, None) + (semantic_types::TypeId::INVALID, None) } }; - let declared_variable = Variable { + let declared_variable = thir::Variable { ty, mutable, initialized, @@ -65,7 +58,7 @@ impl ThirBuilder<'_, '_, L> { let text = name.text(&self.checker.module().ast.file); if let Some(&position) = self.innermost.get(text) && position < self.block_start - && let Local::Variable(outer) = self.names[position].local + && let thir::Local::Variable(outer) = self.names[position].local && self.body.variables[outer].mutable { // Likely meant as `x = ...`: the outer local stays unchanged. @@ -95,8 +88,8 @@ impl ThirBuilder<'_, '_, L> { if let Some(value) = value { self.body.keep_temporaries(value, variable); } - self.declare(name, Local::Variable(variable)); - Stmt::Let { variable, value } + self.declare(name, thir::Local::Variable(variable)); + thir::Stmt::Let { variable, value } } /// `const name: ty = value;`: a name for a value known at compile time. @@ -105,7 +98,7 @@ impl ThirBuilder<'_, '_, L> { pub(crate) fn check_const_statement( &mut self, declaration: Id>, - ) -> Option { + ) -> Option { let ast::Decl::Const { name, ty, value, .. } = self.checker.module().ast.decls[declaration] @@ -130,8 +123,8 @@ impl ThirBuilder<'_, '_, L> { pub(crate) fn check_constant_value( &mut self, value: Id>, - declared: Option, - ) -> Option { + declared: Option, + ) -> Option { let span = self.checker.module().ast.exprs.span(value); let outer = std::mem::replace(&mut self.in_constant, true); let checked = match declared { @@ -144,24 +137,28 @@ impl ThirBuilder<'_, '_, L> { /// `checked`, worked out with `in_constant`, as a constant; reported at /// `span` when it is not one. - pub(crate) fn known_constant(&mut self, checked: Expr, span: Span) -> Option { + pub(crate) fn known_constant( + &mut self, + checked: thir::Expr, + span: Span, + ) -> Option { match checked.kind { - ExprKind::Constant(value) => Some(Constant { + thir::ExprKind::Constant(value) => Some(semantic_types::Constant { ty: checked.ty, value, }), - ExprKind::Invalid => None, + thir::ExprKind::Invalid => None, _ => { let file = self.checker.module().ast.file.clone(); let unknown = self.body.first_named_variable(&checked.kind); let types = &self.checker.types; let message = if unknown.is_some() { "the value of a constant must be known at compile time" - } else if in_memory(types, checked.ty) + } else if layout::in_memory(types, checked.ty) || types[checked.ty].borrows() == Some(true) - || matches!(types[checked.ty], Type::RawPointer { .. }) + || matches!(types[checked.ty], semantic_types::Type::RawPointer { .. }) { - constant_refusal(&types[checked.ty]) + functions::bodies::constant_refusal(&types[checked.ty]) } else { "this value cannot be worked out at compile time yet" }; diff --git a/crates/kernel/semantic/src/statement.rs b/crates/kernel/semantic/src/statement.rs index eca430bf..42b7e1f4 100644 --- a/crates/kernel/semantic/src/statement.rs +++ b/crates/kernel/semantic/src/statement.rs @@ -2,7 +2,6 @@ //! blocks declare. mod assignments; -mod declarations; mod loops; use std::num::NonZeroU32; @@ -33,7 +32,6 @@ use crate::Checker; use crate::Checking; use crate::builder::Declared; use crate::builder::ThirBuilder; -use crate::function::function_declaration; use crate::scope::report_redeclared; impl Checker<'_, L> { @@ -57,7 +55,7 @@ impl Checker<'_, L> { definition, arguments, } = copy; - let function = function_declaration(self.modules, definition); + let function = model::program::function_declaration(self.modules, definition); let Some(block) = function.body else { return false; }; @@ -297,7 +295,7 @@ impl<'a, 'p, L: Checked> ThirBuilder<'a, 'p, L> { /// parameters are in the body's outermost block, as in Go. A type's name, /// built-in or declared, is reported and stays the type's: a value never /// hides a type. - fn declare(&mut self, name: Ident, local: Local) { + pub(crate) fn declare(&mut self, name: Ident, local: Local) { let text = name.text(&self.checker.module().ast.file); if text.is_empty() { return; // missing after a syntax error diff --git a/docs/structure-mapping.md b/docs/structure-mapping.md index 6f424142..0879ac73 100644 --- a/docs/structure-mapping.md +++ b/docs/structure-mapping.md @@ -93,16 +93,18 @@ API: `Language::string_kind` is removed. Its places: | `builder.rs`, `scope.rs`, `fold.rs`, `fold/*`, `testing.rs` | stay | same | | | `function.rs` | move | `functions/bodies.rs` | a body to checked MIR, `evaluate_call` | | `builtin.rs` | move | `functions/builtin.rs` | `#[builtin]` functions | -| `declaration.rs`: `check_function`, `is_builtin_declared`, `signature_type`, `result_origins`, `resolve_signature_type` | extract | `functions/signatures.rs` | a function's type | +| `builtin.rs`: `unsupported_type` | extract | `declaration.rs` | built-in types not handled yet, read only where type names resolve | +| `declaration.rs`: `FunctionKind`, `check_function`, `is_builtin_declared`, `signature_type`, `result_origins`, `resolve_signature_type` | extract | `functions.rs` | a function's type | +| `function.rs`: `function_declaration` | extract | `model::program`, beside `declaration` | a function as written, which `functions`, `generics`, `conformance` and `statement` look up | | `declaration.rs`: `implementation`, `method_type` | extract | `conformance.rs` | whether a type implements an interface; receiver substitution; the cached `ImplementationId` | -| `declaration.rs`: `resolve_type_argument`, `type_argument`, `first_copy_parameter`, `written_inside`, `find_type_argument`, `names_type_parameter` | extract | `generics/arguments.rs` | finding and writing type arguments | +| `declaration.rs`: `resolve_type_argument`, `type_argument`, `first_copy_parameter`, `written_inside`, `find_type_argument`, `names_type_parameter` | extract | `generics.rs` | finding and writing type arguments | | `declaration.rs`: the rest (`check_attributes` for every declaration, type declarations, constants, resolving written types, `is_interface`, `reference_type`, `array_type`, `range_type`, ...) | stays | `declaration.rs` | about 670 of its 1382 lines leave | | `copies.rs` | move | `generics/copies.rs` | the one copy table | | `constraints.rs` | move | `generics/constraints.rs` | `where`: both interface constraints (through `conformance.rs`) and predicate functions run at compile time; neither form changes | | `expression.rs`, `expression/{borrows, literals, operators, places}.rs` | stay | same | | -| `expression/calls.rs`: `check_call`, `call_found`, `function_called`, `method`, `takes_self`, `interface_method`, `argument_count_message` | move (file renamed) | `functions/calls.rs` | function, method and interface method calls | +| `expression/calls.rs`: `check_call`, `call_found`, `function_called`, `method`, `takes_self`, `interface_method` | move (file renamed) | `functions/calls.rs` | function, method and interface method calls | | `expression/calls.rs`: `check_symbol_value`, `constant_expr` | extract | `expression/names.rs` | a name or path used as a value | -| `expression/calls.rs`: `written_type_argument`, `copy_called` | extract | `generics/arguments.rs` | type arguments at a call, the copy a call makes | +| `expression/calls.rs`: `written_type_argument`, `copy_called` | extract | `generics.rs` | type arguments at a call, the copy a call makes | | `statement.rs`, `statement/assignments.rs`, `statement/loops.rs` | stay | same | blocks, `if`, `for`, `return`, `break`, `continue`, `panic` | | `statement/declarations.rs` | move | `locals.rs` | `let`, `const` in a body, `let .{ }`; `statement.rs` declares the module and calls it as before | @@ -111,9 +113,22 @@ in the kernel and call `conformance.rs`; none imports `features`. `conformance.rs` still reads some source declarations as well as checked types; that stays as it is for this restructuring. +The signatures and the type arguments sit in the module files +`functions.rs` and `generics.rs`, the way `expression.rs` and +`statement.rs` hold their main code beside their submodules. That keeps +each free function two levels deep for its callers +(`generics::first_copy_parameter`, `model::program::function_declaration`). +`argument_count_message` sits in `lib.rs`, since calls and copies both +report counts with it; with `function_declaration` in `model`, `generics` +needs nothing from `functions`, and `functions` depends on `generics` +only. + Done when: the full `scripts/check.sh` passes and no fixture output -changes. `conformance.rs` gets its own unit tests: a type that implements, -one that lacks a function, one with a wrong signature. +changes. Conformance is covered by the marked test programs (a missing +method and a wrong signature in `interfaces/negative_interfaces.peep`, a +`const` method in `negative_const_parameters.peep`, a false `where` in +`negative_where_conditions.peep`, the passing cases in `run_interfaces`); +the checker's own tests run in `Bare`, which has no interfaces. ## Step 4: the feature-boundary check (`scripts/check.sh`) From 27b80f074c9a7cbc98d7885accb7621910b8f347 Mon Sep 17 00:00:00 2001 From: itsfuad Date: Wed, 18 Nov 2026 02:18:00 +0600 Subject: [PATCH 07/24] Catch super paths in the feature-boundary check A feature's files may not name another feature. The check now also refuses super paths to another feature (super::enums from structs.rs, super::super::enums from structs/tests.rs), brace imports such as crate::{enums}, and files nested at any depth, not only */tests.rs. The rule moves from a quoted bash -c string into a function, and reads the feature list from the pub mod lines of features/src/lib.rs, so a new feature is covered without editing the check. --- scripts/check.sh | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/scripts/check.sh b/scripts/check.sh index d2138663..f7c913e8 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -44,16 +44,26 @@ check "middle boundary" bash -c " crates/kernel/{eval,flow} crates/backend/llvm" # A phase names no feature: only its tests may use the `features` crate # (docs/feature-front.md section 7); Cargo refuses the cycle for the crates -# `features` depends on, this the others. And a feature's file names no -# other feature: of its own crate, only the list's `Peeper` and enums, so -# no module's path (`crate::structs`). -check "feature boundary" bash -c " - for manifest in crates/{base,backend}/*/Cargo.toml crates/kernel/syntax/*/Cargo.toml \\ +# `features` depends on, this the others. And a feature's files, nested ones +# too, name no other feature: of its own crate, only the list's `Peeper` and +# enums, so no module's path (`crate::structs`, `crate::{structs}`) and no +# `super` path to another feature (`super::structs`, `super::super::structs`). +feature_boundary() { + local manifest file own others + for manifest in crates/{base,backend}/*/Cargo.toml crates/kernel/syntax/*/Cargo.toml \ crates/kernel/{semantic,model,lower,flow,eval}/Cargo.toml crates/driver/project/Cargo.toml; do - sed '/^\[dev-dependencies\]/,\$d' \$manifest | grep -H --label=\$manifest '^features\b' && exit 1 + sed '/^\[dev-dependencies\]/,$d' "$manifest" | grep -H --label="$manifest" '^features\b' && return 1 done - ! grep -nE '\bcrate::[a-z_]' crates/features/src/*.rs crates/features/src/*/tests.rs | - grep -vE '^crates/features/src/(lib|testing)\.rs:|crate::testing\b'" + for file in $(find crates/features/src -name '*.rs' ! -name lib.rs ! -name testing.rs); do + own=${file#crates/features/src/} + own=${own%%[./]*} + others=$(sed -nE 's/^pub mod ([a-z_]+);$/\1/p' crates/features/src/lib.rs | grep -vx "$own" | paste -sd'|') + grep -HnE '\bcrate::([a-z_]|\{)' "$file" | grep -vE 'crate::testing\b' && return 1 + grep -HnE "\bsuper(::super)*::(\{[^}]*)?\b($others)\b" "$file" && return 1 + done + return 0 +} +check "feature boundary" feature_boundary check "tests" cargo test --workspace --no-fail-fast check "bundle" bash scripts/build.sh check "test programs on the bundle" env PEEPER="$PWD/build/bin/peeper" \ From 076c27d8e5b9d07e632ac00db539013a6ec21974 Mon Sep 17 00:00:00 2001 From: itsfuad Date: Wed, 18 Nov 2026 02:18:01 +0600 Subject: [PATCH 08/24] Give a copy being checked its own state The copy table held TypeId::INVALID while a copy was checked, and a later lookup read INVALID as a cycle. That was right only because a copy with an error is always removed. Copied::ty is now an Option, None while the copy is checked, so the two meanings no longer share a value. The cycle fixture in negative_where_conditions fails without the None branch. "No type for T yet" stays INVALID: every reader treats it as a reported error and stays silent, so a second marker would have no consumer. The mapping page records why. --- crates/kernel/semantic/src/generics/copies.rs | 14 +++++++------- crates/kernel/semantic/src/lib.rs | 6 +++--- docs/structure-mapping.md | 10 +++++++--- 3 files changed, 17 insertions(+), 13 deletions(-) diff --git a/crates/kernel/semantic/src/generics/copies.rs b/crates/kernel/semantic/src/generics/copies.rs index 8f79087a..1141d6ac 100644 --- a/crates/kernel/semantic/src/generics/copies.rs +++ b/crates/kernel/semantic/src/generics/copies.rs @@ -58,15 +58,15 @@ impl Checker<'_, L> { return semantic_types::TypeId::INVALID; } if let Some(&Copied { ty, .. }) = self.internals.copies.get(©) { - // Invalid only while it is checked, as one with an error is not - // kept: asked for again there, as a `where` or a field can. - if ty == semantic_types::TypeId::INVALID { + // No type yet: asked for again inside its own check, as a + // `where` or a field can. + return ty.unwrap_or_else(|| { let mut checking = self.internals.declarations_being_checked.iter(); let start = (checking.position(|checking| checking.copy() == copy)) .expect("a copy without a type is being checked"); self.report_cycle(start, used_at); - } - return ty; + semantic_types::TypeId::INVALID + }); } let made_inside = self .internals @@ -106,7 +106,7 @@ impl Checker<'_, L> { self.internals.copies.insert( copy, Copied { - ty: semantic_types::TypeId::INVALID, + ty: None, depth, reported_in, used_in: self.current_module(), @@ -133,7 +133,7 @@ impl Checker<'_, L> { return ty; } let copied = (self.internals.copies.get_mut(©)).expect("the copy was just made"); - copied.ty = ty; + copied.ty = Some(ty); if has_body { self.internals.copies_to_build.push(copy); } diff --git a/crates/kernel/semantic/src/lib.rs b/crates/kernel/semantic/src/lib.rs index 6276a762..51bd6819 100644 --- a/crates/kernel/semantic/src/lib.rs +++ b/crates/kernel/semantic/src/lib.rs @@ -145,9 +145,9 @@ struct CheckerInternals { /// A copy of a declaration with type or `const` parameters /// (`CheckerInternals::copies`). struct Copied { - /// A function copy's function type, or a type copy's type; invalid - /// while it is checked, as one with an error is removed (`copy_type`). - ty: TypeId, + /// A function copy's function type, or a type copy's type; `None` + /// while it is checked. One with an error is removed (`copy_type`). + ty: Option, /// The copies it is made inside, each in the one before, counting /// itself: 1 for one a declaration given nothing makes. depth: u32, diff --git a/docs/structure-mapping.md b/docs/structure-mapping.md index 0879ac73..b3afccc9 100644 --- a/docs/structure-mapping.md +++ b/docs/structure-mapping.md @@ -147,9 +147,13 @@ The check that a feature's file names no other feature also refuses ## Step 6 (separate job) -`TypeId::INVALID` today means "error reported", "no type for `T` yet" and -"copy being checked". The last two become explicit states; `INVALID` stays -for real errors. +`TypeId::INVALID` meant "error reported", "no type for `T` yet" and +"copy being checked". The copy being checked is now its own state: +`Copied::ty` is `None` while the copy is checked. "No type for `T` yet" +stays `INVALID`: every place that meets it stays silent, as for a reported +error, so a second marker would have no reader. Its real split, an abstract +type that checks a generic body once against its `T`, changes what an +uncalled generic function reports, and waits for a language decision. ## Features after the restructuring From b22fefeb5781de1576a42d63bd06d2f6c334a6da Mon Sep 17 00:00:00 2001 From: itsfuad Date: Wed, 18 Nov 2026 02:54:19 +0600 Subject: [PATCH 09/24] Remove the language type parameter from the phases Peeper is one language, so the phases are no longer generic over L. The syntax tree lists every node, feature nodes too (FeatureExpr, FeatureType, FeatureStmt and their node types), and answers the shape questions the Language trait answered (precedence, fields, methods, pointee, element, written_range) with exhaustive matches. The parser carries its rule table: parse and project::load take the rules, which the driver gives as features::RULES. The checker's Checked trait becomes CheckHooks, four plain functions the driver gives as features::CHECK_HOOKS; each is one exhaustive match that hands a node to its feature's file. ExprNode, StmtNode and TypeNode go: a feature file has one rows function and free check, resolve and declare functions taking only what each node uses. Bare goes too: core tests use Rules::core() and hooks that are unreachable. check.sh now refuses a feature node's variant named outside ast.rs and the features crate, which the opaque Feature(L::Expr) used to prevent by type. LiteralType and Fallback are renamed ArrayLiteralType and OrElseFallback, as they now sit among every node in ast. No behaviour changes: string literals are the same but the new unreachable messages; all tests pass, and the LSP opens every test program and answers hovers without a panic. --- crates/backend/llvm/src/tests.rs | 3 +- crates/base/arena/src/lib.rs | 8 - crates/driver/browser/src/main.rs | 15 +- crates/driver/browser/src/tests.rs | 3 +- crates/driver/compile/src/lib.rs | 26 +- crates/driver/compile/src/tests.rs | 7 +- .../compile/tests/checks_through_features.rs | 20 +- .../compile/tests/parses_the_prelude.rs | 5 +- .../driver/compile/tests/path_check_memory.rs | 2 +- crates/driver/lsp/src/checked.rs | 11 +- crates/driver/lsp/src/hover.rs | 15 +- crates/driver/lsp/src/server/requests.rs | 7 +- crates/driver/lsp/src/server/sync.rs | 3 +- crates/driver/peeper/benches/compile.rs | 3 +- crates/driver/peeper/src/driver.rs | 17 +- crates/driver/peeper/src/dump.rs | 5 +- crates/driver/peeper/src/lib.rs | 3 +- crates/driver/project/src/lib.rs | 14 +- crates/driver/project/src/loading.rs | 24 +- crates/driver/project/src/order.rs | 12 +- crates/driver/project/src/tests.rs | 110 +++- crates/features/src/arrays.rs | 203 +++---- crates/features/src/arrays/tests.rs | 16 +- crates/features/src/chars.rs | 53 +- crates/features/src/chars/tests.rs | 3 +- crates/features/src/enums.rs | 193 ++----- crates/features/src/enums/tests.rs | 12 +- crates/features/src/interfaces.rs | 147 +++-- crates/features/src/interfaces/tests.rs | 8 +- crates/features/src/lib.rs | 319 ++++------ crates/features/src/optionals.rs | 102 +--- crates/features/src/optionals/tests.rs | 23 +- crates/features/src/pipes.rs | 88 ++- crates/features/src/pipes/tests.rs | 12 +- crates/features/src/printing.rs | 205 +++---- crates/features/src/printing/tests.rs | 3 +- crates/features/src/ranges.rs | 155 ++--- crates/features/src/ranges/tests.rs | 7 +- crates/features/src/raw_pointers.rs | 126 ++-- crates/features/src/raw_pointers/tests.rs | 10 +- crates/features/src/structs.rs | 386 ++++++------- crates/features/src/structs/tests.rs | 10 +- crates/features/src/testing.rs | 19 +- crates/kernel/lower/src/aggregates.rs | 3 +- crates/kernel/lower/src/expression.rs | 3 +- crates/kernel/lower/src/lib.rs | 11 +- crates/kernel/lower/src/statement.rs | 3 +- crates/kernel/lower/src/tests.rs | 5 +- crates/kernel/model/src/program.rs | 89 +-- crates/kernel/semantic/src/builder.rs | 12 +- crates/kernel/semantic/src/conformance.rs | 3 +- crates/kernel/semantic/src/declaration.rs | 21 +- crates/kernel/semantic/src/expression.rs | 42 +- .../kernel/semantic/src/expression/borrows.rs | 3 +- .../semantic/src/expression/literals.rs | 15 +- .../kernel/semantic/src/expression/names.rs | 3 +- .../semantic/src/expression/operators.rs | 15 +- .../kernel/semantic/src/expression/places.rs | 17 +- crates/kernel/semantic/src/functions.rs | 9 +- .../kernel/semantic/src/functions/bodies.rs | 3 +- .../kernel/semantic/src/functions/builtin.rs | 3 +- crates/kernel/semantic/src/functions/calls.rs | 21 +- crates/kernel/semantic/src/generics.rs | 41 +- .../semantic/src/generics/constraints.rs | 13 +- crates/kernel/semantic/src/generics/copies.rs | 12 +- crates/kernel/semantic/src/lib.rs | 59 +- crates/kernel/semantic/src/locals.rs | 11 +- crates/kernel/semantic/src/scope.rs | 14 +- crates/kernel/semantic/src/statement.rs | 21 +- .../semantic/src/statement/assignments.rs | 15 +- crates/kernel/semantic/src/statement/loops.rs | 9 +- crates/kernel/semantic/src/testing.rs | 112 +--- crates/kernel/syntax/parser/src/decl.rs | 72 +-- crates/kernel/syntax/parser/src/dump.rs | 56 +- crates/kernel/syntax/parser/src/expr.rs | 68 +-- crates/kernel/syntax/parser/src/expr/tests.rs | 5 +- crates/kernel/syntax/parser/src/lib.rs | 71 +-- crates/kernel/syntax/parser/src/literals.rs | 11 +- crates/kernel/syntax/parser/src/pattern.rs | 7 +- crates/kernel/syntax/parser/src/stmt.rs | 39 +- crates/kernel/syntax/parser/src/tests.rs | 57 +- crates/kernel/syntax/parser/src/types.rs | 33 +- crates/kernel/syntax/tree/src/ast.rs | 546 +++++++++++------- docs/feature-front.md | 23 +- docs/structure-mapping.md | 32 +- scripts/check.sh | 15 +- 86 files changed, 1809 insertions(+), 2227 deletions(-) diff --git a/crates/backend/llvm/src/tests.rs b/crates/backend/llvm/src/tests.rs index 3833ae26..decdfdb3 100644 --- a/crates/backend/llvm/src/tests.rs +++ b/crates/backend/llvm/src/tests.rs @@ -1,4 +1,3 @@ -use features::Peeper; use std::collections::HashMap; use std::path::PathBuf; use std::process::Command; @@ -44,7 +43,7 @@ fn program_ll(text: &str, target: &str) -> HashMap { "fn Half(a: i32, b: i32) -> i32 { return a / b; }\n".to_string(), ), ]); - let program = project::load::(&project, &open_files); + let program = project::load(&project, &open_files, &features::RULES); assert!(program.checkable); let files: Vec<_> = (program.modules.iter()) .map(|module| module.ast.file.clone()) diff --git a/crates/base/arena/src/lib.rs b/crates/base/arena/src/lib.rs index 6fbc5d28..abe300a9 100644 --- a/crates/base/arena/src/lib.rs +++ b/crates/base/arena/src/lib.rs @@ -230,14 +230,6 @@ pub trait Node: Sized { /// field of the container, or of a field of it (`children.field_values`). #[macro_export] macro_rules! nodes { - (<$generic:ident: $bound:path> $container:ty; $($node:ty => $($arena:ident).+),* $(,)?) => { - $(impl<$generic: $bound> $crate::Node for $node { - type Container = $container; - fn arena(container: &mut $container) -> &mut $crate::Arena<$node> { - &mut container.$($arena).+ - } - })* - }; ($container:ty; $($node:ty => $($arena:ident).+),* $(,)?) => { $(impl $crate::Node for $node { type Container = $container; diff --git a/crates/driver/browser/src/main.rs b/crates/driver/browser/src/main.rs index 5f4a3aa4..98b05b9e 100644 --- a/crates/driver/browser/src/main.rs +++ b/crates/driver/browser/src/main.rs @@ -8,7 +8,6 @@ //! overflow wasm's stack on very deep code, so a page runs a new instance for each //! check, and one crash loses nothing. -use features::Peeper; use std::collections::HashMap; use std::io::Read; use std::path::Path; @@ -87,17 +86,14 @@ fn project_of(files: &HashMap) -> Result, -) -> model::program::Program { +fn load(project: &project::Project, files: HashMap) -> model::program::Program { let page_files = files .into_iter() .map(|(name, text)| (PathBuf::from(name), text)); let library_files = (LIBRARY_FILES.iter()) .map(|&(path, text)| (Path::new(LIBRARY_ROOT).join(path), text.to_string())); let open_files: HashMap = page_files.chain(library_files).collect(); - project::load::(project, &open_files) + project::load(project, &open_files, &features::RULES) } /// The diagnostics of the program `files` make up, as `peeper check` finds @@ -155,7 +151,7 @@ fn run(files: HashMap) -> Value { /// Every diagnostic of `program` and `results`, the loader's first. fn all_diagnostics<'a>( - program: &'a model::program::Program, + program: &'a model::program::Program, results: &'a compile::Results, ) -> impl Iterator { program.diagnostics.iter().chain(results.diagnostics()) @@ -165,10 +161,7 @@ fn all_diagnostics<'a>( /// `message`, its primary `place` (null when it has none) and the `related` /// places; a place has its `file`, its `start` and `end`, and its own /// `message`. -fn diagnostics_json( - program: &model::program::Program, - results: &compile::Results, -) -> Value { +fn diagnostics_json(program: &model::program::Program, results: &compile::Results) -> Value { let place = |label: &Label| { json!({ "file": label.file.path, diff --git a/crates/driver/browser/src/tests.rs b/crates/driver/browser/src/tests.rs index bca09b6d..57be5352 100644 --- a/crates/driver/browser/src/tests.rs +++ b/crates/driver/browser/src/tests.rs @@ -1,5 +1,4 @@ use super::*; -use features::Peeper; use test_programs::Mark; use test_programs::Mode; use test_programs::TestProgram; @@ -17,7 +16,7 @@ fn files(entries: &[(&str, &str)]) -> HashMap { const MANIFEST: &str = manifest::FILE_NAME; /// What `files` load to, when their peeper.toml gives a project. -fn loaded(files: HashMap) -> model::program::Program { +fn loaded(files: HashMap) -> model::program::Program { let project = project_of(&files).expect("the files are a project"); load(&project, files) } diff --git a/crates/driver/compile/src/lib.rs b/crates/driver/compile/src/lib.rs index c78477e8..a1be83d4 100644 --- a/crates/driver/compile/src/lib.rs +++ b/crates/driver/compile/src/lib.rs @@ -39,8 +39,6 @@ use source::SourceFile; use source::Span; use syntax::ast; -use features::Peeper; - /// What a compile found, kept for the next compile of the same program. #[derive(Default)] pub struct Results { @@ -157,7 +155,7 @@ pub struct Interpreted { /// it did. A program that cannot be checked has only loading's errors, and /// does not start. pub fn interpret( - program: &model::program::Program, + program: &model::program::Program, target: &'static Machine, ) -> (Results, Option) { let modules = program.modules.as_slice(); @@ -240,7 +238,7 @@ pub struct Options { /// the checking and lowering it runs are built once, here, not again in each /// crate that calls it with a closure of its own. pub fn run( - program: &model::program::Program, + program: &model::program::Program, target: &'static Machine, previous: Results, options: Options, @@ -250,7 +248,12 @@ pub fn run( return Results::default(); } let modules = program.modules.as_slice(); - let mut checker = Checker::new(modules, target, options.record_facts); + let mut checker = Checker::new( + modules, + target, + options.record_facts, + &features::CHECK_HOOKS, + ); let mut results: Vec = modules .iter() .map(|module| ModuleResults::new(module.ast.file.clone())) @@ -366,10 +369,7 @@ pub fn run( /// The `main` of the module `entry` and whether it returns the exit code, or /// the error that it has none a program can start at. -fn find_entry_point( - checker: &mut Checker, - entry: ModuleId, -) -> Result<(DefId, bool), Diagnostic> { +fn find_entry_point(checker: &mut Checker, entry: ModuleId) -> Result<(DefId, bool), Diagnostic> { let module = &checker.modules[entry.index()]; let tree = &module.ast; let main = tree @@ -422,7 +422,7 @@ fn find_entry_point( /// or not, and gives each, with its MIR and its own facts for a /// function, then the module's remaining facts, to `use_output`. fn compile_module( - checker: &mut Checker, + checker: &mut Checker, module: ModuleId, thir: &mut thir::Body, record_facts: bool, @@ -496,7 +496,7 @@ fn compile_module( /// and its facts to `use_output`; nothing when it has no body /// or its signature has an error. fn build_function( - checker: &mut Checker, + checker: &mut Checker, module: ModuleId, function: DeclarationCopy, thir: &mut thir::Body, @@ -523,7 +523,7 @@ fn build_function( /// Feeds `ty` to `hasher` by what it is (`Types::hash`): a declared type /// by its module's path and its name. What it holds is in the interface of /// the module declaring it (`interface`). -fn hash_type(checker: &Checker, ty: TypeId, hasher: &mut DefaultHasher) { +fn hash_type(checker: &Checker, ty: TypeId, hasher: &mut DefaultHasher) { let modules = checker.modules; checker.types.hash(ty, hasher, |definition, hasher| { modules[definition.module.index()].path.hash(hasher); @@ -537,7 +537,7 @@ fn hash_type(checker: &Checker, ty: TypeId, hasher: &mut DefaultHasher) /// change reaches every module that can see it through a type, and each /// declaration's kind, name, and type, value or struct fields. Its bodies are /// not part of it. -fn interface(checker: &Checker, module: ModuleId, done: &[ModuleResults]) -> u64 { +fn interface(checker: &Checker, module: ModuleId, done: &[ModuleResults]) -> u64 { let modules = checker.modules; let checked = &checker.module_checks[module.index()]; let (declared_types, constants) = (&checked.declared_types, &checked.constants); diff --git a/crates/driver/compile/src/tests.rs b/crates/driver/compile/src/tests.rs index 395734d3..560d86f8 100644 --- a/crates/driver/compile/src/tests.rs +++ b/crates/driver/compile/src/tests.rs @@ -8,7 +8,6 @@ use super::Output; use super::Results; use super::run; use diagnostics::Diagnostic; -use features::Peeper; use model::machine::Machine; /// The machine the tests check for, but where they test another. @@ -19,7 +18,7 @@ fn x86_64() -> &'static Machine { /// The program of `modules`, each an import path and its text, loaded as /// `peeper check` loads it from `app:main`, with every file given as open /// editor text so nothing is read from disk. Loading must find no error. -fn load(modules: &[(&str, &str)]) -> model::program::Program { +fn load(modules: &[(&str, &str)]) -> model::program::Program { let folder = |package: &str| match package { "core" => PathBuf::from("/peeper-build-test/libs/core/src"), _ => PathBuf::from("/peeper-build-test/src"), @@ -44,7 +43,7 @@ fn load(modules: &[(&str, &str)]) -> model::program::Program { root: PathBuf::from("/peeper-build-test"), name: "app".to_string(), }; - let program = project::load(&project, &open_files); + let program = project::load(&project, &open_files, &features::RULES); let reported: Vec<&str> = program .diagnostics .iter() @@ -810,7 +809,7 @@ fn messages(results: &Results) -> Vec { /// The messages of a first compile of `program` for the machine named /// `target`. -fn messages_on(program: &model::program::Program, target: &str) -> Vec { +fn messages_on(program: &model::program::Program, target: &str) -> Vec { let target = Machine::named(target).unwrap(); let found = run( program, diff --git a/crates/driver/compile/tests/checks_through_features.rs b/crates/driver/compile/tests/checks_through_features.rs index 18ac7313..0734e30f 100644 --- a/crates/driver/compile/tests/checks_through_features.rs +++ b/crates/driver/compile/tests/checks_through_features.rs @@ -1,13 +1,12 @@ //! The checker's tests that need a feature to reach core behaviour. The -//! checker's own tests are written in a language with no feature, as the -//! `features` crate depends on `check`; these are written in Peeper, through the -//! checker's public calls. +//! checker's own tests read the core's rules alone, as the `features` crate +//! depends on `check`; these are written in Peeper, through the checker's +//! public calls. use std::sync::Arc; use check::Checker; use check::scope::collect; -use features::Peeper; use model::ConstArguments; use model::DeclarationCopy; use model::DefId; @@ -25,9 +24,9 @@ use syntax::ast; /// The module `path`, written as `text`, with `imports`; its text must parse /// without errors. -fn module(path: &str, text: &str, imports: Vec) -> model::program::Module { +fn module(path: &str, text: &str, imports: Vec) -> model::program::Module { let file = Arc::new(SourceFile::new("main.peep", text)); - let (ast, parse) = parser::parse(&file); + let (ast, parse) = parser::parse(&file, &features::RULES); assert!(parse.is_empty(), "{parse:?}"); model::program::Module { path: path.to_string(), @@ -46,7 +45,7 @@ type Reported = (&'static str, String, String); /// the diagnostics. fn with_checker( text: &str, - work: impl FnOnce(&mut Checker, ModuleId) -> T, + work: impl FnOnce(&mut Checker, ModuleId) -> T, ) -> (T, Types, Vec) { let (utils_id, main_id) = (ModuleId::from_index(0), ModuleId::from_index(1)); let imports = vec![Import { @@ -59,7 +58,12 @@ fn with_checker( module("app:main", &text, imports), ]; let file = modules[1].ast.file.clone(); - let mut checker = Checker::new(&modules, Machine::named("x86_64-linux").unwrap(), false); + let mut checker = Checker::new( + &modules, + Machine::named("x86_64-linux").unwrap(), + false, + &features::CHECK_HOOKS, + ); let result = work(&mut checker, main_id); let reported = checker .module_checks diff --git a/crates/driver/compile/tests/parses_the_prelude.rs b/crates/driver/compile/tests/parses_the_prelude.rs index 60bee99e..9e090dd4 100644 --- a/crates/driver/compile/tests/parses_the_prelude.rs +++ b/crates/driver/compile/tests/parses_the_prelude.rs @@ -1,9 +1,8 @@ //! The real prelude is written in Peeper, with every feature, so it is -//! read here, not in the parser's own tests (a language with no feature). +//! read here, not in the parser's own tests (the core's rules alone). use std::sync::Arc; -use features::Peeper; use source::SourceFile; use syntax::ast; @@ -16,6 +15,6 @@ fn parses_the_prelude() { ); let text = std::fs::read_to_string(path).unwrap(); let file = Arc::new(SourceFile::new("global.peep", &text)); - let (_, errors): (ast::Tree, _) = parser::parse(&file); + let (_, errors): (ast::Tree, _) = parser::parse(&file, &features::RULES); assert!(errors.is_empty(), "{errors:?}"); } diff --git a/crates/driver/compile/tests/path_check_memory.rs b/crates/driver/compile/tests/path_check_memory.rs index 45ad9bf3..4e535ec5 100644 --- a/crates/driver/compile/tests/path_check_memory.rs +++ b/crates/driver/compile/tests/path_check_memory.rs @@ -36,7 +36,7 @@ fn compile_growth_kb(text: String) -> u64 { }; std::fs::write("/proc/self/clear_refs", "5").unwrap(); // resets `VmHWM` let before = status_kb("VmRSS:"); - let program = project::load(&project, &HashMap::from([(main, text)])); + let program = project::load(&project, &HashMap::from([(main, text)]), &features::RULES); assert!(program.checkable); let target = model::machine::Machine::named("x86_64-linux").unwrap(); let results = compile::run( diff --git a/crates/driver/lsp/src/checked.rs b/crates/driver/lsp/src/checked.rs index 691c2550..6ab9f652 100644 --- a/crates/driver/lsp/src/checked.rs +++ b/crates/driver/lsp/src/checked.rs @@ -1,7 +1,6 @@ //! What the last check found, kept for the next one and for requests: the //! compile results, and each module's facts by name. -use features::Peeper; use std::collections::HashMap; use std::collections::HashSet; use std::path::Path; @@ -34,7 +33,7 @@ pub(crate) struct Checked { /// The program as last compiled, and the facts of each of its modules' /// text and the names of its constants, by file: what definition and /// hover read. - pub(crate) program: Option>, + pub(crate) program: Option, pub(crate) facts: HashMap>, pub(crate) fix_all: HashMap, // each file's sure fixes, as of the last check } @@ -43,7 +42,7 @@ impl Checked { /// keeps the facts of each module's text and the names of its /// constants: a module the compile reused gave no facts, and the facts /// found before still fit it; a module checked again gets its new facts. - pub(crate) fn recompile(&mut self, program: &model::program::Program) { + pub(crate) fn recompile(&mut self, program: &model::program::Program) { let mut found: HashMap> = HashMap::new(); let previous = std::mem::take(&mut self.results); let mut cache_facts = |output: compile::Output| match output { @@ -159,7 +158,7 @@ impl CachedFact { /// `fact`, about the text of a module of `program`, whose types are of /// `types`; a local's name comes with the `body` it belongs to. pub(crate) fn new( - program: &model::program::Program, + program: &model::program::Program, fact: &thir::Fact, body: Option<&thir::Body>, types: &Types, @@ -221,7 +220,7 @@ impl CachedFact { /// the type the copy takes, a `const` one with what it is given, and no /// type parameters. fn copy_signature( - program: &model::program::Program, + program: &model::program::Program, copy: DeclarationCopy, ty: TypeId, types: &Types, @@ -313,7 +312,7 @@ pub(crate) struct ConstantText { impl ConstantText { /// `constant`, of `program`, whose type is in `types`. pub(crate) fn new( - program: &model::program::Program, + program: &model::program::Program, constant: &Constant, types: &Types, ) -> ConstantText { diff --git a/crates/driver/lsp/src/hover.rs b/crates/driver/lsp/src/hover.rs index ac7dc555..1f487678 100644 --- a/crates/driver/lsp/src/hover.rs +++ b/crates/driver/lsp/src/hover.rs @@ -1,6 +1,5 @@ //! Hover text: what a name declares, and the docs of a keyword or built-in. -use features::Peeper; use std::fmt::Write; use arena::Id; @@ -11,7 +10,6 @@ use lsp_types::MarkupKind; use source::SourceFile; use source::Span; use syntax::ast; -use syntax::ast::Language; use crate::checked::ConstantText; @@ -26,8 +24,8 @@ const HIDDEN: &str = "/* ... */"; /// the exported ones when hovered `from_elsewhere`, another module; another /// declaration, or a constant with an error, whole. pub(crate) fn declaration_hover( - tree: &ast::Tree, - declaration: Id>, + tree: &ast::Tree, + declaration: Id, module: &str, constant: Option<&ConstantText>, copy: Option<&str>, @@ -72,7 +70,7 @@ pub(crate) fn declaration_hover( let signature = written(tree.blocks.span(*body).start); (format!("{signature} {{ {HIDDEN} }}"), None) } - (ast::Decl::Type(declared), _) if matches!(tree.types[declared.ty], ast::Type::Feature(ty) if Peeper::fields(&ty).is_some()) => + (ast::Decl::Type(declared), _) if matches!(tree.types[declared.ty], ast::Type::Feature(ty) if ty.fields().is_some()) => { let mut facts = written(span.end).to_string(); write_functions(tree, declared.name, from_elsewhere, &mut facts); @@ -99,12 +97,7 @@ pub(crate) fn declaration_hover( /// its body as `HIDDEN`, after a blank line; only the exported ones when /// `exported_only`. A type's functions are declared in the type's module, /// where its name names one declaration, so the written name finds them. -fn write_functions( - tree: &ast::Tree, - owner: ast::Ident, - exported_only: bool, - facts: &mut String, -) { +fn write_functions(tree: &ast::Tree, owner: ast::Ident, exported_only: bool, facts: &mut String) { let owner = owner.text(&tree.file); let mut separator = "\n\n"; for declaration in tree.decls.ids() { diff --git a/crates/driver/lsp/src/server/requests.rs b/crates/driver/lsp/src/server/requests.rs index 1d87cf7f..be8cf705 100644 --- a/crates/driver/lsp/src/server/requests.rs +++ b/crates/driver/lsp/src/server/requests.rs @@ -1,7 +1,6 @@ //! Answering the editor's requests: hover, go to definition and code //! actions. -use features::Peeper; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; @@ -143,7 +142,7 @@ impl Server<'_> { pub(crate) fn modules_of<'a>( &'a self, file: &Path, - ) -> impl Iterator)> { + ) -> impl Iterator { let open = self.open_files.get(file); let mut programs: Vec<(&PathBuf, &Checked)> = self.checked.iter().collect(); programs.sort_unstable_by_key(|&(entry, _)| entry); @@ -163,7 +162,7 @@ impl Server<'_> { pub(crate) fn name_at( &self, place: &TextDocumentPositionParams, - ) -> Option<(&Checked, &model::program::Module, CachedFact)> { + ) -> Option<(&Checked, &model::program::Module, CachedFact)> { let file = file_path(&place.text_document.uri)?; let holds: [fn(Span, u32) -> bool; 2] = [ |span, offset| span.start <= offset && offset < span.end, @@ -252,7 +251,7 @@ impl Server<'_> { /// and what hover shows for it. A built-in name has no declaration. fn declaration_of<'a>( checked: &'a Checked, - module: &'a model::program::Module, + module: &'a model::program::Module, fact: CachedFact, ) -> Option<(&'a Arc, Span, String)> { let CachedFact { span, kind } = fact; diff --git a/crates/driver/lsp/src/server/sync.rs b/crates/driver/lsp/src/server/sync.rs index 2c91664c..e28ead70 100644 --- a/crates/driver/lsp/src/server/sync.rs +++ b/crates/driver/lsp/src/server/sync.rs @@ -1,7 +1,6 @@ //! Keeping the open files current, checking their programs and //! publishing the diagnostics. -use features::Peeper; use std::collections::HashMap; use std::collections::HashSet; use std::path::Path; @@ -156,7 +155,7 @@ impl Server<'_> { project: project::Project, file: &Path, ) -> Result<(), BoxError> { - let program = project::load::(&project, &self.open_files); + let program = project::load(&project, &self.open_files, &features::RULES); let mut checked = self.checked.remove(&key).unwrap_or_default(); let mut all: Vec<&diagnostics::Diagnostic> = program.diagnostics.iter().collect(); // A program that cannot be checked keeps the last compile for the next. diff --git a/crates/driver/peeper/benches/compile.rs b/crates/driver/peeper/benches/compile.rs index 37047547..3a798191 100644 --- a/crates/driver/peeper/benches/compile.rs +++ b/crates/driver/peeper/benches/compile.rs @@ -9,7 +9,6 @@ //! //! cargo bench -p peeper --bench compile -use features::Peeper; use std::collections::HashMap; use std::fmt::Write; use std::path::Path; @@ -77,7 +76,7 @@ fn main() { let mut clang = Vec::new(); for _ in 0..runs { let start = Instant::now(); - let program = project::load::(&project, &files); + let program = project::load(&project, &files, &features::RULES); load.push(start.elapsed()); assert!(program.checkable, "{:?}", program.diagnostics); let start = Instant::now(); diff --git a/crates/driver/peeper/src/driver.rs b/crates/driver/peeper/src/driver.rs index 6ce24aec..d6026559 100644 --- a/crates/driver/peeper/src/driver.rs +++ b/crates/driver/peeper/src/driver.rs @@ -2,7 +2,6 @@ //! apply the fixes asked for, print its diagnostics, write the dumps asked //! for, and build or run it. -use features::Peeper; use std::collections::HashMap; use std::io::Write; use std::path::Path; @@ -80,7 +79,11 @@ impl Command { } // Read and parse every module, following imports. No editor has // unsaved text here, so every file is read from disk. - let program = project::load::(&project, &HashMap::::new()); + let program = project::load( + &project, + &HashMap::::new(), + &features::RULES, + ); match goal { Goal::Check { dumps, @@ -101,7 +104,7 @@ impl Command { fn execute_check( &mut self, project: &project::Project, - program: &model::program::Program, + program: &model::program::Program, dumps: &[Dump], apply_fixes: bool, mode: BuildMode, @@ -138,7 +141,7 @@ impl Command { fn execute_build( &mut self, project: &project::Project, - program: &model::program::Program, + program: &model::program::Program, output: Option<&Path>, mode: BuildMode, ) -> u8 { @@ -167,7 +170,7 @@ impl Command { /// it with `arguments` and removes it; gives the program's exit code. fn execute_run( &mut self, - program: &model::program::Program, + program: &model::program::Program, arguments: &[String], mode: BuildMode, ) -> u8 { @@ -197,7 +200,7 @@ impl Command { /// `run -interpret`: runs the program on the interpreter, then prints what /// it wrote; gives the program's exit code. - fn execute_interpret(&mut self, program: &model::program::Program) -> u8 { + fn execute_interpret(&mut self, program: &model::program::Program) -> u8 { let (results, ran) = compile::interpret(program, self.target); let found = program.diagnostics.iter().chain(results.diagnostics()); let diagnostics: Vec = found.cloned().collect(); @@ -254,7 +257,7 @@ impl Command { /// `mode`, when linking or a dump needs it; and the dumps, to write when /// there is no error. fn compile<'p>( - program: &'p model::program::Program, + program: &'p model::program::Program, dumps: &'p [Dump], mode: BuildMode, target: &'static Machine, diff --git a/crates/driver/peeper/src/dump.rs b/crates/driver/peeper/src/dump.rs index bb9cf147..afee4516 100644 --- a/crates/driver/peeper/src/dump.rs +++ b/crates/driver/peeper/src/dump.rs @@ -2,7 +2,6 @@ //! text, one file per module and kind, for reading what the compiler made of //! a program. -use features::Peeper; use std::io::Write; use std::path::Path; @@ -37,14 +36,14 @@ impl Dump { /// written once it has no errors. The LLVM text comes from the program's /// `llvm::Module`s, which the driver builds once for dumps and linking. pub struct Dumps<'p> { - program: &'p model::program::Program, + program: &'p model::program::Program, kinds: &'p [Dump], texts: Vec>, // by module, then by kind; empty for `Ll` } impl<'p> Dumps<'p> { /// No text yet for any of the `kinds` of `program`'s modules. - pub fn new(program: &'p model::program::Program, kinds: &'p [Dump]) -> Dumps<'p> { + pub fn new(program: &'p model::program::Program, kinds: &'p [Dump]) -> Dumps<'p> { Dumps { program, kinds, diff --git a/crates/driver/peeper/src/lib.rs b/crates/driver/peeper/src/lib.rs index ff830e2c..2a2f822f 100644 --- a/crates/driver/peeper/src/lib.rs +++ b/crates/driver/peeper/src/lib.rs @@ -2,7 +2,6 @@ //! loading and linking. It is here, not in the command, so the compile //! benchmark times the work a build does. -use features::Peeper; use llvm::BuildMode; use model::DeclarationCopy; use model::machine::Machine; @@ -19,7 +18,7 @@ use model::thir; /// written. Gives the modules, which leave out each function with an error, /// and what the compile found. pub fn write_program<'p>( - program: &'p Program, + program: &'p Program, target: &'static Machine, mode: BuildMode, require_main: bool, diff --git a/crates/driver/project/src/lib.rs b/crates/driver/project/src/lib.rs index 185ecaa3..3d372e6f 100644 --- a/crates/driver/project/src/lib.rs +++ b/crates/driver/project/src/lib.rs @@ -27,7 +27,7 @@ use packages::SOURCE_EXTENSION; use packages::file_of; use packages::import_path_of; use packages::is_source_file; -use parser::Grammar; +use parser::Rules; use crate::loading::Job; use crate::loading::load_module; @@ -257,11 +257,13 @@ pub fn library_packages( /// reads as text, such as a `String`), read instead of what is on disk. Its /// keys, like `project`'s paths, are spelled as `canonical_path` spells them. /// Each `.peep` file of a package in it is loaded too, imported or not, so an -/// editor checks the file it has open. -pub fn load( +/// editor checks the file it has open. `rules` are the core's and each +/// feature's, which every module is parsed with. +pub fn load( project: &Project, open_files: &HashMap + Sync>, -) -> Program { + rules: &'static Rules, +) -> Program { let with_prelude = file_of(&project.packages, PRELUDE_PATH) .is_some_and(|file| file.is_file() || open_files.contains_key(&file)); let workers = if cfg!(target_family = "wasm") { @@ -311,7 +313,7 @@ pub fn load( // A panic goes to the main thread, which would // otherwise wait for this module forever. let loaded = std::panic::catch_unwind(AssertUnwindSafe(|| { - load_module(&project.packages, open_files, job, with_prelude) + load_module(&project.packages, open_files, rules, job, with_prelude) })); _ = send_module.send(loaded); } @@ -346,7 +348,7 @@ pub fn load( let loaded = if workers == 0 { let job = jobs.lock().expect("no worker holds the lock").try_recv(); let job = job.expect("each pending module has a job"); - load_module(&project.packages, open_files, job, with_prelude) + load_module(&project.packages, open_files, rules, job, with_prelude) } else { // This thread holds `send_module`, so a receive always ends. let loaded = done.recv().expect("this thread holds a sender"); diff --git a/crates/driver/project/src/loading.rs b/crates/driver/project/src/loading.rs index 7b8fa463..95b0d6b2 100644 --- a/crates/driver/project/src/loading.rs +++ b/crates/driver/project/src/loading.rs @@ -15,10 +15,9 @@ use model::program::Import; use model::program::ImportKind; use model::program::Module; use model::program::default_alias; -use parser::Grammar; +use parser::Rules; use source::SourceFile; use source::Span; -use syntax::ast::Language; use syntax::ast::Tree; use crate::PRELUDE_PATH; @@ -28,9 +27,9 @@ use crate::path_text; /// A module being loaded: its imports are known by path until every module /// has its place in the program's order. -pub(crate) struct Loaded { +pub(crate) struct Loaded { pub(crate) path: String, - pub(crate) ast: Tree, + pub(crate) ast: Tree, pub(crate) imports: Vec<(ImportKind, String)>, // with the imported module's path pub(crate) imports_complete: bool, // every written import names a module it brings in pub(crate) diagnostics: Vec, @@ -42,15 +41,16 @@ pub(crate) struct Job { pub(crate) standalone: bool, // a file in no package, checked on its own: it cannot import } -/// Reads, parses and resolves the imports of one module, taking its text from -/// `open_files` when it is open there. A file that cannot be read, or is not -/// UTF-8, gets an empty tree and one error. -pub(crate) fn load_module( +/// Reads, parses with `rules` and resolves the imports of one module, taking +/// its text from `open_files` when it is open there. A file that cannot be +/// read, or is not UTF-8, gets an empty tree and one error. +pub(crate) fn load_module( packages: &HashMap, open_files: &HashMap>, + rules: &'static Rules, job: Job, with_prelude: bool, -) -> Loaded { +) -> Loaded { let path = path_text(&job.file); let text = match open_files.get(&job.file) { // Copied: every worker shares the map, and a source file owns its text. @@ -64,7 +64,7 @@ pub(crate) fn load_module( text => text, }; let (ast, diagnostics) = match text.map(String::from_utf8) { - Ok(Ok(text)) => parser::parse(&Arc::new(SourceFile::new(path, text))), + Ok(Ok(text)) => parser::parse(&Arc::new(SourceFile::new(path, text)), rules), Ok(Err(error)) => { // The text up to the bad byte is kept as is, so the error points at it. let at = error.utf8_error().valid_up_to(); @@ -94,9 +94,9 @@ pub(crate) fn load_module( loaded.resolve_imports(packages, open_files, job.standalone, with_prelude); loaded } -impl Loaded { +impl Loaded { /// The module, its imports resolved to the places in `ids`. - pub(crate) fn into_module(self, ids: &HashMap) -> Module { + pub(crate) fn into_module(self, ids: &HashMap) -> Module { let imports = self.imports.iter(); let imports = imports.map(|(kind, path)| Import { kind: *kind, diff --git a/crates/driver/project/src/order.rs b/crates/driver/project/src/order.rs index 303bc51b..bcedd2e2 100644 --- a/crates/driver/project/src/order.rs +++ b/crates/driver/project/src/order.rs @@ -6,8 +6,6 @@ use std::collections::HashMap; use diagnostics::Diagnostic; use model::program::ImportKind; -use syntax::ast::Language; - use crate::loading::Loaded; #[derive(Clone, Copy, PartialEq)] @@ -18,8 +16,8 @@ enum Visit { /// Orders modules so each follows the modules it imports, and reports every /// import cycle. It visits modules and imports in path order, so the result /// does not depend on how the workers were scheduled. -struct Sorter<'a, L: Language> { - modules: &'a HashMap>, +struct Sorter<'a> { + modules: &'a HashMap, visits: HashMap<&'a str, Visit>, /// The modules being visited, outermost first, each with the import that /// reached it: none for the first. @@ -27,9 +25,7 @@ struct Sorter<'a, L: Language> { order: Vec, cycles: Vec, } -pub(crate) fn sort_modules( - modules: &HashMap>, -) -> (Vec, Vec) { +pub(crate) fn sort_modules(modules: &HashMap) -> (Vec, Vec) { let mut sorter = Sorter { modules, visits: HashMap::with_capacity(modules.len()), @@ -46,7 +42,7 @@ pub(crate) fn sort_modules( } (sorter.order, sorter.cycles) } -impl<'a, L: Language> Sorter<'a, L> { +impl<'a> Sorter<'a> { /// Visits the module `path`, reached by the import `reached_by`. fn visit(&mut self, path: &'a str, reached_by: Option) { self.visits.insert(path, Visit::Started); diff --git a/crates/driver/project/src/tests.rs b/crates/driver/project/src/tests.rs index 6d9c97c4..88382b36 100644 --- a/crates/driver/project/src/tests.rs +++ b/crates/driver/project/src/tests.rs @@ -1,6 +1,5 @@ use std::fmt::Write; -use features::Peeper; use model::program::Import; use model::program::Module; @@ -8,13 +7,13 @@ use super::*; use crate::packages::resolve; /// The module of `program` at the import path `path`. -fn module_named<'p>(program: &'p Program, path: &str) -> &'p Module { +fn module_named<'p>(program: &'p Program, path: &str) -> &'p Module { let module = program.modules.iter().find(|module| module.path == path); module.unwrap_or_else(|| panic!("no module {path}")) } /// The paths of `program`'s modules, in its order. -fn order(program: &Program) -> Vec<&str> { +fn order(program: &Program) -> Vec<&str> { program .modules .iter() @@ -48,7 +47,7 @@ fn write(test: &str, files: &[(&str, &str)]) -> Project { /// "module: CODE message" for every diagnostic, sorted. /// Each diagnostic as the path of the module its first label is in, its /// code and its message, sorted. -fn messages(program: &Program) -> Vec { +fn messages(program: &Program) -> Vec { let module = |d: &Diagnostic| { let file = Path::new(&d.labels.first()?.file.path); Some(program.module_of(file)?.path.as_str()) @@ -69,7 +68,7 @@ fn messages(program: &Program) -> Vec { out } -fn imports(program: &Program, module: &Module) -> Vec { +fn imports(program: &Program, module: &Module) -> Vec { let alias = |import: &Import| { let name = import.name(module, &program.modules); name.map_or("", |(name, _)| name) @@ -193,7 +192,11 @@ fn a_library_loads_each_of_its_files() { std::os::unix::fs::symlink(&root, root.join("src/back")).unwrap(); let project = find(&root, &root.join("libs")).unwrap(); assert_eq!(project.entry, None); - let program = load::(&project, &HashMap::::new()); + let program = load( + &project, + &HashMap::::new(), + &features::RULES, + ); assert_eq!(messages(&program), Vec::::new()); assert_eq!(order(&program), ["tools:a", "tools:deep/b"]); assert_eq!(program.entry, None); @@ -211,7 +214,7 @@ fn a_library_without_files_is_an_error() { .root; let project = find(&root, &root.join("libs")).unwrap(); let none = HashMap::::new(); - let missing = load::(&project, &none); + let missing = load(&project, &none, &features::RULES); let got = messages(&missing); assert!( got.len() == 1 && got[0].starts_with("program: M0001 read library: "), @@ -220,14 +223,14 @@ fn a_library_without_files_is_an_error() { assert!(!missing.checkable); std::fs::create_dir(root.join("src")).unwrap(); let source = path_text(&root.join("src")); - let empty = load::(&project, &none); + let empty = load(&project, &none, &features::RULES); assert_eq!( messages(&empty), [format!("program: M0001 no source files in {source}")] ); std::fs::remove_dir(root.join("src")).unwrap(); let open = HashMap::from([(root.join("src/a.peep"), "fn A() {}".to_string())]); - let program = load::(&project, &open); + let program = load(&project, &open, &features::RULES); assert_eq!(messages(&program), Vec::::new()); assert_eq!(order(&program), ["tools:a"]); } @@ -340,7 +343,11 @@ fn loads_nested_imports() { ("libs/core/src/global.peep", "fn Exit(code: i32) {}"), ], ); - let program = load::(&project, &HashMap::::new()); + let program = load( + &project, + &HashMap::::new(), + &features::RULES, + ); assert_eq!(messages(&program), Vec::::new()); assert_eq!( order(&program).join(" "), @@ -366,7 +373,11 @@ fn loads_a_module_with_a_dot_in_its_name() { ("src/a.b.peep", "fn X() {}"), ], ); - let program = load::(&project, &HashMap::::new()); + let program = load( + &project, + &HashMap::::new(), + &features::RULES, + ); assert_eq!(messages(&program), Vec::::new()); assert_eq!(order(&program).join(" "), "myapp:a.b myapp:main"); } @@ -398,7 +409,11 @@ fn import_errors() { ("src/c.peep", ""), ], ); - let program = load::(&project, &HashMap::::new()); + let program = load( + &project, + &HashMap::::new(), + &features::RULES, + ); let missing = project.root.join("src/missing.peep"); let parts = "myapp:main: M0003 import path parts cannot be empty, `.` or `..`, or hold `\\` or `:`" @@ -437,7 +452,11 @@ fn import_errors() { fn guesses_a_missing_module_but_not_itself() { let main = "import \"myapp:shapez\";\nimport \"myapp:mainn\";\nfn main() {}"; let project = write("guess", &[("src/main.peep", main), ("src/shapes.peep", "")]); - let program = load::(&project, &HashMap::::new()); + let program = load( + &project, + &HashMap::::new(), + &features::RULES, + ); let guesses: Vec<&str> = program .diagnostics .iter() @@ -452,7 +471,11 @@ fn reports_imports_at_their_line() { "line", &[("src/main.peep", "fn main() {}\nimport \"myapp:missing\";\n")], ); - let program = load::(&project, &HashMap::::new()); + let program = load( + &project, + &HashMap::::new(), + &features::RULES, + ); let main = module_named(&program, "myapp:main"); assert_eq!(program.diagnostics.len(), 1, "{:?}", messages(&program)); let label = &program.diagnostics[0].labels[0]; @@ -461,7 +484,7 @@ fn reports_imports_at_their_line() { /// Each place of the import cycles `program` found, as the importer's /// path and the place's message, then each note. -fn cycle_steps(program: &Program) -> Vec { +fn cycle_steps(program: &Program) -> Vec { let cycles = program.diagnostics.iter(); let cycles = cycles.filter(|d| d.code == diagnostics::CYCLIC_IMPORT); let steps = |d: &Diagnostic| { @@ -490,7 +513,11 @@ fn reports_a_cycle_with_each_import() { ("src/b.peep", r#"import "myapp:a";"#), ], ); - let program = load::(&project, &HashMap::::new()); + let program = load( + &project, + &HashMap::::new(), + &features::RULES, + ); assert_eq!( messages(&program), ["myapp:a: M0002 modules import each other in a cycle"] @@ -516,7 +543,11 @@ fn a_cycle_through_the_prelude_is_reported_once() { ("libs/core/src/x.peep", r#"import "core:global";"#), ], ); - let program = load::(&project, &HashMap::::new()); + let program = load( + &project, + &HashMap::::new(), + &features::RULES, + ); assert_eq!( cycle_steps(&program), [ @@ -537,7 +568,11 @@ fn a_cycle_through_the_implicit_prelude_import_notes_it() { ("libs/core/src/x.peep", "fn F() {}"), ], ); - let program = load::(&project, &HashMap::::new()); + let program = load( + &project, + &HashMap::::new(), + &features::RULES, + ); assert_eq!( cycle_steps(&program), [ @@ -556,7 +591,11 @@ fn redundant_prelude_import() { ("libs/core/src/global.peep", ""), ], ); - let program = load::(&project, &HashMap::::new()); + let program = load( + &project, + &HashMap::::new(), + &features::RULES, + ); assert_eq!( messages(&program), ["myapp:main: S0004 `core:global` is imported automatically"] @@ -578,7 +617,11 @@ fn a_single_file_cannot_import() { ], ); project.entry = Some(project.root.join("tool.peep")); - let program = load::(&project, &HashMap::::new()); + let program = load( + &project, + &HashMap::::new(), + &features::RULES, + ); assert_eq!( messages(&program), ["tool: M0003 a single file cannot import; check its project folder instead"] @@ -594,14 +637,22 @@ fn a_single_file_cannot_import() { fn unreadable_and_non_utf8_entries() { let mut project = write("unreadable", &[("src/bad.peep", "fn \u{0} main")]); std::fs::write(project.root.join("src/bad.peep"), b"fn \xff main() {}").unwrap(); - let program = load::(&project, &HashMap::::new()); + let program = load( + &project, + &HashMap::::new(), + &features::RULES, + ); let got = messages(&program); assert!( got.len() == 1 && got[0].starts_with("program: M0001 read module: "), "{got:?}" ); project.entry = Some(project.root.join("src/bad.peep")); - let program = load::(&project, &HashMap::::new()); + let program = load( + &project, + &HashMap::::new(), + &features::RULES, + ); assert_eq!( messages(&program), ["myapp:bad: L0001 file is not valid UTF-8"] @@ -627,7 +678,7 @@ fn orders_a_long_import_chain() { project.root.join("src/main.peep"), "import \"myapp:m0\";".to_string(), ); - let program = load::(&project, &open_files); + let program = load(&project, &open_files, &features::RULES); assert_eq!(messages(&program), Vec::::new()); assert_eq!(order(&program).last(), Some(&"myapp:main")); } @@ -652,7 +703,11 @@ fn loads_many_modules_in_a_stable_order() { .map(|(n, t)| (n.as_str(), t.as_str())) .collect(); let project = write("many", &files); - let first = load::(&project, &HashMap::::new()); + let first = load( + &project, + &HashMap::::new(), + &features::RULES, + ); assert!(messages(&first).is_empty()); assert_eq!(first.modules.len(), 202); for (index, module) in first.modules.iter().enumerate() { @@ -667,9 +722,10 @@ fn loads_many_modules_in_a_stable_order() { } for _ in 0..5 { assert_eq!( - order(&load::( + order(&load( &project, - &HashMap::::new() + &HashMap::::new(), + &features::RULES )), order(&first), "order differs between runs" @@ -693,7 +749,7 @@ fn open_files_win_over_disk() { ), (project.root.join("src/b.peep"), "fn B() {}".to_string()), // not on disk ]); - let program = load::(&project, &open_files); + let program = load(&project, &open_files, &features::RULES); assert_eq!(messages(&program), Vec::::new()); assert_eq!(module_named(&program, "myapp:b").ast.file.text, "fn B() {}"); } diff --git a/crates/features/src/arrays.rs b/crates/features/src/arrays.rs index 2a7438b4..f3e50417 100644 --- a/crates/features/src/arrays.rs +++ b/crates/features/src/arrays.rs @@ -6,7 +6,6 @@ //! core's `&`, and indexing. use arena::Id; -use arena::List; use check::Checker; use check::builder::ThirBuilder; use diagnostics::Diagnostic; @@ -19,58 +18,18 @@ use parser::expr::spreadable; use parser::expr::starts_expression; use source::Span; use syntax::ast; -use syntax::operators::Precedence; use token::Token; use token::TokenKind; -use crate::ExprNode; -use crate::FeatureExpr; -use crate::FeatureType; -use crate::Peeper; -use crate::TypeNode; - -/// `[length]element` -#[derive(Clone, Copy, Debug)] -pub struct ArrayType { - /// the written number - pub length: Span, - pub element: Id>, -} - -/// `[N]T{ entries }` or `[_]T{ entries }`; each entry is a value or a -/// `values...` spread. -#[derive(Clone, Copy, Debug)] -pub struct ArrayLiteral { - pub ty: LiteralType, - pub entries: List>, -} - -/// The type an array literal is written with. -#[derive(Clone, Copy, Debug)] -pub enum LiteralType { - /// `[N]T` - Written(Id>), - /// `[_]T`: its length is the number of values its entries give - Counted { element: Id> }, -} - -impl ArrayType { - /// Adds the rule that reads array types to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.type_start(TokenKind::LeftBracket, array_type); - } -} - -impl ArrayLiteral { - /// Adds the rule that reads array literals to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.prefix(TokenKind::LeftBracket, array_literal); - } +/// Adds the rules that read array types and array literals to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.type_start(TokenKind::LeftBracket, array_type); + rules.prefix(TokenKind::LeftBracket, array_literal); } /// Reads the `N]T` of `[N]T`, a type that starts at `start`, with its `[`; /// a `[]T` alone is reported, as it has no fixed size. -fn array_type(p: &mut Parser, start: u32) -> Id> { +fn array_type(p: &mut Parser, start: u32) -> Id { let open = Token { kind: TokenKind::LeftBracket, span: Span { @@ -118,7 +77,7 @@ fn array_type(p: &mut Parser, start: u32) -> Id> { let length = t.span; p.add( start, - ast::Type::Feature(FeatureType::Array(ArrayType { length, element })), + ast::Type::Feature(ast::FeatureType::Array(ast::ArrayType { length, element })), ) } @@ -126,14 +85,14 @@ fn array_type(p: &mut Parser, start: u32) -> Id> { /// values they give); an entry is a value, or `values...`, which spreads an /// array or a range: `(0..3)...` or `0..3...`. Without `{` after it, `[N]T` /// is the type alone. -fn array_literal(p: &mut Parser) -> Id> { +fn array_literal(p: &mut Parser) -> Id { let start = p.tok().span.start; let ty = if p.ahead(1).kind == TokenKind::Underscore { let open = p.next(); p.next(); p.close(TokenKind::RightBracket, open); let element = p.type_expr(); - LiteralType::Counted { element } + ast::ArrayLiteralType::Counted { element } } else { let ty = p.type_expr(); // Without entries `[N]T` is the type alone, as an argument that @@ -141,99 +100,93 @@ fn array_literal(p: &mut Parser) -> Id> { if !p.at(TokenKind::LeftBrace) { return p.add(start, ast::Expr::Type(ty)); } - LiteralType::Written(ty) + ast::ArrayLiteralType::Written(ty) }; let entries = p.delimited( TokenKind::LeftBrace, TokenKind::RightBrace, false, - starts_expression::, + starts_expression, spreadable, ); p.add( start, - ast::Expr::Feature(FeatureExpr::ArrayLiteral(ArrayLiteral { ty, entries })), + ast::Expr::Feature(ast::FeatureExpr::ArrayLiteral(ast::ArrayLiteral { + ty, + entries, + })), ) } -impl TypeNode for ArrayType { - fn element(&self) -> Option>> { - Some(self.element) - } +#[cfg(test)] +mod tests; - /// The type `[length]element`, written at `span`: the length is a whole - /// number without a suffix that an array can hold. - fn resolve(&self, checker: &mut Checker<'_, Peeper>, span: Span) -> TypeId { - let ArrayType { length, element } = *self; - let literal = literal::numeric::split(checker.module().ast.file.slice(length)); - let value = literal.integer_value(); - if !literal.suffix.is_empty() || literal.is_float() { - let message = "an array length is a whole number without a suffix"; - return checker.error(diagnostics::INVALID_TYPE, message, length); - } - if !checker.length_fits(&value, length) { - return TypeId::INVALID; - } - let element = checker.resolve_value_type(element); - checker.array_type(element, value[0], span) +/// The type `[length]element`, written at `span`: the length is a whole +/// number without a suffix that an array can hold. +pub(crate) fn resolve_array_type( + checker: &mut Checker<'_>, + ty: ast::ArrayType, + span: Span, +) -> TypeId { + let ast::ArrayType { length, element } = ty; + let literal = literal::numeric::split(checker.module().ast.file.slice(length)); + let value = literal.integer_value(); + if !literal.suffix.is_empty() || literal.is_float() { + let message = "an array length is a whole number without a suffix"; + return checker.error(diagnostics::INVALID_TYPE, message, length); } -} - -impl ExprNode for ArrayLiteral { - fn precedence(&self) -> Precedence { - Precedence::Call + if !checker.length_fits(&value, length) { + return TypeId::INVALID; } + let element = checker.resolve_value_type(element); + checker.array_type(element, value[0], span) +} - /// `[N]T{ entries }`, written at `span`, or `[_]T{ entries }`, whose - /// length is the number of values its entries give: each entry a `T`, or - /// a spread of a range, an array or a slice (`count_spread`). They must - /// give exactly its length. A slice, or a range whose count is not known - /// now, is counted when the program runs, so its literal needs a written - /// length, which the entries known now must not already pass. - fn check( - &self, - builder: &mut ThirBuilder<'_, '_, Peeper>, - span: Span, - _expected: Option, - ) -> thir::Expr { - let tree = &builder.checker.module().ast; - let (element, length, written) = match self.ty { - LiteralType::Counted { element } => { - // `[_]T`, from its `[` to its element's end - let written = Span { - start: span.start, - end: tree.types.span(element).end, - }; - (builder.checker.resolve_value_type(element), None, written) - } - LiteralType::Written(written) => { - let span = tree.types.span(written); - match builder.checker.resolve_value_type(written) { - ty if ty == TypeId::INVALID => (TypeId::INVALID, None, span), - ty => match builder.checker.types[ty] { - Type::Array { - element, length, .. - } => (element, Some((ty, length)), span), - _ => unreachable!("an array literal's written type is an array type"), - }, - } +/// `[N]T{ entries }`, written at `span`, or `[_]T{ entries }`, whose +/// length is the number of values its entries give: each entry a `T`, or +/// a spread of a range, an array or a slice (`count_spread`). They must +/// give exactly its length. A slice, or a range whose count is not known +/// now, is counted when the program runs, so its literal needs a written +/// length, which the entries known now must not already pass. +pub(crate) fn check_array_literal( + builder: &mut ThirBuilder<'_, '_>, + literal: ast::ArrayLiteral, + span: Span, +) -> thir::Expr { + let tree = &builder.checker.module().ast; + let (element, length, written) = match literal.ty { + ast::ArrayLiteralType::Counted { element } => { + // `[_]T`, from its `[` to its element's end + let written = Span { + start: span.start, + end: tree.types.span(element).end, + }; + (builder.checker.resolve_value_type(element), None, written) + } + ast::ArrayLiteralType::Written(written) => { + let span = tree.types.span(written); + match builder.checker.resolve_value_type(written) { + ty if ty == TypeId::INVALID => (TypeId::INVALID, None, span), + ty => match builder.checker.types[ty] { + Type::Array { + element, length, .. + } => (element, Some((ty, length)), span), + _ => unreachable!("an array literal's written type is an array type"), + }, } - }; - let entries = tree.children.lists.items(self.entries); - let (parts, known, later) = builder.check_entries(entries, element, None); - let Some(known) = known.filter(|_| element != TypeId::INVALID) else { - return thir::Expr::INVALID; - }; - let Some(ty) = builder.array_literal_type(written, element, length, (known, later), span) - else { - return thir::Expr::INVALID; - }; - thir::Expr { - ty, - kind: thir::ExprKind::ArrayLiteral(builder.body.children.lists.add(&parts)), } + }; + let entries = tree.children.lists.items(literal.entries); + let (parts, known, later) = builder.check_entries(entries, element, None); + let Some(known) = known.filter(|_| element != TypeId::INVALID) else { + return thir::Expr::INVALID; + }; + let Some(ty) = builder.array_literal_type(written, element, length, (known, later), span) + else { + return thir::Expr::INVALID; + }; + thir::Expr { + ty, + kind: thir::ExprKind::ArrayLiteral(builder.body.children.lists.add(&parts)), } } - -#[cfg(test)] -mod tests; diff --git a/crates/features/src/arrays/tests.rs b/crates/features/src/arrays/tests.rs index 117a2fa0..9f99e0d2 100644 --- a/crates/features/src/arrays/tests.rs +++ b/crates/features/src/arrays/tests.rs @@ -4,7 +4,6 @@ use arena::Id; use syntax::ast; -use super::*; use crate::testing::Tree; use crate::testing::bodies; use crate::testing::messages; @@ -14,9 +13,9 @@ use crate::testing::with_checker; /// The messages of the errors in `text`. /// The written type `ty` with `[N]` for each array, `&[]` for each slice /// and the innermost type's text. -fn shape(tree: &Tree, ty: Id>) -> String { +fn shape(tree: &Tree, ty: Id) -> String { match tree.types[ty] { - ast::Type::Feature(FeatureType::Array(ArrayType { length, element })) => { + ast::Type::Feature(ast::FeatureType::Array(ast::ArrayType { length, element })) => { format!("[{}]{}", tree.file.slice(length), shape(tree, element)) } ast::Type::Slice { element, .. } => format!("&[]{}", shape(tree, element)), @@ -48,10 +47,15 @@ fn parses_types_and_literals() { for id in tree.exprs.ids() { match tree.exprs[id] { ast::Expr::Type(ty) => literals.push(format!("type {}", shape(&tree, ty))), - ast::Expr::Feature(FeatureExpr::ArrayLiteral(ArrayLiteral { ty, entries })) => { + ast::Expr::Feature(ast::FeatureExpr::ArrayLiteral(ast::ArrayLiteral { + ty, + entries, + })) => { let ty = match ty { - LiteralType::Written(ty) => shape(&tree, ty), - LiteralType::Counted { element } => format!("[_]{}", shape(&tree, element)), + ast::ArrayLiteralType::Written(ty) => shape(&tree, ty), + ast::ArrayLiteralType::Counted { element } => { + format!("[_]{}", shape(&tree, element)) + } }; let entries: Vec<&str> = (tree.children.lists.items(entries)) .map(|entry| match tree.exprs[entry] { diff --git a/crates/features/src/chars.rs b/crates/features/src/chars.rs index e68d9101..a1f51fe4 100644 --- a/crates/features/src/chars.rs +++ b/crates/features/src/chars.rs @@ -3,59 +3,38 @@ use arena::Id; use check::builder::ThirBuilder; -use model::semantic_types::TypeId; use model::thir; use parser::Parser; use parser::Rules; use source::Span; use syntax::ast; -use syntax::operators::Precedence; use token::TokenKind; -use crate::ExprNode; -use crate::FeatureExpr; -use crate::Peeper; - -/// `'x'`, or `b'x'` when `byte` -#[derive(Clone, Copy, Debug)] -pub struct CharLiteral { - pub byte: bool, -} - -impl CharLiteral { - /// Adds the rules that read character literals to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.prefix(TokenKind::Char, char_literal); - rules.prefix(TokenKind::ByteChar, char_literal); - } +/// Adds the rules that read character literals to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.prefix(TokenKind::Char, char_literal); + rules.prefix(TokenKind::ByteChar, char_literal); } /// Reads `'x'` or `b'x'`. -fn char_literal(p: &mut Parser) -> Id> { +fn char_literal(p: &mut Parser) -> Id { let token = p.next(); let byte = token.kind == TokenKind::ByteChar; p.add( token.span.start, - ast::Expr::Feature(FeatureExpr::Char(CharLiteral { byte })), + ast::Expr::Feature(ast::FeatureExpr::Char(ast::CharLiteral { byte })), ) } -impl ExprNode for CharLiteral { - fn precedence(&self) -> Precedence { - Precedence::Call - } - - /// A character literal at `span`, which no check exists for yet. - fn check( - &self, - builder: &mut ThirBuilder<'_, '_, Peeper>, - span: Span, - _expected: Option, - ) -> thir::Expr { - builder.checker.not_supported(span, "character literals"); - thir::Expr::INVALID - } -} - #[cfg(test)] mod tests; + +/// A character literal at `span`, which no check exists for yet. +pub(crate) fn check_char_literal( + builder: &mut ThirBuilder<'_, '_>, + _literal: ast::CharLiteral, + span: Span, +) -> thir::Expr { + builder.checker.not_supported(span, "character literals"); + thir::Expr::INVALID +} diff --git a/crates/features/src/chars/tests.rs b/crates/features/src/chars/tests.rs index 17bc02fe..a6298df0 100644 --- a/crates/features/src/chars/tests.rs +++ b/crates/features/src/chars/tests.rs @@ -2,7 +2,6 @@ use syntax::ast; -use super::*; use crate::testing::bodies; use crate::testing::parse_text; @@ -13,7 +12,7 @@ fn parses_literals() { assert!(errors.is_empty(), "{errors:?}"); let literals: Vec<(bool, &str)> = (tree.exprs.ids()) .filter_map(|id| match tree.exprs[id] { - ast::Expr::Feature(FeatureExpr::Char(CharLiteral { byte })) => { + ast::Expr::Feature(ast::FeatureExpr::Char(ast::CharLiteral { byte })) => { Some((byte, tree.file.slice(tree.exprs.span(id)))) } _ => None, diff --git a/crates/features/src/enums.rs b/crates/features/src/enums.rs index 27194fc7..07d9cee5 100644 --- a/crates/features/src/enums.rs +++ b/crates/features/src/enums.rs @@ -2,7 +2,6 @@ //! literal (`Enum::Case with payload`), a case test (`x is Enum::Case`) and //! `match`. All are read, and refused by the checker until enums exist. -use model::DefId; use std::num::NonZeroU32; use arena::Id; @@ -21,78 +20,24 @@ use syntax::ast; use syntax::operators::Precedence; use token::TokenKind; -use crate::ExprNode; -use crate::FeatureExpr; -use crate::FeatureStmt; -use crate::FeatureType; -use crate::Peeper; -use crate::StmtNode; -use crate::TypeNode; - -/// `enum { variants }` -#[derive(Clone, Copy, Debug)] -pub struct EnumType { - pub variants: List>, -} - -/// `Enum::Variant with payload`; the case is a `Type::Path` -#[derive(Clone, Copy, Debug)] -pub struct VariantLiteral { - pub case: Id>, - pub payload: Id>, -} - -/// `value is Enum::Variant` -#[derive(Clone, Copy, Debug)] -pub struct CaseTest { - pub value: Id>, - pub case: Id>, -} - -/// `match subject { arms }` -#[derive(Clone, Copy, Debug)] -pub struct Match { - pub subject: Id>, - pub arms: List>, -} - -impl EnumType { - /// Adds the rules that read enum types and declarations to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.declaration(TokenKind::Enum, type_decl); - rules.type_start(TokenKind::Enum, enum_type); - } -} - -impl VariantLiteral { - /// Adds the rule that reads variant literals to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.infix(TokenKind::With, Precedence::Call, variant_literal); - } -} - -impl CaseTest { - /// Adds the rule that reads `is` tests to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.infix(TokenKind::Is, Precedence::Equality, case_test); - } -} - -impl Match { - /// Adds the rule that reads `match` to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.statement(TokenKind::Match, match_statement); - } +/// Adds the rules that read enum types and declarations, variant +/// literals, `is` tests and `match` to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.declaration(TokenKind::Enum, type_decl); + rules.type_start(TokenKind::Enum, enum_type); + rules.infix(TokenKind::With, Precedence::Call, variant_literal); + rules.infix(TokenKind::Is, Precedence::Equality, case_test); + rules.statement(TokenKind::Match, match_statement); } /// Reads `{ Name, Name: Payload, ... }`, the variants of an enum type that /// starts at `start`. -fn enum_type(p: &mut Parser, start: u32) -> Id> { +fn enum_type(p: &mut Parser, start: u32) -> Id { let variants = p.delimited( TokenKind::LeftBrace, TokenKind::RightBrace, true, - is_name, + |_, kind| is_name(kind), |p| { let start = p.tok().span.start; let name = p.name(); @@ -103,13 +48,13 @@ fn enum_type(p: &mut Parser, start: u32) -> Id> { p.add(start, ast::Variant { name, payload }) }, ); - let ty = FeatureType::Enum(EnumType { variants }); + let ty = ast::FeatureType::Enum(ast::EnumType { variants }); p.add(start, ast::Type::Feature(ty)) } /// Reports `case` unless it is a full path `Enum::Case` (or a type already /// reported as invalid). -fn require_path(p: &mut Parser, case: Id>) { +fn require_path(p: &mut Parser, case: Id) { if !matches!(p.tree.types[case], ast::Type::Path(_) | ast::Type::Invalid) { let span = p.tree.types.span(case); p.repair( @@ -123,7 +68,7 @@ fn require_path(p: &mut Parser, case: Id>) { } /// Reads `with payload` after `case`, which is a full path `Enum::Case`. -fn variant_literal(p: &mut Parser, case: Id>) -> Id> { +fn variant_literal(p: &mut Parser, case: Id) -> Id { p.next(); let payload = p.expr(Precedence::Lowest); let path = match p.tree.exprs[case] { @@ -140,7 +85,7 @@ fn variant_literal(p: &mut Parser, case: Id>) -> Id, case: Id>) -> Id, value: Id>) -> Id> { +fn case_test(p: &mut Parser, value: Id) -> Id { p.next(); let case = p.type_expr(); require_path(p, case); - let test = FeatureExpr::CaseTest(CaseTest { value, case }); + let test = ast::FeatureExpr::CaseTest(ast::CaseTest { value, case }); p.add(p.start_of(value), ast::Expr::Feature(test)) } /// Reads `match subject { arms }`. An arm is `_ => { }`, `Enum::Case => { }` /// or `Enum::Case with pattern => { }`; arms are not separated by commas. -fn match_statement(p: &mut Parser) -> Id> { +fn match_statement(p: &mut Parser) -> Id { let start = p.next().span.start; let subject = p.expr(Precedence::Lowest); let mut arms = List::EMPTY; @@ -184,13 +129,13 @@ fn match_statement(p: &mut Parser) -> Id> { arms = p.tree.children.lists.add(&read); p.close(TokenKind::RightBrace, open); } - let statement = FeatureStmt::Match(Match { subject, arms }); + let statement = ast::FeatureStmt::Match(ast::Match { subject, arms }); p.add(start, ast::Stmt::Feature(statement)) } /// Reads one arm's pattern, its `=>` and its block. A missing `=>` before /// the block is read as if it were there. -fn match_arm(p: &mut Parser) -> (Id>, Id>) { +fn match_arm(p: &mut Parser) -> (Id, Id) { let t = p.tok(); let pattern = if t.kind == TokenKind::Underscore { let start = p.next().span.start; @@ -217,7 +162,7 @@ fn match_arm(p: &mut Parser) -> (Id>, Id) -> Id> { +fn case_pattern(p: &mut Parser) -> Id { // Cases in cases, `A::B with C::D with ...`, are a deep recursion. source::grow_stack(|| { let start = p.tok().span.start; @@ -233,7 +178,7 @@ fn case_pattern(p: &mut Parser) -> Id> { /// Reads the pattern after `with`: `none`, `_`, a name to bind, /// `.{ fields }`, or another case. -fn payload_pattern(p: &mut Parser) -> Id> { +fn payload_pattern(p: &mut Parser) -> Id { let t = p.tok(); match t.kind { TokenKind::None => { @@ -267,66 +212,54 @@ fn payload_pattern(p: &mut Parser) -> Id> { } } -impl TypeNode for EnumType { - /// An enum type at `span`, which no check exists for yet. - fn resolve(&self, checker: &mut Checker<'_, Peeper>, span: Span) -> TypeId { - checker.not_supported(span, "enum types") - } +#[cfg(test)] +mod tests; - /// The declaration of an enum, written `written`, which no check exists - /// for yet. - fn declare( - &self, - checker: &mut Checker<'_, Peeper>, - _definition: DefId, - written: ast::TypeDecl, - ) -> TypeId { - checker.not_supported(written.name.span, "enum declarations") - } +/// An enum type at `span`, which no check exists for yet. +pub(crate) fn resolve_enum_type( + checker: &mut Checker<'_>, + _ty: ast::EnumType, + span: Span, +) -> TypeId { + checker.not_supported(span, "enum types") } -impl ExprNode for VariantLiteral { - // Ends in an expression read at the lowest precedence. - fn precedence(&self) -> Precedence { - Precedence::Lowest - } - - /// Variant literals, at `span`, which no check exists for yet. - fn check( - &self, - builder: &mut ThirBuilder<'_, '_, Peeper>, - span: Span, - _expected: Option, - ) -> thir::Expr { - builder.checker.not_supported(span, "variant literals"); - thir::Expr::INVALID - } +/// The declaration of an enum, written `written`, which no check exists +/// for yet. +pub(crate) fn declare_enum_type( + checker: &mut Checker<'_>, + _ty: ast::EnumType, + written: ast::TypeDecl, +) -> TypeId { + checker.not_supported(written.name.span, "enum declarations") } -impl ExprNode for CaseTest { - fn precedence(&self) -> Precedence { - Precedence::Equality - } - - /// `is` tests, at `span`, which no check exists for yet. - fn check( - &self, - builder: &mut ThirBuilder<'_, '_, Peeper>, - span: Span, - _expected: Option, - ) -> thir::Expr { - builder.checker.not_supported(span, "`is` tests"); - thir::Expr::INVALID - } +/// Variant literals, at `span`, which no check exists for yet. +pub(crate) fn check_variant_literal( + builder: &mut ThirBuilder<'_, '_>, + _literal: ast::VariantLiteral, + span: Span, +) -> thir::Expr { + builder.checker.not_supported(span, "variant literals"); + thir::Expr::INVALID } -impl StmtNode for Match { - /// A `match` at `span`, which no check exists for yet. - fn check(&self, builder: &mut ThirBuilder<'_, '_, Peeper>, span: Span) -> Option { - builder.checker.not_supported(span, "`match` statements"); - None - } +/// `is` tests, at `span`, which no check exists for yet. +pub(crate) fn check_case_test( + builder: &mut ThirBuilder<'_, '_>, + _test: ast::CaseTest, + span: Span, +) -> thir::Expr { + builder.checker.not_supported(span, "`is` tests"); + thir::Expr::INVALID } -#[cfg(test)] -mod tests; +/// A `match` at `span`, which no check exists for yet. +pub(crate) fn check_match( + builder: &mut ThirBuilder<'_, '_>, + _statement: ast::Match, + span: Span, +) -> Option { + builder.checker.not_supported(span, "`match` statements"); + None +} diff --git a/crates/features/src/enums/tests.rs b/crates/features/src/enums/tests.rs index e367c3ed..d36faaef 100644 --- a/crates/features/src/enums/tests.rs +++ b/crates/features/src/enums/tests.rs @@ -3,7 +3,6 @@ use arena::Id; use syntax::ast; -use super::*; use crate::testing::Tree; use crate::testing::bodies; use crate::testing::messages; @@ -12,7 +11,7 @@ use crate::testing::statements; /// The pattern `pattern` as written, a case's payload pattern in /// parentheses. -fn shape(tree: &Tree, pattern: Id>) -> String { +fn shape(tree: &Tree, pattern: Id) -> String { match tree.patterns[pattern] { ast::Pattern::Case { case, inner } => { let case = tree.file.slice(tree.types.span(case)); @@ -39,7 +38,8 @@ fn parses_declarations() { let ast::Decl::Type(declared) = tree.decls[decl] else { panic!("not a type declaration") }; - let ast::Type::Feature(FeatureType::Enum(EnumType { variants })) = tree.types[declared.ty] + let ast::Type::Feature(ast::FeatureType::Enum(ast::EnumType { variants })) = + tree.types[declared.ty] else { panic!("not an enum") }; @@ -72,7 +72,7 @@ fn parses_expressions() { assert!(errors.is_empty(), "{errors:?}"); let found = statements(&tree); let text = |span| tree.file.slice(span); - let ast::Expr::Feature(FeatureExpr::VariantLiteral(literal)) = tree.exprs[found[0]] else { + let ast::Expr::Feature(ast::FeatureExpr::VariantLiteral(literal)) = tree.exprs[found[0]] else { panic!("not a variant literal: {:?}", tree.exprs[found[0]]) }; assert_eq!(text(tree.types.span(literal.case)), "Shape::Line"); @@ -80,7 +80,7 @@ fn parses_expressions() { let ast::Expr::Binary { left, .. } = tree.exprs[found[1]] else { panic!("not a binary operation: {:?}", tree.exprs[found[1]]) }; - let ast::Expr::Feature(FeatureExpr::CaseTest(test)) = tree.exprs[left] else { + let ast::Expr::Feature(ast::FeatureExpr::CaseTest(test)) = tree.exprs[left] else { panic!("not a case test: {:?}", tree.exprs[left]) }; assert_eq!(text(tree.exprs.span(test.value)), "a"); @@ -106,7 +106,7 @@ fn parses_matches() { assert!(errors.is_empty(), "{errors:?}"); let arms = (tree.stmts.ids()) .find_map(|id| match tree.stmts[id] { - ast::Stmt::Feature(FeatureStmt::Match(Match { arms, .. })) => Some(arms), + ast::Stmt::Feature(ast::FeatureStmt::Match(ast::Match { arms, .. })) => Some(arms), _ => None, }) .unwrap(); diff --git a/crates/features/src/interfaces.rs b/crates/features/src/interfaces.rs index 1cec2aee..bec0b842 100644 --- a/crates/features/src/interfaces.rs +++ b/crates/features/src/interfaces.rs @@ -4,7 +4,6 @@ //! struct to an interface are the core's: they read the checked type. use arena::Id; -use arena::List; use check::Checker; use check::functions; use check::scope::report_redeclared; @@ -18,33 +17,21 @@ use source::Span; use syntax::ast; use token::TokenKind; -use crate::FeatureType; -use crate::Peeper; -use crate::TypeNode; - -/// `iface { methods }`: `Decl::Function`s without bodies. -#[derive(Clone, Copy, Debug)] -pub struct InterfaceType { - pub methods: List>, -} - -impl InterfaceType { - /// Adds the rules that read interfaces to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.declaration(TokenKind::Iface, type_decl); - rules.type_start(TokenKind::Iface, interface_type); - } +/// Adds the rules that read interfaces to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.declaration(TokenKind::Iface, type_decl); + rules.type_start(TokenKind::Iface, interface_type); } /// Reads `{ fn name(parameters) -> Result, ... }`, the methods of an /// interface type that starts at `start`: function signatures without /// bodies. A method takes no default values. -fn interface_type(p: &mut Parser, start: u32) -> Id> { +fn interface_type(p: &mut Parser, start: u32) -> Id { let methods = p.delimited( TokenKind::LeftBrace, TokenKind::RightBrace, true, - |kind| kind == TokenKind::Fn, + |_, kind| kind == TokenKind::Fn, |p| { let start = p.next().span.start; let (name, signature) = p.named_signature(); @@ -62,74 +49,70 @@ fn interface_type(p: &mut Parser, start: u32) -> Id> { ); p.add( start, - ast::Type::Feature(FeatureType::Interface(InterfaceType { methods })), + ast::Type::Feature(ast::FeatureType::Interface(ast::InterfaceType { methods })), ) } -impl TypeNode for InterfaceType { - fn methods(&self) -> Option>> { - Some(self.methods) - } +#[cfg(test)] +mod tests; - /// The type an interface type written at `span` names: none yet, as only a - /// declared interface is checked. - fn resolve(&self, checker: &mut Checker<'_, Peeper>, span: Span) -> TypeId { - checker.not_supported(span, "interface types") - } +/// The type an interface type written at `span` names: none yet, as only a +/// declared interface is checked. +pub(crate) fn resolve_interface_type( + checker: &mut Checker<'_>, + _ty: ast::InterfaceType, + span: Span, +) -> TypeId { + checker.not_supported(span, "interface types") +} - /// The type the module's interface declaration `definition` declares: - /// each method's function type, whose `self` is a reference to the - /// interface (`Type::InterfaceReference`), or the interface taken whole. - /// Invalid when a method has an error or is declared twice, as a struct - /// is when a field has an error. - fn declare( - &self, - checker: &mut Checker<'_, Peeper>, - definition: DefId, - _written: ast::TypeDecl, - ) -> TypeId { - let modules = checker.modules; - let tree = &modules[definition.module.index()].ast; - let declared: Vec<&ast::Function> = - model::program::interface_methods(modules, definition) - .expect("an interface declaration has methods") - .collect(); - let mut methods = Vec::with_capacity(declared.len()); - for (index, method) in declared.iter().enumerate() { - let text = method.name.text(&tree.file); - // An interface has few methods, so the ones before are searched. - if let Some(first) = declared[..index] - .iter() - .find(|first| first.name.text(&tree.file) == text) - { - let diagnostic = report_redeclared( - &tree.file, - text, - "interface", - method.name.span, - first.name.span, - ); - checker.report(diagnostic); - methods.push(TypeId::INVALID); - continue; - } - let kind = &functions::FunctionKind::INTERFACE_METHOD; - methods.push(checker.signature_type(method.name, method.signature, true, kind)); +/// The type the module's interface declaration `definition` declares: +/// each method's function type, whose `self` is a reference to the +/// interface (`Type::InterfaceReference`), or the interface taken whole. +/// Invalid when a method has an error or is declared twice, as a struct +/// is when a field has an error. +pub(crate) fn declare_interface_type( + checker: &mut Checker<'_>, + _ty: ast::InterfaceType, + definition: DefId, +) -> TypeId { + let modules = checker.modules; + let tree = &modules[definition.module.index()].ast; + let declared: Vec<&ast::Function> = model::program::interface_methods(modules, definition) + .expect("an interface declaration has methods") + .collect(); + let mut methods = Vec::with_capacity(declared.len()); + for (index, method) in declared.iter().enumerate() { + let text = method.name.text(&tree.file); + // An interface has few methods, so the ones before are searched. + if let Some(first) = declared[..index] + .iter() + .find(|first| first.name.text(&tree.file) == text) + { + let diagnostic = report_redeclared( + &tree.file, + text, + "interface", + method.name.span, + first.name.span, + ); + checker.report(diagnostic); + methods.push(TypeId::INVALID); + continue; } - let invalid = |ty: TypeId| match &checker.types[ty] { - Type::Function { - parameters, result, .. - } => parameters.contains(&TypeId::INVALID) || *result == TypeId::INVALID, - _ => true, - }; - if methods.iter().any(|&method| invalid(method)) { - return TypeId::INVALID; - } - let named = checker.declared_name(definition); - checker.types.define_interface(named, methods.into()); - named + let kind = &functions::FunctionKind::INTERFACE_METHOD; + methods.push(checker.signature_type(method.name, method.signature, true, kind)); + } + let invalid = |ty: TypeId| match &checker.types[ty] { + Type::Function { + parameters, result, .. + } => parameters.contains(&TypeId::INVALID) || *result == TypeId::INVALID, + _ => true, + }; + if methods.iter().any(|&method| invalid(method)) { + return TypeId::INVALID; } + let named = checker.declared_name(definition); + checker.types.define_interface(named, methods.into()); + named } - -#[cfg(test)] -mod tests; diff --git a/crates/features/src/interfaces/tests.rs b/crates/features/src/interfaces/tests.rs index f80802a8..78343099 100644 --- a/crates/features/src/interfaces/tests.rs +++ b/crates/features/src/interfaces/tests.rs @@ -4,12 +4,11 @@ use arena::Id; use syntax::ast; -use super::*; use crate::testing::Tree; use crate::testing::parse_text; /// The written type `ty` in short: `&self`, `&mut self`, or its text. -fn written_type(tree: &Tree, ty: Id>) -> String { +fn written_type(tree: &Tree, ty: Id) -> String { match tree.types[ty] { ast::Type::Reference { mutable, target } if matches!(tree.types[target], ast::Type::Owner) => @@ -21,8 +20,9 @@ fn written_type(tree: &Tree, ty: Id>) -> String { } /// Each method of the interface type `ty` as `name(name: type, ...) -> result`. -fn methods(tree: &Tree, ty: Id>) -> Vec { - let ast::Type::Feature(FeatureType::Interface(InterfaceType { methods })) = tree.types[ty] +fn methods(tree: &Tree, ty: Id) -> Vec { + let ast::Type::Feature(ast::FeatureType::Interface(ast::InterfaceType { methods })) = + tree.types[ty] else { panic!("not an interface type: {:?}", tree.types[ty]) }; diff --git a/crates/features/src/lib.rs b/crates/features/src/lib.rs index 3b6248ad..674b20bc 100644 --- a/crates/features/src/lib.rs +++ b/crates/features/src/lib.rs @@ -1,240 +1,135 @@ -//! Peeper: the core and the list of its features (docs/feature-front.md, -//! section 7). This is the one place that names every feature: a phase -//! sees only `L`, and asks this list through `Language`, `Grammar` and -//! `Checked`. Each node is listed once (`nodes!`); a feature answers for -//! its own nodes, in its own file (`ExprNode`, `StmtNode`, `TypeNode`). +//! Peeper's features, one file each: a feature reads its own nodes (the +//! tree's `FeatureExpr`, `FeatureStmt` and `FeatureType`) and checks them. +//! This is the one place that names every feature: its parse rules +//! (`RULES`) and how the checker checks its nodes (`CHECK_HOOKS`), which +//! the driver hands to the phases (docs/structure-mapping.md, step 7). -use arena::Id; -use arena::List; -use check::Checked; +use check::CheckHooks; use check::Checker; -use check::builder::ThirBuilder; +use check::builder; use model::DefId; -use model::semantic_types::TypeId; +use model::semantic_types; use model::thir; -use parser::Grammar; use parser::Rules; use source::Span; use syntax::ast; -use syntax::ast::Language; -use syntax::ast::WrittenRange; -use syntax::operators::Precedence; -pub mod arrays; -pub mod chars; -pub mod enums; -pub mod interfaces; -pub mod optionals; -pub mod pipes; -pub mod printing; -pub mod ranges; -pub mod raw_pointers; -pub mod structs; +mod arrays; +mod chars; +mod enums; +mod interfaces; +mod optionals; +mod pipes; +mod printing; +mod ranges; +mod raw_pointers; +mod structs; #[cfg(test)] mod testing; -/// The language this compiler compiles. -#[derive(Clone, Copy, Debug)] -pub enum Peeper {} - -/// What a feature says of an expression of its own, in its own file. -pub(crate) trait ExprNode { - /// The precedence the expression has where it is an operand. - fn precedence(&self) -> Precedence; - - /// The range it writes, if it is one. - fn written_range(&self) -> Option> { - None - } - - /// The expression, written at `span`, checked; `expected` is the type - /// its place asks for. - fn check( - &self, - builder: &mut ThirBuilder<'_, '_, Peeper>, - span: Span, - expected: Option, - ) -> thir::Expr; -} - -/// What a feature says of a statement of its own, in its own file. -pub(crate) trait StmtNode { - /// The statement, written at `span`, checked; `None` after an error. - fn check(&self, builder: &mut ThirBuilder<'_, '_, Peeper>, span: Span) -> Option; -} - -/// What a feature says of a written type of its own, in its own file. -pub(crate) trait TypeNode { - /// Its fields, if it has fields. - fn fields(&self) -> Option>> { - None - } - - /// Its methods, if it declares methods. - fn methods(&self) -> Option>> { - None - } - - /// The type it points to, if it is a pointer to one. - fn pointee(&self) -> Option>> { - None - } - - /// The type of its elements, if it has elements. - fn element(&self) -> Option>> { - None - } - - /// The type it names, written at `span`. - fn resolve(&self, checker: &mut Checker<'_, Peeper>, span: Span) -> TypeId; - - /// The type that `definition`, written `written`, declares with it. - fn declare( - &self, - _checker: &mut Checker<'_, Peeper>, - _definition: DefId, - _written: ast::TypeDecl, - ) -> TypeId { - unreachable!("only `struct`, `iface` and `enum` begin a type declaration") - } -} - -/// Declares `$name`, the nodes of one kind with a variant per listed node; -/// its `node`, which gives a node as what its feature says of it; and its -/// `rows`, the parse rules of every node. -macro_rules! nodes { - ($(#[$doc:meta])* $name:ident: $says:ident { $($variant:ident($node:ty)),* $(,)? }) => { - $(#[$doc])* - #[derive(Clone, Copy, Debug)] - pub enum $name { - $($variant($node)),* - } - - impl $name { - /// The node, to ask what its feature says of it. - fn node(&self) -> &dyn $says { - match self { - $($name::$variant(node) => node),* - } - } - - /// Adds the rules that read each node to `rules`. - const fn rows(rules: &mut Rules) { - $(<$node>::rows(rules);)* - } - } - }; -} - -nodes! { - /// An expression of a feature's, by feature. - FeatureExpr: ExprNode { - ArrayLiteral(arrays::ArrayLiteral), - CaseTest(enums::CaseTest), - Char(chars::CharLiteral), - OrElse(optionals::OrElse), - Pipe(pipes::Pipe), - Print(printing::Print), - Range(ranges::Range), - RawAddress(raw_pointers::RawAddress), - StructLiteral(structs::StructLiteral), - VariantLiteral(enums::VariantLiteral), - } -} - -nodes! { - /// A statement of a feature's, by feature. - FeatureStmt: StmtNode { - Match(enums::Match), - } -} - -nodes! { - /// A written type of a feature's, by feature. - FeatureType: TypeNode { - Array(arrays::ArrayType), - Enum(enums::EnumType), - Interface(interfaces::InterfaceType), - Optional(optionals::OptionalType), - Pointer(raw_pointers::PointerType), - Struct(structs::StructType), - } -} - /// Built once, when the compiler is: two rules for one token fail the build. -static RULES: Rules = { +pub static RULES: Rules = { let mut rules = Rules::core(); - FeatureExpr::rows(&mut rules); - FeatureStmt::rows(&mut rules); - FeatureType::rows(&mut rules); + arrays::rows(&mut rules); + chars::rows(&mut rules); + enums::rows(&mut rules); + interfaces::rows(&mut rules); + optionals::rows(&mut rules); + pipes::rows(&mut rules); + printing::rows(&mut rules); + ranges::rows(&mut rules); + raw_pointers::rows(&mut rules); + structs::rows(&mut rules); rules }; -impl Language for Peeper { - type Expr = FeatureExpr; - type Type = FeatureType; - type Stmt = FeatureStmt; - - fn precedence(expr: &FeatureExpr) -> Precedence { - expr.node().precedence() - } - - fn written_range(expr: &FeatureExpr) -> Option> { - expr.node().written_range() - } - - fn fields(ty: &FeatureType) -> Option>> { - ty.node().fields() - } - - fn methods(ty: &FeatureType) -> Option>> { - ty.node().methods() - } - - fn pointee(ty: &FeatureType) -> Option>> { - ty.node().pointee() - } +/// How the checker checks each feature's nodes: by its feature's file. +pub static CHECK_HOOKS: CheckHooks = CheckHooks { + check_expr, + check_stmt, + resolve_type, + declare_type, +}; - fn element(ty: &FeatureType) -> Option>> { - ty.node().element() +/// The feature expression `expr`, written at `span`, where a value of the +/// type `expected` is wanted, if one is. +fn check_expr( + builder: &mut builder::ThirBuilder<'_, '_>, + expr: ast::FeatureExpr, + span: Span, + expected: Option, +) -> thir::Expr { + match expr { + ast::FeatureExpr::ArrayLiteral(literal) => { + arrays::check_array_literal(builder, literal, span) + } + ast::FeatureExpr::CaseTest(test) => enums::check_case_test(builder, test, span), + ast::FeatureExpr::Char(literal) => chars::check_char_literal(builder, literal, span), + ast::FeatureExpr::OrElse(or_else) => optionals::check_or_else(builder, or_else, span), + ast::FeatureExpr::Pipe(pipe) => pipes::check_pipe(builder, pipe, span), + ast::FeatureExpr::Print(print) => printing::check_print(builder, print, span), + ast::FeatureExpr::Range(range) => ranges::check_range(builder, range, span, expected), + ast::FeatureExpr::RawAddress(address) => { + raw_pointers::check_raw_address(builder, address, span) + } + ast::FeatureExpr::StructLiteral(literal) => { + structs::check_struct_literal(builder, literal, span, expected) + } + ast::FeatureExpr::VariantLiteral(literal) => { + enums::check_variant_literal(builder, literal, span) + } } } -impl Grammar for Peeper { - fn rules() -> &'static Rules { - &RULES +/// The feature statement `stmt`, written at `span`; `None` when it leaves +/// no statement, after an error. +fn check_stmt( + builder: &mut builder::ThirBuilder<'_, '_>, + stmt: ast::FeatureStmt, + span: Span, +) -> Option { + match stmt { + ast::FeatureStmt::Match(statement) => enums::check_match(builder, statement, span), } } -impl Checked for Peeper { - fn check_expr( - builder: &mut ThirBuilder<'_, '_, Peeper>, - expr: FeatureExpr, - span: Span, - expected: Option, - ) -> thir::Expr { - expr.node().check(builder, span, expected) - } - - fn check_stmt( - builder: &mut ThirBuilder<'_, '_, Peeper>, - stmt: FeatureStmt, - span: Span, - ) -> Option { - stmt.node().check(builder, span) - } - - fn resolve_type(checker: &mut Checker<'_, Peeper>, ty: FeatureType, span: Span) -> TypeId { - ty.node().resolve(checker, span) +/// The type the feature type `ty`, written at `span`, names. +fn resolve_type( + checker: &mut Checker<'_>, + ty: ast::FeatureType, + span: Span, +) -> semantic_types::TypeId { + match ty { + ast::FeatureType::Array(ty) => arrays::resolve_array_type(checker, ty, span), + ast::FeatureType::Enum(ty) => enums::resolve_enum_type(checker, ty, span), + ast::FeatureType::Interface(ty) => interfaces::resolve_interface_type(checker, ty, span), + ast::FeatureType::Optional(ty) => optionals::resolve_optional_type(checker, ty, span), + ast::FeatureType::Pointer(ty) => raw_pointers::resolve_pointer_type(checker, ty, span), + ast::FeatureType::Struct(ty) => structs::resolve_struct_type(checker, ty, span), } +} - fn declare_type( - checker: &mut Checker<'_, Peeper>, - definition: DefId, - written: ast::TypeDecl, - ty: FeatureType, - ) -> TypeId { - ty.node().declare(checker, definition, written) +/// The type the module's type declaration `definition`, written `written`, +/// declares with the feature type `ty`. +fn declare_type( + checker: &mut Checker<'_>, + definition: DefId, + written: ast::TypeDecl, + ty: ast::FeatureType, +) -> semantic_types::TypeId { + match ty { + ast::FeatureType::Enum(ty) => enums::declare_enum_type(checker, ty, written), + ast::FeatureType::Interface(ty) => { + interfaces::declare_interface_type(checker, ty, definition) + } + ast::FeatureType::Struct(ty) => { + structs::declare_struct_type(checker, ty, definition, written) + } + ast::FeatureType::Array(_) + | ast::FeatureType::Optional(_) + | ast::FeatureType::Pointer(_) => { + unreachable!("only `struct`, `iface` and `enum` begin a type declaration") + } } } diff --git a/crates/features/src/optionals.rs b/crates/features/src/optionals.rs index 8b2bc406..e518e3bd 100644 --- a/crates/features/src/optionals.rs +++ b/crates/features/src/optionals.rs @@ -13,101 +13,61 @@ use syntax::ast; use syntax::operators::Precedence; use token::TokenKind; -use crate::ExprNode; -use crate::FeatureExpr; -use crate::FeatureType; -use crate::Peeper; -use crate::TypeNode; - -/// `?T` -#[derive(Clone, Copy, Debug)] -pub struct OptionalType { - pub inner: Id>, -} - -/// `value orelse fallback` -#[derive(Clone, Copy, Debug)] -pub struct OrElse { - pub value: Id>, - pub fallback: Fallback, -} - -/// What `orelse` gives when its value is missing. -#[derive(Clone, Copy, Debug)] -pub enum Fallback { - Value(Id>), - Block(Id>), -} - -impl OptionalType { - /// Adds the rules that read optional types to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.type_start(TokenKind::Question, optional_type); - rules.type_start(TokenKind::QuestionQuestion, doubled_optional_type); - } -} - -impl OrElse { - /// Adds the rule that reads `orelse` to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.infix(TokenKind::Orelse, Precedence::OrElse, or_else); - } +/// Adds the rules that read optional types and `orelse` to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.type_start(TokenKind::Question, optional_type); + rules.type_start(TokenKind::QuestionQuestion, doubled_optional_type); + rules.infix(TokenKind::Orelse, Precedence::OrElse, or_else); } /// Reads the type after a `?` that starts at `start`. -fn optional_type(p: &mut Parser, start: u32) -> Id> { +fn optional_type(p: &mut Parser, start: u32) -> Id { let inner = p.type_expr(); - let optional = FeatureType::Optional(OptionalType { inner }); + let optional = ast::FeatureType::Optional(ast::OptionalType { inner }); p.add(start, ast::Type::Feature(optional)) } /// Reads the type after a `??`, one token holding two markers. The second /// changes nothing (`??T` is `?T`); it is kept in the tree as written and /// left to a lint to report. -fn doubled_optional_type(p: &mut Parser, start: u32) -> Id> { +fn doubled_optional_type(p: &mut Parser, start: u32) -> Id { let inner = optional_type(p, start + 1); - let optional = FeatureType::Optional(OptionalType { inner }); + let optional = ast::FeatureType::Optional(ast::OptionalType { inner }); p.add(start, ast::Type::Feature(optional)) } /// Reads `orelse fallback` or `orelse { block }` after `value`. The fallback /// may itself end in `orelse`: a orelse b orelse c is a orelse (b orelse c). -fn or_else(p: &mut Parser, value: Id>) -> Id> { +fn or_else(p: &mut Parser, value: Id) -> Id { p.next(); let fallback = if p.at(TokenKind::LeftBrace) { - Fallback::Block(p.block()) + ast::OrElseFallback::Block(p.block()) } else { // One below OrElse: groups to the right. - Fallback::Value(p.expr(Precedence::Lowest)) + ast::OrElseFallback::Value(p.expr(Precedence::Lowest)) }; - let or_else = FeatureExpr::OrElse(OrElse { value, fallback }); + let or_else = ast::FeatureExpr::OrElse(ast::OrElse { value, fallback }); p.add(p.start_of(value), ast::Expr::Feature(or_else)) } -impl TypeNode for OptionalType { - /// `?T` at `span`, which no check exists for yet. - fn resolve(&self, checker: &mut Checker<'_, Peeper>, span: Span) -> TypeId { - checker.not_supported(span, "optional types") - } -} - -impl ExprNode for OrElse { - // `orelse` ends in an expression read at the lowest precedence. - fn precedence(&self) -> Precedence { - Precedence::Lowest - } +#[cfg(test)] +mod tests; - /// `value orelse fallback` at `span`, which no check exists for yet. - fn check( - &self, - builder: &mut ThirBuilder<'_, '_, Peeper>, - span: Span, - _expected: Option, - ) -> thir::Expr { - builder.checker.not_supported(span, "`orelse` fallbacks"); - thir::Expr::INVALID - } +/// `?T` at `span`, which no check exists for yet. +pub(crate) fn resolve_optional_type( + checker: &mut Checker<'_>, + _ty: ast::OptionalType, + span: Span, +) -> TypeId { + checker.not_supported(span, "optional types") } -#[cfg(test)] -mod tests; +/// `value orelse fallback` at `span`, which no check exists for yet. +pub(crate) fn check_or_else( + builder: &mut ThirBuilder<'_, '_>, + _or_else: ast::OrElse, + span: Span, +) -> thir::Expr { + builder.checker.not_supported(span, "`orelse` fallbacks"); + thir::Expr::INVALID +} diff --git a/crates/features/src/optionals/tests.rs b/crates/features/src/optionals/tests.rs index d67a3795..40cca7bd 100644 --- a/crates/features/src/optionals/tests.rs +++ b/crates/features/src/optionals/tests.rs @@ -3,7 +3,6 @@ use arena::Id; use syntax::ast; -use super::*; use crate::testing::Tree; use crate::testing::bodies; use crate::testing::messages; @@ -11,12 +10,12 @@ use crate::testing::parse_text; use crate::testing::statements; /// `expr` with each `orelse` in parentheses; a block fallback as `{}`. -fn grouped(tree: &Tree, expr: Id>) -> String { +fn grouped(tree: &Tree, expr: Id) -> String { match tree.exprs[expr] { - ast::Expr::Feature(FeatureExpr::OrElse(OrElse { value, fallback })) => { + ast::Expr::Feature(ast::FeatureExpr::OrElse(ast::OrElse { value, fallback })) => { let fallback = match fallback { - Fallback::Value(fallback) => grouped(tree, fallback), - Fallback::Block(_) => "{}".to_string(), + ast::OrElseFallback::Value(fallback) => grouped(tree, fallback), + ast::OrElseFallback::Block(_) => "{}".to_string(), }; format!("({} orelse {fallback})", grouped(tree, value)) } @@ -46,7 +45,12 @@ fn parses_or_else() { ); // The last one is a range whose end is the `orelse`. let last = (tree.exprs.ids()) - .filter(|&id| matches!(tree.exprs[id], ast::Expr::Feature(FeatureExpr::OrElse(_)))) + .filter(|&id| { + matches!( + tree.exprs[id], + ast::Expr::Feature(ast::FeatureExpr::OrElse(_)) + ) + }) .last() .unwrap(); assert_eq!(tree.file.slice(tree.exprs.span(last)), "h orelse i"); @@ -59,7 +63,12 @@ fn parses_types() { let (tree, errors) = parse_text("fn f(a: ?i32, b: ??i32, c: ? ??u8);"); assert!(errors.is_empty(), "{errors:?}"); let optionals = (tree.types.ids()) - .filter(|&id| matches!(tree.types[id], ast::Type::Feature(FeatureType::Optional(_)))) + .filter(|&id| { + matches!( + tree.types[id], + ast::Type::Feature(ast::FeatureType::Optional(_)) + ) + }) .map(|id| tree.file.slice(tree.types.span(id))) .collect::>(); assert_eq!(optionals.len(), 6, "{optionals:?}"); diff --git a/crates/features/src/pipes.rs b/crates/features/src/pipes.rs index 6e2b8a03..87fc7c1f 100644 --- a/crates/features/src/pipes.rs +++ b/crates/features/src/pipes.rs @@ -2,7 +2,6 @@ use arena::Id; use check::builder::ThirBuilder; -use model::semantic_types::TypeId; use model::thir; use parser::Parser; use parser::Rules; @@ -11,69 +10,48 @@ use syntax::ast; use syntax::operators::Precedence; use token::TokenKind; -use crate::ExprNode; -use crate::FeatureExpr; -use crate::Peeper; - -/// `value |> target`, as written -#[derive(Clone, Copy, Debug)] -pub struct Pipe { - pub value: Id>, - pub target: Id>, -} - -impl Pipe { - /// Adds the rule that reads pipes to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.infix(TokenKind::PipeArrow, Precedence::Pipe, pipe); - } +/// Adds the rule that reads pipes to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.infix(TokenKind::PipeArrow, Precedence::Pipe, pipe); } /// Reads `|> target` after `value`. The target takes only what binds /// tighter than a prefix operator, so `a |> len() as i32` is /// (a |> len()) as i32. -fn pipe(p: &mut Parser, value: Id>) -> Id> { +fn pipe(p: &mut Parser, value: Id) -> Id { p.next(); let target = p.expr(Precedence::Prefix); - let pipe = FeatureExpr::Pipe(Pipe { value, target }); + let pipe = ast::FeatureExpr::Pipe(ast::Pipe { value, target }); p.add(p.start_of(value), ast::Expr::Feature(pipe)) } -impl ExprNode for Pipe { - // A pipe reads its target at prefix precedence. - fn precedence(&self) -> Precedence { - Precedence::Prefix - } - - /// `value |> target` at `span`: its target must be a call, which is checked - /// with the value as its first written argument, so a method takes it after - /// its `self`. - fn check( - &self, - builder: &mut ThirBuilder<'_, '_, Peeper>, - span: Span, - _expected: Option, - ) -> thir::Expr { - let tree = &builder.checker.module().ast; - let ast::Expr::Call { - callee, - type_arguments, - arguments, - } = tree.exprs[self.target] - else { - let target = tree.exprs.span(self.target); - let message = "a pipe's target must be a call"; - builder - .checker - .error(diagnostics::INVALID_OPERATION, message, target); - builder.add_expr(self.value, None); // for its own errors - return thir::Expr::INVALID; - }; - let mut given = vec![self.value]; - given.extend(tree.children.lists.items(arguments)); - builder.check_call(callee, type_arguments, &given, span) - } -} - #[cfg(test)] mod tests; + +/// `value |> target` at `span`: its target must be a call, which is checked +/// with the value as its first written argument, so a method takes it after +/// its `self`. +pub(crate) fn check_pipe( + builder: &mut ThirBuilder<'_, '_>, + pipe: ast::Pipe, + span: Span, +) -> thir::Expr { + let tree = &builder.checker.module().ast; + let ast::Expr::Call { + callee, + type_arguments, + arguments, + } = tree.exprs[pipe.target] + else { + let target = tree.exprs.span(pipe.target); + let message = "a pipe's target must be a call"; + builder + .checker + .error(diagnostics::INVALID_OPERATION, message, target); + builder.add_expr(pipe.value, None); // for its own errors + return thir::Expr::INVALID; + }; + let mut given = vec![pipe.value]; + given.extend(tree.children.lists.items(arguments)); + builder.check_call(callee, type_arguments, &given, span) +} diff --git a/crates/features/src/pipes/tests.rs b/crates/features/src/pipes/tests.rs index 3698a6cc..0be712dc 100644 --- a/crates/features/src/pipes/tests.rs +++ b/crates/features/src/pipes/tests.rs @@ -3,16 +3,15 @@ use arena::Id; use syntax::ast; -use super::*; use crate::testing::Tree; use crate::testing::bodies; use crate::testing::parse_text; use crate::testing::statements; /// `expr` with each pipe in parentheses. -fn grouped(tree: &Tree, expr: Id>) -> String { +fn grouped(tree: &Tree, expr: Id) -> String { match tree.exprs[expr] { - ast::Expr::Feature(FeatureExpr::Pipe(Pipe { value, target })) => { + ast::Expr::Feature(ast::FeatureExpr::Pipe(ast::Pipe { value, target })) => { format!("({} |> {})", grouped(tree, value), grouped(tree, target)) } _ => tree.file.slice(tree.exprs.span(expr)).to_string(), @@ -35,7 +34,12 @@ fn parses_pipes() { ["((a |> f(b)) |> g())", "(a + b |> f())", "(a |> b)"] ); let last = (tree.exprs.ids()) - .filter(|&id| matches!(tree.exprs[id], ast::Expr::Feature(FeatureExpr::Pipe(_)))) + .filter(|&id| { + matches!( + tree.exprs[id], + ast::Expr::Feature(ast::FeatureExpr::Pipe(_)) + ) + }) .last() .unwrap(); assert_eq!(tree.file.slice(tree.exprs.span(last)), "c |> len()"); diff --git a/crates/features/src/printing.rs b/crates/features/src/printing.rs index d863d9ac..a5475d3b 100644 --- a/crates/features/src/printing.rs +++ b/crates/features/src/printing.rs @@ -5,7 +5,6 @@ use source::Span; use std::num::NonZeroU32; use arena::Id; -use arena::List; use bigint::Limbs; use check::builder::ThirBuilder; use model::Callee; @@ -27,36 +26,23 @@ use syntax::ast; use syntax::operators::Precedence; use token::TokenKind; -use crate::ExprNode; -use crate::FeatureExpr; -use crate::Peeper; - -/// `print(values)`, or `println(values)` when `newline` -#[derive(Clone, Copy, Debug)] -pub struct Print { - pub newline: bool, - pub values: List>, -} - -impl Print { - /// Adds the rules that read `print` and `println` to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.prefix(TokenKind::Print, print); - rules.prefix(TokenKind::Println, print); - } +/// Adds the rules that read `print` and `println` to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.prefix(TokenKind::Print, print); + rules.prefix(TokenKind::Println, print); } /// Reads `print(values)` or `println(values)`, which take any number of /// values. -fn print(p: &mut Parser) -> Id> { +fn print(p: &mut Parser) -> Id { let keyword = p.next(); - let print = FeatureExpr::Print(Print { + let print = ast::FeatureExpr::Print(ast::Print { newline: keyword.kind == TokenKind::Println, values: p.delimited( TokenKind::LeftParen, TokenKind::RightParen, false, - starts_expression::, + starts_expression, |p| p.expr(Precedence::Lowest), ), }); @@ -68,96 +54,11 @@ fn print(p: &mut Parser) -> Id> { /// literal is printed as a `&cstr`, though it is not one anywhere else. // shortcut: a built-in until a library function takes any number of // values of any printable type; then delete it. -impl ExprNode for Print { - fn precedence(&self) -> Precedence { - Precedence::Call - } - - /// A block of calls of the prelude's print functions, one for each - /// value by its type, then one that writes out what they kept back. - fn check( - &self, - builder: &mut ThirBuilder<'_, '_, Peeper>, - span: Span, - _expected: Option, - ) -> thir::Expr { - let Print { newline, values } = *self; - let tree = &builder.checker.module().ast; - let mut checked = Vec::with_capacity(values.len()); - for value in tree.children.lists.items(values) { - let span = tree.exprs.span(value); - let expr = builder.check_expr(value, None); - let ty = expr.ty; - let types = &builder.checker.types; - // On an error the others are still checked, for their own. - if !printable(types, ty) { - if ty != TypeId::INVALID { - let message = format!("`{}` cannot be printed", builder.checker.type_text(ty)); - (builder.checker).error(diagnostics::INVALID_OPERATION, message, span); - } - continue; - } - let mut printed = builder.body.add(expr, span); - // Printing reads a value, never takes it: a `&mut` reference in - // a place, the one printable value that moves, is lent as `&`. - if let Type::Reference { - mutable: true, - target, - } = types[ty] - && builder - .start_variable(builder.place_root(printed).0) - .is_some() - { - let reference = builder.body.exprs[printed].clone(); - let shared = builder.checker.reference_type(false, target); - let lent = builder.reborrow(reference, span, shared); - printed = builder.body.add(lent, span); - } - checked.push(printed); - } - if checked.len() < values.len() { - return thir::Expr::INVALID; - } - let mut written = None; - let block = builder.add_block(span, |builder| { - let mut statements = Vec::new(); - // Every value is worked out, in order, before any is written: - // a value's code may print too, and a reference among them is - // in use until it is written. So each is kept in a hidden - // variable; one value alone, or a constant, is as good as it is. - let alone = checked.len() == 1; - for value in &mut checked { - let thir::Expr { ty, kind } = &builder.body.exprs[*value]; - if matches!(kind, thir::ExprKind::Constant(_)) { - continue; - } - // An integer is kept even alone, as the runtime reads it: - // from memory, which must not be the program's own variable. - if let Type::Integer(integer) = builder.checker.types[*ty] { - *value = widened(builder, *value, integer); - } else if alone { - continue; - } - *value = kept(builder, &mut statements, *value, span); - } - written = print_values(builder, &mut statements, &checked, newline, span); - statements - }); - if written.is_none() { - return thir::Expr::INVALID; // reported - } - thir::Expr { - ty: TypeId::VOID, - kind: thir::ExprKind::Block(block), - } - } -} - /// The calls that print `values`, a space between each, then a newline /// when `newline`, then the one that writes out what they kept back, added /// to `statements`. `None` at the first that cannot be made, reported. fn print_values( - builder: &mut ThirBuilder<'_, '_, Peeper>, + builder: &mut ThirBuilder<'_, '_>, statements: &mut Vec>, values: &[Id], newline: bool, @@ -179,7 +80,7 @@ fn print_values( /// The calls that print `value`, added to `statements`; `None` when one /// cannot be made, reported. fn print_value( - builder: &mut ThirBuilder<'_, '_, Peeper>, + builder: &mut ThirBuilder<'_, '_>, statements: &mut Vec>, mut value: Id, span: Span, @@ -194,7 +95,7 @@ fn print_value( ty: TypeId::I32, kind: thir::ExprKind::Constant(Value::Integer(Limbs::new(32, &[u64::from(value)]))), }; - let read = |builder: &ThirBuilder<'_, '_, Peeper>| builder.body.exprs[value].clone(); + let read = |builder: &ThirBuilder<'_, '_>| builder.body.exprs[value].clone(); match builder.checker.types[ty] { // The runtime reads an integer from memory (`widened`): where it // is kept or referred to, else a temporary. @@ -275,7 +176,7 @@ fn print_value( /// every target, all little-endian. So it is widened to a multiple of 64 /// bits. fn widened( - builder: &mut ThirBuilder<'_, '_, Peeper>, + builder: &mut ThirBuilder<'_, '_>, value: Id, integer: Integer, ) -> Id { @@ -297,7 +198,7 @@ fn widened( /// A hidden variable set to `value` by a statement added to `statements`. fn kept( - builder: &mut ThirBuilder<'_, '_, Peeper>, + builder: &mut ThirBuilder<'_, '_>, statements: &mut Vec>, value: Id, span: Span, @@ -318,7 +219,7 @@ fn kept( /// The statement that prints `text` (`library_call`). fn print_text( - builder: &mut ThirBuilder<'_, '_, Peeper>, + builder: &mut ThirBuilder<'_, '_>, text: &[u8], span: Span, ) -> Option> { @@ -334,7 +235,7 @@ fn print_text( /// it with a parameter of each argument's type and no result, or when its /// declaration has an error, reported there. fn library_call( - builder: &mut ThirBuilder<'_, '_, Peeper>, + builder: &mut ThirBuilder<'_, '_>, name: &str, arguments: Vec, span: Span, @@ -410,3 +311,81 @@ fn printable(types: &Types, mut ty: TypeId) -> bool { #[cfg(test)] mod tests; + +/// A block of calls of the prelude's print functions, one for each +/// value by its type, then one that writes out what they kept back. +pub(crate) fn check_print( + builder: &mut ThirBuilder<'_, '_>, + print: ast::Print, + span: Span, +) -> thir::Expr { + let ast::Print { newline, values } = print; + let tree = &builder.checker.module().ast; + let mut checked = Vec::with_capacity(values.len()); + for value in tree.children.lists.items(values) { + let span = tree.exprs.span(value); + let expr = builder.check_expr(value, None); + let ty = expr.ty; + let types = &builder.checker.types; + // On an error the others are still checked, for their own. + if !printable(types, ty) { + if ty != TypeId::INVALID { + let message = format!("`{}` cannot be printed", builder.checker.type_text(ty)); + (builder.checker).error(diagnostics::INVALID_OPERATION, message, span); + } + continue; + } + let mut printed = builder.body.add(expr, span); + // Printing reads a value, never takes it: a `&mut` reference in + // a place, the one printable value that moves, is lent as `&`. + if let Type::Reference { + mutable: true, + target, + } = types[ty] + && builder + .start_variable(builder.place_root(printed).0) + .is_some() + { + let reference = builder.body.exprs[printed].clone(); + let shared = builder.checker.reference_type(false, target); + let lent = builder.reborrow(reference, span, shared); + printed = builder.body.add(lent, span); + } + checked.push(printed); + } + if checked.len() < values.len() { + return thir::Expr::INVALID; + } + let mut written = None; + let block = builder.add_block(span, |builder| { + let mut statements = Vec::new(); + // Every value is worked out, in order, before any is written: + // a value's code may print too, and a reference among them is + // in use until it is written. So each is kept in a hidden + // variable; one value alone, or a constant, is as good as it is. + let alone = checked.len() == 1; + for value in &mut checked { + let thir::Expr { ty, kind } = &builder.body.exprs[*value]; + if matches!(kind, thir::ExprKind::Constant(_)) { + continue; + } + // An integer is kept even alone, as the runtime reads it: + // from memory, which must not be the program's own variable. + if let Type::Integer(integer) = builder.checker.types[*ty] { + *value = widened(builder, *value, integer); + } else if alone { + continue; + } + *value = kept(builder, &mut statements, *value, span); + } + written = print_values(builder, &mut statements, &checked, newline, span); + statements + }); + if written.is_none() { + return thir::Expr::INVALID; // reported + } + thir::Expr { + ty: TypeId::VOID, + kind: thir::ExprKind::Block(block), + } +} diff --git a/crates/features/src/printing/tests.rs b/crates/features/src/printing/tests.rs index 7bd1b3e1..f5cf31bc 100644 --- a/crates/features/src/printing/tests.rs +++ b/crates/features/src/printing/tests.rs @@ -3,7 +3,6 @@ use syntax::ast; -use super::*; use crate::testing::messages; use crate::testing::parse_text; @@ -15,7 +14,7 @@ fn parses_prints() { assert!(errors.is_empty(), "{errors:?}"); let prints: Vec<(bool, usize)> = (tree.exprs.ids()) .filter_map(|id| match tree.exprs[id] { - ast::Expr::Feature(FeatureExpr::Print(Print { newline, values })) => { + ast::Expr::Feature(ast::FeatureExpr::Print(ast::Print { newline, values })) => { Some((newline, values.len())) } _ => None, diff --git a/crates/features/src/ranges.rs b/crates/features/src/ranges.rs index cda666d4..16f781f7 100644 --- a/crates/features/src/ranges.rs +++ b/crates/features/src/ranges.rs @@ -1,6 +1,6 @@ //! Ranges: `a..b`, `a..=b`, `a..b:step`, and `..b` or `a..` before a `]`. //! The written parts are the core's `WrittenRange`, as slicing reads them -//! (`Language::written_range`); this file reads them and checks a range +//! (`Tree::written_range`); this file reads them and checks a range //! value into the core's `range[T]`, so the phases after it know nothing of //! them. @@ -20,45 +20,28 @@ use syntax::ast::WrittenRange; use syntax::operators::Precedence; use token::TokenKind; -use crate::ExprNode; -use crate::FeatureExpr; -use crate::Peeper; - -/// A range, as written: its parts are the core's, which slicing and loops -/// read (`Language::written_range`). -#[derive(Clone, Copy, Debug)] -pub struct Range { - pub written: WrittenRange, -} - -impl Range { - /// Adds the rules that read ranges to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.prefix(TokenKind::DotDot, open_range); - rules.prefix(TokenKind::DotDotEqual, open_range); - rules.infix(TokenKind::DotDot, Precedence::Range, range); - rules.infix(TokenKind::DotDotEqual, Precedence::Range, range); - } +/// Adds the rules that read ranges to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.prefix(TokenKind::DotDot, open_range); + rules.prefix(TokenKind::DotDotEqual, open_range); + rules.infix(TokenKind::DotDot, Precedence::Range, range); + rules.infix(TokenKind::DotDotEqual, Precedence::Range, range); } /// Reads a range with no start: `..b`, `..=b`, or `..` before `]`. -fn open_range(p: &mut Parser) -> Id> { +fn open_range(p: &mut Parser) -> Id { let start = p.tok().span.start; range_from(p, start, None) } /// Reads a range from `low`: `a..b`, `a..=b`, or `a..` before `]`. -fn range(p: &mut Parser, low: Id>) -> Id> { +fn range(p: &mut Parser, low: Id) -> Id { range_from(p, p.start_of(low), Some(low)) } /// Reads `..` or `..=` and what follows it: an end, then `:step` to step by /// more than one. Only right before the `]` may a range leave out its end. -fn range_from( - p: &mut Parser, - start: u32, - low: Option>>, -) -> Id> { +fn range_from(p: &mut Parser, start: u32, low: Option>) -> Id { let op = p.next(); let mut high = None; if !p.at(TokenKind::RightBracket) { @@ -90,78 +73,17 @@ fn range_from( }; p.add( start, - ast::Expr::Feature(FeatureExpr::Range(Range { written })), + ast::Expr::Feature(ast::FeatureExpr::Range(ast::Range { written })), ) } -impl ExprNode for Range { - fn precedence(&self) -> Precedence { - Precedence::Range - } - - fn written_range(&self) -> Option> { - Some(self.written) - } - - /// The range `start..end`, or `..=`, stepping by `start..end:step`, at - /// `span`: a `range[T]` of its ends' integer type `T`. A literal end - /// without a suffix takes the other end's type, or `T` when a - /// `range[T]` is `expected`; the step is of the range type's step type - /// and not a constant zero (`check_range_step`). A range without both - /// ends is not supported yet. - fn check( - &self, - builder: &mut ThirBuilder<'_, '_, Peeper>, - span: Span, - expected: Option, - ) -> thir::Expr { - let WrittenRange { - inclusive, - start: Some(start), - end: Some(end), - step, - } = self.written - else { - builder - .checker - .not_supported(span, "ranges without both ends"); - return thir::Expr::INVALID; - }; - let hint = expected.and_then(|ty| match builder.checker.types[ty] { - Type::Range { element, .. } => Some(element), - _ => None, - }); - let (start, end) = builder.check_range_ends(start, end, hint); - let ty = builder - .checker - .range_type(builder.body.exprs[start].ty, span); - let step_type = match builder.checker.types[ty] { - Type::Range { step, .. } => step, - _ => TypeId::INVALID, - }; - let step = check_range_step(builder, step, step_type, span); - if ty == TypeId::INVALID { - return thir::Expr::INVALID; - } - thir::Expr { - ty, - kind: thir::ExprKind::Range { - start, - end, - step, - inclusive, - }, - } - } -} - /// The step of a range, written `step` or else 1 at `range_span`, of /// the range type's step type `step_type` (`Types::range`), and not a /// constant zero. With an invalid `step_type`, after an error in the /// ends, it is checked only for its own errors. fn check_range_step( - builder: &mut ThirBuilder<'_, '_, Peeper>, - step: Option>>, + builder: &mut ThirBuilder<'_, '_>, + step: Option>, step_type: TypeId, range_span: Span, ) -> Id { @@ -193,3 +115,54 @@ fn check_range_step( #[cfg(test)] mod tests; + +/// The range `start..end`, or `..=`, stepping by `start..end:step`, at +/// `span`: a `range[T]` of its ends' integer type `T`. A literal end +/// without a suffix takes the other end's type, or `T` when a +/// `range[T]` is `expected`; the step is of the range type's step type +/// and not a constant zero (`check_range_step`). A range without both +/// ends is not supported yet. +pub(crate) fn check_range( + builder: &mut ThirBuilder<'_, '_>, + range: ast::Range, + span: Span, + expected: Option, +) -> thir::Expr { + let WrittenRange { + inclusive, + start: Some(start), + end: Some(end), + step, + } = range.written + else { + builder + .checker + .not_supported(span, "ranges without both ends"); + return thir::Expr::INVALID; + }; + let hint = expected.and_then(|ty| match builder.checker.types[ty] { + Type::Range { element, .. } => Some(element), + _ => None, + }); + let (start, end) = builder.check_range_ends(start, end, hint); + let ty = builder + .checker + .range_type(builder.body.exprs[start].ty, span); + let step_type = match builder.checker.types[ty] { + Type::Range { step, .. } => step, + _ => TypeId::INVALID, + }; + let step = check_range_step(builder, step, step_type, span); + if ty == TypeId::INVALID { + return thir::Expr::INVALID; + } + thir::Expr { + ty, + kind: thir::ExprKind::Range { + start, + end, + step, + inclusive, + }, + } +} diff --git a/crates/features/src/ranges/tests.rs b/crates/features/src/ranges/tests.rs index fa4693f3..26f5ab14 100644 --- a/crates/features/src/ranges/tests.rs +++ b/crates/features/src/ranges/tests.rs @@ -5,24 +5,23 @@ use arena::Id; use syntax::ast; use syntax::ast::WrittenRange; -use super::*; use crate::testing::Tree; use crate::testing::bodies; use crate::testing::parse_text; /// The expression `id` with each range and binary operation in /// parentheses, and the rest as written. -fn grouped(tree: &Tree, id: Id>) -> String { +fn grouped(tree: &Tree, id: Id) -> String { let text = |span| tree.file.slice(span).to_string(); match tree.exprs[id] { - ast::Expr::Feature(FeatureExpr::Range(Range { written })) => { + ast::Expr::Feature(ast::FeatureExpr::Range(ast::Range { written })) => { let WrittenRange { inclusive, start, end, step, } = written; - let part = |part: Option>>| { + let part = |part: Option>| { part.map_or(String::new(), |part| grouped(tree, part)) }; let op = if inclusive { "..=" } else { ".." }; diff --git a/crates/features/src/raw_pointers.rs b/crates/features/src/raw_pointers.rs index eaab2e84..8051916e 100644 --- a/crates/features/src/raw_pointers.rs +++ b/crates/features/src/raw_pointers.rs @@ -17,119 +17,83 @@ use syntax::ast; use syntax::operators::Precedence; use token::TokenKind; -use crate::ExprNode; -use crate::FeatureExpr; -use crate::FeatureType; -use crate::Peeper; -use crate::TypeNode; - -/// `*T`, or `rawptr` without a `target` -#[derive(Clone, Copy, Debug)] -pub struct PointerType { - pub target: Option>>, -} - -/// `@place` -#[derive(Clone, Copy, Debug)] -pub struct RawAddress { - pub place: Id>, -} - -impl PointerType { - /// Adds the rules that read raw pointer types to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.type_start(TokenKind::Asterisk, typed_pointer); - rules.type_start(TokenKind::Rawptr, raw_pointer); - // types that cannot be values - rules.prefix(TokenKind::Asterisk, type_value); - rules.prefix(TokenKind::Rawptr, type_value); - } -} - -impl RawAddress { - /// Adds the rule that reads `@place` to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.prefix(TokenKind::At, raw_address); - } +/// Adds the rules that read raw pointer types and `@place` to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.type_start(TokenKind::Asterisk, typed_pointer); + rules.type_start(TokenKind::Rawptr, raw_pointer); + // types that cannot be values + rules.prefix(TokenKind::Asterisk, type_value); + rules.prefix(TokenKind::Rawptr, type_value); + rules.prefix(TokenKind::At, raw_address); } /// Reads the `T` of `*T`, a pointer type that starts at `start`. -fn typed_pointer(p: &mut Parser, start: u32) -> Id> { +fn typed_pointer(p: &mut Parser, start: u32) -> Id { let target = Some(p.type_expr()); p.add( start, - ast::Type::Feature(FeatureType::Pointer(PointerType { target })), + ast::Type::Feature(ast::FeatureType::Pointer(ast::PointerType { target })), ) } /// `rawptr`, which starts at `start`. -fn raw_pointer(p: &mut Parser, start: u32) -> Id> { +fn raw_pointer(p: &mut Parser, start: u32) -> Id { p.add( start, - ast::Type::Feature(FeatureType::Pointer(PointerType { target: None })), + ast::Type::Feature(ast::FeatureType::Pointer(ast::PointerType { target: None })), ) } /// Reads a type that cannot be a value (`*T`, `rawptr`) where a value could /// go. -fn type_value(p: &mut Parser) -> Id> { +fn type_value(p: &mut Parser) -> Id { let start = p.tok().span.start; let ty = p.type_expr(); p.add(start, ast::Expr::Type(ty)) } /// Reads `@x`. -fn raw_address(p: &mut Parser) -> Id> { +fn raw_address(p: &mut Parser) -> Id { let start = p.next().span.start; let place = p.expr(Precedence::Prefix); p.add( start, - ast::Expr::Feature(FeatureExpr::RawAddress(RawAddress { place })), + ast::Expr::Feature(ast::FeatureExpr::RawAddress(ast::RawAddress { place })), ) } -impl TypeNode for PointerType { - fn pointee(&self) -> Option>> { - self.target - } +#[cfg(test)] +mod tests; - /// The type `rawptr`, or `*target`, written at `span`. - fn resolve(&self, checker: &mut Checker<'_, Peeper>, span: Span) -> TypeId { - let Some(target) = self.target else { - return TypeId::RAWPTR; - }; - // A pointer only names its target, so a struct can point to itself. - // shortcut: `*[2]Node` or `*Alias` of `Node` in `Node` is a cycle, as - // an array's element and an alias's target are complete, and so is - // any cycle through such a pointer; let them stay names too if a - // program needs it. - let pointee = checker.resolve_type(target); - match checker.written_pointer_target(pointee, span) { - Some(target) => checker.types.intern(Type::RawPointer { - target: Some(target), - }), - None => TypeId::INVALID, - } +/// The type `rawptr`, or `*target`, written at `span`. +pub(crate) fn resolve_pointer_type( + checker: &mut Checker<'_>, + ty: ast::PointerType, + span: Span, +) -> TypeId { + let Some(target) = ty.target else { + return TypeId::RAWPTR; + }; + // A pointer only names its target, so a struct can point to itself. + // shortcut: `*[2]Node` or `*Alias` of `Node` in `Node` is a cycle, as + // an array's element and an alias's target are complete, and so is + // any cycle through such a pointer; let them stay names too if a + // program needs it. + let pointee = checker.resolve_type(target); + match checker.written_pointer_target(pointee, span) { + Some(target) => checker.types.intern(Type::RawPointer { + target: Some(target), + }), + None => TypeId::INVALID, } } -impl ExprNode for RawAddress { - // `@` reads its place at prefix precedence. - fn precedence(&self) -> Precedence { - Precedence::Prefix - } - - /// `@place`, written at `span`. - fn check( - &self, - builder: &mut ThirBuilder<'_, '_, Peeper>, - span: Span, - _expected: Option, - ) -> thir::Expr { - let place = builder.add_expr(self.place, None); - builder.check_address(place, span) - } +/// `@place`, written at `span`. +pub(crate) fn check_raw_address( + builder: &mut ThirBuilder<'_, '_>, + address: ast::RawAddress, + span: Span, +) -> thir::Expr { + let place = builder.add_expr(address.place, None); + builder.check_address(place, span) } - -#[cfg(test)] -mod tests; diff --git a/crates/features/src/raw_pointers/tests.rs b/crates/features/src/raw_pointers/tests.rs index 7ffa69f0..2703b07d 100644 --- a/crates/features/src/raw_pointers/tests.rs +++ b/crates/features/src/raw_pointers/tests.rs @@ -4,19 +4,18 @@ use arena::Id; use syntax::ast; -use super::*; use crate::testing::Tree; use crate::testing::parse_text; use crate::testing::statements; /// The written type `ty` as `*` for each pointer to a pointer, then /// `rawptr` or the innermost type's text. -fn shape(tree: &Tree, ty: Id>) -> String { +fn shape(tree: &Tree, ty: Id) -> String { match tree.types[ty] { - ast::Type::Feature(FeatureType::Pointer(PointerType { + ast::Type::Feature(ast::FeatureType::Pointer(ast::PointerType { target: Some(target), })) => format!("*{}", shape(tree, target)), - ast::Type::Feature(FeatureType::Pointer(PointerType { target: None })) => { + ast::Type::Feature(ast::FeatureType::Pointer(ast::PointerType { target: None })) => { "rawptr".to_string() } ast::Type::Reference { target, .. } => format!("&{}", shape(tree, target)), @@ -64,7 +63,8 @@ fn parses_expressions() { }) .collect(); assert_eq!(types, ["*Node", "rawptr"]); - let ast::Expr::Feature(FeatureExpr::RawAddress(RawAddress { place })) = tree.exprs[found[1]] + let ast::Expr::Feature(ast::FeatureExpr::RawAddress(ast::RawAddress { place })) = + tree.exprs[found[1]] else { panic!("not a raw address: {:?}", tree.exprs[found[1]]) }; diff --git a/crates/features/src/structs.rs b/crates/features/src/structs.rs index ae9ecea6..0d661055 100644 --- a/crates/features/src/structs.rs +++ b/crates/features/src/structs.rs @@ -5,7 +5,6 @@ //! in `point.x`. use arena::Id; -use arena::List; use check::Checker; use check::builder::ThirBuilder; use check::scope::report_redeclared; @@ -25,49 +24,23 @@ use syntax::ast; use syntax::operators::Precedence; use token::TokenKind; -use crate::ExprNode; -use crate::FeatureExpr; -use crate::FeatureType; -use crate::Peeper; -use crate::TypeNode; - -/// `Type.{ name = value }`, or `.{ ... }` without a type -#[derive(Clone, Copy, Debug)] -pub struct StructLiteral { - pub ty: Option>>, - pub fields: List>, -} - -/// `struct { fields }` -#[derive(Clone, Copy, Debug)] -pub struct StructType { - pub fields: List>, -} - -impl StructType { - /// Adds the rules that read struct types and declarations to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.declaration(TokenKind::Struct, type_decl); - rules.type_start(TokenKind::Struct, struct_type); - } -} - -impl StructLiteral { - /// Adds the rules that read struct literals to `rules`. - pub(crate) const fn rows(rules: &mut Rules) { - rules.prefix(TokenKind::Dot, anonymous_literal); - rules.after_path(TokenKind::Dot, TokenKind::LeftBrace, typed_literal); - } +/// Adds the rules that read struct types, declarations and literals +/// to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.declaration(TokenKind::Struct, type_decl); + rules.type_start(TokenKind::Struct, struct_type); + rules.prefix(TokenKind::Dot, anonymous_literal); + rules.after_path(TokenKind::Dot, TokenKind::LeftBrace, typed_literal); } /// Reads `{ name: Type, ... }`, the fields of a struct type that starts at /// `start`. -fn struct_type(p: &mut Parser, start: u32) -> Id> { +fn struct_type(p: &mut Parser, start: u32) -> Id { let fields = p.delimited( TokenKind::LeftBrace, TokenKind::RightBrace, true, - is_name, + |_, kind| is_name(kind), |p| { let start = p.tok().span.start; let name = p.name(); @@ -78,18 +51,18 @@ fn struct_type(p: &mut Parser, start: u32) -> Id> { ); p.add( start, - ast::Type::Feature(FeatureType::Struct(StructType { fields })), + ast::Type::Feature(ast::FeatureType::Struct(ast::StructType { fields })), ) } /// Reads `.{ name = value, ... }`, a struct literal without a type. -fn anonymous_literal(p: &mut Parser) -> Id> { +fn anonymous_literal(p: &mut Parser) -> Id { let start = p.tok().span.start; literal(p, None, start) } /// Reads `.{ name = value, ... }` after the type `path`. -fn typed_literal(p: &mut Parser, path: Id>) -> Id> { +fn typed_literal(p: &mut Parser, path: Id) -> Id { let start = p.tree.types.span(path).start; literal(p, Some(path), start) } @@ -98,18 +71,14 @@ fn typed_literal(p: &mut Parser, path: Id>) -> Id, - ty: Option>>, - start: u32, -) -> Id> { +fn literal(p: &mut Parser, ty: Option>, start: u32) -> Id { p.next(); // `.` let mut colons = Vec::new(); let fields = p.delimited( TokenKind::LeftBrace, TokenKind::RightBrace, false, - is_name, + |_, kind| is_name(kind), |p| { let field_start = p.tok().span.start; let name = p.name(); @@ -134,189 +103,182 @@ fn literal( } p.add( start, - ast::Expr::Feature(FeatureExpr::StructLiteral(StructLiteral { ty, fields })), + ast::Expr::Feature(ast::FeatureExpr::StructLiteral(ast::StructLiteral { + ty, + fields, + })), ) } -impl TypeNode for StructType { - fn fields(&self) -> Option>> { - Some(self.fields) - } +#[cfg(test)] +mod tests; - /// The type a struct type written at `span` names: none yet, as only a - /// declared struct is checked. - fn resolve(&self, checker: &mut Checker<'_, Peeper>, span: Span) -> TypeId { - checker.not_supported(span, "struct types") - } +/// The type a struct type written at `span` names: none yet, as only a +/// declared struct is checked. +pub(crate) fn resolve_struct_type( + checker: &mut Checker<'_>, + _ty: ast::StructType, + span: Span, +) -> TypeId { + checker.not_supported(span, "struct types") +} - /// The type the struct declaration `definition`, written `written` with the - /// fields of `ty`, declares, its fields laid out for the target. - fn declare( - &self, - checker: &mut Checker<'_, Peeper>, - definition: DefId, - written: ast::TypeDecl, - ) -> TypeId { - let tree = &checker.module().ast; - let fields = self.fields; - let mut field_types = Vec::with_capacity(fields.len()); - let name_of = |field: Id>| tree.children.fields[field].name; - for (index, field) in tree.children.lists.items(fields).enumerate() { - let ast::Field { name, ty } = tree.children.fields[field]; - let text = name.text(&tree.file); - // A struct has few fields, so the ones before are searched. - let mut before = tree.children.lists.items(fields).take(index).map(name_of); - if let Some(first) = before.find(|first| first.text(&tree.file) == text) { - let diagnostic = - report_redeclared(&tree.file, text, "struct", name.span, first.span); - checker.report(diagnostic); - } - // A struct held by value is checked here: one that holds - // itself, however deep, is a cycle, as is one a reference - // field reaches: a reference's target is a complete type. - // A raw pointer's need not be (`resolve_type`). - field_types.push(checker.resolve_value_type(ty)); - } - // Invalid when a field is, as an array is when its element - // is, so no later phase lays out a field it cannot. - if field_types.contains(&TypeId::INVALID) { - return TypeId::INVALID; - } - let (offsets, size, align) = struct_layout(&checker.types, &field_types, checker.target); - let named = checker.declared_name(definition); - let mut ty = checker.fits_target(named, size, written.name.span); - let holders = checker.types.holders_in_fields(&field_types); - if checker.reports_too_many_holders(named, holders, written.name.span) { - ty = TypeId::INVALID; - } - if ty != TypeId::INVALID { - checker - .types - .define_struct(named, field_types.into(), (offsets, size, align)); +/// The type the struct declaration `definition`, written `written` with the +/// fields of `ty`, declares, its fields laid out for the target. +pub(crate) fn declare_struct_type( + checker: &mut Checker<'_>, + ty: ast::StructType, + definition: DefId, + written: ast::TypeDecl, +) -> TypeId { + let tree = &checker.module().ast; + let fields = ty.fields; + let mut field_types = Vec::with_capacity(fields.len()); + let name_of = |field: Id| tree.children.fields[field].name; + for (index, field) in tree.children.lists.items(fields).enumerate() { + let ast::Field { name, ty } = tree.children.fields[field]; + let text = name.text(&tree.file); + // A struct has few fields, so the ones before are searched. + let mut before = tree.children.lists.items(fields).take(index).map(name_of); + if let Some(first) = before.find(|first| first.text(&tree.file) == text) { + let diagnostic = report_redeclared(&tree.file, text, "struct", name.span, first.span); + checker.report(diagnostic); } - ty + // A struct held by value is checked here: one that holds + // itself, however deep, is a cycle, as is one a reference + // field reaches: a reference's target is a complete type. + // A raw pointer's need not be (`resolve_type`). + field_types.push(checker.resolve_value_type(ty)); } -} - -impl ExprNode for StructLiteral { - // A struct literal ends with its `}`. - fn precedence(&self) -> Precedence { - Precedence::Call + // Invalid when a field is, as an array is when its element + // is, so no later phase lays out a field it cannot. + if field_types.contains(&TypeId::INVALID) { + return TypeId::INVALID; + } + let (offsets, size, align) = struct_layout(&checker.types, &field_types, checker.target); + let named = checker.declared_name(definition); + let mut ty = checker.fits_target(named, size, written.name.span); + let holders = checker.types.holders_in_fields(&field_types); + if checker.reports_too_many_holders(named, holders, written.name.span) { + ty = TypeId::INVALID; } + if ty != TypeId::INVALID { + checker + .types + .define_struct(named, field_types.into(), (offsets, size, align)); + } + ty +} - /// `Type.{ name = value, ... }`, written at `span`, or `.{ ... }` taking - /// the struct type `expected`: a struct value with each field set once. - /// A field that is unknown, set twice or missing is reported. - fn check( - &self, - builder: &mut ThirBuilder<'_, '_, Peeper>, - span: Span, - expected: Option, - ) -> thir::Expr { - let StructLiteral { - ty: written, - fields, - } = *self; - let tree = &builder.checker.module().ast; - let ty = match (written, expected) { - (Some(written), _) => builder.checker.resolve_value_type(written), - (None, Some(expected)) - if matches!(builder.checker.types[expected], Type::Struct { .. }) => - { - expected - } - // Reported where it was written, or a `T` only a copy knows: - // `let b: Box = .{ ... }` in a generic function's own body. - (None, Some(TypeId::INVALID)) => TypeId::INVALID, - (None, _) => { - let message = "this struct literal needs its type: write it before `.{`"; - builder - .checker - .error(diagnostics::MISSING_TYPE, message, span) - } - }; - let Type::Struct { - definition, - fields: field_types, - .. - } = &builder.checker.types[ty] - else { - if ty != TypeId::INVALID { - let message = format!( - "expected a struct type, found `{}`", - builder.checker.type_text(ty) - ); - let span = written.map_or(span, |written| tree.types.span(written)); - builder - .checker - .error(diagnostics::TYPE_MISMATCH, message, span); - } - // For their own errors; what each field's type is, is not known. - for field in tree.children.lists.items(fields) { - let value = tree.children.field_values[field].value; - builder.add_expr(value, Some(TypeId::INVALID)); - } - return thir::Expr::INVALID; - }; - let definition = *definition; - // Where each field is set, by its index. - let mut set: Vec> = vec![None; field_types.len()]; - let mut checked: Vec = Vec::with_capacity(fields.len()); - for field in tree.children.lists.items(fields) { - let ast::FieldValue { name, value } = tree.children.field_values[field]; - let Some((index, field_type)) = builder.field_index(ty, name) else { - builder.add_expr(value, Some(TypeId::INVALID)); // for its own errors - continue; - }; - if let Some(first) = set[index] { - let text = name.text(&tree.file); - builder.checker.report( - Diagnostic::new( - diagnostics::DUPLICATE_FIELD, - format!("field `{text}` is set twice"), - ) - .label(&tree.file, name.span, "") - .label(&tree.file, first, "first set here"), - ); - builder.add_expr(value, None); - continue; - } - set[index] = Some(name.span); - let value = builder.add_required(value, field_type); - let index = index as u32; - checked.push( - builder - .body - .add(thir::FieldValue { index, value }, name.span) - .into(), - ); +/// `Type.{ name = value, ... }`, written at `span`, or `.{ ... }` taking +/// the struct type `expected`: a struct value with each field set once. +/// A field that is unknown, set twice or missing is reported. +pub(crate) fn check_struct_literal( + builder: &mut ThirBuilder<'_, '_>, + literal: ast::StructLiteral, + span: Span, + expected: Option, +) -> thir::Expr { + let ast::StructLiteral { + ty: written, + fields, + } = literal; + let tree = &builder.checker.module().ast; + let ty = match (written, expected) { + (Some(written), _) => builder.checker.resolve_value_type(written), + (None, Some(expected)) + if matches!(builder.checker.types[expected], Type::Struct { .. }) => + { + expected } - let missing: Vec = model::program::field_names(builder.checker.modules, definition) - .zip(&set) - .filter(|(_, set)| set.is_none()) - .map(|(name, _)| format!("`{name}`")) - .collect(); - if !missing.is_empty() { - let fields = if missing.len() == 1 { - "field" - } else { - "fields" - }; + // Reported where it was written, or a `T` only a copy knows: + // `let b: Box = .{ ... }` in a generic function's own body. + (None, Some(TypeId::INVALID)) => TypeId::INVALID, + (None, _) => { + let message = "this struct literal needs its type: write it before `.{`"; + builder + .checker + .error(diagnostics::MISSING_TYPE, message, span) + } + }; + let Type::Struct { + definition, + fields: field_types, + .. + } = &builder.checker.types[ty] + else { + if ty != TypeId::INVALID { let message = format!( - "missing {fields} {} in `{}`", - missing.join(", "), + "expected a struct type, found `{}`", builder.checker.type_text(ty) ); + let span = written.map_or(span, |written| tree.types.span(written)); builder .checker - .error(diagnostics::MISSING_FIELD, message, span); + .error(diagnostics::TYPE_MISMATCH, message, span); } - thir::Expr { - ty, - kind: thir::ExprKind::StructLiteral(builder.body.children.lists.add(&checked)), + // For their own errors; what each field's type is, is not known. + for field in tree.children.lists.items(fields) { + let value = tree.children.field_values[field].value; + builder.add_expr(value, Some(TypeId::INVALID)); } + return thir::Expr::INVALID; + }; + let definition = *definition; + // Where each field is set, by its index. + let mut set: Vec> = vec![None; field_types.len()]; + let mut checked: Vec = Vec::with_capacity(fields.len()); + for field in tree.children.lists.items(fields) { + let ast::FieldValue { name, value } = tree.children.field_values[field]; + let Some((index, field_type)) = builder.field_index(ty, name) else { + builder.add_expr(value, Some(TypeId::INVALID)); // for its own errors + continue; + }; + if let Some(first) = set[index] { + let text = name.text(&tree.file); + builder.checker.report( + Diagnostic::new( + diagnostics::DUPLICATE_FIELD, + format!("field `{text}` is set twice"), + ) + .label(&tree.file, name.span, "") + .label(&tree.file, first, "first set here"), + ); + builder.add_expr(value, None); + continue; + } + set[index] = Some(name.span); + let value = builder.add_required(value, field_type); + let index = index as u32; + checked.push( + builder + .body + .add(thir::FieldValue { index, value }, name.span) + .into(), + ); + } + let missing: Vec = model::program::field_names(builder.checker.modules, definition) + .zip(&set) + .filter(|(_, set)| set.is_none()) + .map(|(name, _)| format!("`{name}`")) + .collect(); + if !missing.is_empty() { + let fields = if missing.len() == 1 { + "field" + } else { + "fields" + }; + let message = format!( + "missing {fields} {} in `{}`", + missing.join(", "), + builder.checker.type_text(ty) + ); + builder + .checker + .error(diagnostics::MISSING_FIELD, message, span); + } + thir::Expr { + ty, + kind: thir::ExprKind::StructLiteral(builder.body.children.lists.add(&checked)), } } - -#[cfg(test)] -mod tests; diff --git a/crates/features/src/structs/tests.rs b/crates/features/src/structs/tests.rs index 944391d8..bb791cf2 100644 --- a/crates/features/src/structs/tests.rs +++ b/crates/features/src/structs/tests.rs @@ -6,7 +6,6 @@ use diagnostics::Diagnostic; use source::Span; use syntax::ast; -use super::*; use crate::testing::Tree; use crate::testing::messages; use crate::testing::parse_text; @@ -38,8 +37,9 @@ fn written(tree: &Tree, span: Span) -> &str { /// The fields of the struct type `ty`: each as `name: type`, the type as /// written, and the type. -fn fields(tree: &Tree, ty: Id>) -> Vec<(String, Id>)> { - let ast::Type::Feature(FeatureType::Struct(StructType { fields })) = tree.types[ty] else { +fn fields(tree: &Tree, ty: Id) -> Vec<(String, Id)> { + let ast::Type::Feature(ast::FeatureType::Struct(ast::StructType { fields })) = tree.types[ty] + else { panic!("not a struct type: {:?}", tree.types[ty]) }; let field = |id| { @@ -56,8 +56,8 @@ fn fields(tree: &Tree, ty: Id>) -> Vec<(String, Id>) -> (Option<&str>, Vec) { - let ast::Expr::Feature(FeatureExpr::StructLiteral(StructLiteral { ty, fields })) = +fn literal(tree: &Tree, expr: Id) -> (Option<&str>, Vec) { + let ast::Expr::Feature(ast::FeatureExpr::StructLiteral(ast::StructLiteral { ty, fields })) = tree.exprs[expr] else { panic!("not a struct literal: {:?}", tree.exprs[expr]) diff --git a/crates/features/src/testing.rs b/crates/features/src/testing.rs index 30b862b5..16ed4668 100644 --- a/crates/features/src/testing.rs +++ b/crates/features/src/testing.rs @@ -16,13 +16,11 @@ use source::SourceFile; use source::Span; use syntax::ast; -use crate::Peeper; - -pub(crate) type Tree = ast::Tree; +pub(crate) type Tree = ast::Tree; /// The tree of `text` and its syntax errors. pub(crate) fn parse_text(text: &str) -> (Tree, Vec) { - parser::parse(&Arc::new(SourceFile::new("t.peep", text))) + parser::parse(&Arc::new(SourceFile::new("t.peep", text)), &crate::RULES) } /// The message of each syntax error of `text`. @@ -39,10 +37,10 @@ pub(crate) type Reported = (&'static str, String, String); /// gives and the diagnostics. pub(crate) fn with_checker( text: &str, - work: impl FnOnce(&mut Checker, &[(DefId, Span)]) -> T, + work: impl FnOnce(&mut Checker, &[(DefId, Span)]) -> T, ) -> (T, Vec) { let file = Arc::new(SourceFile::new("main.peep", text)); - let (ast, parse) = parser::parse::(&file); + let (ast, parse) = parser::parse(&file, &crate::RULES); assert!(parse.is_empty(), "{parse:?}"); let modules = [model::program::Module { path: "app:main".to_string(), @@ -60,7 +58,12 @@ pub(crate) fn with_checker( _ => None, }) .collect(); - let mut checker = Checker::new(&modules, Machine::named("x86_64-linux").unwrap(), false); + let mut checker = Checker::new( + &modules, + Machine::named("x86_64-linux").unwrap(), + false, + &crate::CHECK_HOOKS, + ); let result = work(&mut checker, &functions); let reported = (checker.module_checks.iter()) .flat_map(|module| &module.diagnostics) @@ -73,7 +76,7 @@ pub(crate) fn with_checker( } /// The expressions of the statements of the first function of `tree`. -pub(crate) fn statements(tree: &Tree) -> Vec>> { +pub(crate) fn statements(tree: &Tree) -> Vec> { let decl = tree.declarations().next().unwrap(); let ast::Decl::Function(function) = tree.decls[decl] else { panic!("not a function") diff --git a/crates/kernel/lower/src/aggregates.rs b/crates/kernel/lower/src/aggregates.rs index 1a7ac88c..e8048486 100644 --- a/crates/kernel/lower/src/aggregates.rs +++ b/crates/kernel/lower/src/aggregates.rs @@ -25,7 +25,6 @@ use runtime_abi::messages::SLICE_BOUNDS_MESSAGE; use runtime_abi::messages::SLICE_ORDER_MESSAGE; use runtime_abi::messages::array_parts_message; use source::Span; -use syntax::ast::Language; use crate::Loop; use crate::Lowering; @@ -66,7 +65,7 @@ enum Part { Range(RangeWalk), } -impl Lowering<'_, L> { +impl Lowering<'_> { /// A struct value of the type `ty` from `fields`, at `place` /// (`lower_into`): each computed in the order written, right at its /// offset. diff --git a/crates/kernel/lower/src/expression.rs b/crates/kernel/lower/src/expression.rs index d5e21a14..4714275f 100644 --- a/crates/kernel/lower/src/expression.rs +++ b/crates/kernel/lower/src/expression.rs @@ -35,7 +35,6 @@ use runtime_abi::messages::SLICE_INDEX_MESSAGE; use runtime_abi::messages::array_index_message; use runtime_abi::messages::shift_count_message; use source::Span; -use syntax::ast::Language; use syntax::operators::BinaryOp; use syntax::operators::UnaryOp; @@ -55,7 +54,7 @@ pub(super) enum Length { Read(Operand), } -impl Lowering<'_, L> { +impl Lowering<'_> { /// The value of `expression`, computed in the block being filled. pub(super) fn lower_expr(&mut self, expression: Id) -> Option { // A long chain of operators, calls or parentheses is a deep recursion. diff --git a/crates/kernel/lower/src/lib.rs b/crates/kernel/lower/src/lib.rs index a9108300..0d65d282 100644 --- a/crates/kernel/lower/src/lib.rs +++ b/crates/kernel/lower/src/lib.rs @@ -13,7 +13,6 @@ mod statement; mod tests; use std::num::NonZeroU32; -use syntax::ast::Language; use arena::Arena; use arena::Id; @@ -67,12 +66,12 @@ pub struct ProgramDebugTypes { /// `function`, for `target`. `None` when checking it reported an error /// (`has_errors`) or left it incomplete. `modules` names types for a /// debugger (`debug_types`, shared by the program's bodies). -pub fn lower( +pub fn lower( body: &thir::Body, function: TypeId, types: &Types, target: &'static Machine, - modules: &[Module], + modules: &[Module], debug_types: &mut ProgramDebugTypes, ) -> Option { if body.has_errors { @@ -191,11 +190,11 @@ fn slot_of(variable: Id) -> Id { Id::from_index(variable.index()) } -struct Lowering<'t, L: Language> { +struct Lowering<'t> { thir: &'t thir::Body, types: &'t Types, target: &'static Machine, - modules: &'t [Module], + modules: &'t [Module], debug_types: &'t mut ProgramDebugTypes, mir: Body, block: Id, // the block being filled @@ -257,7 +256,7 @@ impl Value { /// clang runs out of stack on debug types tens of thousands of nodes deep. const DEEPEST_DEBUG_TYPE: u32 = 5_000; -impl Lowering<'_, L> { +impl Lowering<'_> { /// A new block starting at `span`; `finish` gives it its instructions and /// terminator. fn new_block(&mut self, span: Span) -> Id { diff --git a/crates/kernel/lower/src/statement.rs b/crates/kernel/lower/src/statement.rs index 98414d84..88c9bf47 100644 --- a/crates/kernel/lower/src/statement.rs +++ b/crates/kernel/lower/src/statement.rs @@ -10,14 +10,13 @@ use model::mir::Slot; use model::mir::Terminator; use model::thir; use source::Span; -use syntax::ast::Language; use crate::Loop; use crate::Lowering; use crate::Value; use crate::slot_of; -impl Lowering<'_, L> { +impl Lowering<'_> { /// Lowers the statements of the source block `block`, whose debug /// scope has the same id and whose slots start at `start` in /// `declared`. diff --git a/crates/kernel/lower/src/tests.rs b/crates/kernel/lower/src/tests.rs index 5b93d4ad..5e65f981 100644 --- a/crates/kernel/lower/src/tests.rs +++ b/crates/kernel/lower/src/tests.rs @@ -4,7 +4,6 @@ use std::sync::Arc; use check::Checker; -use features::Peeper; use model::ConstArguments; use model::DeclarationCopy; use model::DefId; @@ -27,7 +26,7 @@ fn lowered(text: &str) -> String { /// MIR and the debug types lowering made. fn lower_main(text: &str, target: &str) -> (String, mir::Body, DebugTypes) { let file = Arc::new(SourceFile::new("main.peep", text)); - let (ast, parse) = parser::parse::(&file); + let (ast, parse) = parser::parse(&file, &features::RULES); assert!(parse.is_empty(), "{parse:?}"); let modules = [model::program::Module { path: "app:main".to_string(), @@ -35,7 +34,7 @@ fn lower_main(text: &str, target: &str) -> (String, mir::Body, DebugTypes) { imports: Vec::new(), }]; let target = Machine::named(target).unwrap(); - let mut checker = Checker::new(&modules, target, false); + let mut checker = Checker::new(&modules, target, false, &features::CHECK_HOOKS); let tree = &modules[0].ast; let (index, name) = tree .declarations() diff --git a/crates/kernel/model/src/program.rs b/crates/kernel/model/src/program.rs index 631a03e3..0091626d 100644 --- a/crates/kernel/model/src/program.rs +++ b/crates/kernel/model/src/program.rs @@ -21,29 +21,25 @@ use crate::semantic_types::TypeId; use crate::semantic_types::Types; use syntax::ast; use syntax::ast::Ident; -use syntax::ast::Language; use syntax::ast::Tree; /// One source file, read and parsed. Its source file is `ast.file`. What /// `load` read never changes; what a compile finds, its scope included, is /// kept by the compile (`check::Checker`). -pub struct Module { +pub struct Module { pub path: String, // import path, such as "myapp:utils/file" or "core:global" - pub ast: Tree, + pub ast: Tree, pub imports: Vec, // in source order; the implicit prelude import last, in every module but the prelude } /// The declaration `definition` of `modules` names. -pub fn declaration(modules: &[Module], definition: DefId) -> &ast::Decl { +pub fn declaration(modules: &[Module], definition: DefId) -> &ast::Decl { let tree = &modules[definition.module.index()].ast; &tree.decls[tree.declaration(definition.index)] } /// The function `definition`, as written. -pub fn function_declaration( - modules: &[Module], - definition: DefId, -) -> &ast::Function { +pub fn function_declaration(modules: &[Module], definition: DefId) -> &ast::Function { match declaration(modules, definition) { ast::Decl::Function(function) => function, _ => unreachable!("`{definition:?}` is a function"), @@ -51,7 +47,7 @@ pub fn function_declaration( } /// The text of the name the declaration `definition` of `modules` declares. -pub fn declared_text(modules: &[Module], definition: DefId) -> &str { +pub fn declared_text(modules: &[Module], definition: DefId) -> &str { let (name, file) = declared_name(modules, definition); name.text(file) } @@ -63,7 +59,7 @@ pub fn is_exported(name: &str) -> bool { /// The name of the declaration `definition` of `modules` as a program calls /// it: its own name, or `Owner::name` for a function of the type `Owner`. -pub fn declared_path(modules: &[Module], definition: DefId) -> String { +pub fn declared_path(modules: &[Module], definition: DefId) -> String { let name = declared_text(modules, definition); match declaration(modules, definition) { ast::Decl::Function(ast::Function { @@ -78,16 +74,13 @@ pub fn declared_path(modules: &[Module], definition: DefId) -> S /// The type `ty` of `types` as a message names it, each declared type by the /// name its declaration in `modules` gives it (`Types::text`). -pub fn type_text(modules: &[Module], types: &Types, ty: TypeId) -> String { +pub fn type_text(modules: &[Module], types: &Types, ty: TypeId) -> String { types.text(ty, |definition| declared_text(modules, definition)) } /// The name the declaration `definition` of `modules` declares, and the file /// it is in. -pub fn declared_name( - modules: &[Module], - definition: DefId, -) -> (Ident, &Arc) { +pub fn declared_name(modules: &[Module], definition: DefId) -> (Ident, &Arc) { ( declaration(modules, definition).name(), &modules[definition.module.index()].ast.file, @@ -102,10 +95,7 @@ pub const EXTERN_ATTRIBUTE: &str = "extern"; /// error is where an `extern` attribute of another shape, a second one, or /// one whose name no symbol can have is written, which the checker /// reports. -pub fn extern_symbol( - modules: &[Module], - definition: DefId, -) -> Result, Span> { +pub fn extern_symbol(modules: &[Module], definition: DefId) -> Result, Span> { let tree = &modules[definition.module.index()].ast; let ast::Decl::Function(function) = declaration(modules, definition) else { return Ok(None); @@ -139,8 +129,8 @@ pub fn extern_symbol( /// What a copy of the declaration `definition` of `modules` is made for, as /// `copy_parameters` says: a function's from its signature, a type's its /// ``, as in `struct Box`; none for any other declaration. -pub fn declaration_copy_parameters( - modules: &[Module], +pub fn declaration_copy_parameters( + modules: &[Module], definition: DefId, ) -> impl Iterator> { let tree = &modules[definition.module.index()].ast; @@ -160,9 +150,9 @@ pub fn declaration_copy_parameters( /// the order its `ConstArguments` hold them: each type parameter, ``, /// then each `const` parameter. `Some` is where one that stands for a type /// is named, `` or `const T: type`; `None` is a `const` value. -pub fn copy_parameters( - tree: &ast::Tree, - signature: ast::Signature, +pub fn copy_parameters( + tree: &ast::Tree, + signature: ast::Signature, ) -> impl Iterator> { let type_parameters = (tree.children.lists.items(signature.type_parameters)) .map(|parameter| Some(tree.children.names.span(parameter))); @@ -182,7 +172,7 @@ pub const BUILTIN_ATTRIBUTE: &str = "builtin"; /// Whether the declaration `definition` of `modules` is a function with a /// `#[builtin]`: it has no body, and a call of it is a constant the checker /// works out from the type it is given. -pub fn is_builtin(modules: &[Module], definition: DefId) -> bool { +pub fn is_builtin(modules: &[Module], definition: DefId) -> bool { let tree = &modules[definition.module.index()].ast; let ast::Decl::Function(function) = declaration(modules, definition) else { return false; @@ -194,19 +184,19 @@ pub fn is_builtin(modules: &[Module], definition: DefId) -> bool /// Whether the function `definition` of `modules` is a C function: it has /// an `extern`, well formed or not, so the checker gives it C's rules. -pub fn is_extern(modules: &[Module], definition: DefId) -> bool { +pub fn is_extern(modules: &[Module], definition: DefId) -> bool { extern_symbol(modules, definition) != Ok(None) } /// The C name of the function `definition` of a program the checker /// accepted, if it is a C function (`extern_symbol`). -pub fn c_symbol(modules: &[Module], definition: DefId) -> Option { +pub fn c_symbol(modules: &[Module], definition: DefId) -> Option { extern_symbol(modules, definition).expect("the checker reported a malformed `extern`") } /// The name the linker knows the function `definition` by: its `#[extern]` /// name, else its module's path and its name (`myapp:util.Parse`). -pub fn symbol(modules: &[Module], definition: DefId) -> String { +pub fn symbol(modules: &[Module], definition: DefId) -> String { c_symbol(modules, definition).unwrap_or_else(|| { let path = &modules[definition.module.index()].path; let name = declared_path(modules, definition); @@ -219,11 +209,7 @@ pub fn symbol(modules: &[Module], definition: DefId) -> String { /// (`myapp:main.New`), so two modules' types of one name /// make two names, and each float value by its bits, as two NaNs print /// alike. -pub fn copy_symbol( - modules: &[Module], - types: &Types, - copy: DeclarationCopy, -) -> String { +pub fn copy_symbol(modules: &[Module], types: &Types, copy: DeclarationCopy) -> String { let qualified = |definition: DefId| { let path = &modules[definition.module.index()].path; format!("{path}.{}", declared_text(modules, definition)) @@ -247,11 +233,7 @@ pub fn copy_symbol( /// The copy `copy` as a program names it: its declared path, with its /// `const` arguments as Peeper text (`Stack.New`); what messages, /// dumps and a debugger show. -pub fn copy_name( - modules: &[Module], - types: &Types, - copy: DeclarationCopy, -) -> String { +pub fn copy_name(modules: &[Module], types: &Types, copy: DeclarationCopy) -> String { let declared = declared_path(modules, copy.definition); types.copy_text(declared, copy.arguments, |definition| { declared_text(modules, definition) @@ -260,16 +242,13 @@ pub fn copy_name( /// The names of the fields of the struct declaration `definition` of /// `modules`, in order. -pub fn field_names( - modules: &[Module], - definition: DefId, -) -> impl Iterator { +pub fn field_names(modules: &[Module], definition: DefId) -> impl Iterator { let tree = &modules[definition.module.index()].ast; let &ast::Decl::Type(written) = declaration(modules, definition) else { unreachable!("`{definition:?}` is a type declaration") }; let fields = match tree.types[written.ty] { - ast::Type::Feature(ty) => L::fields(&ty), + ast::Type::Feature(ty) => ty.fields(), _ => None, }; let fields = fields.unwrap_or_else(|| unreachable!("`{definition:?}` declares a struct")); @@ -279,10 +258,10 @@ pub fn field_names( /// The method declarations of the interface `definition`, in order; `None` /// when it declares something else. The parser puts only functions in one. -pub fn interface_methods( - modules: &[Module], +pub fn interface_methods( + modules: &[Module], definition: DefId, -) -> Option>> { +) -> Option> { let tree = &modules[definition.module.index()].ast; let &ast::Decl::Type(written) = declaration(modules, definition) else { return None; @@ -290,7 +269,7 @@ pub fn interface_methods( let ast::Type::Feature(ty) = tree.types[written.ty] else { return None; }; - let methods = L::methods(&ty)?; + let methods = ty.methods()?; Some( tree.children .lists @@ -319,7 +298,7 @@ pub enum ImportKind { impl ImportKind { /// The import as written in `importer`; `None` for the prelude's. - pub fn declaration(self, importer: &Tree) -> Option<&ast::Import> { + pub fn declaration(self, importer: &Tree) -> Option<&ast::Import> { match self { ImportKind::Declared(index) => Some(&importer.imports[index as usize]), ImportKind::Prelude => None, @@ -332,11 +311,7 @@ impl Import { /// its alias, else the last segment of the imported module's path (in /// `modules`), at the import. `None` for the prelude, whose names are /// looked up, not brought in. - pub fn name<'a, L: Language>( - &self, - importer: &'a Module, - modules: &'a [Module], - ) -> Option<(&'a str, Span)> { + pub fn name<'a>(&self, importer: &'a Module, modules: &'a [Module]) -> Option<(&'a str, Span)> { let declaration = self.kind.declaration(&importer.ast)?; let name = match declaration.alias { Some(alias) => alias.text(&importer.ast.file), @@ -353,10 +328,10 @@ pub fn default_alias(path: &str) -> &str { } /// Every module reachable from an entry file. -pub struct Program { +pub struct Program { /// Each module after the modules it imports; outside cycles, the same /// order every run. - pub modules: Vec>, + pub modules: Vec, /// What loading found: import cycles first, then each module's errors, /// in the program's order. One list for the whole program, because every /// load reads every module again; what a compile finds is kept per @@ -377,9 +352,9 @@ pub struct Program { pub entry: Option, } -impl Program { +impl Program { /// The module read from `file`. - pub fn module_of(&self, file: &Path) -> Option<&Module> { + pub fn module_of(&self, file: &Path) -> Option<&Module> { self.modules .iter() .find(|module| Path::new(&module.ast.file.path) == file) diff --git a/crates/kernel/semantic/src/builder.rs b/crates/kernel/semantic/src/builder.rs index 1faecd28..db43a628 100644 --- a/crates/kernel/semantic/src/builder.rs +++ b/crates/kernel/semantic/src/builder.rs @@ -7,9 +7,7 @@ use model::thir::Block; use model::thir::Body; use model::thir::Local; use rustc_hash::FxHashMap; -use syntax::ast::Language; -use crate::Checked; use crate::Checker; /// A name declared in a block, and what it stands for. @@ -23,10 +21,10 @@ pub(crate) struct Declared<'p> { /// Building the THIR of one piece of code: a function's body, or a /// constant's value. It checks the code as it builds it. -pub struct ThirBuilder<'a, 'p, L: Language> { +pub struct ThirBuilder<'a, 'p> { /// The checker, borrowed for the build: its module, tables and /// diagnostics. - pub checker: &'a mut Checker<'p, L>, + pub checker: &'a mut Checker<'p>, pub body: &'a mut Body, /// The names declared in the enclosing blocks so far, innermost last. pub(crate) names: Vec>, @@ -44,13 +42,13 @@ pub struct ThirBuilder<'a, 'p, L: Language> { pub(crate) in_constant: bool, } -impl<'a, 'p, L: Checked> ThirBuilder<'a, 'p, L> { +impl<'a, 'p> ThirBuilder<'a, 'p> { /// Building code into `body` whose `return` gives `result`. pub(crate) fn new( - checker: &'a mut Checker<'p, L>, + checker: &'a mut Checker<'p>, body: &'a mut Body, result: TypeId, - ) -> ThirBuilder<'a, 'p, L> { + ) -> ThirBuilder<'a, 'p> { ThirBuilder { checker, body, diff --git a/crates/kernel/semantic/src/conformance.rs b/crates/kernel/semantic/src/conformance.rs index a0bda17f..5a858d0b 100644 --- a/crates/kernel/semantic/src/conformance.rs +++ b/crates/kernel/semantic/src/conformance.rs @@ -7,11 +7,10 @@ use model::semantic_types; use model::thir; use source::Span; -use crate::Checked; use crate::Checker; use crate::generics; -impl Checker<'_, L> { +impl Checker<'_> { /// The functions of the struct `structure` that are the methods of the /// interface `interface`, for a reference to the struct used as a /// reference to the interface at `span`: for each method, the struct's diff --git a/crates/kernel/semantic/src/declaration.rs b/crates/kernel/semantic/src/declaration.rs index 530448da..46155698 100644 --- a/crates/kernel/semantic/src/declaration.rs +++ b/crates/kernel/semantic/src/declaration.rs @@ -24,7 +24,6 @@ use model::thir::Symbol; use source::Span; use syntax::ast; -use crate::Checked; use crate::Checker; use crate::Checking; use crate::builder::ThirBuilder; @@ -38,7 +37,7 @@ use crate::scope; // lifetime, as Rust does. const MOST_HOLDERS: usize = 4_096; -impl Checker<'_, L> { +impl Checker<'_> { /// The type the module's type declaration or alias `definition` declares: /// a feature's (`declare_type`), or the type an alias names. One with /// type parameters, `struct Box`, declares a type in each copy @@ -63,12 +62,12 @@ impl Checker<'_, L> { unreachable!("the parser gives a type declaration only a feature's type") }; if written.type_parameters.is_empty() || self.in_copy() { - return L::declare_type(self, definition, written, ty); + return (self.hooks.declare_type)(self, definition, written, ty); } let module = definition.module.index(); let reported = self.module_checks[module].diagnostics.len(); // Invalid whenever a field is of a type `T` names, which reports nothing. - L::declare_type(self, definition, written, ty); + (self.hooks.declare_type)(self, definition, written, ty); let found = &self.module_checks[module].diagnostics[reported..]; if found.iter().any(Diagnostic::is_error) { return TypeId::INVALID; @@ -112,7 +111,7 @@ impl Checker<'_, L> { pub(crate) fn const_value_type( &mut self, definition: DefId, - ty: Id>, + ty: Id, used_at: Span, ) -> TypeId { let checking = Checking { @@ -136,7 +135,7 @@ impl Checker<'_, L> { /// The type of a value whose type is written `ty`: a named type is the /// type its declaration declares, so a value's type is complete (an /// alias names a complete type already). - pub fn resolve_value_type(&mut self, ty: Id>) -> TypeId { + pub fn resolve_value_type(&mut self, ty: Id) -> TypeId { let resolved = self.resolve_type(ty); self.value_type(resolved, ty) } @@ -144,7 +143,7 @@ impl Checker<'_, L> { /// `resolve_value_type` of `resolved`, the type written `ty`. An /// interface method's `self` taken whole is the interface being checked, /// so it stays a name. - fn value_type(&mut self, resolved: TypeId, ty: Id>) -> TypeId { + fn value_type(&mut self, resolved: TypeId, ty: Id) -> TypeId { let tree = &self.module().ast; if let ast::Type::Owner = tree.types[ty] && self.is_interface(resolved) @@ -433,7 +432,7 @@ impl Checker<'_, L> { /// `resolve_type_argument` before it is made a value's type, as /// `resolve_type` is. - pub(crate) fn expression_type(&mut self, expression: Id>) -> TypeId { + pub(crate) fn expression_type(&mut self, expression: Id) -> TypeId { source::grow_stack(|| { let tree = &self.module().ast; let span = tree.exprs.span(expression); @@ -476,13 +475,15 @@ impl Checker<'_, L> { /// its declaration is checked; a value's type is `resolve_value_type`. A /// local never names a type /// (`ThirBuilder::declare`), so only top-level names are looked up. - pub fn resolve_type(&mut self, ty: Id>) -> TypeId { + pub fn resolve_type(&mut self, ty: Id) -> TypeId { // Types written in types, `& & ... i32`, are a deep recursion. source::grow_stack(|| { let tree = &self.module().ast; let span = tree.types.span(ty); let what = match tree.types[ty] { - ast::Type::Feature(feature) => return L::resolve_type(self, feature, span), + ast::Type::Feature(feature) => { + return (self.hooks.resolve_type)(self, feature, span); + } // `self`'s type: the owner of the function being checked, which // has one (`check_function`). An owner that is not a struct // was reported by `scope::collect`. diff --git a/crates/kernel/semantic/src/expression.rs b/crates/kernel/semantic/src/expression.rs index ee7d166c..5125b39e 100644 --- a/crates/kernel/semantic/src/expression.rs +++ b/crates/kernel/semantic/src/expression.rs @@ -19,22 +19,20 @@ use model::thir::Expr; use model::thir::ExprKind; use source::Span; use syntax::ast; -use syntax::ast::Language; use syntax::operators::Precedence; -use crate::Checked; use crate::builder::ThirBuilder; -impl ThirBuilder<'_, '_, L> { +impl ThirBuilder<'_, '_> { /// `expression` (`check_expr`), added to the body. - pub fn add_expr(&mut self, expression: Id>, expected: Option) -> Id { + pub fn add_expr(&mut self, expression: Id, expected: Option) -> Id { let checked = self.check_expr(expression, expected); self.body .add(checked, self.checker.module().ast.exprs.span(expression)) } /// `expression` (`check_required`), added to the body. - pub fn add_required(&mut self, expression: Id>, ty: TypeId) -> Id { + pub fn add_required(&mut self, expression: Id, ty: TypeId) -> Id { let checked = self.check_required(expression, ty); self.body .add(checked, self.checker.module().ast.exprs.span(expression)) @@ -47,7 +45,7 @@ impl ThirBuilder<'_, '_, L> { fn coerce( &mut self, expr: Expr, - expression: Id>, + expression: Id, to: TypeId, ) -> Result { if expr.ty == TypeId::INVALID || to == TypeId::INVALID { @@ -89,7 +87,7 @@ impl ThirBuilder<'_, '_, L> { fn help_cast( &self, mismatch: Diagnostic, - expression: Id>, + expression: Id, found: TypeId, to: TypeId, ) -> Diagnostic { @@ -206,7 +204,7 @@ impl ThirBuilder<'_, '_, L> { /// The THIR of `expression`, as a value of the type `ty`, or that /// converts to it without `as` (`coerce`); a mismatch is reported. - pub(crate) fn check_required(&mut self, expression: Id>, ty: TypeId) -> Expr { + pub(crate) fn check_required(&mut self, expression: Id, ty: TypeId) -> Expr { let checked = self.check_expr(expression, Some(ty)); self.require(checked, expression, ty) } @@ -215,13 +213,15 @@ impl ThirBuilder<'_, '_, L> { /// operation leaves no nodes for its operands. `expected` is the type a /// number literal without a suffix takes, if any; the value may have /// another type. - pub fn check_expr(&mut self, expression: Id>, expected: Option) -> Expr { + pub fn check_expr(&mut self, expression: Id, expected: Option) -> Expr { // A long chain of operators, calls or parentheses is a deep recursion. source::grow_stack(|| { let tree = &self.checker.module().ast; let span = tree.exprs.span(expression); match tree.exprs[expression] { - ast::Expr::Feature(feature) => L::check_expr(self, feature, span, expected), + ast::Expr::Feature(feature) => { + (self.checker.hooks.check_expr)(self, feature, span, expected) + } ast::Expr::Name => { let symbol = self.resolve(span); self.check_symbol_value(symbol, span) @@ -241,7 +241,7 @@ impl ThirBuilder<'_, '_, L> { // `*p` of a variable `p` reads as C's dereference, which // is written `p.*`. if let ast::Type::Feature(written) = tree.types[ty] - && let Some(target) = L::pointee(&written) + && let Some(target) = written.pointee() && let ast::Type::Name = tree.types[target] && let name = tree.file.slice(tree.types.span(target)) && self.innermost.contains_key(name) @@ -261,7 +261,7 @@ impl ThirBuilder<'_, '_, L> { type_arguments, arguments, } => { - let arguments: Vec>> = + let arguments: Vec> = tree.children.lists.items(arguments).collect(); self.check_call(callee, type_arguments, &arguments, span) } @@ -299,7 +299,7 @@ impl ThirBuilder<'_, '_, L> { fn check_reference( &mut self, mutable: bool, - value: Id>, + value: Id, span: Span, expected: Option, ) -> Expr { @@ -340,12 +340,7 @@ impl ThirBuilder<'_, '_, L> { /// `checked`, from `expression`, as a value of the type `ty` (`coerce`); /// a mismatch is reported, with a guess that adds `as` when only `as` /// converts it. - pub(crate) fn require( - &mut self, - checked: Expr, - expression: Id>, - ty: TypeId, - ) -> Expr { + pub(crate) fn require(&mut self, checked: Expr, expression: Id, ty: TypeId) -> Expr { let found = checked.ty; self.coerce(checked, expression, ty) .unwrap_or_else(|mismatch| { @@ -365,7 +360,7 @@ impl ThirBuilder<'_, '_, L> { code: Code, message: String, span: Span, - operand: Id>, + operand: Id, found: TypeId, accepts: impl Fn(TypeId) -> bool, ) -> Diagnostic { @@ -387,7 +382,7 @@ impl ThirBuilder<'_, '_, L> { /// the operand's last part: `&n.*` reads `n`, so `&n` needs `(&n).*`. fn append_fixes( &self, - operand: Id>, + operand: Id, suffix: &str, precedence: Precedence, ) -> Vec { @@ -410,10 +405,7 @@ impl ThirBuilder<'_, '_, L> { } /// The text of `expression` if it is a number literal without a suffix. -pub(crate) fn unsuffixed_literal( - tree: &ast::Tree, - expression: Id>, -) -> Option<&str> { +pub(crate) fn unsuffixed_literal(tree: &ast::Tree, expression: Id) -> Option<&str> { let text = tree.file.slice(tree.exprs.span(expression)); let number = matches!(tree.exprs[expression], ast::Expr::Number); (number && literal::numeric::split(text).suffix.is_empty()).then_some(text) diff --git a/crates/kernel/semantic/src/expression/borrows.rs b/crates/kernel/semantic/src/expression/borrows.rs index 04d123c5..2a4c3f19 100644 --- a/crates/kernel/semantic/src/expression/borrows.rs +++ b/crates/kernel/semantic/src/expression/borrows.rs @@ -10,10 +10,9 @@ use model::thir::ExprKind; use model::thir::Variable; use source::Span; -use crate::Checked; use crate::builder::ThirBuilder; -impl ThirBuilder<'_, '_, L> { +impl ThirBuilder<'_, '_> { /// A `&place` or `&mut place` reference to the checked place `place`. /// `&mut` needs a place that can be written. pub(crate) fn check_borrow(&mut self, mutable: bool, place: Id) -> Expr { diff --git a/crates/kernel/semantic/src/expression/literals.rs b/crates/kernel/semantic/src/expression/literals.rs index e6c6e907..08c9fdda 100644 --- a/crates/kernel/semantic/src/expression/literals.rs +++ b/crates/kernel/semantic/src/expression/literals.rs @@ -17,11 +17,10 @@ use source::Span; use syntax::ast; use syntax::operators::Precedence; -use crate::Checked; use crate::builder::ThirBuilder; use crate::expression::unsuffixed_literal; -impl ThirBuilder<'_, '_, L> { +impl ThirBuilder<'_, '_> { /// The string literal at `span`, a `&str` or with its `c` a `&cstr` (`ty`): /// its bytes. pub(crate) fn string_literal(&mut self, span: Span, ty: TypeId) -> Expr { @@ -68,7 +67,7 @@ impl ThirBuilder<'_, '_, L> { /// Without an element type, each entry is checked for its own errors. pub fn check_entries( &mut self, - entries: impl Iterator>>, + entries: impl Iterator>, element: TypeId, alone_in: Option, ) -> (Vec, Option, Option<(Span, &'static str)>) { @@ -134,7 +133,7 @@ impl ThirBuilder<'_, '_, L> { fn help_spread( &self, mismatch: Diagnostic, - written: Id>, + written: Id, value: Id, alone_in: Option, ) -> Diagnostic { @@ -191,7 +190,7 @@ impl ThirBuilder<'_, '_, L> { /// reach the variables named. pub(crate) fn check_variadic( &mut self, - values: &[Id>], + values: &[Id], parameter: TypeId, span: Span, ) -> Id { @@ -294,7 +293,7 @@ impl ThirBuilder<'_, '_, L> { } /// The written `values` of a spread into `element`s, checked. - fn add_spread(&mut self, values: Id>, element: TypeId) -> Id { + fn add_spread(&mut self, values: Id, element: TypeId) -> Id { // Only an integer element has ranges, whose ends then take its type. let hint = self.checker.types.range(element); self.add_expr(values, hint) @@ -410,8 +409,8 @@ impl ThirBuilder<'_, '_, L> { /// such literals. pub fn check_range_ends( &mut self, - start: Id>, - end: Id>, + start: Id, + end: Id, hint: Option, ) -> (Id, Id) { let tree = &self.checker.module().ast; diff --git a/crates/kernel/semantic/src/expression/names.rs b/crates/kernel/semantic/src/expression/names.rs index 780de524..511a9a10 100644 --- a/crates/kernel/semantic/src/expression/names.rs +++ b/crates/kernel/semantic/src/expression/names.rs @@ -4,10 +4,9 @@ use model::semantic_types; use model::thir; use source::Span; -use crate::Checked; use crate::builder; -impl builder::ThirBuilder<'_, '_, L> { +impl builder::ThirBuilder<'_, '_> { /// The name or path written at `span`, which stands for `symbol`, as a /// value. `None` when finding the symbol reported an error. pub(super) fn check_symbol_value( diff --git a/crates/kernel/semantic/src/expression/operators.rs b/crates/kernel/semantic/src/expression/operators.rs index 5a3f3dcf..17884b70 100644 --- a/crates/kernel/semantic/src/expression/operators.rs +++ b/crates/kernel/semantic/src/expression/operators.rs @@ -16,11 +16,10 @@ use syntax::ast; use syntax::operators::BinaryOp; use syntax::operators::UnaryOp; -use crate::Checked; use crate::builder::ThirBuilder; use crate::expression::unsuffixed_literal; -impl ThirBuilder<'_, '_, L> { +impl ThirBuilder<'_, '_> { /// The number literal at `number`, or its negation written at `negated` /// (`-128`, which fits `i8` where `128` does not). It takes its suffix's /// type, else the type `expected` if it can (`takes_type`), else `i32` or @@ -92,7 +91,7 @@ impl ThirBuilder<'_, '_, L> { pub(super) fn check_unary( &mut self, op: UnaryOp, - operand: Id>, + operand: Id, span: Span, expected: Option, ) -> Expr { @@ -141,8 +140,8 @@ impl ThirBuilder<'_, '_, L> { pub(super) fn check_binary( &mut self, op: BinaryOp, - left_operand: Id>, - right_operand: Id>, + left_operand: Id, + right_operand: Id, span: Span, expected: Option, ) -> Expr { @@ -312,7 +311,7 @@ impl ThirBuilder<'_, '_, L> { &mut self, op: &str, ty: TypeId, - operand: Id>, + operand: Id, span: Span, fits: impl Fn(&Type) -> bool, ) -> Expr { @@ -339,8 +338,8 @@ impl ThirBuilder<'_, '_, L> { /// can, so `300 as u8` is an error. pub(super) fn check_cast( &mut self, - value: Id>, - ty: Id>, + value: Id, + ty: Id, span: Span, ) -> Expr { let to = self.checker.resolve_value_type(ty); diff --git a/crates/kernel/semantic/src/expression/places.rs b/crates/kernel/semantic/src/expression/places.rs index a2aa8b38..d21eef0d 100644 --- a/crates/kernel/semantic/src/expression/places.rs +++ b/crates/kernel/semantic/src/expression/places.rs @@ -16,15 +16,14 @@ use syntax::ast; use syntax::ast::Ident; use syntax::ast::WrittenRange; -use crate::Checked; use crate::builder::ThirBuilder; -impl ThirBuilder<'_, '_, L> { +impl ThirBuilder<'_, '_> { /// `value.field`: the field of a struct value, or of the struct a /// reference or typed raw pointer points to; or `len`, an array's, a /// slice's or a `&str`'s only field. An array's type gives it, so the /// array is not read. - pub(super) fn check_field(&mut self, value: Id>, field: Ident) -> Expr { + pub(super) fn check_field(&mut self, value: Id, field: Ident) -> Expr { let value = self.add_expr(value, None); let ty = self.body.exprs[value].ty; let pointee = self.checker.types[ty].pointee(); @@ -111,8 +110,8 @@ impl ThirBuilder<'_, '_, L> { /// program runs. A written range slices, which only `&` does. pub(super) fn check_index( &mut self, - array: Id>, - index: Id>, + array: Id, + index: Id, span: Span, ) -> Expr { let tree = &self.checker.module().ast; @@ -200,7 +199,7 @@ impl ThirBuilder<'_, '_, L> { /// index is (`ExprKind::Slice`). Ends known at compile time must be /// inside the array and in order; others, and every end of a slice's, /// are checked when the program runs. A step is an error. - pub(super) fn check_slice(&mut self, mutable: bool, indexed: Id>) -> Expr { + pub(super) fn check_slice(&mut self, mutable: bool, indexed: Id) -> Expr { let tree = &self.checker.module().ast; let ast::Expr::Index { value: array, @@ -272,11 +271,11 @@ impl ThirBuilder<'_, '_, L> { /// order when both are; `None` after an error. pub(super) fn check_slice_ends( &mut self, - ends: [Option>>; 2], + ends: [Option>; 2], inclusive: bool, viewed: TypeId, length: Option, - range: Id>, + range: Id, ) -> Option<[Option>; 2]> { // No slice is longer than the largest `usize`. let limit = length.unwrap_or(u64::MAX >> (64 - self.checker.target.pointer_bits)); @@ -334,7 +333,7 @@ impl ThirBuilder<'_, '_, L> { /// `reference.*`, written at `span`: the value a reference or a typed /// raw pointer points to. - pub(super) fn check_dereference(&mut self, reference: Id>, span: Span) -> Expr { + pub(super) fn check_dereference(&mut self, reference: Id, span: Span) -> Expr { let reference = self.add_expr(reference, None); let ty = self.body.exprs[reference].ty; match &self.checker.types[ty] { diff --git a/crates/kernel/semantic/src/functions.rs b/crates/kernel/semantic/src/functions.rs index c9758749..112ee605 100644 --- a/crates/kernel/semantic/src/functions.rs +++ b/crates/kernel/semantic/src/functions.rs @@ -13,7 +13,6 @@ use model::semantic_types; use source::Span; use syntax::ast; -use crate::Checked; use crate::Checker; use crate::generics; use crate::scope; @@ -76,7 +75,7 @@ impl FunctionKind { }; } -impl Checker<'_, L> { +impl Checker<'_> { /// The type of the module's function or method `definition`. pub(crate) fn check_function(&mut self, definition: DefId) -> semantic_types::TypeId { let tree = &self.module().ast; @@ -203,7 +202,7 @@ impl Checker<'_, L> { pub fn signature_type( &mut self, name: ast::Ident, - signature: ast::Signature, + signature: ast::Signature, has_owner: bool, kind: &FunctionKind, ) -> semantic_types::TypeId { @@ -324,7 +323,7 @@ impl Checker<'_, L> { /// `None` when an error was reported. fn result_origins( &mut self, - signature: &ast::Signature, + signature: &ast::Signature, parameters: &[semantic_types::TypeId], result: semantic_types::TypeId, ) -> Option> { @@ -445,7 +444,7 @@ impl Checker<'_, L> { /// type when `c_types` (`FunctionKind::c_types`). fn resolve_signature_type( &mut self, - ty: Id>, + ty: Id, c_types: bool, ) -> semantic_types::TypeId { let resolved = self.resolve_value_type(ty); diff --git a/crates/kernel/semantic/src/functions/bodies.rs b/crates/kernel/semantic/src/functions/bodies.rs index 9e795854..5d66c293 100644 --- a/crates/kernel/semantic/src/functions/bodies.rs +++ b/crates/kernel/semantic/src/functions/bodies.rs @@ -13,7 +13,6 @@ use model::thir; use rustc_hash::FxHashSet; use source::Span; -use crate::Checked; use crate::Checker; /// How far the body of a function is built (`Checker::build_function`), @@ -26,7 +25,7 @@ pub(crate) enum Built { Kept(Option>), } -impl Checker<'_, L> { +impl Checker<'_> { /// Builds the body of the function `copy`, asked for at `used_at`, into /// `thir`, recording its facts when `records_facts` (not when it is /// built only to run at compile time, `evaluate_call`): checks it diff --git a/crates/kernel/semantic/src/functions/builtin.rs b/crates/kernel/semantic/src/functions/builtin.rs index a27817e5..d329724c 100644 --- a/crates/kernel/semantic/src/functions/builtin.rs +++ b/crates/kernel/semantic/src/functions/builtin.rs @@ -7,7 +7,6 @@ use model::layout; use model::semantic_types; use source::Span; -use crate::Checked; use crate::Checker; /// What a `#[builtin]` function gives of the type it takes, on the target @@ -51,7 +50,7 @@ pub(crate) fn type_fact(name: &str) -> Option { } } -impl Checker<'_, L> { +impl Checker<'_> { /// What the `#[builtin]` function `function`, a copy for the type it /// is given, answers when its call at `span` runs (`evaluate_call`): the /// fact of that type its name asks for. `None` for a type the fact is diff --git a/crates/kernel/semantic/src/functions/calls.rs b/crates/kernel/semantic/src/functions/calls.rs index 357bc9d7..48cfa203 100644 --- a/crates/kernel/semantic/src/functions/calls.rs +++ b/crates/kernel/semantic/src/functions/calls.rs @@ -15,12 +15,11 @@ use model::thir; use source::Span; use syntax::ast; -use crate::Checked; use crate::builder; use crate::generics; use crate::scope; -impl builder::ThirBuilder<'_, '_, L> { +impl builder::ThirBuilder<'_, '_> { /// `callee(arguments)`, written at `span`; a pipe gives its value as the /// first of `arguments`. Only a module's function, by /// its name or its path, can be called, or with a dot, `x.name(arguments)`, @@ -31,9 +30,9 @@ impl builder::ThirBuilder<'_, '_, L> { /// (`copy_called`). pub fn check_call( &mut self, - callee: Id>, - type_arguments: List>, - arguments: &[Id>], + callee: Id, + type_arguments: List, + arguments: &[Id], span: Span, ) -> thir::Expr { let tree = &self.checker.module().ast; @@ -92,8 +91,8 @@ impl builder::ThirBuilder<'_, '_, L> { found: Option<(Callee, semantic_types::TypeId)>, receiver: Option>, callee_span: Span, - type_arguments: List>, - arguments: &[Id>], + type_arguments: List, + arguments: &[Id], span: Span, ) -> thir::Expr { let tree = &self.checker.module().ast; @@ -150,7 +149,7 @@ impl builder::ThirBuilder<'_, '_, L> { } found => found, }; - let not_const = |&(place, _): &(usize, Id>)| !const_places.contains(&place); + let not_const = |&(place, _): &(usize, Id)| !const_places.contains(&place); let signature = found.map(|(callee, ty)| (callee, ty, self.checker.types[ty].clone())); let Some(( callee, @@ -164,7 +163,7 @@ impl builder::ThirBuilder<'_, '_, L> { )) = signature else { let written = arguments.iter().copied().enumerate(); - let unchecked = |&(place, _): &(usize, Id>)| { + let unchecked = |&(place, _): &(usize, Id)| { checked_early.get(place).is_none_or(Option::is_none) }; for (_, argument) in written.filter(not_const).filter(unchecked) { @@ -220,7 +219,7 @@ impl builder::ThirBuilder<'_, '_, L> { checked.push(argument.into()); } if variadic { - let rest: Vec>> = given.map(|(_, argument)| argument).collect(); + let rest: Vec> = given.map(|(_, argument)| argument).collect(); let slice = self.check_variadic(&rest, parameters[first + fixed], span); self.reborrow_in_place(slice); checked.push(slice.into()); @@ -316,7 +315,7 @@ impl builder::ThirBuilder<'_, '_, L> { /// cannot be both (`scope::collect`). fn method( &mut self, - value: Id>, + value: Id, name: ast::Ident, span: Span, ) -> Option<(Id, Callee, semantic_types::TypeId)> { diff --git a/crates/kernel/semantic/src/generics.rs b/crates/kernel/semantic/src/generics.rs index ae6f3b0f..8d484603 100644 --- a/crates/kernel/semantic/src/generics.rs +++ b/crates/kernel/semantic/src/generics.rs @@ -16,18 +16,17 @@ use model::thir; use source::Span; use syntax::ast; -use crate::Checked; use crate::Checker; use crate::builder; -impl Checker<'_, L> { +impl Checker<'_> { /// The value type the argument `argument` is read as where a parameter /// takes a type: a type the parser read (`ast::Expr::Type`), or a value /// spelled like a type, a name, a path, `&x`, `&mut x` or `range[x]`. /// Anything else is reported as not a type. pub(crate) fn resolve_type_argument( &mut self, - argument: Id>, + argument: Id, ) -> semantic_types::TypeId { let resolved = self.expression_type(argument); let span = self.module().ast.exprs.span(argument); @@ -49,13 +48,13 @@ impl Checker<'_, L> { } } -impl builder::ThirBuilder<'_, '_, L> { +impl builder::ThirBuilder<'_, '_> { /// The type `argument`, written in the body for a type (a `const T: /// type` argument, a constraint's subject), names. A local of its name /// is a value, reported; a type of its name elsewhere is still the type. pub(crate) fn written_type_argument( &mut self, - argument: Id>, + argument: Id, ) -> semantic_types::TypeId { let tree = &self.checker.module().ast; let written = tree.exprs.span(argument); @@ -88,8 +87,8 @@ impl builder::ThirBuilder<'_, '_, L> { pub(crate) fn copy_called( &mut self, definition: DefId, - type_arguments: List>, - arguments: &[Id>], + type_arguments: List, + arguments: &[Id], first: usize, const_places: &mut Vec, checked_early: &mut Vec>, @@ -100,7 +99,7 @@ impl builder::ThirBuilder<'_, '_, L> { let declared = model::program::function_declaration(modules, definition); let parameters = tree.children.lists.items(declared.signature.parameters); // The parameters past the receiver, each with its written argument's place. - let written_parameters: Vec<(usize, ast::Param)> = (parameters.skip(first)) + let written_parameters: Vec<(usize, ast::Param)> = (parameters.skip(first)) .map(|parameter| tree.children.params[parameter]) .enumerate() .collect(); @@ -132,7 +131,7 @@ impl builder::ThirBuilder<'_, '_, L> { .map(|parameter| tree.file.slice(tree.children.names.span(parameter))) .collect(); let calling = &self.checker.module().ast; - let written_types: Vec>> = + let written_types: Vec> = calling.children.lists.items(type_arguments).collect(); let function = model::program::declared_path(modules, definition); let mut failed = false; @@ -249,10 +248,7 @@ impl builder::ThirBuilder<'_, '_, L> { /// Where the first parameter of `signature`, in `tree`, that a copy is /// made for is written, if it has one: a type parameter, ``, or a /// `const` parameter. -pub fn first_copy_parameter( - tree: &ast::Tree, - signature: ast::Signature, -) -> Option { +pub fn first_copy_parameter(tree: &ast::Tree, signature: ast::Signature) -> Option { if let Some(parameter) = tree.children.lists.items(signature.type_parameters).next() { return Some(tree.children.names.span(parameter)); } @@ -266,10 +262,7 @@ pub fn first_copy_parameter( /// element of a slice, a `...`, an array or a range. `None` for a name and /// for a type not looked into: a path names another module's type, and a /// type the checker refuses (`resolve_type`), such as `?T`, is reported. -fn written_inside( - tree: &ast::Tree, - ty: Id>, -) -> Option>> { +fn written_inside(tree: &ast::Tree, ty: Id) -> Option> { match tree.types[ty] { ast::Type::Bracketed { inner: written, .. } | ast::Type::Reference { @@ -285,7 +278,7 @@ fn written_inside( // array's element are looked into; a struct's fields and an // interface's methods are taken to name no type parameter, as a // written one is not supported yet. - ast::Type::Feature(ty) => L::pointee(&ty).or_else(|| L::element(&ty)), + ast::Type::Feature(ty) => ty.pointee().or_else(|| ty.element()), ast::Type::Name | ast::Type::Path(_) | ast::Type::Generic { .. } @@ -303,10 +296,10 @@ fn written_inside( /// around the name (`written_inside`) takes the argument's type one step /// in; an argument of another shape finds another type, or none, and the /// call reports the mismatch. -pub(crate) fn find_type_argument( - tree: &ast::Tree, +pub(crate) fn find_type_argument( + tree: &ast::Tree, types: &semantic_types::Types, - written: Id>, + written: Id, ty: semantic_types::TypeId, names: &[&str], found: &mut [Option], @@ -349,9 +342,9 @@ pub(crate) fn find_type_argument( /// Whether the type written `ty` in `tree` names one of `parameters`, the /// names of a function's type parameters, `` or `const T: type`, which /// only its copies know. -pub(crate) fn names_type_parameter( - tree: &ast::Tree, - ty: Id>, +pub(crate) fn names_type_parameter( + tree: &ast::Tree, + ty: Id, parameters: &[&str], ) -> bool { let mut ty = ty; diff --git a/crates/kernel/semantic/src/generics/constraints.rs b/crates/kernel/semantic/src/generics/constraints.rs index 999e5278..b803e4a0 100644 --- a/crates/kernel/semantic/src/generics/constraints.rs +++ b/crates/kernel/semantic/src/generics/constraints.rs @@ -12,11 +12,10 @@ use model::semantic_types; use model::thir; use syntax::ast; -use crate::Checked; use crate::Checker; use crate::builder; -impl Checker<'_, L> { +impl Checker<'_> { /// Whether the constraints of `signature`, after `where`, hold for what /// is being checked, whose parameters are of the types `parameters` /// (`constraint_value`). Its `const` values are declared as in a body. @@ -25,7 +24,7 @@ impl Checker<'_, L> { /// for a copy at the call it was made for: each such call has the error. pub(crate) fn constraints_hold( &mut self, - signature: ast::Signature, + signature: ast::Signature, parameters: &[semantic_types::TypeId], ) -> bool { let checking = (self.internals.declarations_being_checked.last()) @@ -34,7 +33,7 @@ impl Checker<'_, L> { let known = self.in_copy() || arguments == ConstArguments::NONE; let module = copy.definition.module.index(); let tree = &self.module().ast; - let constraints: Vec>> = + let constraints: Vec> = tree.children.lists.items(signature.constraints).collect(); let span = tree.children.constraints.span(constraints[0]); let mut body = thir::Body::default(); @@ -83,13 +82,13 @@ impl Checker<'_, L> { } } -impl builder::ThirBuilder<'_, '_, L> { +impl builder::ThirBuilder<'_, '_> { /// Whether `constraint`, after a function's `where`, holds: its subject, /// a type, implements the interface its bound names, or the function its /// bound names gives `true` when called at compile time with the subject /// first, then the constraint's arguments. `None` when that is not /// known: after an error, reported, or for a subject only a copy knows. - fn constraint_value(&mut self, constraint: Id>) -> Option { + fn constraint_value(&mut self, constraint: Id) -> Option { let tree = &self.checker.module().ast; let span = tree.children.constraints.span(constraint); let ast::Constraint { @@ -99,7 +98,7 @@ impl builder::ThirBuilder<'_, '_, L> { } = tree.children.constraints[constraint]; let bound_span = tree.exprs.span(bound); let bound_text = tree.file.slice(bound_span); - let given: Vec>> = std::iter::once(subject) + let given: Vec> = std::iter::once(subject) .chain(tree.children.lists.items(arguments)) .collect(); let symbol = match tree.exprs[bound] { diff --git a/crates/kernel/semantic/src/generics/copies.rs b/crates/kernel/semantic/src/generics/copies.rs index 1141d6ac..b95ff441 100644 --- a/crates/kernel/semantic/src/generics/copies.rs +++ b/crates/kernel/semantic/src/generics/copies.rs @@ -19,12 +19,11 @@ use source::Span; use syntax::ast; use crate::COPY_DEPTH_LIMIT; -use crate::Checked; use crate::Checker; use crate::Checking; use crate::Copied; -impl Checker<'_, L> { +impl Checker<'_> { /// The type of `copy`, asked for at `used_at`: given nothing, its /// declaration's own (`function_type`, `declared_type`); else the type /// of its copy for what it is given, made the first time it is asked @@ -196,12 +195,11 @@ impl Checker<'_, L> { &mut self, definition: DefId, name: &str, - written: List>, + written: List, span: Span, - ) -> Option>>> { + ) -> Option>> { let count = model::program::declaration_copy_parameters(self.modules, definition).count(); - let written: Vec>> = - self.module().ast.children.lists.items(written).collect(); + let written: Vec> = self.module().ast.children.lists.items(written).collect(); if written.len() == count { return Some(written); } @@ -255,7 +253,7 @@ impl Checker<'_, L> { } } -impl Checker<'_, L> { +impl Checker<'_> { /// Makes the fact that the name ending at `name_end` is a function /// (`record`) the fact that its call there made `copy`, of the type /// `ty`. Only a body checked once has it: a copy has no facts, and a diff --git a/crates/kernel/semantic/src/lib.rs b/crates/kernel/semantic/src/lib.rs index 51bd6819..b3ded92e 100644 --- a/crates/kernel/semantic/src/lib.rs +++ b/crates/kernel/semantic/src/lib.rs @@ -61,47 +61,44 @@ use rustc_hash::FxHashMap; use scope::Scope; use source::Span; use syntax::ast; -use syntax::ast::Language; -/// What the checker asks of a language: how each feature's nodes are -/// checked (docs/feature-front.md, section 7). -pub trait Checked: Language { +/// How the checker checks the nodes of the features, which the `features` +/// crate gives: one function per kind of node, each a `match` that hands +/// the node to its feature (docs/structure-mapping.md, step 7). +pub struct CheckHooks { /// The feature expression `expr`, written at `span`, where a value of /// the type `expected` is wanted, if one is. - fn check_expr( - builder: &mut ThirBuilder<'_, '_, Self>, - expr: Self::Expr, + pub check_expr: fn( + builder: &mut ThirBuilder<'_, '_>, + expr: ast::FeatureExpr, span: Span, expected: Option, - ) -> thir::Expr; - + ) -> thir::Expr, /// The feature statement `stmt`, written at `span`; `None` when it /// leaves no statement, after an error. - fn check_stmt( - builder: &mut ThirBuilder<'_, '_, Self>, - stmt: Self::Stmt, + pub check_stmt: fn( + builder: &mut ThirBuilder<'_, '_>, + stmt: ast::FeatureStmt, span: Span, - ) -> Option; - + ) -> Option, /// The type the feature type `ty`, written at `span`, names. - fn resolve_type(checker: &mut Checker<'_, Self>, ty: Self::Type, span: Span) -> TypeId; - + pub resolve_type: fn(checker: &mut Checker<'_>, ty: ast::FeatureType, span: Span) -> TypeId, /// The type the module's type declaration `definition`, written /// `written`, declares with the feature type `ty`. - fn declare_type( - checker: &mut Checker<'_, Self>, + pub declare_type: fn( + checker: &mut Checker<'_>, definition: DefId, - written: ast::TypeDecl, - ty: Self::Type, - ) -> TypeId; + written: ast::TypeDecl, + ty: ast::FeatureType, + ) -> TypeId, } /// Checks a program's declarations. Each module-scope declaration (`DefId`) /// is checked once, the first time anything asks for it, and its result is /// kept in the table of its category: types, functions or constants. A body's /// own names (`Symbol::Local`) are checked in place with the body. -pub struct Checker<'p, L: Language> { - pub modules: &'p [model::program::Module], // in the program's order +pub struct Checker<'p> { + pub modules: &'p [model::program::Module], // in the program's order /// What checking each module found so far, by `ModuleId`. pub module_checks: Vec>, pub types: Types, // the program's types, built-in and declared @@ -111,6 +108,8 @@ pub struct Checker<'p, L: Language> { /// The machine the program is for: the width of `isize` and `usize` is /// its `pointer_bits`, and a value may take its `largest_object` bytes. pub target: &'static Machine, + /// How the features' nodes are checked. + hooks: &'static CheckHooks, internals: CheckerInternals, } @@ -230,15 +229,16 @@ pub enum State { Done(T), } -impl<'p, L: Checked> Checker<'p, L> { +impl<'p> Checker<'p> { /// Nothing checked yet of `modules` but their scopes, whose errors are /// each module's first diagnostics, for `target`. /// Facts are recorded when `record_facts`, as for an editor. pub fn new( - modules: &'p [model::program::Module], + modules: &'p [model::program::Module], target: &'static Machine, record_facts: bool, - ) -> Checker<'p, L> { + hooks: &'static CheckHooks, + ) -> Checker<'p> { let module_checks = (0..modules.len()) .map(|index| { let mut diagnostics = Vec::new(); @@ -261,6 +261,7 @@ impl<'p, L: Checked> Checker<'p, L> { types: Types::new(target.pointer_bits), debug_types: ProgramDebugTypes::default(), target, + hooks, internals: CheckerInternals { known_implementations: FxHashMap::default(), records_editor_facts: record_facts, @@ -517,7 +518,7 @@ impl<'p, L: Checked> Checker<'p, L> { } /// The module being checked. - pub fn module(&self) -> &'p model::program::Module { + pub fn module(&self) -> &'p model::program::Module { &self.modules[self.current_module().index()] } @@ -634,11 +635,11 @@ impl<'p, L: Checked> Checker<'p, L> { /// `module::Type::name`. A path that names nothing or is not supported is /// reported. Another module's name is reachable only if it starts with an /// upper case letter. - pub(crate) fn resolve_path(&mut self, path: Id>) -> Option { + pub(crate) fn resolve_path(&mut self, path: Id) -> Option { let tree = &self.module().ast; let span = tree.types.span(path); // A `Type::Generic` alone, as `Box`, is one segment. - let segments: Vec>> = match tree.types[path] { + let segments: Vec> = match tree.types[path] { ast::Type::Path(segments) => tree.children.lists.items(segments).collect(), _ => vec![path], }; diff --git a/crates/kernel/semantic/src/locals.rs b/crates/kernel/semantic/src/locals.rs index 31bc07b1..9aff204c 100644 --- a/crates/kernel/semantic/src/locals.rs +++ b/crates/kernel/semantic/src/locals.rs @@ -9,19 +9,18 @@ use model::thir; use source::Span; use syntax::ast; -use crate::Checked; use crate::builder; use crate::functions; -impl builder::ThirBuilder<'_, '_, L> { +impl builder::ThirBuilder<'_, '_> { /// `let mut name: ty = value;`. The variable is declared after its value is /// checked, so the value cannot use it. pub(super) fn check_let_statement( &mut self, mutable: bool, name: ast::Ident, - ty: Option>>, - value: Option>>, + ty: Option>, + value: Option>, ) -> thir::Stmt { let declared = ty.map(|ty| self.checker.resolve_value_type(ty)); let initialized = value.is_some(); @@ -97,7 +96,7 @@ impl builder::ThirBuilder<'_, '_, L> { /// value, or `None` after an error. pub(crate) fn check_const_statement( &mut self, - declaration: Id>, + declaration: Id, ) -> Option { let ast::Decl::Const { name, ty, value, .. @@ -122,7 +121,7 @@ impl builder::ThirBuilder<'_, '_, L> { /// it is known only when the program runs, reported. pub(crate) fn check_constant_value( &mut self, - value: Id>, + value: Id, declared: Option, ) -> Option { let span = self.checker.module().ast.exprs.span(value); diff --git a/crates/kernel/semantic/src/scope.rs b/crates/kernel/semantic/src/scope.rs index d14d87ae..abf209a4 100644 --- a/crates/kernel/semantic/src/scope.rs +++ b/crates/kernel/semantic/src/scope.rs @@ -17,7 +17,6 @@ use rustc_hash::FxHashMap; use source::SourceFile; use source::Span; use syntax::ast; -use syntax::ast::Language; /// A place that holds declarations, and where each name is written. A module /// has one for its top-level declarations, imports and type functions. A name @@ -51,9 +50,9 @@ impl<'p> Scope<'p> { /// (`fn Point::name`, `has_functions`); `None` for any other name. A type /// here is always this module's: imports bring in modules, and the /// prelude is not copied in. - pub(crate) fn owner_named( + pub(crate) fn owner_named( &self, - modules: &[model::program::Module], + modules: &[model::program::Module], name: &str, ) -> Option { match self.get(None, name) { @@ -92,10 +91,7 @@ impl<'p> Scope<'p> { /// Whether the declaration `definition` can have functions /// (`fn Point::name`): any type it declares, not an alias, which names a /// type declared elsewhere. -pub(crate) fn has_functions( - modules: &[model::program::Module], - definition: DefId, -) -> bool { +pub(crate) fn has_functions(modules: &[model::program::Module], definition: DefId) -> bool { matches!( model::program::declaration(modules, definition), ast::Decl::Type(_) @@ -140,9 +136,9 @@ pub fn report_redeclared( /// top-level names, since a type may be declared below its functions; the /// type must be one this module declares, so it has the same functions /// everywhere. -pub fn collect<'p, L: Language>( +pub fn collect<'p>( id: ModuleId, - modules: &'p [model::program::Module], + modules: &'p [model::program::Module], diagnostics: &mut Vec, ) -> Scope<'p> { let module = &modules[id.index()]; diff --git a/crates/kernel/semantic/src/statement.rs b/crates/kernel/semantic/src/statement.rs index 42b7e1f4..3807674b 100644 --- a/crates/kernel/semantic/src/statement.rs +++ b/crates/kernel/semantic/src/statement.rs @@ -27,14 +27,13 @@ use source::Span; use syntax::ast; use syntax::ast::Ident; -use crate::Checked; use crate::Checker; use crate::Checking; use crate::builder::Declared; use crate::builder::ThirBuilder; use crate::scope::report_redeclared; -impl Checker<'_, L> { +impl Checker<'_> { /// Puts in `body` the THIR of the body of the function `copy`, /// asked for at `used_at`, recording its facts when `records_facts` /// (`Checking`), with `has_errors` set when it has an error (`Body`); @@ -107,7 +106,7 @@ impl Checker<'_, L> { } } -impl<'a, 'p, L: Checked> ThirBuilder<'a, 'p, L> { +impl<'a, 'p> ThirBuilder<'a, 'p> { /// Declares the parameters of `signature`, of the function being /// checked, in `scope`: each one that is not `const` as a variable of /// its type in `types`, and each `const` value as a constant, the value @@ -116,7 +115,7 @@ impl<'a, 'p, L: Checked> ThirBuilder<'a, 'p, L> { /// `const T: type`, is a type (`resolve_global`). pub(crate) fn declare_parameters( &mut self, - signature: ast::Signature, + signature: ast::Signature, arguments: ConstArguments, types: &[TypeId], scope: Id, @@ -166,7 +165,7 @@ impl<'a, 'p, L: Checked> ThirBuilder<'a, 'p, L> { fn check_statements( &mut self, first: Option>, - statements: List>, + statements: List, ) -> List { let mut checked: Vec = Vec::with_capacity(statements.len() + 1); checked.extend(first.map(NonZeroU32::from)); @@ -212,7 +211,7 @@ impl<'a, 'p, L: Checked> ThirBuilder<'a, 'p, L> { /// The THIR of `block`; the names it declares end with it. It is added /// before the blocks inside it. - fn check_block(&mut self, block: Id>) -> Id { + fn check_block(&mut self, block: Id) -> Id { let enclosing = self.open_block(block); self.close_block(block, enclosing, None) } @@ -241,7 +240,7 @@ impl<'a, 'p, L: Checked> ThirBuilder<'a, 'p, L> { /// Makes `block` the current block, for names declared before its /// statements; gives the enclosing block and where its names start, for /// `close_block`. - fn open_block(&mut self, block: Id>) -> (Id, usize) { + fn open_block(&mut self, block: Id) -> (Id, usize) { let opened = Block { parent: Some(self.block), statements: List::EMPTY, @@ -258,7 +257,7 @@ impl<'a, 'p, L: Checked> ThirBuilder<'a, 'p, L> { /// again. fn close_block( &mut self, - block: Id>, + block: Id, enclosing: (Id, usize), first: Option>, ) -> Id { @@ -367,7 +366,7 @@ impl<'a, 'p, L: Checked> ThirBuilder<'a, 'p, L> { /// The THIR of `statement`; `None` for a `const`, which only declares a /// name, and for a statement with an error. - fn check_statement(&mut self, statement: Id>) -> Option> { + fn check_statement(&mut self, statement: Id) -> Option> { // Blocks in blocks and long `else if` chains are a deep recursion. source::grow_stack(|| { let tree = &self.checker.module().ast; @@ -391,7 +390,7 @@ impl<'a, 'p, L: Checked> ThirBuilder<'a, 'p, L> { } ast::Stmt::Return(value) => Stmt::Return(self.check_return_value(span, value)), ast::Stmt::Panic(message) => self.check_panic(message)?, - ast::Stmt::Feature(stmt) => L::check_stmt(self, stmt, span)?, + ast::Stmt::Feature(stmt) => (self.checker.hooks.check_stmt)(self, stmt, span)?, ast::Stmt::Expression(value) => Stmt::Expression(self.add_expr(value, None)), ast::Stmt::Assign { target, value } => self.assign(target, value)?, ast::Stmt::If { @@ -501,7 +500,7 @@ impl<'a, 'p, L: Checked> ThirBuilder<'a, 'p, L> { } /// `panic message;`: the message is a plain string literal. - fn check_panic(&mut self, message: Id>) -> Option { + fn check_panic(&mut self, message: Id) -> Option { let tree = &self.checker.module().ast; let message = tree.unparenthesized(message); let span = tree.exprs.span(message); diff --git a/crates/kernel/semantic/src/statement/assignments.rs b/crates/kernel/semantic/src/statement/assignments.rs index dcf4fe8d..92d54e47 100644 --- a/crates/kernel/semantic/src/statement/assignments.rs +++ b/crates/kernel/semantic/src/statement/assignments.rs @@ -13,15 +13,14 @@ use model::thir::Variable; use source::Span; use syntax::ast; -use crate::Checked; use crate::builder::ThirBuilder; -impl ThirBuilder<'_, '_, L> { +impl ThirBuilder<'_, '_> { /// The value of `return value;`, checked against the function's result. pub(super) fn check_return_value( &mut self, span: Span, - value: Option>>, + value: Option>, ) -> Option> { match value { Some(value) if self.result == TypeId::VOID => { @@ -81,11 +80,7 @@ impl ThirBuilder<'_, '_, L> { /// temporaries of its value as long as that variable, as a `let` does; /// one behind a reference or slice is in storage the variable does not /// own. - pub(super) fn assign( - &mut self, - target: Id>, - value: Id>, - ) -> Option { + pub(super) fn assign(&mut self, target: Id, value: Id) -> Option { let Some(target) = self.assigned_place(target) else { self.add_expr(value, None); // for its own errors return None; @@ -102,7 +97,7 @@ impl ThirBuilder<'_, '_, L> { /// The variable, field, element or referred value that `target` names, /// reporting one that cannot be set (`report_unwritable`). One that cannot /// be set is still given, so the value is checked against its type. - pub(super) fn assigned_place(&mut self, target: Id>) -> Option> { + pub(super) fn assigned_place(&mut self, target: Id) -> Option> { let tree = &self.checker.module().ast; let place = match tree.exprs[target] { ast::Expr::Selector { .. } | ast::Expr::Dereference(_) | ast::Expr::Index { .. } => { @@ -160,7 +155,7 @@ impl ThirBuilder<'_, '_, L> { /// The variable that `target` names, reporting a target that is not a /// variable. - pub(super) fn assigned_variable(&mut self, target: Id>) -> Option> { + pub(super) fn assigned_variable(&mut self, target: Id) -> Option> { let tree = &self.checker.module().ast; let span = tree.exprs.span(target); let symbol = match tree.exprs[target] { diff --git a/crates/kernel/semantic/src/statement/loops.rs b/crates/kernel/semantic/src/statement/loops.rs index d5b7b8f1..b93a9f16 100644 --- a/crates/kernel/semantic/src/statement/loops.rs +++ b/crates/kernel/semantic/src/statement/loops.rs @@ -20,15 +20,14 @@ use source::Span; use syntax::ast; use syntax::ast::Ident; -use crate::Checked; use crate::builder::ThirBuilder; -impl ThirBuilder<'_, '_, L> { +impl ThirBuilder<'_, '_> { /// `close_block` for a loop's `body`, in which `break` and `continue` /// are allowed. pub(super) fn check_loop_body( &mut self, - body: Id>, + body: Id, enclosing: (Id, usize), first: Option>, ) -> Id { @@ -63,7 +62,7 @@ impl ThirBuilder<'_, '_, L> { index: Option, value: Option, range: Id, - body: Id>, + body: Id, ) -> Stmt { let element = match self.checker.types[self.body.exprs[range].ty] { Type::Range { element, .. } => element, @@ -105,7 +104,7 @@ impl ThirBuilder<'_, '_, L> { index: Option, value: Ident, iterable: Id, - body: Id>, + body: Id, ) -> Option { self.reborrow_in_place(iterable); let (items_type, span) = (self.body.exprs[iterable].ty, self.body.exprs.span(iterable)); diff --git a/crates/kernel/semantic/src/testing.rs b/crates/kernel/semantic/src/testing.rs index 40746dde..a7e7188f 100644 --- a/crates/kernel/semantic/src/testing.rs +++ b/crates/kernel/semantic/src/testing.rs @@ -1,104 +1,29 @@ //! What the checking tests share: a one-module program read from text, whose //! declarations are checked one at a time. -use arena::Id; -use arena::List; -use model::DefId; -use model::semantic_types::TypeId; -use model::thir; -use parser::Grammar; -use parser::Rules; -use source::Span; -use std::convert::Infallible; use std::sync::Arc; -use syntax::ast; -use syntax::ast::Language; -use syntax::operators::Precedence; use model::ModuleId; use model::machine::Machine; use model::program::ImportKind; use model::semantic_types::Types; +use parser::Rules; use source::SourceFile; -use crate::Checked; +use crate::CheckHooks; use crate::Checker; -use crate::builder::ThirBuilder; - -/// The language the checking tests are written in: the core, with no -/// feature, since the `features` crate depends on this one. -#[derive(Clone, Copy, Debug)] -pub(crate) enum Bare {} - -impl Language for Bare { - type Expr = Infallible; - type Type = Infallible; - type Stmt = Infallible; - - fn precedence(expr: &Infallible) -> Precedence { - match *expr {} - } - - fn fields(ty: &Infallible) -> Option>> { - match *ty {} - } - - fn methods(ty: &Infallible) -> Option>> { - match *ty {} - } - - fn pointee(ty: &Infallible) -> Option>> { - match *ty {} - } - - fn element(ty: &Infallible) -> Option>> { - match *ty {} - } - fn written_range(expr: &Infallible) -> Option> { - match *expr {} - } -} - -static RULES: Rules = Rules::core(); - -impl Grammar for Bare { - fn rules() -> &'static Rules { - &RULES - } -} - -impl Checked for Bare { - fn check_expr( - _: &mut ThirBuilder<'_, '_, Bare>, - expr: Infallible, - _: Span, - _: Option, - ) -> thir::Expr { - match expr {} - } - - fn check_stmt( - _: &mut ThirBuilder<'_, '_, Bare>, - stmt: Infallible, - _: Span, - ) -> Option { - match stmt {} - } +/// The core's rules alone: the checking tests read no feature, since the +/// `features` crate depends on this one. +static RULES: Rules = Rules::core(); - fn resolve_type(_: &mut Checker<'_, Bare>, ty: Infallible, _: Span) -> TypeId { - match ty {} - } - - fn declare_type( - _: &mut Checker<'_, Bare>, - _: DefId, - _: ast::TypeDecl, - ty: Infallible, - ) -> TypeId { - match ty {} - } -} +/// The core's rules make no feature node, so no hook is ever asked. +static HOOKS: CheckHooks = CheckHooks { + check_expr: |_, _, _, _| unreachable!("the core rules read no feature expression"), + check_stmt: |_, _, _| unreachable!("the core rules read no feature statement"), + resolve_type: |_, _, _| unreachable!("the core rules read no feature type"), + declare_type: |_, _, _, _| unreachable!("the core rules read no feature type"), +}; /// The module `path`, written as `text`, with `imports`; its text must parse /// without errors. @@ -106,9 +31,9 @@ pub(crate) fn module( path: &str, text: &str, imports: Vec, -) -> model::program::Module { +) -> model::program::Module { let file = Arc::new(SourceFile::new("main.peep", text)); - let (ast, parse) = parser::parse(&file); + let (ast, parse) = parser::parse(&file, &RULES); assert!(parse.is_empty(), "{parse:?}"); model::program::Module { path: path.to_string(), @@ -128,7 +53,7 @@ pub(crate) type Reported = (&'static str, String, String); /// types and the diagnostics. pub(crate) fn with_checker( text: &str, - work: impl FnOnce(&mut Checker, ModuleId) -> T, + work: impl FnOnce(&mut Checker, ModuleId) -> T, ) -> (T, Types, Vec) { let (utils_id, main_id) = (ModuleId::from_index(0), ModuleId::from_index(1)); let imports = vec![model::program::Import { @@ -141,7 +66,12 @@ pub(crate) fn with_checker( module("app:main", &text, imports), ]; let file = modules[1].ast.file.clone(); - let mut checker = Checker::new(&modules, Machine::named("x86_64-linux").unwrap(), false); + let mut checker = Checker::new( + &modules, + Machine::named("x86_64-linux").unwrap(), + false, + &HOOKS, + ); let result = work(&mut checker, main_id); let reported = checker .module_checks diff --git a/crates/kernel/syntax/parser/src/decl.rs b/crates/kernel/syntax/parser/src/decl.rs index e1f15a60..c26a9af2 100644 --- a/crates/kernel/syntax/parser/src/decl.rs +++ b/crates/kernel/syntax/parser/src/decl.rs @@ -21,7 +21,6 @@ use syntax::ast::TypeDecl; use syntax::operators::Precedence; use token::TokenKind; -use crate::Grammar; use crate::Parser; use crate::Rules; use crate::expr::name_or_path; @@ -31,40 +30,40 @@ use crate::types::starts_type; /// Reads the declaration the current keyword begins, with its doc comment and /// attributes. -pub type DeclarationRule = fn(&mut Parser, Metadata) -> Id>; +pub type DeclarationRule = fn(&mut Parser, Metadata) -> Id; /// The reader of each declaration a keyword begins, indexed by token kind; /// each takes the declaration's doc comment and attributes. -pub(crate) const fn declaration_rows(rules: &mut Rules) { +pub(crate) const fn declaration_rows(rules: &mut Rules) { rules.declaration(TokenKind::Fn, function_decl); rules.declaration(TokenKind::Const, const_decl); rules.declaration(TokenKind::Type, type_decl); } /// Whether `kind` begins a declaration or an import. -pub(crate) fn starts_declaration(kind: TokenKind) -> bool { - L::rules().declarations[kind as usize].is_some() || kind == TokenKind::Import +pub(crate) fn starts_declaration(p: &Parser, kind: TokenKind) -> bool { + p.rules.declarations[kind as usize].is_some() || kind == TokenKind::Import } -fn starts_parameter(kind: TokenKind) -> bool { +fn starts_parameter(p: &Parser, kind: TokenKind) -> bool { matches!( kind, TokenKind::Const | TokenKind::Mut | TokenKind::Underscore | TokenKind::SelfValue - ) || starts_type::(kind) + ) || starts_type(p, kind) } -impl Parser { +impl Parser { pub(crate) fn module(&mut self) { let mut imports = Vec::new(); let mark = self.list_items.len(); loop { let metadata = self.metadata(); let kind = self.tok().kind; - if starts_declaration::(kind) { + if starts_declaration(self, kind) { self.recovering = false; } let first = self.tree.children.lists.items(metadata.attributes).next(); - if L::rules().declarations[kind as usize].is_none() + if self.rules.declarations[kind as usize].is_none() && let Some(attribute) = first { let span = self.tree.children.attributes.span(attribute); @@ -83,7 +82,7 @@ impl Parser { return; } TokenKind::Import => imports.extend(self.import_decl()), - kind if let Some(read) = L::rules().declarations[kind as usize] => { + kind if let Some(read) = self.rules.declarations[kind as usize] => { let decl = read(self, metadata); self.list_items.push(decl.into()); } @@ -114,7 +113,7 @@ impl Parser { .label(&self.tree.file, t.span, "expected a declaration here") .help("move this statement into a function", Vec::new()), ); - while !self.at(TokenKind::Eof) && !starts_declaration::(self.tok().kind) { + while !self.at(TokenKind::Eof) && !starts_declaration(self, self.tok().kind) { self.next(); } } @@ -123,7 +122,7 @@ impl Parser { } /// Reads the doc comment and attributes in front of a declaration. - fn metadata(&mut self) -> Metadata { + fn metadata(&mut self) -> Metadata { let doc_comment = self.doc_comment(); let mark = self.list_items.len(); while self.at(TokenKind::Hash) { @@ -158,7 +157,7 @@ impl Parser { } /// Reads `#[name]` or `#[name(arguments)]`; one attribute per block. - fn attribute(&mut self) -> Id> { + fn attribute(&mut self) -> Id { let start = self.next().span.start; let Some(open) = self.expect(TokenKind::LeftBracket) else { let name = Ident { span: self.here() }; @@ -177,7 +176,7 @@ impl Parser { TokenKind::LeftParen, TokenKind::RightParen, false, - starts_expression::, + starts_expression, |p| p.expr(Precedence::Lowest), ); } @@ -196,7 +195,7 @@ impl Parser { ); while !self.at(TokenKind::RightBracket) && !self.at(TokenKind::Eof) - && !starts_declaration::(self.tok().kind) + && !starts_declaration(self, self.tok().kind) { self.next(); } @@ -225,10 +224,10 @@ impl Parser { /// Reads `name(parameters) -> Result in origins where T: Bound` /// after a function's `fn` and owner: its name and signature. - pub fn named_signature(&mut self) -> (Ident, Signature) { + pub fn named_signature(&mut self) -> (Ident, Signature) { let name = self.name(); let type_parameters = self.type_parameters(); - let mut signature = self.signature(type_parameters, starts_parameter::, Self::parameter); + let mut signature = self.signature(type_parameters, starts_parameter, Self::parameter); if self.at(TokenKind::Where) { self.next(); let mark = self.list_items.len(); @@ -248,7 +247,7 @@ impl Parser { } /// Reads `T: Bound` or `T: Bound(arguments)`, a constraint after `where`. - fn constraint(&mut self) -> Id> { + fn constraint(&mut self) -> Id { let start = self.tok().span.start; let subject = self.name(); let subject = self.tree.add(Expr::Name, subject.span); @@ -265,7 +264,7 @@ impl Parser { TokenKind::LeftParen, TokenKind::RightParen, false, - starts_expression::, + starts_expression, |p| p.expr(Precedence::Lowest), ); } @@ -300,18 +299,19 @@ impl Parser { return List::EMPTY; } let open = self.next(); - let names = self.items(TokenKind::Greater, false, is_name, Self::name_node); + let names = self.items( + TokenKind::Greater, + false, + |_, kind| is_name(kind), + Self::name_node, + ); self.close_angle(open); names } /// Reads `name: Type = value;` after `let` or `const`; the type and the /// value may be left out. - #[expect( - clippy::type_complexity, - reason = "three parts; only the language parameter is long" - )] - pub(crate) fn binding(&mut self) -> (Ident, Option>>, Option>>) { + pub(crate) fn binding(&mut self) -> (Ident, Option>, Option>) { let name = self.name(); let ty = self.at(TokenKind::Colon).then(|| { self.next(); @@ -330,7 +330,7 @@ impl Parser { /// or `...mut T`; `const name: type`, which takes a type; or `self`, /// `mut self`, `&self` or `&mut self`, the parameter `self` of the type /// the function belongs to. - fn parameter(&mut self) -> Id> { + fn parameter(&mut self) -> Id { let start = self.tok().span.start; let reference = self.at(TokenKind::Ampersand); let mutable = self.ahead(usize::from(reference)).kind == TokenKind::Mut; @@ -455,9 +455,9 @@ impl Parser { pub(crate) fn signature( &mut self, type_parameters: List, - starts_parameter: fn(TokenKind) -> bool, - parameter: impl FnMut(&mut Self) -> Id>, - ) -> Signature { + starts_parameter: fn(&Parser, TokenKind) -> bool, + parameter: impl FnMut(&mut Self) -> Id, + ) -> Signature { let parameters = self.delimited( TokenKind::LeftParen, TokenKind::RightParen, @@ -470,7 +470,7 @@ impl Parser { if kind == TokenKind::Arrow { self.next(); result = Some(self.type_expr()); - } else if starts_type::(kind) && !starts_declaration::(kind) { + } else if starts_type(self, kind) && !starts_declaration(self, kind) { // A type right after the parameters can only be the result; `fn`, // `struct`, `enum` or `iface` there starts the next declaration. let at = self.here(); @@ -493,7 +493,7 @@ impl Parser { TokenKind::LeftParen, TokenKind::RightParen, false, - |kind| is_name(kind) || kind == TokenKind::SelfValue, + |_, kind| is_name(kind) || kind == TokenKind::SelfValue, Self::origin, ); } else { @@ -514,7 +514,7 @@ impl Parser { /// Reads `fn name(parameters) -> Result in origins where T: Bound`, with `Owner::` /// before the name for a function of the type `Owner`, followed by a body, /// or by `;` for a function defined elsewhere. -fn function_decl(p: &mut Parser, metadata: Metadata) -> Id> { +fn function_decl(p: &mut Parser, metadata: Metadata) -> Id { let start = p.next().span.start; let owner = (p.at(TokenKind::Ident) && p.ahead(1).kind == TokenKind::ColonColon).then(|| { let owner = p.name(); @@ -553,7 +553,7 @@ fn function_decl(p: &mut Parser, metadata: Metadata) -> Id(p: &mut Parser, metadata: Metadata) -> Id> { +pub(crate) fn const_decl(p: &mut Parser, metadata: Metadata) -> Id { let start = p.next().span.start; let (name, ty, value) = p.binding(); p.add( @@ -570,12 +570,12 @@ pub(crate) fn const_decl(p: &mut Parser, metadata: Metadata) - /// Reads `type Name = Type;`, or a keyword, a name and the rest of the /// type the keyword begins: `enum Name { variants }`. A `;` after the /// `}` is allowed. -pub fn type_decl(p: &mut Parser, metadata: Metadata) -> Id> { +pub fn type_decl(p: &mut Parser, metadata: Metadata) -> Id { let keyword = p.next(); let name = p.name(); let type_parameters = p.type_parameters(); let start = p.tok().span.start; - let ty = if let Some(read) = L::rules().type_starts[keyword.kind as usize] { + let ty = if let Some(read) = p.rules.type_starts[keyword.kind as usize] { read(p, start) } else { p.expect(TokenKind::Assign); diff --git a/crates/kernel/syntax/parser/src/dump.rs b/crates/kernel/syntax/parser/src/dump.rs index afc575c2..b2a1e538 100644 --- a/crates/kernel/syntax/parser/src/dump.rs +++ b/crates/kernel/syntax/parser/src/dump.rs @@ -27,9 +27,7 @@ use syntax::ast::Type; use token::TokenKind; -use crate::tests::Bare; - -pub(crate) fn dump(tree: &Tree, spans: bool) -> String { +pub(crate) fn dump(tree: &Tree, spans: bool) -> String { let mut d = Dumper { tree, spans, @@ -46,21 +44,21 @@ pub(crate) fn dump(tree: &Tree, spans: bool) -> String { #[derive(Clone, Copy)] enum Item { Import(Import), - Metadata(Metadata), - Attribute(Id>), - Decl(Id>), - Param(Id>), - Constraint(Id>), - Type(Id>), - Block(Id>), - Stmt(Id>), - Pattern(Id>), - Expr(Id>), + Metadata(Metadata), + Attribute(Id), + Decl(Id), + Param(Id), + Constraint(Id), + Type(Id), + Block(Id), + Stmt(Id), + Pattern(Id), + Expr(Id), Leaf(&'static str, Span), } struct Dumper<'t> { - tree: &'t Tree, + tree: &'t Tree, spans: bool, out: String, } @@ -110,7 +108,7 @@ impl<'t> Dumper<'t> { } } - fn metadata(&self, metadata: Metadata) -> Option { + fn metadata(&self, metadata: Metadata) -> Option { (metadata.doc_comment.is_some() || !metadata.attributes.is_empty()) .then_some(Item::Metadata(metadata)) } @@ -250,7 +248,7 @@ impl<'t> Dumper<'t> { /// A signature's parts, with the function's `name`, if any, in source /// order. - fn signature(&self, name: Option, signature: Signature) -> Vec { + fn signature(&self, name: Option, signature: Signature) -> Vec { let mut nested: Vec = name.map(declared).into_iter().collect(); nested.extend(self.names("declared name", signature.type_parameters)); let parameters = self.tree.children.lists.items(signature.parameters); @@ -262,15 +260,12 @@ impl<'t> Dumper<'t> { nested } - fn type_node( - &self, - id: Id>, - ) -> (&'static str, Option<&'static str>, Span, Vec) { + fn type_node(&self, id: Id) -> (&'static str, Option<&'static str>, Span, Vec) { let t = self.tree; let span = t.types.span(id); - let one = |ty: Id>| vec![Item::Type(ty)]; + let one = |ty: Id| vec![Item::Type(ty)]; let (kind, op, nested) = match t.types[id] { - Type::Feature(feature) => match feature {}, + Type::Feature(_) => unreachable!("the core rules read no feature type"), Type::Name => ("type name", None, vec![]), Type::Path(segments) => ( "path", @@ -304,7 +299,7 @@ impl<'t> Dumper<'t> { (kind, op, span, nested) } - fn stmt(&self, id: Id>) -> (&'static str, Option<&'static str>, Span, Vec) { + fn stmt(&self, id: Id) -> (&'static str, Option<&'static str>, Span, Vec) { let t = self.tree; let (kind, op, nested) = match t.stmts[id] { Stmt::Let { @@ -324,7 +319,7 @@ impl<'t> Dumper<'t> { value.map(Item::Expr).into_iter().collect(), ), Stmt::Panic(message) => ("panic statement", None, vec![Item::Expr(message)]), - Stmt::Feature(feature) => match feature {}, + Stmt::Feature(_) => unreachable!("the core rules read no feature statement"), Stmt::Expression(e) => ("expression statement", None, vec![Item::Expr(e)]), Stmt::Assign { target, value } => ( "assign statement", @@ -372,10 +367,7 @@ impl<'t> Dumper<'t> { (kind, op, t.stmts.span(id), nested) } - fn pattern( - &self, - id: Id>, - ) -> (&'static str, Option<&'static str>, Span, Vec) { + fn pattern(&self, id: Id) -> (&'static str, Option<&'static str>, Span, Vec) { let t = self.tree; let (kind, nested) = match t.patterns[id] { Pattern::Wildcard => ("wildcard pattern", vec![]), @@ -401,12 +393,12 @@ impl<'t> Dumper<'t> { (kind, None, t.patterns.span(id), nested) } - fn expr(&self, id: Id>) -> (&'static str, Option<&'static str>, Span, Vec) { + fn expr(&self, id: Id) -> (&'static str, Option<&'static str>, Span, Vec) { let t = self.tree; - let one = |e: Id>| vec![Item::Expr(e)]; - let two = |a: Id>, b: Item| vec![Item::Expr(a), b]; + let one = |e: Id| vec![Item::Expr(e)]; + let two = |a: Id, b: Item| vec![Item::Expr(a), b]; let (kind, op, nested) = match t.exprs[id] { - Expr::Feature(feature) => match feature {}, + Expr::Feature(_) => unreachable!("the core rules read no feature expression"), Expr::Name => ("name reference", None, vec![]), Expr::Number => ("number literal", None, vec![]), Expr::None => ("none literal", None, vec![]), diff --git a/crates/kernel/syntax/parser/src/expr.rs b/crates/kernel/syntax/parser/src/expr.rs index 866a52f6..62fe8717 100644 --- a/crates/kernel/syntax/parser/src/expr.rs +++ b/crates/kernel/syntax/parser/src/expr.rs @@ -16,23 +16,22 @@ use syntax::operators::Precedence; use syntax::operators::UnaryOp; use token::TokenKind; -use crate::Grammar; use crate::Parser; use crate::Rules; use crate::literals; /// Reads the expression the current token begins. -pub type PrefixRule = fn(&mut Parser) -> Id>; +pub type PrefixRule = fn(&mut Parser) -> Id; /// Reads what continues the path `path` in an expression, from the token /// after it. -pub type AfterPathRule = fn(&mut Parser, Id>) -> Id>; +pub type AfterPathRule = fn(&mut Parser, Id) -> Id; /// Reads what the current token adds to the expression `left`. -pub type InfixRule = fn(&mut Parser, Id>) -> Id>; +pub type InfixRule = fn(&mut Parser, Id) -> Id; -impl Rules { - pub const fn prefix(&mut self, kind: TokenKind, read: PrefixRule) { +impl Rules { + pub const fn prefix(&mut self, kind: TokenKind, read: PrefixRule) { assert!( self.prefix[kind as usize].is_none(), "two rules begin an expression with one token" @@ -40,7 +39,7 @@ impl Rules { self.prefix[kind as usize] = Some(read); } - pub const fn infix(&mut self, kind: TokenKind, precedence: Precedence, read: InfixRule) { + pub const fn infix(&mut self, kind: TokenKind, precedence: Precedence, read: InfixRule) { assert!( self.infix[kind as usize].is_none(), "two rules continue an expression with one token" @@ -50,7 +49,7 @@ impl Rules { /// The rule that reads what continues a path when the two tokens after /// it are `first` and `second`. - fn after_path_rule(&self, first: TokenKind, second: TokenKind) -> Option> { + fn after_path_rule(&self, first: TokenKind, second: TokenKind) -> Option { let (paired, read) = self.after_path[first as usize]?; (paired == second).then_some(read) } @@ -62,7 +61,7 @@ impl Rules { } /// Adds the core's expression rules to `rules`. -pub(crate) const fn expression_rows(rules: &mut Rules) { +pub(crate) const fn expression_rows(rules: &mut Rules) { // values rules.prefix(TokenKind::Ident, name_or_path); rules.prefix(TokenKind::SelfValue, self_name); @@ -116,16 +115,16 @@ pub(crate) const fn expression_rows(rules: &mut Rules) { } /// Whether an expression can begin with `kind`. -pub fn starts_expression(kind: TokenKind) -> bool { - L::rules().prefix[kind as usize].is_some() +pub fn starts_expression(p: &Parser, kind: TokenKind) -> bool { + p.rules.prefix[kind as usize].is_some() } -impl Parser { +impl Parser { /// Reads an expression whose operators bind tighter than `min`. - pub fn expr(&mut self, min: Precedence) -> Id> { + pub fn expr(&mut self, min: Precedence) -> Id { source::grow_stack(|| { let t = self.tok(); - let Some(read) = L::rules().prefix[t.kind as usize] else { + let Some(read) = self.rules.prefix[t.kind as usize] else { self.fail( Diagnostic::new( diagnostics::EXPECTED_TOKEN, @@ -140,7 +139,7 @@ impl Parser { return self.add(self.last_end, Expr::Invalid); }; let mut left = read(self); - while let Some((precedence, read)) = L::rules().infix[self.tok().kind as usize] + while let Some((precedence, read)) = self.rules.infix[self.tok().kind as usize] && precedence > min { left = read(self, left); @@ -150,13 +149,13 @@ impl Parser { } /// Reads the current token as an expression without children. - pub(crate) fn leaf(&mut self, node: Expr) -> Id> { + pub(crate) fn leaf(&mut self, node: Expr) -> Id { let start = self.next().span.start; self.add(start, node) } /// The start of expression `id`, where an infix expression on it starts. - pub fn start_of(&self, id: Id>) -> u32 { + pub fn start_of(&self, id: Id) -> u32 { self.tree.exprs.span(id).start } @@ -166,7 +165,8 @@ impl Parser { fn starts_path(&self) -> bool { match self.ahead(1).kind { TokenKind::ColonColon => true, - first => L::rules() + first => self + .rules .after_path_rule(first, self.ahead(2).kind) .is_some(), } @@ -174,34 +174,34 @@ impl Parser { } /// Reads `self`, the name of a type's function's first parameter. -fn self_name(p: &mut Parser) -> Id> { +fn self_name(p: &mut Parser) -> Id { p.leaf(Expr::Name) } /// Reads a name; or, when a path or type arguments follow it, a path /// (`a::B`, `Box::::new`) or what a feature reads after one /// (`Point.{...}`). -pub(crate) fn name_or_path(p: &mut Parser) -> Id> { +pub(crate) fn name_or_path(p: &mut Parser) -> Id { if !p.starts_path() { return p.leaf(Expr::Name); } let path = p.expression_path(); let start = p.tree.types.span(path).start; - if let Some(read) = L::rules().after_path_rule(p.tok().kind, p.ahead(1).kind) { + if let Some(read) = p.rules.after_path_rule(p.tok().kind, p.ahead(1).kind) { return read(p, path); } p.add(start, Expr::Path(path)) } /// Reads `as Type` after `value`. -fn cast(p: &mut Parser, value: Id>) -> Id> { +fn cast(p: &mut Parser, value: Id) -> Id { p.next(); let ty = p.type_expr(); p.add(p.start_of(value), Expr::Cast { value, ty }) } /// Reads `( expression )`. -fn parentheses(p: &mut Parser) -> Id> { +fn parentheses(p: &mut Parser) -> Id { let open = p.next(); let inner = p.expr(Precedence::Lowest); p.close(TokenKind::RightParen, open); @@ -211,9 +211,9 @@ fn parentheses(p: &mut Parser) -> Id> { /// Reads a binary operator and its right side. The right side takes only /// operators that bind tighter, so operators of one precedence group to the /// left: a - b - c is (a - b) - c. -fn binary(p: &mut Parser, left: Id>) -> Id> { +fn binary(p: &mut Parser, left: Id) -> Id { let kind = p.next().kind; - let op = L::rules().binary[kind as usize].expect("binary is the rule of operator tokens only"); + let op = p.rules.binary[kind as usize].expect("binary is the rule of operator tokens only"); let right = p.expr(op.precedence()); p.add(p.start_of(left), Expr::Binary { op, left, right }) } @@ -221,12 +221,12 @@ fn binary(p: &mut Parser, left: Id>) -> Id> { /// Reads the arguments of a call to `callee`. The type arguments of a /// callee written `f::` or `a::f::` are the call's, and the callee /// is the name or path without them. -fn call(p: &mut Parser, callee: Id>) -> Id> { +fn call(p: &mut Parser, callee: Id) -> Id { let start = p.start_of(callee); let mut callee = callee; let mut type_arguments = List::EMPTY; if let Expr::Path(path) = p.tree.exprs[callee] { - let segments: Vec>> = match p.tree.types[path] { + let segments: Vec> = match p.tree.types[path] { Type::Path(segments) => p.tree.children.lists.items(segments).collect(), _ => vec![path], }; @@ -249,7 +249,7 @@ fn call(p: &mut Parser, callee: Id>) -> Id> { TokenKind::LeftParen, TokenKind::RightParen, false, - starts_expression::, + starts_expression, spreadable, ); p.add( @@ -264,7 +264,7 @@ fn call(p: &mut Parser, callee: Id>) -> Id> { /// Reads an entry of an array literal or an argument of a call: `value` or /// `value...`. -pub fn spreadable(p: &mut Parser) -> Id> { +pub fn spreadable(p: &mut Parser) -> Id { let start = p.tok().span.start; let value = p.expr(Precedence::Lowest); if !p.at(TokenKind::Ellipsis) { @@ -276,7 +276,7 @@ pub fn spreadable(p: &mut Parser) -> Id> { /// Reads `+x` as `x`, reporting the `+`: there is no unary `+`, as it would /// change nothing. -fn leading_plus(p: &mut Parser) -> Id> { +fn leading_plus(p: &mut Parser) -> Id { let plus = p.next().span; let fix = p.fix(plus, ""); p.repair( @@ -291,7 +291,7 @@ fn leading_plus(p: &mut Parser) -> Id> { } /// Reads `-x`, `!x` or `~x`. -fn unary(p: &mut Parser) -> Id> { +fn unary(p: &mut Parser) -> Id { let token = p.next(); let op = match token.kind { TokenKind::Minus => UnaryOp::Negate, @@ -304,7 +304,7 @@ fn unary(p: &mut Parser) -> Id> { } /// Reads `&x` or `&mut x`. -fn reference(p: &mut Parser) -> Id> { +fn reference(p: &mut Parser) -> Id { let start = p.next().span.start; // `&[]T` and `&mut []T` are slice types; nothing after `&` reads `[]`. let after_mut = usize::from(p.at(TokenKind::Mut)); @@ -338,7 +338,7 @@ fn reference(p: &mut Parser) -> Id> { } /// Reads `[index]` after `value`. -fn index(p: &mut Parser, value: Id>) -> Id> { +fn index(p: &mut Parser, value: Id) -> Id { let open = p.next(); let index = p.expr(Precedence::Lowest); p.close(TokenKind::RightBracket, open); @@ -346,7 +346,7 @@ fn index(p: &mut Parser, value: Id>) -> Id> { } /// Reads `.name` or `.*` after `value`. -fn selector(p: &mut Parser, value: Id>) -> Id> { +fn selector(p: &mut Parser, value: Id) -> Id { p.next(); if p.at(TokenKind::Asterisk) { p.next(); diff --git a/crates/kernel/syntax/parser/src/expr/tests.rs b/crates/kernel/syntax/parser/src/expr/tests.rs index 6e7e0b03..406bcf36 100644 --- a/crates/kernel/syntax/parser/src/expr/tests.rs +++ b/crates/kernel/syntax/parser/src/expr/tests.rs @@ -4,7 +4,6 @@ use syntax::ast::StringKind; use syntax::ast::Tree; use super::*; -use crate::tests::Bare; use crate::tests::dump_of; use crate::tests::messages; use crate::tests::one_error; @@ -54,7 +53,7 @@ fn operators_are_written_as_their_tokens() { } /// The expression of the first statement of the first function. -fn first_expression(tree: &Tree) -> Id> { +fn first_expression(tree: &Tree) -> Id { let decl = tree.declarations().next().unwrap(); let Decl::Function(f) = tree.decls[decl] else { panic!("not a function") @@ -72,7 +71,7 @@ fn first_expression(tree: &Tree) -> Id> { } /// An expression with each binary operation and cast in parentheses. -fn grouped(t: &Tree, id: Id>) -> String { +fn grouped(t: &Tree, id: Id) -> String { let text = |span| t.file.slice(span).to_string(); match t.exprs[id] { Expr::Cast { value, ty } => { diff --git a/crates/kernel/syntax/parser/src/lib.rs b/crates/kernel/syntax/parser/src/lib.rs index cbfae99c..a07333c4 100644 --- a/crates/kernel/syntax/parser/src/lib.rs +++ b/crates/kernel/syntax/parser/src/lib.rs @@ -36,7 +36,6 @@ use diagnostics::fix::Fix; use source::SourceFile; use source::Span; use syntax::ast::Ident; -use syntax::ast::Language; use syntax::ast::Tree; use syntax::operators::BinaryOp; use syntax::operators::Precedence; @@ -50,37 +49,30 @@ use crate::expr::PrefixRule; use crate::stmt::StatementRule; use crate::types::TypeStartRule; -/// What the parser asks of a language: the rules of each token -/// (docs/feature-front.md, section 4.1). -pub trait Grammar: Language { - /// The core's rows (`Rules::core`) and each feature's, built once. - fn rules() -> &'static Rules; -} - /// The rules of each token, indexed by token kind. A token without a prefix /// rule cannot begin an expression; a token without an infix rule never /// continues one. `binary` is the operator a token of the `binary` rule /// writes. A statement or declaration rule reads what its keyword begins; /// any other token begins an expression statement. Two rules for one token /// are a build error, not one replacing the other. -pub struct Rules { - prefix: [Option>; 256], +pub struct Rules { + prefix: [Option; 256], /// After a path, the rule of the token there when the token after it is /// the one paired with it (`Point.{` begins a struct literal). - after_path: [Option<(TokenKind, AfterPathRule)>; 256], - infix: [Option<(Precedence, InfixRule)>; 256], + after_path: [Option<(TokenKind, AfterPathRule)>; 256], + infix: [Option<(Precedence, InfixRule)>; 256], binary: [Option; 256], - statements: [Option>; 256], - declarations: [Option>; 256], + statements: [Option; 256], + declarations: [Option; 256], /// The type each token begins (`struct { ... }`, `[4]T`), read after the /// token; a declaration of one by its keyword (`struct Name { ... }`) /// reads it after the name (`type_decl`). - type_starts: [Option>; 256], + type_starts: [Option; 256], } -impl Rules { +impl Rules { /// The core's rules, which each feature's are added to. - pub const fn core() -> Rules { + pub const fn core() -> Rules { let mut rules = Rules { prefix: [None; 256], after_path: [None; 256], @@ -97,7 +89,7 @@ impl Rules { } /// Reads the statement the keyword `kind` begins with `read`. - pub const fn statement(&mut self, kind: TokenKind, read: StatementRule) { + pub const fn statement(&mut self, kind: TokenKind, read: StatementRule) { assert!( self.statements[kind as usize].is_none(), "two rules begin a statement with one token" @@ -106,7 +98,7 @@ impl Rules { } /// Reads the declaration `kind` begins with `read`. - pub const fn declaration(&mut self, kind: TokenKind, read: DeclarationRule) { + pub const fn declaration(&mut self, kind: TokenKind, read: DeclarationRule) { assert!( self.declarations[kind as usize].is_none(), "two rules begin a declaration with one token" @@ -117,7 +109,7 @@ impl Rules { /// Reads the type the token `kind` begins with `read`. A token the /// core's types begin with cannot be one: `Parser::type_expr` reads /// those first. - pub const fn type_start(&mut self, kind: TokenKind, read: TypeStartRule) { + pub const fn type_start(&mut self, kind: TokenKind, read: TypeStartRule) { assert!( !types::starts_core_type(kind) && self.type_starts[kind as usize].is_none(), "two rules begin a type with one token" @@ -127,12 +119,7 @@ impl Rules { /// Reads with `read` what a path continues with when the token after it /// is `first` and the next one `second`. - pub const fn after_path( - &mut self, - first: TokenKind, - second: TokenKind, - read: AfterPathRule, - ) { + pub const fn after_path(&mut self, first: TokenKind, second: TokenKind, read: AfterPathRule) { assert!( self.after_path[first as usize].is_none(), "two rules continue a path with one token" @@ -141,10 +128,12 @@ impl Rules { } } -/// Returns the syntax tree of `file` and the lexical and syntax errors in it. -pub fn parse(file: &Arc) -> (Tree, Vec) { +/// Returns the syntax tree of `file`, read with `rules`, and the lexical and +/// syntax errors in it. +pub fn parse(file: &Arc, rules: &'static Rules) -> (Tree, Vec) { let (tokens, errors) = lexer::scan(file); let mut p = Parser { + rules, tree: Tree::new(file.clone()), tokens, pos: 0, @@ -159,8 +148,10 @@ pub fn parse(file: &Arc) -> (Tree, Vec) { (p.tree, p.errors) } -pub struct Parser { - pub tree: Tree, // the tree being built +pub struct Parser { + /// The core's rules and each feature's (`Rules::core`), built once. + rules: &'static Rules, + pub tree: Tree, // the tree being built tokens: Vec, pos: usize, last_end: u32, // end of the last token read @@ -170,7 +161,7 @@ pub struct Parser { list_items: Vec, // the items of the lists being read, innermost last } -impl Parser { +impl Parser { /// The index of the current token: the next one that is not a doc comment. /// Doc comments are read only where a declaration may begin (see /// `doc_comment`); everywhere else the parser looks past them. @@ -242,7 +233,7 @@ impl Parser { /// Adds `node`, spanning from `start`, where the token beginning it was, to /// the end of the last token read. A node that read nothing (its start lies /// past what was read) is an empty span at the read position. - pub fn add>>(&mut self, start: u32, node: T) -> Id { + pub fn add>(&mut self, start: u32, node: T) -> Id { let span = Span::new(start.min(self.last_end) as usize, self.last_end as usize); self.tree.add(node, span) } @@ -382,7 +373,7 @@ impl Parser { self.recovering = false; return; } - kind if depth == 0 && starts_statement::(kind) => return, + kind if depth == 0 && starts_statement(self, kind) => return, _ => {} } self.next(); @@ -403,7 +394,7 @@ impl Parser { &mut self, close: TokenKind, in_declaration: bool, - starts_item: fn(TokenKind) -> bool, + starts_item: fn(&Parser, TokenKind) -> bool, mut item: impl FnMut(&mut Self) -> Id, ) -> List { let mark = self.list_items.len(); @@ -413,7 +404,7 @@ impl Parser { while self.at(TokenKind::Comma) { self.next(); } - if !starts_item(self.tok().kind) { + if !starts_item(self, self.tok().kind) { break; // neither the close nor the end of file starts an item } let id = item(self); @@ -437,7 +428,7 @@ impl Parser { } // `>` is no bracket the closer scan follows; in `` the next name // can only be another item. - if starts_item(t.kind) + if starts_item(self, t.kind) && (close == TokenKind::Greater || self.tokens[self.closer_ahead()].kind == close) { missing.push(self.fix(self.here(), ",")); @@ -476,7 +467,7 @@ impl Parser { open: TokenKind, close: TokenKind, in_declaration: bool, - starts_item: fn(TokenKind) -> bool, + starts_item: fn(&Parser, TokenKind) -> bool, item: impl FnMut(&mut Self) -> Id, ) -> List { let Some(open) = self.expect(open) else { @@ -552,7 +543,7 @@ impl Parser { let next_starts = matches!( t.kind, TokenKind::RightBrace | TokenKind::Eof | TokenKind::Ident - ) || starts_statement::(t.kind); + ) || starts_statement(self, t.kind); if next_line && next_starts { let d = self.missing(TokenKind::Semicolon); self.repair(d); @@ -566,8 +557,8 @@ impl Parser { /// Whether `kind` begins a statement or declaration wherever it appears, so /// parsing is in step again there. -fn starts_statement(kind: TokenKind) -> bool { - stmt::is_statement_keyword::(kind) || decl::starts_declaration::(kind) +fn starts_statement(p: &Parser, kind: TokenKind) -> bool { + stmt::is_statement_keyword(p, kind) || decl::starts_declaration(p, kind) } pub fn is_name(kind: TokenKind) -> bool { diff --git a/crates/kernel/syntax/parser/src/literals.rs b/crates/kernel/syntax/parser/src/literals.rs index 6ed1042a..986fd964 100644 --- a/crates/kernel/syntax/parser/src/literals.rs +++ b/crates/kernel/syntax/parser/src/literals.rs @@ -7,10 +7,9 @@ use syntax::ast::StringKind; use token::Token; use token::TokenKind; -use crate::Grammar; use crate::Parser; -impl Parser { +impl Parser { /// Checks the type suffix of number literal `t`, the part of a number the /// lexer leaves to the parser. Whether the value fits its type is the type /// checker's to decide. @@ -39,18 +38,18 @@ impl Parser { } /// Reads `none`. -pub(crate) fn none_literal(p: &mut Parser) -> Id> { +pub(crate) fn none_literal(p: &mut Parser) -> Id { p.leaf(Expr::None) } /// Reads `true` or `false`. -pub(crate) fn bool_literal(p: &mut Parser) -> Id> { +pub(crate) fn bool_literal(p: &mut Parser) -> Id { let value = p.tok().kind == TokenKind::True; p.leaf(Expr::Bool(value)) } /// Reads `"text"` or `c"text"`. -pub(crate) fn string_literal(p: &mut Parser) -> Id> { +pub(crate) fn string_literal(p: &mut Parser) -> Id { let kind = match p.tok().kind { TokenKind::CString => StringKind::C, _ => StringKind::Plain, @@ -59,7 +58,7 @@ pub(crate) fn string_literal(p: &mut Parser) -> Id> { } /// Reads a number and checks its type suffix. -pub(crate) fn number_literal(p: &mut Parser) -> Id> { +pub(crate) fn number_literal(p: &mut Parser) -> Id { p.check_number(p.tok()); p.leaf(Expr::Number) } diff --git a/crates/kernel/syntax/parser/src/pattern.rs b/crates/kernel/syntax/parser/src/pattern.rs index a2b7843f..2fc5a29e 100644 --- a/crates/kernel/syntax/parser/src/pattern.rs +++ b/crates/kernel/syntax/parser/src/pattern.rs @@ -6,21 +6,20 @@ use syntax::ast::Pattern; use token::TokenKind; -use crate::Grammar; use crate::Parser; use crate::is_name; -impl Parser { +impl Parser { /// Reads `.{ a, b as c, _ }`: fields to bind, each by its own name or by the /// name after `as`, and a `_` for the fields left out, which must come last. /// A `=` written for `as` is read as `as`. - pub fn struct_pattern(&mut self) -> Id> { + pub fn struct_pattern(&mut self) -> Id { let start = self.next().span.start; // `.` let fields = self.delimited( TokenKind::LeftBrace, TokenKind::RightBrace, false, - |kind| is_name(kind) || kind == TokenKind::Underscore, + |_, kind| is_name(kind) || kind == TokenKind::Underscore, |p| { let field_token = p.tok(); if field_token.kind == TokenKind::Underscore { diff --git a/crates/kernel/syntax/parser/src/stmt.rs b/crates/kernel/syntax/parser/src/stmt.rs index 7c1d2066..a971d613 100644 --- a/crates/kernel/syntax/parser/src/stmt.rs +++ b/crates/kernel/syntax/parser/src/stmt.rs @@ -11,7 +11,6 @@ use syntax::operators::BinaryOp; use syntax::operators::Precedence; use token::TokenKind; -use crate::Grammar; use crate::Parser; use crate::decl::const_decl; use crate::decl::starts_declaration; @@ -19,11 +18,11 @@ use crate::expr::starts_expression; use crate::starts_statement; /// Reads the statement the current keyword begins. -pub type StatementRule = fn(&mut Parser) -> Id>; +pub type StatementRule = fn(&mut Parser) -> Id; /// The reader of each statement a keyword begins, indexed by token kind; any /// other token begins an expression statement. -pub(crate) const fn statement_rows(statements: &mut [Option>; 256]) { +pub(crate) const fn statement_rows(statements: &mut [Option; 256]) { statements[TokenKind::Let as usize] = Some(let_statement); statements[TokenKind::Const as usize] = Some(|p| { let decl = const_decl(p, Metadata::NONE); @@ -43,15 +42,15 @@ pub(crate) const fn statement_rows(statements: &mut [Option(kind: TokenKind) -> bool { - L::rules().statements[kind as usize].is_some() +pub(crate) fn is_statement_keyword(p: &Parser, kind: TokenKind) -> bool { + p.rules.statements[kind as usize].is_some() } -impl Parser { +impl Parser { /// Reads a block. A keyword that begins a declaration but not a statement /// means its `}` is missing: the block ends there and the declaration is /// read next. - pub fn block(&mut self) -> Id> { + pub fn block(&mut self) -> Id { let Some(open) = self.expect(TokenKind::LeftBrace) else { return self.add( self.last_end, @@ -65,7 +64,7 @@ impl Parser { let kind = self.tok().kind; if kind == TokenKind::RightBrace || kind == TokenKind::Eof - || starts_declaration::(kind) && !is_statement_keyword::(kind) + || starts_declaration(self, kind) && !is_statement_keyword(self, kind) { break; } @@ -74,7 +73,7 @@ impl Parser { self.next(); continue; } - if starts_statement::(kind) { + if starts_statement(self, kind) { self.recovering = false; } let statement = self.stmt(); @@ -90,9 +89,9 @@ impl Parser { /// Reads a statement: one a keyword begins, or an expression statement, or /// an assignment `target = value;`. - fn stmt(&mut self) -> Id> { + fn stmt(&mut self) -> Id { source::grow_stack(|| { - if let Some(read) = L::rules().statements[self.tok().kind as usize] { + if let Some(read) = self.rules.statements[self.tok().kind as usize] { return read(self); } let start = self.tok().span.start; @@ -109,14 +108,14 @@ impl Parser { } /// Makes `block` a statement: a block inside a block, or an `else` block. - fn block_statement(&mut self, block: Id>) -> Id> { + fn block_statement(&mut self, block: Id) -> Id { let span = self.tree.blocks.span(block); self.tree.add(Stmt::Block(block), span) } /// Reads the block of an if, else or for; when it is missing, it reports /// "missing body" where the block should start. - fn body(&mut self, what: &str) -> Option>> { + fn body(&mut self, what: &str) -> Option> { if self.at(TokenKind::LeftBrace) { return Some(self.block()); } @@ -134,7 +133,7 @@ impl Parser { /// Reads `let mut name: Type = value;`, where `mut`, the type and the value /// may be left out, or `let .{ fields } = value;`. -fn let_statement(p: &mut Parser) -> Id> { +fn let_statement(p: &mut Parser) -> Id { let start = p.next().span.start; if p.at(TokenKind::Dot) { let pattern = p.struct_pattern(); @@ -161,7 +160,7 @@ fn let_statement(p: &mut Parser) -> Id> { /// Reads `if condition { } else if ... else { }`. A `=` written for `==` in /// the condition is read as `==`. -fn if_statement(p: &mut Parser) -> Id> { +fn if_statement(p: &mut Parser) -> Id { source::grow_stack(|| { let start = p.next().span.start; let mut condition = p.expr(Precedence::Lowest); @@ -212,7 +211,7 @@ fn if_statement(p: &mut Parser) -> Id> { /// Reads `for { }`, `for control { }`, `for value in items { }` or `for /// index, value in items { }`. Whether `control` is a condition or a range /// to count through is its type's to say, which the checker decides. -fn for_statement(p: &mut Parser) -> Id> { +fn for_statement(p: &mut Parser) -> Id { let start = p.next().span.start; let unnamed_index = p.at(TokenKind::Underscore) && p.ahead(1).kind == TokenKind::Comma; if unnamed_index @@ -263,7 +262,7 @@ fn for_statement(p: &mut Parser) -> Id> { /// Reads `break;` or `continue;`. Loop labels are not part of the language /// yet; a label is reported and skipped. -fn jump_statement(p: &mut Parser) -> Id> { +fn jump_statement(p: &mut Parser) -> Id { let keyword = p.next(); let t = p.tok(); if t.kind == TokenKind::Ident { @@ -291,15 +290,15 @@ fn jump_statement(p: &mut Parser) -> Id> { /// Reads `return value;`; the value may be left out, so a token that cannot /// begin one, such as the `}` after a `return` missing its `;`, ends it. -fn return_statement(p: &mut Parser) -> Id> { +fn return_statement(p: &mut Parser) -> Id { let start = p.next().span.start; - let value = starts_expression::(p.tok().kind).then(|| p.expr(Precedence::Lowest)); + let value = starts_expression(p, p.tok().kind).then(|| p.expr(Precedence::Lowest)); p.end(); p.add(start, Stmt::Return(value)) } /// Reads `panic message;`. -fn panic_statement(p: &mut Parser) -> Id> { +fn panic_statement(p: &mut Parser) -> Id { let start = p.next().span.start; let message = p.expr(Precedence::Lowest); p.end(); diff --git a/crates/kernel/syntax/parser/src/tests.rs b/crates/kernel/syntax/parser/src/tests.rs index 5c913d3c..cb45d277 100644 --- a/crates/kernel/syntax/parser/src/tests.rs +++ b/crates/kernel/syntax/parser/src/tests.rs @@ -1,58 +1,11 @@ -use std::convert::Infallible; - -use syntax::ast::Decl; -use syntax::ast::Field; -use syntax::ast::Type; -use syntax::ast::WrittenRange; -use syntax::operators::Precedence; - use super::*; -/// The language the parser's tests are written in: the core, with no -/// feature, since the `features` crate depends on this one. -#[derive(Clone, Copy, Debug)] -pub(crate) enum Bare {} - -impl Language for Bare { - type Expr = Infallible; - type Type = Infallible; - type Stmt = Infallible; - - fn precedence(expr: &Infallible) -> Precedence { - match *expr {} - } - - fn fields(ty: &Infallible) -> Option>> { - match *ty {} - } - - fn methods(ty: &Infallible) -> Option>> { - match *ty {} - } - - fn pointee(ty: &Infallible) -> Option>> { - match *ty {} - } - - fn element(ty: &Infallible) -> Option>> { - match *ty {} - } - - fn written_range(expr: &Infallible) -> Option> { - match *expr {} - } -} - -static RULES: Rules = Rules::core(); - -impl Grammar for Bare { - fn rules() -> &'static Rules { - &RULES - } -} +/// The core's rules alone: the parser's tests read no feature, since the +/// `features` crate depends on this one. +static RULES: Rules = Rules::core(); -pub(crate) fn parse_text(text: &str) -> (Tree, Vec) { - parse(&Arc::new(SourceFile::new("t.peep", text))) +pub(crate) fn parse_text(text: &str) -> (Tree, Vec) { + parse(&Arc::new(SourceFile::new("t.peep", text)), &RULES) } /// The tree of `text` in the dump format. diff --git a/crates/kernel/syntax/parser/src/types.rs b/crates/kernel/syntax/parser/src/types.rs index 140d5e18..e3a625ce 100644 --- a/crates/kernel/syntax/parser/src/types.rs +++ b/crates/kernel/syntax/parser/src/types.rs @@ -10,12 +10,11 @@ use syntax::ast::Type; use token::Token; use token::TokenKind; -use crate::Grammar; use crate::Parser; /// Reads the type a token begins, after the token, as one starting at /// `start`. -pub type TypeStartRule = fn(&mut Parser, u32) -> Id>; +pub type TypeStartRule = fn(&mut Parser, u32) -> Id; /// Whether `kind` begins one of the types `Parser::type_expr` has an arm /// for, so a new arm there is added here too. @@ -31,13 +30,13 @@ pub(crate) const fn starts_core_type(kind: TokenKind) -> bool { } /// Whether a type can begin with `kind`. -pub(crate) fn starts_type(kind: TokenKind) -> bool { - starts_core_type(kind) || L::rules().type_starts[kind as usize].is_some() +pub(crate) fn starts_type(p: &Parser, kind: TokenKind) -> bool { + starts_core_type(kind) || p.rules.type_starts[kind as usize].is_some() } -impl Parser { +impl Parser { /// Reads a type. - pub fn type_expr(&mut self) -> Id> { + pub fn type_expr(&mut self) -> Id { source::grow_stack(|| { let t = self.tok(); match t.kind { @@ -68,7 +67,7 @@ impl Parser { self.add(t.span.start, Type::Type) } _ => { - if let Some(read) = L::rules().type_starts[t.kind as usize] { + if let Some(read) = self.rules.type_starts[t.kind as usize] { self.next(); return read(self, t.span.start); } @@ -92,7 +91,7 @@ impl Parser { /// Reads what follows a `&` that starts at `start`: `mut`, if written, /// then the target type, or `[]T` for a slice, its own type, not a /// reference to a `[]T`. - pub(crate) fn reference_type(&mut self, start: u32) -> Id> { + pub(crate) fn reference_type(&mut self, start: u32) -> Id { let mutable = self.at(TokenKind::Mut); if mutable { self.next(); @@ -109,7 +108,7 @@ impl Parser { /// Reads a type name with its type arguments, if any (`Box`), or a path /// of them (`a::B`). - pub(crate) fn named_type(&mut self) -> Id> { + pub(crate) fn named_type(&mut self) -> Id { let start = self.tok().span.start; let first = self.type_segment(); if !self.at(TokenKind::ColonColon) { @@ -126,7 +125,7 @@ impl Parser { self.add(start, Type::Path(segments)) } - fn type_segment(&mut self) -> Id> { + fn type_segment(&mut self) -> Id { let start = self.tok().span.start; let name = self.name(); if !self.at(TokenKind::Less) { @@ -139,7 +138,7 @@ impl Parser { /// Reads a path in an expression: `a::B`, or with type arguments after /// `::`, `Box::::new`. There a `<` right after a name compares, so /// only `::` opens type arguments. - pub(crate) fn expression_path(&mut self) -> Id> { + pub(crate) fn expression_path(&mut self) -> Id { let start = self.tok().span.start; let first = self.expression_segment(); if !self.at(TokenKind::ColonColon) { @@ -157,7 +156,7 @@ impl Parser { } /// Reads a name of an expression's path and the `::` it may take. - fn expression_segment(&mut self) -> Id> { + fn expression_segment(&mut self) -> Id { let start = self.tok().span.start; let name = self.name(); if !(self.at(TokenKind::ColonColon) && self.ahead(1).kind == TokenKind::Less) { @@ -169,11 +168,9 @@ impl Parser { } /// Reads ``, the types a generic name is given, from its `<`. - fn type_arguments(&mut self) -> List> { + fn type_arguments(&mut self) -> List { let open = self.next(); - let arguments = self.items(TokenKind::Greater, false, starts_type::, |p| { - p.type_expr() - }); + let arguments = self.items(TokenKind::Greater, false, starts_type, |p| p.type_expr()); self.close_angle(open); arguments } @@ -196,11 +193,11 @@ impl Parser { } /// Reads `fn(name: T, U) -> R in name`; parameter names are optional. - fn function_type(&mut self) -> Id> { + fn function_type(&mut self) -> Id { let start = self.next().span.start; let signature = self.signature( List::EMPTY, - |kind| kind == TokenKind::Underscore || starts_type::(kind), + |p, kind| kind == TokenKind::Underscore || starts_type(p, kind), |p| { let start = p.tok().span.start; let name = p.parameter_name(); diff --git a/crates/kernel/syntax/tree/src/ast.rs b/crates/kernel/syntax/tree/src/ast.rs index eb9af087..e8841c08 100644 --- a/crates/kernel/syntax/tree/src/ast.rs +++ b/crates/kernel/syntax/tree/src/ast.rs @@ -4,7 +4,6 @@ //! A name or child that is missing after a syntax error is an empty span or an //! `Invalid` node. -use std::fmt::Debug; use std::sync::Arc; use arena::Arena; @@ -20,51 +19,16 @@ use crate::operators::BinaryOp; use crate::operators::Precedence; use crate::operators::UnaryOp; -/// The language a tree is written in: the core's nodes, plus the nodes of -/// each feature, which the `features` crate lists (docs/feature-front.md, section -/// 7). A feature's node sits in the core's arena as a `Feature` kind, so it -/// keeps the core's ids and spans. -pub trait Language: Copy + Debug + 'static { - /// A feature's expression: one kind per feature, each the feature's own. - type Expr: Copy + Debug + Send + Sync; - /// A feature's written type. - type Type: Copy + Debug + Send + Sync; - /// A feature's statement. - type Stmt: Copy + Debug + Send + Sync; - - /// The precedence the feature expression `expr`'s last part was read at - /// (`Expr::precedence`). - fn precedence(expr: &Self::Expr) -> Precedence; - - /// The fields of the feature type `ty`, if it has fields. - fn fields(ty: &Self::Type) -> Option>>; - - /// The methods of the feature type `ty`, if it is an interface: - /// `Decl::Function`s without bodies. - fn methods(ty: &Self::Type) -> Option>>; - - /// The written type the feature type `ty` points to, if it is a typed - /// pointer (`*T`). - fn pointee(ty: &Self::Type) -> Option>>; - - /// The written element type of the feature type `ty`, if it is an - /// array type (`[N]T`). - fn element(ty: &Self::Type) -> Option>>; - - /// The parts of the feature expression `expr`, if it is a written range. - fn written_range(expr: &Self::Expr) -> Option>; -} - /// A range as written: `start..end`, or `start..=end` when `inclusive`, /// stepping by `start..end:step`, inside `[ ]`, after `in` or as an array /// literal's value; an end may be left out before a `]`. Slicing reads it, /// so it is the core's. #[derive(Clone, Copy, Debug)] -pub struct WrittenRange { +pub struct WrittenRange { pub inclusive: bool, - pub start: Option>>, - pub end: Option>>, - pub step: Option>>, + pub start: Option>, + pub end: Option>, + pub step: Option>, } /// A string literal's kind: `"..."` is a `str`, `c"..."` a `cstr`. @@ -75,36 +39,36 @@ pub enum StringKind { } nodes! { - Tree; - Decl => decls, - Type => types, - Stmt => stmts, - Block => blocks, - Expr => exprs, - Pattern => patterns, - Attribute => children.attributes, - Param => children.params, - Field => children.fields, - Variant => children.variants, - FieldValue => children.field_values, - MatchArm => children.match_arms, + Tree; + Decl => decls, + Type => types, + Stmt => stmts, + Block => blocks, + Expr => exprs, + Pattern => patterns, + Attribute => children.attributes, + Param => children.params, + Field => children.fields, + Variant => children.variants, + FieldValue => children.field_values, + MatchArm => children.match_arms, } /// The syntax tree of one file. It never changes once the parser returns it. -pub struct Tree { +pub struct Tree { pub file: Arc, pub imports: Vec, /// The module's own declarations, in source order: what a `DefId` /// counts. A body's `const` is in `decls` but not here. - pub top_level: List>, + pub top_level: List, - pub decls: Arena>, // every declaration, top-level or in a body - pub types: Arena>, - pub stmts: Arena>, - pub blocks: Arena>, - pub exprs: Arena>, - pub patterns: Arena>, - pub children: Children, + pub decls: Arena, // every declaration, top-level or in a body + pub types: Arena, + pub stmts: Arena, + pub blocks: Arena, + pub exprs: Arena, + pub patterns: Arena, + pub children: Children, /// Whether every token of the text is in the tree: false after a lexical /// error, after a syntax error the parser skipped text for, and for text @@ -114,37 +78,21 @@ pub struct Tree { /// How a node holds several others: storage reached only through the node /// that holds it, never by an id from elsewhere. -pub struct Children { +#[derive(Default)] +pub struct Children { pub names: Arena, - pub constraints: Arena>, - pub attributes: Arena>, - pub params: Arena>, - pub fields: Arena>, - pub variants: Arena>, - pub field_values: Arena>, - pub match_arms: Arena>, + pub constraints: Arena, + pub attributes: Arena, + pub params: Arena, + pub fields: Arena, + pub variants: Arena, + pub field_values: Arena, + pub match_arms: Arena, pub lists: Lists, } -// Derived, it would require `L: Default`. -impl Default for Children { - fn default() -> Children { - Children { - names: Arena::default(), - constraints: Arena::default(), - attributes: Arena::default(), - params: Arena::default(), - fields: Arena::default(), - variants: Arena::default(), - field_values: Arena::default(), - match_arms: Arena::default(), - lists: Lists::default(), - } - } -} - -impl Tree { - pub fn new(file: Arc) -> Tree { +impl Tree { + pub fn new(file: Arc) -> Tree { Tree { file, imports: Vec::new(), @@ -162,13 +110,13 @@ impl Tree { /// The top-level declaration at `index` of `top_level`, the place a /// `DefId` names. - pub fn declaration(&self, index: u32) -> Id> { + pub fn declaration(&self, index: u32) -> Id { self.children.lists.get(self.top_level, index as usize) } /// Whether `parameter` of a function is `self`, `&self` or `&mut self`: /// of the type the function belongs to. - pub fn is_self(&self, parameter: Param) -> bool { + pub fn is_self(&self, parameter: Param) -> bool { let taken = match self.types[parameter.ty] { Type::Reference { target, .. } => target, _ => parameter.ty, @@ -177,12 +125,12 @@ impl Tree { } /// The module's own declarations, in source order (`top_level`). - pub fn declarations(&self) -> impl ExactSizeIterator>> + '_ { + pub fn declarations(&self) -> impl ExactSizeIterator> + '_ { self.children.lists.items(self.top_level) } /// `expr` without the parentheses written around it, which only group. - pub fn unparenthesized(&self, mut expr: Id>) -> Id> { + pub fn unparenthesized(&self, mut expr: Id) -> Id { while let Expr::Parentheses(inner) = self.exprs[expr] { expr = inner; } @@ -190,15 +138,15 @@ impl Tree { } /// The parts of `expr`, if it is a written range. - pub fn written_range(&self, expr: Id>) -> Option> { + pub fn written_range(&self, expr: Id) -> Option { match &self.exprs[expr] { - Expr::Feature(feature) => L::written_range(feature), + Expr::Feature(FeatureExpr::Range(range)) => Some(range.written), _ => None, } } /// Adds `node` with `span` to its arena. - pub fn add>>(&mut self, node: T, span: Span) -> Id { + pub fn add>(&mut self, node: T, span: Span) -> Id { T::arena(self).push(node, span) } } @@ -213,13 +161,13 @@ pub struct Import { /// The doc comment and attributes before a declaration. #[derive(Clone, Copy, Debug)] -pub struct Metadata { +pub struct Metadata { pub doc_comment: Option, // the `///` lines - pub attributes: List>, + pub attributes: List, } -impl Metadata { - pub const NONE: Metadata = Metadata { +impl Metadata { + pub const NONE: Metadata = Metadata { doc_comment: None, attributes: List::EMPTY, }; @@ -227,9 +175,9 @@ impl Metadata { /// `#[name(arguments)]` #[derive(Clone, Copy, Debug)] -pub struct Attribute { +pub struct Attribute { pub name: Ident, - pub arguments: List>, + pub arguments: List, } /// An identifier written in the source, by where it is written: its text is @@ -252,23 +200,23 @@ impl Ident { pub struct Name; #[derive(Clone, Copy, Debug)] -pub enum Decl { - Function(Function), +pub enum Decl { + Function(Function), /// `const name: Type = value;`, also as a statement Const { - metadata: Metadata, + metadata: Metadata, name: Ident, - ty: Option>>, - value: Option>>, + ty: Option>, + value: Option>, }, /// a feature's, such as `struct Name { fields }` or /// `iface Name { methods }`; its type, a `Type::Feature`, says which - Type(TypeDecl), + Type(TypeDecl), /// `type Name = Type;` - Alias(TypeDecl), + Alias(TypeDecl), } -impl Decl { +impl Decl { /// The declaration's name. pub fn name(&self) -> Ident { match *self { @@ -279,7 +227,7 @@ impl Decl { } /// The doc comment and attributes before the declaration. - pub fn metadata(&self) -> Metadata { + pub fn metadata(&self) -> Metadata { match *self { Decl::Function(function) => function.metadata, Decl::Const { metadata, .. } => metadata, @@ -292,13 +240,13 @@ impl Decl { /// `;` for a body defined elsewhere; an interface method has no body. /// Everything but the owner, the name and the body is its signature. #[derive(Clone, Copy, Debug)] -pub struct Function { - pub metadata: Metadata, +pub struct Function { + pub metadata: Metadata, /// `Point` in `fn Point::name`: the type the function belongs to. pub owner: Option, pub name: Ident, - pub signature: Signature, - pub body: Option>>, + pub signature: Signature, + pub body: Option>, } /// A function's type: its type parameters, parameters, result, the origins @@ -307,14 +255,14 @@ pub struct Function { /// parameters only a name and a type. A method's first parameter is `self`, /// of the type `Type::Owner`. #[derive(Clone, Copy, Debug)] -pub struct Signature { +pub struct Signature { pub type_parameters: List, - pub parameters: List>, - pub result: Option>>, + pub parameters: List, + pub result: Option>, pub origins: List, // what a returned reference may point into /// After `where`: what the types and `const` values a call gives must /// satisfy. - pub constraints: List>, + pub constraints: List, } /// `T: Shape` or `T: Sized(8)` after `where`: the `subject`, a type @@ -322,136 +270,133 @@ pub struct Signature { /// `bound` is a function that gives `true` when called with the subject /// first, then the `arguments`. #[derive(Clone, Copy, Debug)] -pub struct Constraint { - pub subject: Id>, - pub bound: Id>, - pub arguments: List>, +pub struct Constraint { + pub subject: Id, + pub bound: Id, + pub arguments: List, } #[derive(Clone, Copy, Debug)] -pub struct TypeDecl { - pub metadata: Metadata, +pub struct TypeDecl { + pub metadata: Metadata, pub name: Ident, pub type_parameters: List, - pub ty: Id>, + pub ty: Id, } /// `mut name: Type = default`; in a function type, only the name and type. A /// parameter written `_: Type` has no name. #[derive(Clone, Copy, Debug)] -pub struct Param { +pub struct Param { /// `const name: type`: the call gives a type, known when compiling. pub constant: bool, pub mutable: bool, pub name: Option, - pub ty: Id>, - pub default: Option>>, + pub ty: Id, + pub default: Option>, } /// `name: Type` in a struct. #[derive(Clone, Copy, Debug)] -pub struct Field { +pub struct Field { pub name: Ident, - pub ty: Id>, + pub ty: Id, } /// `Name` or `Name: Payload` in an enum. #[derive(Clone, Copy, Debug)] -pub struct Variant { +pub struct Variant { pub name: Ident, - pub payload: Option>>, + pub payload: Option>, } #[derive(Clone, Copy, Debug)] -pub enum Type { +pub enum Type { /// a type written as a name; its text is its span Name, /// `a::B`; the segments are `Name`s and `Generic`s - Path(List>), + Path(List), /// `Box` - Generic { - name: Ident, - arguments: List>, - }, + Generic { name: Ident, arguments: List }, /// `range[T]`: a built-in type's name with a type in brackets after it, /// part of how that type is written, not type arguments; the checker /// says which names take one - Bracketed { name: Ident, inner: Id> }, + Bracketed { name: Ident, inner: Id }, /// `&T` or `&mut T` - Reference { mutable: bool, target: Id> }, + Reference { mutable: bool, target: Id }, /// `&[]T`, or `&mut []T` when `mutable` - Slice { mutable: bool, element: Id> }, + Slice { mutable: bool, element: Id }, /// `...T`, or `...mut T` when `mutable`: a variadic parameter's type, the /// slice `&[]T` or `&mut []T` that holds the call's last arguments - Variadic { mutable: bool, element: Id> }, + Variadic { mutable: bool, element: Id }, /// `fn(T) -> R in a` - Function(Signature), + Function(Signature), /// The type the function belongs to, `Point` in `fn Point::sum(&self)`; /// in an interface, the type that meets it. Only `self` has it. Owner, /// `type`, written as a parameter's type: the parameter takes a type Type, /// a feature's written type - Feature(L::Type), + Feature(FeatureType), /// a type that could not be parsed Invalid, } /// `{ statements }` #[derive(Clone, Copy, Debug)] -pub struct Block { - pub statements: List>, +pub struct Block { + pub statements: List, } #[derive(Clone, Copy, Debug)] -pub enum Stmt { - Block(Id>), +pub enum Stmt { + Block(Id), /// `let mut name: Type = value;` Let { mutable: bool, name: Ident, - ty: Option>>, - value: Option>>, + ty: Option>, + value: Option>, }, /// a `Decl::Const` - Const(Id>), - Return(Option>>), + Const(Id), + Return(Option>), /// `panic message;` - Panic(Id>), + Panic(Id), /// a feature's statement - Feature(L::Stmt), + Feature(FeatureStmt), /// an expression followed by `;` - Expression(Id>), + Expression(Id), /// `target = value;` Assign { - target: Id>, - value: Id>, + target: Id, + value: Id, }, /// `let .{ a, b as c } = value;`; the pattern is a `Pattern::Struct` Destructure { - pattern: Id>, - value: Id>, + pattern: Id, + value: Id, }, /// `if condition { } else { }`; the else is a `Stmt::Block` or a `Stmt::If` If { - condition: Id>, - then: Option>>, - otherwise: Option>>, + condition: Id, + then: Option>, + otherwise: Option>, }, /// `for { }` or `for control { }`, where `control` is a `bool` /// condition or a range to count through (`for 0..n { }`, `for r { }`), /// as its type says. Loop { - control: Option>>, - body: Option>>, + control: Option>, + body: Option>, }, /// `for value in items { }` or `for index, value in items { }`, with no /// index for `for _, value in`; the iterable may be a range. ForIn { index: Option, value: Ident, - iterable: Id>, - body: Option>>, + iterable: Id, + body: Option>, }, Break, Continue, @@ -459,13 +404,13 @@ pub enum Stmt { /// `pattern => { }`; the pattern is a `Pattern::Wildcard` or a `Pattern::Case`. #[derive(Clone, Copy, Debug)] -pub struct MatchArm { - pub pattern: Id>, - pub body: Id>, +pub struct MatchArm { + pub pattern: Id, + pub body: Id, } #[derive(Clone, Copy, Debug)] -pub enum Pattern { +pub enum Pattern { /// `_`: a match arm's or a payload's pattern that binds nothing Wildcard, /// `none` @@ -473,13 +418,13 @@ pub enum Pattern { /// `Enum::Case` or `Enum::Case with pattern`; the inner pattern is a `None`, /// a `Wildcard`, a `Binding`, a `Struct` or a `Case` Case { - case: Id>, - inner: Option>>, + case: Id, + inner: Option>, }, /// a name to bind; its text is its span Binding, /// `.{ a, b as c, _ }`: `Field`s, then perhaps a `Rest` - Struct(List>), + Struct(List), /// `a`, or `a as b`; without a binding, the field's own name is bound Field { field: Ident, @@ -492,12 +437,12 @@ pub enum Pattern { } #[derive(Clone, Copy, Debug)] -pub enum Expr { +pub enum Expr { /// a use of a declared name; its text is its span Name, /// a path such as `a::B` or `Box::::new`; the type is a `Type::Path` or a /// `Type::Generic` - Path(Id>), + Path(Id), /// the number is its text Number, /// `none` @@ -508,49 +453,46 @@ pub enum Expr { /// decodes String(StringKind), /// `value as ty` - Cast { value: Id>, ty: Id> }, + Cast { value: Id, ty: Id }, /// `left op right` Binary { op: BinaryOp, - left: Id>, - right: Id>, + left: Id, + right: Id, }, /// `-x`, `!x` or `~x` - Unary { op: UnaryOp, value: Id> }, + Unary { op: UnaryOp, value: Id }, /// `&x` or `&mut x` - Reference { mutable: bool, value: Id> }, + Reference { mutable: bool, value: Id }, /// `f(arguments)`, or `f::(arguments)` with the types its type /// parameters are given Call { - callee: Id>, - type_arguments: List>, - arguments: List>, + callee: Id, + type_arguments: List, + arguments: List, }, /// `x.name` - Selector { value: Id>, field: Ident }, + Selector { value: Id, field: Ident }, /// `x.*`: the value a reference refers to - Dereference(Id>), + Dereference(Id), /// `x[index]`; the index may be a `Range` - Index { - value: Id>, - index: Id>, - }, + Index { value: Id, index: Id }, /// `values...`, an entry of an array literal or an argument of a call: /// each value of the array, slice or range `values` in order - Spread(Id>), + Spread(Id), /// `( expression )` - Parentheses(Id>), + Parentheses(Id), /// a type where a value could go, written so it can only be a type /// (`*T`, `rawptr`, `[N]T` with no `{` after it, `&[]T`): only an /// argument that takes a type accepts it - Type(Id>), + Type(Id), /// a feature's expression - Feature(L::Expr), + Feature(FeatureExpr), /// an expression that could not be parsed Invalid, } -impl Expr { +impl Expr { /// The precedence the expression's last part was read at: an operator /// written after it that binds tighter joins that part, not the whole /// (`-a.*` reads `a`, `a + b as T` casts `b`). @@ -573,14 +515,222 @@ impl Expr { | Expr::Parentheses(_) | Expr::Type(_) | Expr::Invalid => Precedence::Call, - Expr::Feature(expr) => L::precedence(expr), + Expr::Feature(expr) => match expr { + FeatureExpr::ArrayLiteral(_) + | FeatureExpr::Char(_) + | FeatureExpr::Print(_) + | FeatureExpr::StructLiteral(_) => Precedence::Call, + FeatureExpr::CaseTest(_) => Precedence::Equality, + FeatureExpr::OrElse(_) | FeatureExpr::VariantLiteral(_) => Precedence::Lowest, + FeatureExpr::Pipe(_) | FeatureExpr::RawAddress(_) => Precedence::Prefix, + FeatureExpr::Range(_) => Precedence::Range, + }, } } } /// `name = value` in a struct literal. #[derive(Clone, Copy, Debug)] -pub struct FieldValue { +pub struct FieldValue { pub name: Ident, - pub value: Id>, + pub value: Id, +} + +// The nodes of the features: each feature's file in the `features` crate +// parses and checks its own (docs/structure-mapping.md, step 7). + +/// An expression of a feature's, by feature. +#[derive(Clone, Copy, Debug)] +pub enum FeatureExpr { + ArrayLiteral(ArrayLiteral), + CaseTest(CaseTest), + Char(CharLiteral), + OrElse(OrElse), + Pipe(Pipe), + Print(Print), + Range(Range), + RawAddress(RawAddress), + StructLiteral(StructLiteral), + VariantLiteral(VariantLiteral), +} + +/// A statement of a feature's, by feature. +#[derive(Clone, Copy, Debug)] +pub enum FeatureStmt { + Match(Match), +} + +/// A written type of a feature's, by feature. +#[derive(Clone, Copy, Debug)] +pub enum FeatureType { + Array(ArrayType), + Enum(EnumType), + Interface(InterfaceType), + Optional(OptionalType), + Pointer(PointerType), + Struct(StructType), +} + +impl FeatureType { + /// Its fields, if it has fields. + pub fn fields(&self) -> Option> { + match self { + FeatureType::Struct(ty) => Some(ty.fields), + _ => None, + } + } + + /// Its methods, if it is an interface: `Decl::Function`s without bodies. + pub fn methods(&self) -> Option> { + match self { + FeatureType::Interface(ty) => Some(ty.methods), + _ => None, + } + } + + /// The written type it points to, if it is a typed pointer (`*T`). + pub fn pointee(&self) -> Option> { + match self { + FeatureType::Pointer(ty) => ty.target, + _ => None, + } + } + + /// The written element type, if it is an array type (`[N]T`). + pub fn element(&self) -> Option> { + match self { + FeatureType::Array(ty) => Some(ty.element), + _ => None, + } + } +} + +/// `[length]element` +#[derive(Clone, Copy, Debug)] +pub struct ArrayType { + /// the written number + pub length: Span, + pub element: Id, +} + +/// `[N]T{ entries }` or `[_]T{ entries }`; each entry is a value or a +/// `values...` spread. +#[derive(Clone, Copy, Debug)] +pub struct ArrayLiteral { + pub ty: ArrayLiteralType, + pub entries: List, +} + +/// The type an array literal is written with. +#[derive(Clone, Copy, Debug)] +pub enum ArrayLiteralType { + /// `[N]T` + Written(Id), + /// `[_]T`: its length is the number of values its entries give + Counted { element: Id }, +} + +/// `'x'`, or `b'x'` when `byte` +#[derive(Clone, Copy, Debug)] +pub struct CharLiteral { + pub byte: bool, +} + +/// `enum { variants }` +#[derive(Clone, Copy, Debug)] +pub struct EnumType { + pub variants: List, +} + +/// `Enum::Variant with payload`; the case is a `Type::Path` +#[derive(Clone, Copy, Debug)] +pub struct VariantLiteral { + pub case: Id, + pub payload: Id, +} + +/// `value is Enum::Variant` +#[derive(Clone, Copy, Debug)] +pub struct CaseTest { + pub value: Id, + pub case: Id, +} + +/// `match subject { arms }` +#[derive(Clone, Copy, Debug)] +pub struct Match { + pub subject: Id, + pub arms: List, +} + +/// `iface { methods }`: `Decl::Function`s without bodies. +#[derive(Clone, Copy, Debug)] +pub struct InterfaceType { + pub methods: List, +} + +/// `?T` +#[derive(Clone, Copy, Debug)] +pub struct OptionalType { + pub inner: Id, +} + +/// `value orelse fallback` +#[derive(Clone, Copy, Debug)] +pub struct OrElse { + pub value: Id, + pub fallback: OrElseFallback, +} + +/// What `orelse` gives when its value is missing. +#[derive(Clone, Copy, Debug)] +pub enum OrElseFallback { + Value(Id), + Block(Id), +} + +/// `value |> target`, as written +#[derive(Clone, Copy, Debug)] +pub struct Pipe { + pub value: Id, + pub target: Id, +} + +/// `print(values)`, or `println(values)` when `newline` +#[derive(Clone, Copy, Debug)] +pub struct Print { + pub newline: bool, + pub values: List, +} + +/// A range, as written: its parts are the core's, which slicing and loops +/// read (`Tree::written_range`). +#[derive(Clone, Copy, Debug)] +pub struct Range { + pub written: WrittenRange, +} + +/// `*T`, or `rawptr` without a `target` +#[derive(Clone, Copy, Debug)] +pub struct PointerType { + pub target: Option>, +} + +/// `@place` +#[derive(Clone, Copy, Debug)] +pub struct RawAddress { + pub place: Id, +} + +/// `Type.{ name = value }`, or `.{ ... }` without a type +#[derive(Clone, Copy, Debug)] +pub struct StructLiteral { + pub ty: Option>, + pub fields: List, +} + +/// `struct { fields }` +#[derive(Clone, Copy, Debug)] +pub struct StructType { + pub fields: List, } diff --git a/docs/feature-front.md b/docs/feature-front.md index d8d402ad..2951d9a5 100644 --- a/docs/feature-front.md +++ b/docs/feature-front.md @@ -1,11 +1,14 @@ # Design page: a front split by feature -Since 2026-11-13 the features are files of one crate, not a crate each: -`crates/features/src/lib.rs` is the list (`Peeper`, `FeatureExpr`, -`FeatureType`, `FeatureStmt`), and `crates/features/src/.rs` holds a feature's -nodes, parse rows and checking, written for `Peeper`. Where this page says -"the top crate", "`driver/compile/src/language.rs`" or "a feature crate", -read that; the phases are generic over `L` as described. +Since 2026-11-13 the features are files of one crate, not a crate each, +and since 2026-11-18 the phases are not generic over `L` +(docs/structure-mapping.md, step 7): the tree lists every feature's node +(`ast::FeatureExpr`, `FeatureType`, `FeatureStmt`), `crates/features/src/.rs` +holds a feature's parse rows and checking, and `crates/features/src/lib.rs` +names every feature once, in the parse rules (`RULES`) and the checker's +hooks (`CHECK_HOOKS`). Where this page says "the top crate", +"`driver/compile/src/language.rs`", "a feature crate", `L`, `Language`, +`Grammar` or `Checked`, read that. Status: **draft for review, 2026-11-13.** Step 17 of `middle-cleanup.localplan.md`. No code is written for steps 18-20 until this @@ -463,8 +466,8 @@ crate (step 19): with none, it cannot fail. crates/ base/ arena, bigint, diagnostics, literal, source, runtime_abi kernel/ - syntax/ token, lexer, tree (the `syntax` crate: the tree and the - `Language` trait), parser (the engine and its rule table) + syntax/ token, lexer, tree (the `syntax` crate: the tree, every + feature's node too), parser (the engine and its rule table) semantic the `check` crate model THIR, MIR, layout, machine lower, flow, eval @@ -490,8 +493,8 @@ nodes to the feature. A consequence for tests: a crate's own tests cannot use a crate that depends on it, so the core's tests cannot write a feature's syntax. Each -core crate (`parser`, `check`) tests in a language of its own with no -feature (`Bare`). A feature's file tests its syntax and checking in +core crate (`parser`, `check`) tests with the core's rules alone +(`Rules::core()`). A feature's file tests its syntax and checking in `Peeper`, naming no other feature (`src//tests.rs`). A core test that needs a feature only to reach core behaviour (an `extern` function taking a struct, a type's functions) moves unchanged to the top crate's tests diff --git a/docs/structure-mapping.md b/docs/structure-mapping.md index b3afccc9..aa2009f9 100644 --- a/docs/structure-mapping.md +++ b/docs/structure-mapping.md @@ -1,6 +1,7 @@ # Structure mapping: from today's crates to `kernel/` and `features/` -Status: final, agreed by Fuad, GPT and Claude. Nothing has moved yet. +Status: agreed by Fuad, GPT and Claude. Steps 1 to 4, 6 and 7 are done; +step 5 waits for enums. Each line says what kind of change it is: @@ -155,6 +156,35 @@ error, so a second marker would have no reader. Its real split, an abstract type that checks a generic body once against its `T`, changes what an uncalled generic function reports, and waits for a language decision. +## Step 7: no `L` (closed tree, static feature dispatch) + +Peeper is one language, so the phases stop being generic over a language +type. The tree lists every node, feature nodes too; a feature's file keeps +its parse rules and its checks. Decided by Fuad and GPT; it replaces the +`Language`, `Grammar` and `Checked` traits, so it adds no hook (rule 6). + +| Today | Kind | New | +| --- | --- | --- | +| `` on `Tree`, `Expr`, `Type`, `Stmt`, `WrittenRange`, `Parser`, `Rules`, `Module`, `Program`, `Checker`, `ThirBuilder` (about 480 uses: tree 143, parser 124, semantic 146, model 41, project 13, lower 8, lsp 2, peeper 1) | API | no type parameter | +| `features/src/lib.rs`: `FeatureExpr`, `FeatureStmt`, `FeatureType` (built by `nodes!`) | API | closed enums in `syntax/tree` | +| the node data in each feature file (`ArrayLiteral`, `StructLiteral`, `Range`, `Pipe`, `Print`, `CaseTest`, `VariantLiteral`, `OrElse`, `RawAddress`, `CharLiteral`, `Match`, `ArrayType`, `StructType`, `EnumType`, `InterfaceType`, `OptionalType`, `PointerType`) | extract | `syntax/tree`, beside the enums that hold them | +| `Language::{precedence, written_range, fields, methods, pointee, element}`, answered per feature through `ExprNode` and `TypeNode` | API | exhaustive `match` methods on the closed enums in `syntax/tree` | +| `Grammar::rules()`, read as `L::rules()` (14 places) | API | `Parser` holds `rules: &'static Rules`; `parser::parse(file, rules)` | +| `starts_expression`, `starts_type`, `starts_declaration`, `is_statement_keyword`, `starts_statement` (`fn(TokenKind) -> bool`, passed to `Parser::delimited`) | API | read the parser's rules: `fn(&Parser, TokenKind) -> bool` | +| `project::load::(...)` (4 callers: `peeper` driver, its bench, `lsp`, `browser`) | API | `project::load(..., rules)`; `project` keeps `features` as a dev-dependency only | +| `Checked::{check_expr, check_stmt, resolve_type, declare_type}` | API | `check::CheckHooks`, four plain functions; `Checker::new(..., hooks)` | +| `features/src/lib.rs`: `impl Checked for Peeper`, the `dyn` dispatch in `nodes!` | extract | four functions with one exhaustive `match` each, delegating to the feature's file; `features::RULES` and `features::CHECK_HOOKS` handed over by the driver | +| `Peeper`, `Bare` (parser tests, checker tests) | API | removed; core tests use `Rules::core()` and hooks that are `unreachable!` (the core rules make no feature node) | +| parser `dump.rs`: `match feature {}` | API | `unreachable!`, for the same reason | +| `ExprNode`, `StmtNode`, `TypeNode` and each feature's `impl Node { rows }` (the tree's types cannot have impls outside `syntax`) | API | free functions in the feature's file: one `rows`, and `check_*`, `resolve_*`, `declare_*` taking only what each node uses | +| (new) `scripts/check.sh`, "feature boundary" | API | only `ast.rs` and the `features` crate name a feature node's variant (`FeatureExpr::Range`); elsewhere a node is `Feature(_)`, handed to its feature | + +Kept: no kernel crate depends on `features`; no registry or global +state; the parser's static rule table; every diagnostic and LSP answer. +Done when no `Language`, `Grammar`, `Checked`, `Peeper` or `Bare` is left, +and the full `scripts/check.sh` passes with no fixture output changed. +Separate from enums and the pattern engine. + ## Features after the restructuring `features/src`: `arrays`, `chars`, `enums`, `interfaces`, `optionals`, diff --git a/scripts/check.sh b/scripts/check.sh index f7c913e8..87116444 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -43,17 +43,22 @@ check "middle boundary" bash -c " ! grep -rnE '\bsyntax::' crates/kernel/model/src/{mir,machine,constant,lib}.rs \ crates/kernel/{eval,flow} crates/backend/llvm" # A phase names no feature: only its tests may use the `features` crate -# (docs/feature-front.md section 7); Cargo refuses the cycle for the crates -# `features` depends on, this the others. And a feature's files, nested ones -# too, name no other feature: of its own crate, only the list's `Peeper` and -# enums, so no module's path (`crate::structs`, `crate::{structs}`) and no -# `super` path to another feature (`super::structs`, `super::super::structs`). +# (docs/structure-mapping.md, step 7); Cargo refuses the cycle for the crates +# `features` depends on, this the others. The tree lists every feature's node, +# but only the tree's own shape answers (`ast.rs`) and the `features` crate +# name one (`FeatureExpr::Range`): elsewhere a node is only `Feature(_)`, +# handed to its feature. And a feature's files, nested ones too, name no +# other feature: of their own crate, no module's path (`crate::structs`, +# `crate::{structs}`) and no `super` path to another feature +# (`super::structs`, `super::super::structs`). feature_boundary() { local manifest file own others for manifest in crates/{base,backend}/*/Cargo.toml crates/kernel/syntax/*/Cargo.toml \ crates/kernel/{semantic,model,lower,flow,eval}/Cargo.toml crates/driver/project/Cargo.toml; do sed '/^\[dev-dependencies\]/,$d' "$manifest" | grep -H --label="$manifest" '^features\b' && return 1 done + grep -rnE --include='*.rs' '\bFeature(Expr|Stmt|Type)::[A-Z]' crates | + grep -vE '^crates/(features/|kernel/syntax/tree/src/ast\.rs:)' && return 1 for file in $(find crates/features/src -name '*.rs' ! -name lib.rs ! -name testing.rs); do own=${file#crates/features/src/} own=${own%%[./]*} From 0d6605caa7ba81ac8e30e613896bb23ecec9fb4f Mon Sep 17 00:00:00 2001 From: itsfuad Date: Wed, 18 Nov 2026 23:55:38 +0600 Subject: [PATCH 10/24] Lay the compiler out by phase and concept Follow docs/compiler-layout.md: one closed list per phase, one exhaustive dispatch per phase, one file per concept named the same in the parser and the checker, and each fact about a type decided in one place. - Dissolve the `features` crate into concept files of the parser and the checker; one `parser::RULES` table built at compile time, where two rules for one token fail the build. - Type facts are one exhaustive function each (`borrows`, `holds_loans`, `holders_in`, `layout::held`); `layout::in_memory` and lowering's own list of held types are gone. One `builtin_types!` table names every built-in type, `range[T]` included. - Conversions are decided in `semantic_types/conversions.rs`, carrying the `mir::Cast` (renamed from `mir::Conversion`); lowering and the constant folder no longer decide them again. - Crates move out of `crates/kernel/`; the tree crate is `tree`, the checker `check`. Parser files are named as the checker's (`expression.rs`, `statement.rs`, `declaration.rs`). - The no-wildcard lints sit on every dispatch: the checker, the dump, lowering, the interpreter, LLVM and MIR's own walks. - Test-only folders are inlined as `mod tests`; check.sh fails on a source file no `mod` names. No language behavior changes. --- Cargo.lock | 55 +- Cargo.toml | 34 +- crates/backend/llvm/Cargo.toml | 1 - crates/backend/llvm/src/body.rs | 466 ++++++------ crates/backend/llvm/src/tests.rs | 2 +- crates/{kernel/semantic => check}/Cargo.toml | 2 +- crates/check/src/arrays.rs | 176 +++++ .../{kernel/semantic => check}/src/builder.rs | 2 +- crates/check/src/chars.rs | 33 + .../semantic => check}/src/conformance.rs | 0 .../semantic => check}/src/declaration.rs | 101 ++- crates/check/src/enums.rs | 84 ++ .../semantic => check}/src/expression.rs | 61 +- .../src/expression/borrows.rs | 10 +- .../src/expression/literals.rs | 12 +- .../src/expression/names.rs | 0 .../src/expression/operators.rs | 6 +- .../src/expression/places.rs | 10 +- crates/{kernel/semantic => check}/src/fold.rs | 0 .../src/fold/conversions.rs | 30 +- .../semantic => check}/src/fold/operators.rs | 6 +- .../semantic => check}/src/fold/tests.rs | 22 +- .../semantic => check}/src/functions.rs | 16 +- .../src/functions/bodies.rs | 0 .../src/functions/builtin.rs | 0 .../semantic => check}/src/functions/calls.rs | 4 +- .../semantic => check}/src/generics.rs | 16 +- .../src/generics/constraints.rs | 2 +- .../semantic => check}/src/generics/copies.rs | 2 +- crates/check/src/interfaces.rs | 76 ++ crates/{kernel/semantic => check}/src/lib.rs | 77 +- .../{kernel/semantic => check}/src/locals.rs | 4 +- crates/check/src/optionals.rs | 45 ++ crates/check/src/pipes.rs | 68 ++ crates/{features => check}/src/printing.rs | 168 ++-- crates/check/src/ranges.rs | 139 ++++ crates/check/src/raw_pointers.rs | 46 ++ .../{kernel/semantic => check}/src/scope.rs | 10 +- .../semantic => check}/src/statement.rs | 47 +- .../src/statement/assignments.rs | 2 +- .../semantic => check}/src/statement/loops.rs | 4 +- .../semantic => check}/src/statement/tests.rs | 2 +- crates/{features => check}/src/structs.rs | 177 +---- crates/check/src/testing.rs | 136 ++++ .../tests/declarations.rs} | 22 +- .../semantic => check}/tests/llvm_parity.rs | 34 +- crates/driver/browser/Cargo.toml | 1 - crates/driver/browser/src/main.rs | 2 +- crates/driver/compile/Cargo.toml | 3 +- crates/driver/compile/src/lib.rs | 9 +- crates/driver/compile/src/tests.rs | 2 +- .../compile/tests/parses_the_prelude.rs | 8 +- .../driver/compile/tests/path_check_memory.rs | 2 +- crates/driver/lsp/Cargo.toml | 3 +- crates/driver/lsp/src/checked.rs | 2 +- crates/driver/lsp/src/hover.rs | 5 +- crates/driver/lsp/src/server/requests.rs | 6 +- crates/driver/lsp/src/server/sync.rs | 2 +- crates/driver/lsp/src/tests.rs | 4 +- crates/driver/peeper/Cargo.toml | 1 - crates/driver/peeper/benches/compile.rs | 2 +- crates/driver/peeper/src/args.rs | 295 ++++++- crates/driver/peeper/src/args/tests.rs | 292 ------- crates/driver/peeper/src/driver.rs | 220 +++++- crates/driver/peeper/src/driver/tests.rs | 211 ----- crates/driver/project/Cargo.toml | 3 +- crates/driver/project/src/lib.rs | 14 +- crates/driver/project/src/loading.rs | 8 +- crates/driver/project/src/tests.rs | 100 +-- crates/{kernel => }/eval/Cargo.toml | 0 crates/{kernel => }/eval/src/interpreter.rs | 0 .../eval/src/interpreter/instructions.rs | 111 +-- .../eval/src/interpreter/memory.rs | 0 .../eval/src/interpreter/program.rs | 0 crates/{kernel => }/eval/src/lib.rs | 0 crates/{kernel => }/eval/src/operations.rs | 196 +++-- crates/features/Cargo.toml | 22 - crates/features/src/arrays.rs | 192 ----- crates/features/src/arrays/tests.rs | 211 ----- crates/features/src/chars.rs | 40 - crates/features/src/chars/tests.rs | 33 - crates/features/src/enums.rs | 265 ------- crates/features/src/enums/tests.rs | 199 ----- crates/features/src/interfaces.rs | 118 --- crates/features/src/interfaces/tests.rs | 108 --- crates/features/src/lib.rs | 135 ---- crates/features/src/optionals.rs | 73 -- crates/features/src/optionals/tests.rs | 106 --- crates/features/src/pipes.rs | 57 -- crates/features/src/pipes/tests.rs | 69 -- crates/features/src/printing/tests.rs | 33 - crates/features/src/ranges.rs | 168 ---- crates/features/src/ranges/tests.rs | 115 --- crates/features/src/raw_pointers.rs | 99 --- crates/features/src/raw_pointers/tests.rs | 93 --- crates/features/src/structs/tests.rs | 222 ------ crates/features/src/testing.rs | 117 --- crates/{kernel => }/flow/Cargo.toml | 0 crates/{kernel => }/flow/src/lib.rs | 0 crates/{kernel => }/flow/src/loans/errors.rs | 0 crates/{kernel => }/flow/src/loans/holders.rs | 0 crates/{kernel => }/flow/src/loans/mod.rs | 0 crates/{kernel => }/flow/src/loans/passes.rs | 0 crates/{kernel => }/flow/src/loans/places.rs | 0 .../{kernel => }/flow/src/loans/two_phase.rs | 0 .../{kernel => }/flow/src/missing_return.rs | 0 crates/{kernel => }/flow/src/unreachable.rs | 0 .../{kernel => }/flow/src/variable_state.rs | 0 crates/kernel/model/src/layout.rs | 113 --- crates/kernel/model/src/layout/tests.rs | 53 -- crates/kernel/semantic/src/testing.rs | 94 --- crates/kernel/syntax/parser/src/decl/tests.rs | 265 ------- crates/kernel/syntax/parser/src/expr.rs | 360 --------- crates/kernel/syntax/parser/src/expr/tests.rs | 359 --------- crates/kernel/syntax/parser/src/stmt/tests.rs | 167 ---- crates/{kernel => }/lower/Cargo.toml | 3 +- crates/{kernel => }/lower/src/aggregates.rs | 427 ++++++----- crates/{kernel => }/lower/src/arithmetic.rs | 32 +- crates/{kernel => }/lower/src/c_abi.rs | 0 crates/{kernel => }/lower/src/expression.rs | 602 ++++++++------- crates/{kernel => }/lower/src/lib.rs | 438 ++++++----- crates/{kernel => }/lower/src/statement.rs | 11 +- crates/{kernel => }/lower/src/tests.rs | 6 +- crates/{kernel => }/model/Cargo.toml | 2 +- crates/{kernel => }/model/src/constant.rs | 0 crates/model/src/layout.rs | 203 +++++ crates/{kernel => }/model/src/lib.rs | 2 +- crates/{kernel => }/model/src/machine.rs | 0 crates/{kernel => }/model/src/mir.rs | 48 +- crates/{kernel => }/model/src/program.rs | 15 +- .../{kernel => }/model/src/semantic_types.rs | 603 +++------------ crates/model/src/semantic_types/arrays.rs | 36 + crates/model/src/semantic_types/builtin.rs | 182 +++++ .../model/src/semantic_types/conversions.rs | 108 +++ crates/model/src/semantic_types/integers.rs | 133 ++++ crates/model/src/semantic_types/interfaces.rs | 53 ++ crates/model/src/semantic_types/primitive.rs | 17 + crates/model/src/semantic_types/ranges.rs | 48 ++ crates/model/src/semantic_types/structs.rs | 62 ++ .../model/src/semantic_types/tests.rs | 112 ++- crates/{kernel => }/model/src/thir.rs | 4 +- crates/{kernel => }/syntax/lexer/Cargo.toml | 0 crates/{kernel => }/syntax/lexer/src/lib.rs | 0 crates/{kernel => }/syntax/lexer/src/tests.rs | 0 crates/{kernel => }/syntax/parser/Cargo.toml | 2 +- crates/syntax/parser/src/arrays.rs | 228 ++++++ crates/syntax/parser/src/chars.rs | 43 ++ .../parser/src/declaration.rs} | 340 ++++++++- crates/{kernel => }/syntax/parser/src/dump.rs | 203 ++++- crates/syntax/parser/src/enums.rs | 387 ++++++++++ crates/syntax/parser/src/expression.rs | 718 ++++++++++++++++++ .../parser/src/expression}/literals.rs | 6 +- crates/syntax/parser/src/interfaces.rs | 152 ++++ crates/{kernel => }/syntax/parser/src/lib.rs | 159 ++-- crates/syntax/parser/src/optionals.rs | 122 +++ .../{kernel => }/syntax/parser/src/pattern.rs | 6 +- crates/syntax/parser/src/pipes.rs | 67 ++ crates/syntax/parser/src/printing.rs | 68 ++ crates/syntax/parser/src/ranges.rs | 151 ++++ crates/syntax/parser/src/raw_pointers.rs | 136 ++++ .../parser/src/statement.rs} | 229 +++++- crates/syntax/parser/src/structs.rs | 312 ++++++++ crates/syntax/parser/src/testing.rs | 37 + .../{kernel => }/syntax/parser/src/tests.rs | 186 ++++- .../{kernel => }/syntax/parser/src/types.rs | 19 +- crates/{kernel => }/syntax/token/Cargo.toml | 0 crates/{kernel => }/syntax/token/src/lib.rs | 0 crates/{kernel => }/syntax/tree/Cargo.toml | 2 +- crates/{kernel => }/syntax/tree/src/ast.rs | 270 ++----- crates/{kernel => }/syntax/tree/src/lib.rs | 2 +- .../{kernel => }/syntax/tree/src/operators.rs | 0 docs/architecture.md | 29 +- docs/compiler-layout.md | 150 ++++ docs/feature-free-mir.md | 5 +- docs/feature-front.md | 4 + docs/flow-crate.md | 5 +- docs/ir-design.md | 11 +- docs/structure-mapping.md | 4 + rust-style.md | 4 +- scripts/check.sh | 69 +- 180 files changed, 7674 insertions(+), 7197 deletions(-) rename crates/{kernel/semantic => check}/Cargo.toml (96%) create mode 100644 crates/check/src/arrays.rs rename crates/{kernel/semantic => check}/src/builder.rs (98%) create mode 100644 crates/check/src/chars.rs rename crates/{kernel/semantic => check}/src/conformance.rs (100%) rename crates/{kernel/semantic => check}/src/declaration.rs (87%) create mode 100644 crates/check/src/enums.rs rename crates/{kernel/semantic => check}/src/expression.rs (87%) rename crates/{kernel/semantic => check}/src/expression/borrows.rs (96%) rename crates/{kernel/semantic => check}/src/expression/literals.rs (98%) rename crates/{kernel/semantic => check}/src/expression/names.rs (100%) rename crates/{kernel/semantic => check}/src/expression/operators.rs (99%) rename crates/{kernel/semantic => check}/src/expression/places.rs (98%) rename crates/{kernel/semantic => check}/src/fold.rs (100%) rename crates/{kernel/semantic => check}/src/fold/conversions.rs (66%) rename crates/{kernel/semantic => check}/src/fold/operators.rs (98%) rename crates/{kernel/semantic => check}/src/fold/tests.rs (93%) rename crates/{kernel/semantic => check}/src/functions.rs (98%) rename crates/{kernel/semantic => check}/src/functions/bodies.rs (100%) rename crates/{kernel/semantic => check}/src/functions/builtin.rs (100%) rename crates/{kernel/semantic => check}/src/functions/calls.rs (99%) rename crates/{kernel/semantic => check}/src/generics.rs (96%) rename crates/{kernel/semantic => check}/src/generics/constraints.rs (99%) rename crates/{kernel/semantic => check}/src/generics/copies.rs (99%) create mode 100644 crates/check/src/interfaces.rs rename crates/{kernel/semantic => check}/src/lib.rs (93%) rename crates/{kernel/semantic => check}/src/locals.rs (98%) create mode 100644 crates/check/src/optionals.rs create mode 100644 crates/check/src/pipes.rs rename crates/{features => check}/src/printing.rs (75%) create mode 100644 crates/check/src/ranges.rs create mode 100644 crates/check/src/raw_pointers.rs rename crates/{kernel/semantic => check}/src/scope.rs (97%) rename crates/{kernel/semantic => check}/src/statement.rs (94%) rename crates/{kernel/semantic => check}/src/statement/assignments.rs (99%) rename crates/{kernel/semantic => check}/src/statement/loops.rs (99%) rename crates/{kernel/semantic => check}/src/statement/tests.rs (99%) rename crates/{features => check}/src/structs.rs (53%) create mode 100644 crates/check/src/testing.rs rename crates/{driver/compile/tests/checks_through_features.rs => check/tests/declarations.rs} (95%) rename crates/{kernel/semantic => check}/tests/llvm_parity.rs (95%) delete mode 100644 crates/driver/peeper/src/args/tests.rs delete mode 100644 crates/driver/peeper/src/driver/tests.rs rename crates/{kernel => }/eval/Cargo.toml (100%) rename crates/{kernel => }/eval/src/interpreter.rs (100%) rename crates/{kernel => }/eval/src/interpreter/instructions.rs (69%) rename crates/{kernel => }/eval/src/interpreter/memory.rs (100%) rename crates/{kernel => }/eval/src/interpreter/program.rs (100%) rename crates/{kernel => }/eval/src/lib.rs (100%) rename crates/{kernel => }/eval/src/operations.rs (60%) delete mode 100644 crates/features/Cargo.toml delete mode 100644 crates/features/src/arrays.rs delete mode 100644 crates/features/src/arrays/tests.rs delete mode 100644 crates/features/src/chars.rs delete mode 100644 crates/features/src/chars/tests.rs delete mode 100644 crates/features/src/enums.rs delete mode 100644 crates/features/src/enums/tests.rs delete mode 100644 crates/features/src/interfaces.rs delete mode 100644 crates/features/src/interfaces/tests.rs delete mode 100644 crates/features/src/lib.rs delete mode 100644 crates/features/src/optionals.rs delete mode 100644 crates/features/src/optionals/tests.rs delete mode 100644 crates/features/src/pipes.rs delete mode 100644 crates/features/src/pipes/tests.rs delete mode 100644 crates/features/src/printing/tests.rs delete mode 100644 crates/features/src/ranges.rs delete mode 100644 crates/features/src/ranges/tests.rs delete mode 100644 crates/features/src/raw_pointers.rs delete mode 100644 crates/features/src/raw_pointers/tests.rs delete mode 100644 crates/features/src/structs/tests.rs delete mode 100644 crates/features/src/testing.rs rename crates/{kernel => }/flow/Cargo.toml (100%) rename crates/{kernel => }/flow/src/lib.rs (100%) rename crates/{kernel => }/flow/src/loans/errors.rs (100%) rename crates/{kernel => }/flow/src/loans/holders.rs (100%) rename crates/{kernel => }/flow/src/loans/mod.rs (100%) rename crates/{kernel => }/flow/src/loans/passes.rs (100%) rename crates/{kernel => }/flow/src/loans/places.rs (100%) rename crates/{kernel => }/flow/src/loans/two_phase.rs (100%) rename crates/{kernel => }/flow/src/missing_return.rs (100%) rename crates/{kernel => }/flow/src/unreachable.rs (100%) rename crates/{kernel => }/flow/src/variable_state.rs (100%) delete mode 100644 crates/kernel/model/src/layout.rs delete mode 100644 crates/kernel/model/src/layout/tests.rs delete mode 100644 crates/kernel/semantic/src/testing.rs delete mode 100644 crates/kernel/syntax/parser/src/decl/tests.rs delete mode 100644 crates/kernel/syntax/parser/src/expr.rs delete mode 100644 crates/kernel/syntax/parser/src/expr/tests.rs delete mode 100644 crates/kernel/syntax/parser/src/stmt/tests.rs rename crates/{kernel => }/lower/Cargo.toml (90%) rename crates/{kernel => }/lower/src/aggregates.rs (66%) rename crates/{kernel => }/lower/src/arithmetic.rs (66%) rename crates/{kernel => }/lower/src/c_abi.rs (100%) rename crates/{kernel => }/lower/src/expression.rs (67%) rename crates/{kernel => }/lower/src/lib.rs (66%) rename crates/{kernel => }/lower/src/statement.rs (97%) rename crates/{kernel => }/lower/src/tests.rs (99%) rename crates/{kernel => }/model/Cargo.toml (95%) rename crates/{kernel => }/model/src/constant.rs (100%) create mode 100644 crates/model/src/layout.rs rename crates/{kernel => }/model/src/lib.rs (97%) rename crates/{kernel => }/model/src/machine.rs (100%) rename crates/{kernel => }/model/src/mir.rs (97%) rename crates/{kernel => }/model/src/program.rs (97%) rename crates/{kernel => }/model/src/semantic_types.rs (59%) create mode 100644 crates/model/src/semantic_types/arrays.rs create mode 100644 crates/model/src/semantic_types/builtin.rs create mode 100644 crates/model/src/semantic_types/conversions.rs create mode 100644 crates/model/src/semantic_types/integers.rs create mode 100644 crates/model/src/semantic_types/interfaces.rs create mode 100644 crates/model/src/semantic_types/primitive.rs create mode 100644 crates/model/src/semantic_types/ranges.rs create mode 100644 crates/model/src/semantic_types/structs.rs rename crates/{kernel => }/model/src/semantic_types/tests.rs (85%) rename crates/{kernel => }/model/src/thir.rs (99%) rename crates/{kernel => }/syntax/lexer/Cargo.toml (100%) rename crates/{kernel => }/syntax/lexer/src/lib.rs (100%) rename crates/{kernel => }/syntax/lexer/src/tests.rs (100%) rename crates/{kernel => }/syntax/parser/Cargo.toml (94%) create mode 100644 crates/syntax/parser/src/arrays.rs create mode 100644 crates/syntax/parser/src/chars.rs rename crates/{kernel/syntax/parser/src/decl.rs => syntax/parser/src/declaration.rs} (70%) rename crates/{kernel => }/syntax/parser/src/dump.rs (70%) create mode 100644 crates/syntax/parser/src/enums.rs create mode 100644 crates/syntax/parser/src/expression.rs rename crates/{kernel/syntax/parser/src => syntax/parser/src/expression}/literals.rs (94%) create mode 100644 crates/syntax/parser/src/interfaces.rs rename crates/{kernel => }/syntax/parser/src/lib.rs (84%) create mode 100644 crates/syntax/parser/src/optionals.rs rename crates/{kernel => }/syntax/parser/src/pattern.rs (94%) create mode 100644 crates/syntax/parser/src/pipes.rs create mode 100644 crates/syntax/parser/src/printing.rs create mode 100644 crates/syntax/parser/src/ranges.rs create mode 100644 crates/syntax/parser/src/raw_pointers.rs rename crates/{kernel/syntax/parser/src/stmt.rs => syntax/parser/src/statement.rs} (57%) create mode 100644 crates/syntax/parser/src/structs.rs create mode 100644 crates/syntax/parser/src/testing.rs rename crates/{kernel => }/syntax/parser/src/tests.rs (70%) rename crates/{kernel => }/syntax/parser/src/types.rs (93%) rename crates/{kernel => }/syntax/token/Cargo.toml (100%) rename crates/{kernel => }/syntax/token/src/lib.rs (100%) rename crates/{kernel => }/syntax/tree/Cargo.toml (95%) rename crates/{kernel => }/syntax/tree/src/ast.rs (75%) rename crates/{kernel => }/syntax/tree/src/lib.rs (75%) rename crates/{kernel => }/syntax/tree/src/operators.rs (100%) create mode 100644 docs/compiler-layout.md diff --git a/Cargo.lock b/Cargo.lock index 7c2c65e0..34a19fed 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -50,7 +50,6 @@ dependencies = [ "compile", "diagnostics", "eval", - "features", "lexer", "model", "project", @@ -91,7 +90,7 @@ dependencies = [ "runtime_abi", "rustc-hash", "source", - "syntax", + "tree", ] [[package]] @@ -102,14 +101,13 @@ dependencies = [ "check", "diagnostics", "eval", - "features", "lower", "model", "parser", "project", "runtime_abi", "source", - "syntax", + "tree", ] [[package]] @@ -208,22 +206,6 @@ dependencies = [ "source", ] -[[package]] -name = "features" -version = "0.3.1" -dependencies = [ - "arena", - "bigint", - "check", - "diagnostics", - "literal", - "model", - "parser", - "source", - "syntax", - "token", -] - [[package]] name = "filetime" version = "0.2.29" @@ -438,7 +420,6 @@ version = "0.3.1" dependencies = [ "arena", "compile", - "features", "model", "project", "runtime_abi", @@ -460,14 +441,13 @@ dependencies = [ "arena", "bigint", "check", - "features", "model", "parser", "project", "runtime_abi", "rustc-hash", "source", - "syntax", + "tree", ] [[package]] @@ -477,7 +457,6 @@ dependencies = [ "arena", "compile", "diagnostics", - "features", "lexer", "lsp-server", "lsp-types", @@ -485,8 +464,8 @@ dependencies = [ "project", "serde_json", "source", - "syntax", "test_programs", + "tree", ] [[package]] @@ -542,7 +521,7 @@ dependencies = [ "runtime_abi", "rustc-hash", "source", - "syntax", + "tree", ] [[package]] @@ -563,8 +542,8 @@ dependencies = [ "lexer", "literal", "source", - "syntax", "token", + "tree", ] [[package]] @@ -574,7 +553,6 @@ dependencies = [ "compile", "diagnostics", "eval", - "features", "lexer", "llvm", "lsp", @@ -612,13 +590,12 @@ name = "project" version = "0.3.1" dependencies = [ "diagnostics", - "features", "literal", "model", "parser", "source", - "syntax", "toml_edit", + "tree", ] [[package]] @@ -784,15 +761,6 @@ dependencies = [ "syn", ] -[[package]] -name = "syntax" -version = "0.3.1" -dependencies = [ - "arena", - "literal", - "source", -] - [[package]] name = "tar" version = "0.4.46" @@ -874,6 +842,15 @@ dependencies = [ "tar", ] +[[package]] +name = "tree" +version = "0.3.1" +dependencies = [ + "arena", + "literal", + "source", +] + [[package]] name = "typenum" version = "1.20.1" diff --git a/Cargo.toml b/Cargo.toml index 368a29e2..cb9e1309 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,13 +1,12 @@ [workspace] members = [ "crates/base/*", - "crates/kernel/syntax/*", - "crates/kernel/semantic", - "crates/kernel/model", - "crates/kernel/lower", - "crates/kernel/flow", - "crates/kernel/eval", - "crates/features", + "crates/syntax/*", + "crates/check", + "crates/model", + "crates/lower", + "crates/flow", + "crates/eval", "crates/backend/*", "crates/driver/*", "crates/tools/*", @@ -23,23 +22,22 @@ publish = false [workspace.dependencies] source = { path = "crates/base/source" } diagnostics = { path = "crates/base/diagnostics" } -token = { path = "crates/kernel/syntax/token" } -lexer = { path = "crates/kernel/syntax/lexer" } +token = { path = "crates/syntax/token" } +lexer = { path = "crates/syntax/lexer" } arena = { path = "crates/base/arena" } bigint = { path = "crates/base/bigint" } runtime_abi = { path = "crates/base/runtime_abi" } -parser = { path = "crates/kernel/syntax/parser" } +parser = { path = "crates/syntax/parser" } literal = { path = "crates/base/literal" } -syntax = { path = "crates/kernel/syntax/tree" } +tree = { path = "crates/syntax/tree" } test_programs = { path = "crates/driver/test_programs" } -model = { path = "crates/kernel/model" } -eval = { path = "crates/kernel/eval" } -check = { path = "crates/kernel/semantic" } -lower = { path = "crates/kernel/lower" } -flow = { path = "crates/kernel/flow" } +model = { path = "crates/model" } +eval = { path = "crates/eval" } +check = { path = "crates/check" } +lower = { path = "crates/lower" } +flow = { path = "crates/flow" } llvm = { path = "crates/backend/llvm" } compile = { path = "crates/driver/compile" } -features = { path = "crates/features" } project = { path = "crates/driver/project" } lsp = { path = "crates/driver/lsp" } unicode-general-category = "1.1.0" @@ -74,7 +72,7 @@ single_match_else = "warn" uninlined_format_args = "warn" [profile.release] -# The phases and the features are separate crates that call each other often; +# The phases are separate crates that call each other often; # this lets those calls be inlined (one compile ran 3% fewer instructions). lto = "thin" debug = "line-tables-only" diff --git a/crates/backend/llvm/Cargo.toml b/crates/backend/llvm/Cargo.toml index a02f8579..1c4c6699 100644 --- a/crates/backend/llvm/Cargo.toml +++ b/crates/backend/llvm/Cargo.toml @@ -18,7 +18,6 @@ toml_edit.workspace = true [dev-dependencies] compile.workspace = true -features.workspace = true project.workspace = true [lints] diff --git a/crates/backend/llvm/src/body.rs b/crates/backend/llvm/src/body.rs index 2551dd26..f05f7152 100644 --- a/crates/backend/llvm/src/body.rs +++ b/crates/backend/llvm/src/body.rs @@ -11,45 +11,17 @@ use std::fmt::Write; use arena::Id; use model::DeclarationCopy; -use model::mir::Block; -use model::mir::Body; -use model::mir::CPassing; -use model::mir::CSignature; -use model::mir::Callee; -use model::mir::Class; -use model::mir::Comparison; -use model::mir::Conversion; -use model::mir::DebugScope; -use model::mir::DebugTypes; -use model::mir::Extension; -use model::mir::FloatOp; -use model::mir::Global; -use model::mir::Instruction; -use model::mir::InstructionKind; -use model::mir::IntegerOp; -use model::mir::Operand; -use model::mir::Passing; -use model::mir::Place; -use model::mir::Root; -use model::mir::Signature; -use model::mir::Slot; -use model::mir::Step; -use model::mir::Terminator; -use model::mir::constant_value; -use runtime_abi::abi::PANIC_EXIT_CODE; -use runtime_abi::abi::STDERR; -use runtime_abi::messages::panic_text; -use runtime_abi::symbols::Runtime; +use model::mir; +use runtime_abi::abi; +use runtime_abi::messages; +use runtime_abi::symbols; use rustc_hash::FxHashMap; use source::SourceFile; use source::Span; use crate::Module; -use crate::debug_info::DebugLocation; -use crate::debug_info::debug_position; -use crate::text::comma_separated; -use crate::text::global; -use crate::text::quoted; +use crate::debug_info; +use crate::text; /// The intrinsic that copies bytes from one place to another. const MEMCPY: &str = "llvm.memcpy.p0.p0.i64"; @@ -63,7 +35,7 @@ pub(crate) struct Defined { /// Where its name is declared, for its line in a debugger; empty in a /// release build. pub(crate) declared_at: Span, - pub(crate) body: Body, + pub(crate) body: mir::Body, } impl Module<'_> { @@ -76,7 +48,7 @@ impl Module<'_> { defined: &Defined, file: &SourceFile, symbols: &FxHashMap, - debug_types: &DebugTypes, + debug_types: &mir::DebugTypes, ) { let Defined { copy, @@ -87,8 +59,8 @@ impl Module<'_> { let symbol = &symbols[copy]; let globals = (body.globals.iter()) .map(|global| match global { - Global::Bytes(bytes) => self.add_string(bytes), - Global::Functions(entries) => self.add_table(entries, symbols), + mir::Global::Bytes(bytes) => self.add_string(bytes), + mir::Global::Functions(entries) => self.add_table(entries, symbols), }) .collect(); let (subprogram, scopes) = self @@ -126,8 +98,8 @@ impl Module<'_> { _ = write!( out, "define {result} {}({})", - global(symbol), - comma_separated(parameters) + text::global(symbol), + text::comma_separated(parameters) ); if let Some(subprogram) = subprogram { _ = write!(out, " !dbg !{subprogram}"); @@ -158,11 +130,11 @@ impl Module<'_> { /// Notes the `declare` of `symbol`, a function taking and giving values /// as `signature` says, in Peeper's convention, and gives its LLVM name. - fn declare_function(&mut self, symbol: &str, signature: &Signature) -> String { - let callee = global(symbol); + fn declare_function(&mut self, symbol: &str, signature: &mir::Signature) -> String { + let callee = text::global(symbol); self.declare(symbol, || { let (result, parameters) = peeper_types(signature); - let parameters = comma_separated(parameters.iter()); + let parameters = text::comma_separated(parameters.iter()); format!("declare {result} {callee}({parameters})\n\n") }); callee @@ -172,7 +144,7 @@ impl Module<'_> { /// per module, with a `declare` of each. fn add_table( &mut self, - entries: &[(DeclarationCopy, Signature)], + entries: &[(DeclarationCopy, mir::Signature)], symbols: &FxHashMap, ) -> String { let mut constant = format!("[{} x ptr] [", entries.len()); @@ -199,10 +171,10 @@ impl Module<'_> { } /// The LLVM type of a register of `class`. -fn llvm_type(class: Class) -> impl Display { +fn llvm_type(class: mir::Class) -> impl Display { fmt::from_fn(move |out| match class { - Class::F32 => out.write_str("float"), - Class::F64 => out.write_str("double"), + mir::Class::F32 => out.write_str("float"), + mir::Class::F64 => out.write_str("double"), // `i32`, `i200`, `ptr`, as the MIR's dump names them. _ => class.fmt(out), }) @@ -210,67 +182,67 @@ fn llvm_type(class: Class) -> impl Display { /// The instruction an `Integer` of `operation` is; a signed division by /// what may be -1 is `signed_division`'s lines. -pub fn integer_instruction(operation: IntegerOp) -> &'static str { +pub fn integer_instruction(operation: mir::IntegerOp) -> &'static str { match operation { - IntegerOp::Add => "add", - IntegerOp::Subtract => "sub", - IntegerOp::Multiply => "mul", - IntegerOp::SignedDivide => "sdiv", - IntegerOp::UnsignedDivide => "udiv", - IntegerOp::SignedRemainder => "srem", - IntegerOp::UnsignedRemainder => "urem", - IntegerOp::ShiftLeft => "shl", - IntegerOp::SignedShiftRight => "ashr", - IntegerOp::UnsignedShiftRight => "lshr", - IntegerOp::And => "and", - IntegerOp::Or => "or", - IntegerOp::Xor => "xor", + mir::IntegerOp::Add => "add", + mir::IntegerOp::Subtract => "sub", + mir::IntegerOp::Multiply => "mul", + mir::IntegerOp::SignedDivide => "sdiv", + mir::IntegerOp::UnsignedDivide => "udiv", + mir::IntegerOp::SignedRemainder => "srem", + mir::IntegerOp::UnsignedRemainder => "urem", + mir::IntegerOp::ShiftLeft => "shl", + mir::IntegerOp::SignedShiftRight => "ashr", + mir::IntegerOp::UnsignedShiftRight => "lshr", + mir::IntegerOp::And => "and", + mir::IntegerOp::Or => "or", + mir::IntegerOp::Xor => "xor", } } /// The instruction a `Float` of `operation` is. -pub fn float_instruction(operation: FloatOp) -> &'static str { +pub fn float_instruction(operation: mir::FloatOp) -> &'static str { match operation { - FloatOp::Add => "fadd", - FloatOp::Subtract => "fsub", - FloatOp::Multiply => "fmul", - FloatOp::Divide => "fdiv", - FloatOp::Remainder => "frem", + mir::FloatOp::Add => "fadd", + mir::FloatOp::Subtract => "fsub", + mir::FloatOp::Multiply => "fmul", + mir::FloatOp::Divide => "fdiv", + mir::FloatOp::Remainder => "frem", } } /// The `icmp` or `fcmp` with its condition that compares two registers of /// `class` as `comparison`. -pub fn comparison_instruction(comparison: Comparison, class: Class) -> &'static str { - let float = matches!(class, Class::F32 | Class::F64); +pub fn comparison_instruction(comparison: mir::Comparison, class: mir::Class) -> &'static str { + let float = matches!(class, mir::Class::F32 | mir::Class::F64); match comparison { - Comparison::Equal if float => "fcmp oeq", - Comparison::NotEqual if float => "fcmp une", - Comparison::Equal => "icmp eq", - Comparison::NotEqual => "icmp ne", - Comparison::SignedLess => "icmp slt", - Comparison::SignedLessOrEqual => "icmp sle", - Comparison::UnsignedLess => "icmp ult", - Comparison::UnsignedLessOrEqual => "icmp ule", - Comparison::FloatLess => "fcmp olt", - Comparison::FloatLessOrEqual => "fcmp ole", + mir::Comparison::Equal if float => "fcmp oeq", + mir::Comparison::NotEqual if float => "fcmp une", + mir::Comparison::Equal => "icmp eq", + mir::Comparison::NotEqual => "icmp ne", + mir::Comparison::SignedLess => "icmp slt", + mir::Comparison::SignedLessOrEqual => "icmp sle", + mir::Comparison::UnsignedLess => "icmp ult", + mir::Comparison::UnsignedLessOrEqual => "icmp ule", + mir::Comparison::FloatLess => "fcmp olt", + mir::Comparison::FloatLessOrEqual => "fcmp ole", } } -/// The cast instruction of `conversion`; a float to an integer is the -/// saturating intrinsic `saturating_conversion` names instead. -pub fn conversion_instruction(conversion: Conversion) -> &'static str { - match conversion { - Conversion::SignExtend => "sext", - Conversion::ZeroExtend => "zext", - Conversion::Truncate => "trunc", - Conversion::SignedToFloat => "sitofp", - Conversion::UnsignedToFloat => "uitofp", - Conversion::FloatWiden => "fpext", - Conversion::FloatNarrow => "fptrunc", - Conversion::PointerCast => "bitcast", - Conversion::FloatToSigned { .. } | Conversion::FloatToUnsigned { .. } => { - unreachable!("a float becomes an integer by `saturating_conversion`") +/// The cast instruction of `cast`; a float to an integer is the +/// saturating intrinsic `saturating_cast` names instead. +pub fn cast_instruction(cast: mir::Cast) -> &'static str { + match cast { + mir::Cast::SignExtend => "sext", + mir::Cast::ZeroExtend => "zext", + mir::Cast::Truncate => "trunc", + mir::Cast::SignedToFloat => "sitofp", + mir::Cast::UnsignedToFloat => "uitofp", + mir::Cast::FloatWiden => "fpext", + mir::Cast::FloatNarrow => "fptrunc", + mir::Cast::PointerCast => "bitcast", + mir::Cast::FloatToSigned { .. } | mir::Cast::FloatToUnsigned { .. } => { + unreachable!("a float becomes an integer by `saturating_cast`") } } } @@ -278,14 +250,18 @@ pub fn conversion_instruction(conversion: Conversion) -> &'static str { /// The intrinsic that converts a float of `from` to an integer of `bits` /// bits, toward zero and to the nearest end of its range, for a /// `FloatTo*` conversion, and whether it is signed. -pub fn saturating_conversion(conversion: Conversion, from: Class) -> (String, bool) { - let (bits, signed) = match conversion { - Conversion::FloatToSigned { bits } => (bits, true), - Conversion::FloatToUnsigned { bits } => (bits, false), +pub fn saturating_cast(cast: mir::Cast, from: mir::Class) -> (String, bool) { + let (bits, signed) = match cast { + mir::Cast::FloatToSigned { bits } => (bits, true), + mir::Cast::FloatToUnsigned { bits } => (bits, false), _ => unreachable!("only a float to an integer saturates"), }; let kind = if signed { "fptosi" } else { "fptoui" }; - let float = if from == Class::F32 { "f32" } else { "f64" }; + let float = if from == mir::Class::F32 { + "f32" + } else { + "f64" + }; (format!("llvm.{kind}.sat.i{bits}.{float}"), signed) } @@ -295,7 +271,7 @@ pub fn saturating_conversion(conversion: Conversion, from: Class) -> (String, bo /// by 1 instead and negates, so the remainder is 0 as it should be. pub fn signed_division( name: &str, - operation: IntegerOp, + operation: mir::IntegerOp, ty: &dyn Display, left: &dyn Display, right: &dyn Display, @@ -305,7 +281,7 @@ pub fn signed_division( " {name}.m = icmp eq {ty} {right}, -1{location}\n \ {name}.d = select i1 {name}.m, {ty} 1, {ty} {right}{location}\n" ); - if operation == IntegerOp::SignedRemainder { + if operation == mir::IntegerOp::SignedRemainder { _ = writeln!(out, " {name} = srem {ty} {left}, {name}.d{location}"); return out; } @@ -322,20 +298,20 @@ pub fn signed_division( /// values must match LLVM"): an integer in decimal, read as signed, a float /// as the hexadecimal of its value as an `f64`, as LLVM reads a `float` /// too, and the pointer 0 as `null`. -pub fn constant_text(class: Class, bits: [u64; 2]) -> impl Display { +pub fn constant_text(class: mir::Class, bits: [u64; 2]) -> impl Display { fmt::from_fn(move |out| match class { - Class::I128 => write!(out, "{}", constant_value(bits) as i128), - Class::I8 | Class::I16 | Class::I32 | Class::I64 => { + mir::Class::I128 => write!(out, "{}", mir::constant_value(bits) as i128), + mir::Class::I8 | mir::Class::I16 | mir::Class::I32 | mir::Class::I64 => { let unused = 64 - class.bits(); write!(out, "{}", ((bits[0] << unused) as i64) >> unused) } - Class::F32 => write!(out, "0x{:016X}", widened(bits[0] as u32)), - Class::F64 => write!(out, "0x{:016X}", bits[0]), - Class::Pointer => { + mir::Class::F32 => write!(out, "0x{:016X}", widened(bits[0] as u32)), + mir::Class::F64 => write!(out, "0x{:016X}", bits[0]), + mir::Class::Pointer => { assert_eq!(bits[0], 0, "a pointer constant is null"); out.write_str("null") } - Class::Wide(_) => unreachable!("a wide constant is read-only data"), + mir::Class::Wide(_) => unreachable!("a wide constant is read-only data"), }) } @@ -353,11 +329,11 @@ fn widened(bits: u32) -> u64 { /// The LLVM types a function of `signature` gives and takes, in Peeper's /// convention: a value in memory by its address, a result in memory where /// a hidden first parameter points. -fn peeper_types(signature: &Signature) -> (String, Vec) { +fn peeper_types(signature: &mir::Signature) -> (String, Vec) { let mut parameters = Vec::with_capacity(signature.parameters.len() + 1); let result = match signature.result { - Some(Passing::Register { class, .. }) => llvm_type(class).to_string(), - Some(Passing::Memory { .. }) => { + Some(mir::Passing::Register { class, .. }) => llvm_type(class).to_string(), + Some(mir::Passing::Memory { .. }) => { parameters.push("ptr".to_string()); "void".to_string() } @@ -373,10 +349,10 @@ fn peeper_types(signature: &Signature) -> (String, Vec) { /// The LLVM type of a register of `class` C widens as `extension` says, /// with the attribute that tells so: after the type for a parameter /// (`i8 zeroext`), before it for a `result` (`zeroext i8`). -fn c_register_type(class: Class, extension: Option, result: bool) -> String { +fn c_register_type(class: mir::Class, extension: Option, result: bool) -> String { let attribute = match extension { - Some(Extension::Sign) => "signext", - Some(Extension::Zero) => "zeroext", + Some(mir::Extension::Sign) => "signext", + Some(mir::Extension::Zero) => "zeroext", None => return llvm_type(class).to_string(), }; let ty = llvm_type(class); @@ -390,7 +366,7 @@ fn c_register_type(class: Class, extension: Option, result: bool) -> /// Writing one function's `define`, into the `out` its methods are given. struct Writer<'m, 'p, 'b> { module: &'m mut Module<'p>, - body: &'b Body, + body: &'b mir::Body, file: &'b SourceFile, // the function's own, which a copy's module may not be symbols: &'b FxHashMap, globals: Vec, // each global's address @@ -400,9 +376,9 @@ struct Writer<'m, 'p, 'b> { /// The `alloca` of the memory a C call passes a value in, for the entry /// block, so a loop reuses it. memory: String, - block: usize, // the MIR block being written - checked: usize, // its checks so far, each of which starts a block - targets: Vec>, // where a jump to each block goes (`jump_targets`) + block: usize, // the MIR block being written + checked: usize, // its checks so far, each of which starts a block + targets: Vec>, // where a jump to each block goes (`jump_targets`) /// By instruction, whether its value is read as a byte, not only as a /// truth; a comparison is widened to a byte only then. read: Vec, @@ -411,7 +387,7 @@ struct Writer<'m, 'p, 'b> { impl Writer<'_, '_, '_> { /// The `alloca` of each slot and, in a debug build, the debug /// declaration of each one a debugger shows. - fn write_slots(&mut self, out: &mut String, debug_types: &DebugTypes) { + fn write_slots(&mut self, out: &mut String, debug_types: &mir::DebugTypes) { let body = self.body; for slot in body.slots.ids() { let index = slot.index(); @@ -439,7 +415,7 @@ impl Writer<'_, '_, '_> { }; let declared = metadata.add(format_args!( "!DILocalVariable(name: {}, {argument}scope: !{}, file: !{file_metadata}, line: {line}, type: !{debug_type})", - quoted(self.file.slice(span).as_bytes()), + text::quoted(self.file.slice(span).as_bytes()), self.scopes[data.debug_scope.index()], )); let location = self.location(span, data.debug_scope); @@ -454,9 +430,13 @@ impl Writer<'_, '_, '_> { /// The DILocation of where `span` starts, in the debug scope /// `debug_scope`, as the end of a line; nothing in a release build. - fn location(&mut self, span: Span, debug_scope: Id) -> DebugLocation { + fn location( + &mut self, + span: Span, + debug_scope: Id, + ) -> debug_info::DebugLocation { let Some(metadata) = &mut self.module.metadata else { - return DebugLocation(None); + return debug_info::DebugLocation(None); }; let scope = self.scopes[debug_scope.index()]; let file = self.file; @@ -466,47 +446,48 @@ impl Writer<'_, '_, '_> { .locations .entry((scope, span.start)) .or_insert_with(|| { - let (line, column) = debug_position(file, span.start as usize); + let (line, column) = debug_info::debug_position(file, span.start as usize); metadata.add(format_args!( "!DILocation(line: {line}, column: {column}, scope: !{scope})" )) }); - DebugLocation(Some(id)) + debug_info::DebugLocation(Some(id)) } - fn operand(&self, operand: Operand) -> impl Display { + fn operand(&self, operand: mir::Operand) -> impl Display { fmt::from_fn(move |out| self.write_operand(out, operand)) } /// Writes `operand`. The address of a place no step moves from is its /// root's, which no instruction computes (`write_place`). - fn write_operand(&self, out: &mut fmt::Formatter, operand: Operand) -> fmt::Result { + fn write_operand(&self, out: &mut fmt::Formatter, operand: mir::Operand) -> fmt::Result { match operand { - Operand::Value(id) => match &self.body.instructions[id].kind { - InstructionKind::Address { place, .. } | InstructionKind::Borrow { place, .. } + mir::Operand::Value(id) => match &self.body.instructions[id].kind { + mir::InstructionKind::Address { place, .. } + | mir::InstructionKind::Borrow { place, .. } if place.steps.iter().all(|&step| folded(step).is_none()) => { self.root(place.root).fmt(out) } _ => write!(out, "%i{}", id.index()), }, - Operand::Constant { class, bits } => constant_text(class, bits).fmt(out), - Operand::Parameter(index) => write!(out, "%a{index}"), - Operand::Global(index) => out.write_str(&self.globals[index as usize]), + mir::Operand::Constant { class, bits } => constant_text(class, bits).fmt(out), + mir::Operand::Parameter(index) => write!(out, "%a{index}"), + mir::Operand::Global(index) => out.write_str(&self.globals[index as usize]), } } /// The address `root` names. - fn root(&self, root: Root) -> impl Display { + fn root(&self, root: mir::Root) -> impl Display { fmt::from_fn(move |out| match root { - Root::Slot(slot) => out.write_str(&slot_name(self.body, slot)), - Root::At(at) => self.write_operand(out, at), - Root::Result => out.write_str("%result"), + mir::Root::Slot(slot) => out.write_str(&slot_name(self.body, slot)), + mir::Root::At(at) => self.write_operand(out, at), + mir::Root::Result => out.write_str("%result"), }) } /// `operand` with its type before it, as an argument. - fn typed(&self, operand: Operand) -> impl Display { + fn typed(&self, operand: mir::Operand) -> impl Display { let class = self .body .class_of(operand) @@ -520,12 +501,12 @@ impl Writer<'_, '_, '_> { fn write_truth( &self, out: &mut String, - condition: Operand, + condition: mir::Operand, name: &str, - location: &DebugLocation, + location: &debug_info::DebugLocation, ) -> String { - if let Operand::Value(id) = condition - && let InstructionKind::Compare { .. } = self.body.instructions[id].kind + if let mir::Operand::Value(id) = condition + && let mir::InstructionKind::Compare { .. } = self.body.instructions[id].kind { return format!("%i{}.c", id.index()); } @@ -543,16 +524,16 @@ impl Writer<'_, '_, '_> { fn write_place( &mut self, out: &mut String, - place: &Place, + place: &mir::Place, name: &str, - location: &DebugLocation, + location: &debug_info::DebugLocation, ) -> String { let mut at = self.root(place.root).to_string(); // Offsets in a row, with constant indexes, add up to one. - let mut steps: Vec = Vec::with_capacity(place.steps.len()); + let mut steps: Vec = Vec::with_capacity(place.steps.len()); for step in place.steps.iter().filter_map(|&step| folded(step)) { match (step, steps.last_mut()) { - (Step::Offset(bytes), Some(Step::Offset(sum))) => *sum += bytes, + (mir::Step::Offset(bytes), Some(mir::Step::Offset(sum))) => *sum += bytes, _ => steps.push(step), } } @@ -563,15 +544,15 @@ impl Writer<'_, '_, '_> { format!("{name}.{}", position + 1) }; match step { - Step::Offset(bytes) => { + mir::Step::Offset(bytes) => { _ = writeln!( out, " {to} = getelementptr inbounds i8, ptr {at}, i64 {bytes}{location}" ); } - Step::Through => _ = writeln!(out, " {to} = load ptr, ptr {at}{location}"), + mir::Step::Through => _ = writeln!(out, " {to} = load ptr, ptr {at}{location}"), // Lowering checked the index is inside. - Step::Index { index, size, .. } => { + mir::Step::Index { index, size, .. } => { _ = writeln!( out, " {to} = getelementptr inbounds [{size} x i8], ptr {at}, {}{location}", @@ -584,7 +565,7 @@ impl Writer<'_, '_, '_> { at } - fn write_block(&mut self, out: &mut String, block: Id) { + fn write_block(&mut self, out: &mut String, block: Id) { _ = writeln!(out, "bb{}:", block.index()); let body = self.body; let data = &body.blocks[block]; @@ -594,12 +575,12 @@ impl Writer<'_, '_, '_> { } // The line, then the location of its span, if it has one. let span = match &data.terminator { - &Terminator::Jump(target) => { + &mir::Terminator::Jump(target) => { let target = self.targets[target.index()]; _ = write!(out, " br label %bb{}", target.index()); None } - &Terminator::Branch { + &mir::Terminator::Branch { condition, span, then, @@ -616,45 +597,49 @@ impl Writer<'_, '_, '_> { ); Some(span) } - &Terminator::Return { + &mir::Terminator::Return { value: Some(value), span, } => { _ = write!(out, " ret {}", self.typed(value)); Some(span) } - Terminator::Panic { message, span } => { + mir::Terminator::Panic { message, span } => { self.write_panic(out, message, *span, data.debug_scope); None } // The missing-return check gives such a function an error, and // a function with an error is not written. - &Terminator::FallOff(_) if body.signature.result.is_some() => { + &mir::Terminator::FallOff(_) if body.signature.result.is_some() => { unreachable!("a function with a result falls off its end") } - &Terminator::Return { value: None, span } | &Terminator::FallOff(span) => { + &mir::Terminator::Return { value: None, span } | &mir::Terminator::FallOff(span) => { out.push_str(" ret void"); Some(span) } }; - let location = span.map_or(DebugLocation(None), |span| { + let location = span.map_or(debug_info::DebugLocation(None), |span| { self.location(span, data.debug_scope) }); _ = writeln!(out, "{location}"); } - fn write_instruction(&mut self, out: &mut String, id: Id) { + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] + fn write_instruction(&mut self, out: &mut String, id: Id) { let body = self.body; - let Instruction { kind, debug_scope } = &body.instructions[id]; + let mir::Instruction { kind, debug_scope } = &body.instructions[id]; if !kind.runs() { return; // for the path checks only } let location = self.location(body.instructions.span(id), *debug_scope); let name = format!("%i{}", id.index()); match kind { - InstructionKind::Integer { - operation: IntegerOp::Add, - class: Class::Pointer, + mir::InstructionKind::Integer { + operation: mir::IntegerOp::Add, + class: mir::Class::Pointer, left, right, } => { @@ -666,8 +651,9 @@ impl Writer<'_, '_, '_> { self.typed(*right) ); } - &InstructionKind::Integer { - operation: operation @ (IntegerOp::SignedDivide | IntegerOp::SignedRemainder), + &mir::InstructionKind::Integer { + operation: + operation @ (mir::IntegerOp::SignedDivide | mir::IntegerOp::SignedRemainder), class, left, right, @@ -682,7 +668,7 @@ impl Writer<'_, '_, '_> { &location, )); } - InstructionKind::Integer { + mir::InstructionKind::Integer { operation, class, left, @@ -697,7 +683,7 @@ impl Writer<'_, '_, '_> { self.operand(*right) ); } - InstructionKind::Float { + mir::InstructionKind::Float { operation, class, left, @@ -712,7 +698,7 @@ impl Writer<'_, '_, '_> { self.operand(*right) ); } - InstructionKind::Compare { + mir::InstructionKind::Compare { comparison, class, left, @@ -730,15 +716,14 @@ impl Writer<'_, '_, '_> { _ = writeln!(out, " {name} = zext i1 {name}.c to i8{location}"); } } - &InstructionKind::Convert { - conversion: - conversion @ (Conversion::FloatToSigned { bits } - | Conversion::FloatToUnsigned { bits }), + &mir::InstructionKind::Convert { + cast: + cast @ (mir::Cast::FloatToSigned { bits } | mir::Cast::FloatToUnsigned { bits }), from, to, value, } => { - let (intrinsic, signed) = saturating_conversion(conversion, from); + let (intrinsic, signed) = saturating_cast(cast, from); let (from_text, saturated) = (llvm_type(from), format!("i{bits}")); self.module.declare(&intrinsic, || { format!("declare {saturated} @{intrinsic}({from_text})\n\n") @@ -762,8 +747,8 @@ impl Writer<'_, '_, '_> { ); } } - InstructionKind::Convert { - conversion, + mir::InstructionKind::Convert { + cast, from, to, value, @@ -771,18 +756,19 @@ impl Writer<'_, '_, '_> { _ = writeln!( out, " {name} = {} {} {} to {}{location}", - conversion_instruction(*conversion), + cast_instruction(*cast), llvm_type(*from), self.operand(*value), llvm_type(*to) ); } - InstructionKind::Load { class, place } => { + mir::InstructionKind::Load { class, place } => { let address = self.write_place(out, place, &format!("{name}.a"), &location); // Read-only data is bytes, aligned to none. - let align = match place.root { - Root::At(Operand::Global(_)) => ", align 1", - _ => "", + let align = if let mir::Root::At(mir::Operand::Global(_)) = place.root { + ", align 1" + } else { + "" }; _ = writeln!( out, @@ -790,7 +776,7 @@ impl Writer<'_, '_, '_> { llvm_type(*class) ); } - InstructionKind::Store { + mir::InstructionKind::Store { class, place, value, @@ -803,7 +789,7 @@ impl Writer<'_, '_, '_> { self.operand(*value) ); } - InstructionKind::Copy { to, from, size } => { + mir::InstructionKind::Copy { to, from, size } => { let to = self.write_place(out, to, &format!("{name}.t"), &location); let from = self.write_place(out, from, &format!("{name}.f"), &location); self.module.declare(MEMCPY, || { @@ -815,10 +801,11 @@ impl Writer<'_, '_, '_> { ); } // With no step, the address is the root's (`write_operand`). - InstructionKind::Address { place, .. } | InstructionKind::Borrow { place, .. } => { + mir::InstructionKind::Address { place, .. } + | mir::InstructionKind::Borrow { place, .. } => { self.write_place(out, place, &name, &location); } - InstructionKind::Call { + mir::InstructionKind::Call { callee, signature, arguments, @@ -838,7 +825,7 @@ impl Writer<'_, '_, '_> { self.write_call(out, &name, callee, signature, at, arguments, &location); } } - InstructionKind::Check { failed, message } => { + mir::InstructionKind::Check { failed, message } => { self.checked += 1; let next = format!("bb{}.{}", self.block, self.checked); let panic = format!("{next}.panic"); @@ -854,7 +841,7 @@ impl Writer<'_, '_, '_> { panics.push('\n'); self.panics = panics; } - InstructionKind::Moved { .. } | InstructionKind::Dead(_) => { + mir::InstructionKind::Moved { .. } | mir::InstructionKind::Dead(_) => { unreachable!("returned above") } } @@ -862,12 +849,12 @@ impl Writer<'_, '_, '_> { /// Whether `divisor`, of `class`, is a constant other than -1, by which /// a signed division cannot overflow. - fn divides_by_other_than_minus_one(&self, divisor: Operand, class: Class) -> bool { - let Operand::Constant { bits, .. } = divisor else { + fn divides_by_other_than_minus_one(&self, divisor: mir::Operand, class: mir::Class) -> bool { + let mir::Operand::Constant { bits, .. } = divisor else { return false; }; let all = u128::MAX >> (128 - class.bits()); - constant_value(bits) != all + mir::constant_value(bits) != all } /// Writes the call, as `name`, of `callee` in Peeper's convention, with @@ -878,17 +865,17 @@ impl Writer<'_, '_, '_> { &mut self, out: &mut String, name: &str, - callee: Callee, - signature: &Signature, + callee: mir::Callee, + signature: &mir::Signature, result_at: Option<&str>, - arguments: &[Operand], - location: &DebugLocation, + arguments: &[mir::Operand], + location: &debug_info::DebugLocation, ) { let callee = match callee { - Callee::Function(function) => self + mir::Callee::Function(function) => self .module .declare_function(&self.symbols[&function], signature), - Callee::Pointer(address) => self.operand(address).to_string(), + mir::Callee::Pointer(address) => self.operand(address).to_string(), }; let (result, _) = peeper_types(signature); let separator = if arguments.is_empty() { "" } else { ", " }; @@ -896,9 +883,10 @@ impl Writer<'_, '_, '_> { Some(address) => write!(out, "ptr {address}{separator}"), None => Ok(()), }); - let arguments = comma_separated(arguments.iter().map(|&argument| self.typed(argument))); + let arguments = + text::comma_separated(arguments.iter().map(|&argument| self.typed(argument))); out.push_str(" "); - if let Some(Passing::Register { .. }) = signature.result { + if let Some(mir::Passing::Register { .. }) = signature.result { _ = write!(out, "{name} = "); } _ = writeln!( @@ -915,15 +903,15 @@ impl Writer<'_, '_, '_> { &mut self, out: &mut String, name: &str, - signature: &Signature, - c: &CSignature, - arguments: &[Operand], - location: &DebugLocation, + signature: &mir::Signature, + c: &mir::CSignature, + arguments: &[mir::Operand], + location: &debug_info::DebugLocation, ) { // The memory a result C gives there or in pieces is read from. let returned = format!("{name}.r"); let (mut declared, mut passed) = (Vec::new(), Vec::new()); - if let Some(CPassing::Memory { size, align, .. }) = c.result { + if let Some(mir::CPassing::Memory { size, align, .. }) = c.result { _ = writeln!( self.memory, " {returned} = alloca [{size} x i8], align {align}" @@ -937,7 +925,7 @@ impl Writer<'_, '_, '_> { .zip(&c.parameters) .zip(&signature.parameters); for (index, ((&argument, &passing), &peeper)) in parameters.enumerate() { - let Passing::Register { class, signed } = peeper else { + let mir::Passing::Register { class, signed } = peeper else { unreachable!("only a scalar passes to C") }; let (path, value) = ( @@ -945,12 +933,12 @@ impl Writer<'_, '_, '_> { self.operand(argument).to_string(), ); match passing { - CPassing::Register { extension } => { + mir::CPassing::Register { extension } => { let parameter = c_register_type(class, extension, false); passed.push(format!("{parameter} {value}")); declared.push(parameter); } - CPassing::Pieces { count, bits } => { + mir::CPassing::Pieces { count, bits } => { let width = count * bits; let whole = format!("{path}.x"); let whole = @@ -967,7 +955,7 @@ impl Writer<'_, '_, '_> { } } // A copy C may change. - CPassing::Memory { + mir::CPassing::Memory { size, align, by_value, @@ -992,25 +980,25 @@ impl Writer<'_, '_, '_> { passed.push(format!("{parameter} {path}")); declared.push(parameter); } - CPassing::Vector { .. } => unreachable!("only a result is passed as a vector"), + mir::CPassing::Vector { .. } => unreachable!("only a result is passed as a vector"), } } let result = match c.result { - None | Some(CPassing::Memory { .. }) => "void".to_string(), - Some(CPassing::Register { extension }) => { - let Some(Passing::Register { class, .. }) = signature.result else { + None | Some(mir::CPassing::Memory { .. }) => "void".to_string(), + Some(mir::CPassing::Register { extension }) => { + let Some(mir::Passing::Register { class, .. }) = signature.result else { unreachable!("C gives a scalar") }; c_register_type(class, extension, true) } - Some(CPassing::Pieces { count, bits }) => { + Some(mir::CPassing::Pieces { count, bits }) => { let pieces = vec![format!("i{bits}"); count as usize]; format!("{{ {} }}", pieces.join(", ")) } - Some(CPassing::Vector { count, bits }) => format!("<{count} x i{bits}>"), + Some(mir::CPassing::Vector { count, bits }) => format!("<{count} x i{bits}>"), }; let symbol = &*c.symbol; - let callee = global(symbol); + let callee = text::global(symbol); self.module.declare(symbol, || { format!("declare {result} {callee}({})\n\n", declared.join(", ")) }); @@ -1022,15 +1010,15 @@ impl Writer<'_, '_, '_> { _ = writeln!(out, " {call}{location}"); return; } - Some(CPassing::Register { .. }) => { + Some(mir::CPassing::Register { .. }) => { _ = writeln!(out, " {name} = {call}{location}"); return; } - Some(CPassing::Memory { size, align, .. }) => { + Some(mir::CPassing::Memory { size, align, .. }) => { _ = writeln!(out, " {call}{location}"); (size, align) } - Some(CPassing::Pieces { count, bits } | CPassing::Vector { count, bits }) => { + Some(mir::CPassing::Pieces { count, bits } | mir::CPassing::Vector { count, bits }) => { let size = u64::from(count * bits / 8); _ = writeln!(self.memory, " {returned} = alloca [{size} x i8], align 16"); _ = writeln!( @@ -1041,7 +1029,7 @@ impl Writer<'_, '_, '_> { (size, 16) } }; - let Some(Passing::Register { class, signed }) = signature.result else { + let Some(mir::Passing::Register { class, signed }) = signature.result else { unreachable!("C gives a scalar") }; let width = (size * 8) as u32; @@ -1068,19 +1056,19 @@ impl Writer<'_, '_, '_> { out: &mut String, message: &[u8], span: Span, - debug_scope: Id, + debug_scope: Id, ) { let location = self.location(span, debug_scope); - let text = panic_text(self.module.root, self.file, message, span); + let text = messages::panic_text(self.module.root, self.file, message, span); let string = self.module.add_string(&text); let (stderr, length, code) = ( - STDERR.to_string(), + abi::STDERR.to_string(), text.len().to_string(), - PANIC_EXIT_CODE.to_string(), + abi::PANIC_EXIT_CODE.to_string(), ); let written: [&str; 3] = [&stderr, &string, &length]; - self.write_runtime_call(out, Runtime::PanicWrite, &written, &location); - self.write_runtime_call(out, Runtime::PanicExit, &[&code], &location); + self.write_runtime_call(out, symbols::Runtime::PanicWrite, &written, &location); + self.write_runtime_call(out, symbols::Runtime::PanicExit, &[&code], &location); out.push_str(" unreachable"); } @@ -1090,12 +1078,12 @@ impl Writer<'_, '_, '_> { fn write_runtime_call( &mut self, out: &mut String, - runtime: Runtime, + runtime: symbols::Runtime, arguments: &[&str], - location: &DebugLocation, + location: &debug_info::DebugLocation, ) { - let usize = Class::integer(self.module.target.pointer_bits); - let signature = Signature::of_runtime(runtime, usize); + let usize = mir::Class::integer(self.module.target.pointer_bits); + let signature = mir::Signature::of_runtime(runtime, usize); assert_eq!(arguments.len(), signature.parameters.len(), "{runtime:?}"); let callee = self .module @@ -1106,7 +1094,7 @@ impl Writer<'_, '_, '_> { _ = writeln!( out, " call {result} {callee}({}){location}", - comma_separated(arguments) + text::comma_separated(arguments) ); } } @@ -1116,10 +1104,10 @@ impl Writer<'_, '_, '_> { /// branch holding only `break`. The path checks keep these blocks in the /// MIR; LLVM needs none of them. A jump into an endless loop of such blocks /// stops on one of them. -fn jump_targets(body: &Body) -> Vec> { - let passed_through = |block: Id| { +fn jump_targets(body: &mir::Body) -> Vec> { + let passed_through = |block: Id| { let data = &body.blocks[block]; - let Terminator::Jump(next) = data.terminator else { + let mir::Terminator::Jump(next) = data.terminator else { return None; }; let writes = @@ -1127,7 +1115,7 @@ fn jump_targets(body: &Body) -> Vec> { (!writes).then_some(next) }; // Each block is followed once: a chain found is kept for every block on it. - let mut targets: Vec>> = vec![None; body.blocks.len()]; + let mut targets: Vec>> = vec![None; body.blocks.len()]; let mut on_path = vec![false; body.blocks.len()]; let mut path = Vec::new(); for start in body.blocks.ids() { @@ -1159,17 +1147,17 @@ fn jump_targets(body: &Body) -> Vec> { /// By instruction, whether its value is read as a byte: by anything but a /// `Branch`'s condition or a `Check`'s, which read a comparison's `i1` /// (`Writer::write_truth`). -fn values_read(body: &Body) -> Vec { +fn values_read(body: &mir::Body) -> Vec { let mut operands = Vec::new(); for id in body.instructions.ids() { let kind = &body.instructions[id].kind; - if !matches!(kind, InstructionKind::Check { .. }) { + if !matches!(kind, mir::InstructionKind::Check { .. }) { kind.operands(|operand| operands.push(operand)); } kind.accesses(|access| operands.extend(access.place.operands())); } for block in body.blocks.ids() { - if let Terminator::Return { + if let mir::Terminator::Return { value: Some(value), .. } = body.blocks[block].terminator { @@ -1178,7 +1166,7 @@ fn values_read(body: &Body) -> Vec { } let mut read = vec![false; body.instructions.len()]; for operand in operands { - if let Operand::Value(id) = operand { + if let mir::Operand::Value(id) = operand { read[id.index()] = true; } } @@ -1187,7 +1175,7 @@ fn values_read(body: &Body) -> Vec { /// The LLVM name of the address of `slot` of `body`: its `alloca`, or the /// parameter it is when passed in memory (`Body::parameter_in_memory`). -fn slot_name(body: &Body, slot: Id) -> String { +fn slot_name(body: &mir::Body, slot: Id) -> String { match body.parameter_in_memory(slot) { Some(parameter) => format!("%a{parameter}"), None => format!("%s{}", slot.index()), @@ -1196,16 +1184,16 @@ fn slot_name(body: &Body, slot: Id) -> String { /// `step` with a constant index as the offset it is, as `write_place` /// writes it; `None` when it moves nowhere. -fn folded(step: Step) -> Option { +fn folded(step: mir::Step) -> Option { let step = match step { - Step::Index { - index: Operand::Constant { bits, .. }, + mir::Step::Index { + index: mir::Operand::Constant { bits, .. }, size, .. - } => Step::Offset(bits[0] * size), + } => mir::Step::Offset(bits[0] * size), step => step, }; - (step != Step::Offset(0)).then_some(step) + (step != mir::Step::Offset(0)).then_some(step) } /// Writes `value`, an integer of `from` bits, as one of `to` bits named @@ -1218,7 +1206,7 @@ fn write_resized( from: u32, to: u32, signed: bool, - location: &DebugLocation, + location: &debug_info::DebugLocation, ) -> String { let instruction = match (from.cmp(&to), signed) { (std::cmp::Ordering::Equal, _) => return value.to_string(), diff --git a/crates/backend/llvm/src/tests.rs b/crates/backend/llvm/src/tests.rs index decdfdb3..30aff845 100644 --- a/crates/backend/llvm/src/tests.rs +++ b/crates/backend/llvm/src/tests.rs @@ -43,7 +43,7 @@ fn program_ll(text: &str, target: &str) -> HashMap { "fn Half(a: i32, b: i32) -> i32 { return a / b; }\n".to_string(), ), ]); - let program = project::load(&project, &open_files, &features::RULES); + let program = project::load(&project, &open_files); assert!(program.checkable); let files: Vec<_> = (program.modules.iter()) .map(|module| module.ast.file.clone()) diff --git a/crates/kernel/semantic/Cargo.toml b/crates/check/Cargo.toml similarity index 96% rename from crates/kernel/semantic/Cargo.toml rename to crates/check/Cargo.toml index 134102c7..08e7cf79 100644 --- a/crates/kernel/semantic/Cargo.toml +++ b/crates/check/Cargo.toml @@ -11,7 +11,7 @@ source.workspace = true diagnostics.workspace = true arena.workspace = true model.workspace = true -syntax.workspace = true +tree.workspace = true eval.workspace = true lower.workspace = true flow.workspace = true diff --git a/crates/check/src/arrays.rs b/crates/check/src/arrays.rs new file mode 100644 index 00000000..b7ef57eb --- /dev/null +++ b/crates/check/src/arrays.rs @@ -0,0 +1,176 @@ +//! Arrays: the checker's file for `[N]T` and the array literals `[N]T{ ... }` +//! and `[_]T{ ... }`, as the parser reads them. The checker gives a +//! `Type::Array` and an `ExprKind::ArrayLiteral`, so the phases after it know +//! nothing of this file. A literal's entries and their `...` spreads are +//! checked in `expression/literals.rs`, as a call to a `...` parameter checks +//! them too; slices (read after `&`) and indexing in `expression/places.rs`. + +use crate::Checker; +use crate::builder; +use arena::Id; +use arena::List; +use model::semantic_types; +use model::thir; +use source::Span; +use tree::ast; + +/// The type `[length]element`, written at `span`: the length is a whole +/// number without a suffix that an array can hold. +pub(crate) fn resolve_array_type( + checker: &mut Checker<'_>, + length: Span, + element: Id, + span: Span, +) -> semantic_types::TypeId { + let literal = literal::numeric::split(checker.module().ast.file.slice(length)); + let value = literal.integer_value(); + if !literal.suffix.is_empty() || literal.is_float() { + let message = "an array length is a whole number without a suffix"; + return checker.error(diagnostics::INVALID_TYPE, message, length); + } + if !checker.length_fits(&value, length) { + return semantic_types::TypeId::INVALID; + } + let element = checker.resolve_value_type(element); + checker.array_type(element, value[0], span) +} + +/// `[N]T{ entries }`, written at `span`, or `[_]T{ entries }`, whose +/// length is the number of values its entries give: each entry a `T`, or +/// a spread of a range, an array or a slice (`count_spread`). They must +/// give exactly its length. A slice, or a range whose count is not known +/// now, is counted when the program runs, so its literal needs a written +/// length, which the entries known now must not already pass. +pub(crate) fn check_array_literal( + builder: &mut builder::ThirBuilder<'_, '_>, + ty: ast::ArrayLiteralType, + entries: List, + span: Span, +) -> thir::Expr { + let tree = &builder.checker.module().ast; + let (element, length, written) = match ty { + ast::ArrayLiteralType::Counted { element } => { + // `[_]T`, from its `[` to its element's end + let written = Span { + start: span.start, + end: tree.types.span(element).end, + }; + (builder.checker.resolve_value_type(element), None, written) + } + ast::ArrayLiteralType::Written(written) => { + let span = tree.types.span(written); + match builder.checker.resolve_value_type(written) { + ty if ty == semantic_types::TypeId::INVALID => { + (semantic_types::TypeId::INVALID, None, span) + } + ty => match builder.checker.types[ty] { + semantic_types::Type::Array { + element, length, .. + } => (element, Some((ty, length)), span), + _ => unreachable!("an array literal's written type is an array type"), + }, + } + } + }; + let entries = tree.children.lists.items(entries); + let (parts, known, later) = builder.check_entries(entries, element, None); + let Some(known) = known.filter(|_| element != semantic_types::TypeId::INVALID) else { + return thir::Expr::INVALID; + }; + let Some(ty) = builder.array_literal_type(written, element, length, (known, later), span) + else { + return thir::Expr::INVALID; + }; + thir::Expr { + ty, + kind: thir::ExprKind::ArrayLiteral(builder.body.children.lists.add(&parts)), + } +} + +#[cfg(test)] +mod tests { + //! Checking arrays: the literals' lengths and entries, temporaries, and + //! `const` values whose type names a type parameter. + + use crate::testing; + + /// `[_]T` takes its length from its entries, a spread's too; `[N]T` needs + /// that many. + #[test] + fn literals() { + let (bodies, reported) = testing::bodies( + "fn f(a: [2]i32) { + let b = [_]i32{ 1, a..., 4 }; + let c = [3]i32{ 1, 2 }; + }", + ); + assert_eq!( + reported, + [( + "T0001", + "`[3]i32` needs 3 values, found 2".to_string(), + "[3]i32{ 1, 2 }".to_string() + )] + ); + assert_eq!( + bodies, + [" let b.1 = [4]i32{ 1:i32, (a.0)..., 4:i32 }\n let c.2 = invalid\n"] + ); + } + + /// A temporary is stored where it is computed, and each one a `let`'s + /// value makes is marked to last with it; one in a plain statement is not. + /// An array's temporary is indexed and looped over as a variable is. + #[test] + fn temporaries() { + let (bodies, reported) = testing::bodies( + "fn make() -> [2]i32 { return [2]i32{1, 2}; } + fn id(r: &mut i32) -> &mut i32 in r { return r; } + fn sum(values: &[]i32) -> i32 { return values[0]; } + fn f() { + let total = sum(&make()); + let kept = &make(); + let first = make()[0]; + let mut x = 1; + id(&mut x).* = 2; + for v in &make() { } + }", + ); + assert!(reported.is_empty(), "{reported:?}"); + assert_eq!( + bodies[3], + " let total.1 = call f2(&(kept _.0 = call f0():[2]i32)):i32 + let kept.3 = &(kept _.2 = call f0():[2]i32) + let first.5 = (kept _.4 = call f0():[2]i32)[at 0:u64] + let mut x.6 = 1:i32 + (_.7 = call f1(&mut x.6):&mut i32).* = 2:i32 + { + let _.9 = &(kept _.8 = call f0():[2]i32) + for _.10 in 0:u64..2:u64 by 1:u64 { + let v.11 = &_.9.*[at _.10] + } + } +" + ); + } + + /// A `const` value's type is read again at each call, which cannot know a + /// type parameter yet, so one naming it through an array is refused. + #[test] + fn const_array_of_a_type_parameter() { + let text = "fn Typed(const T: type, const a: [2]T) {}"; + let ((), reported) = testing::with_functions(text, |checker, functions| { + let (definition, name) = functions[0]; + checker.function_type(definition, name); + }); + assert_eq!( + reported, + [( + "T0043", + "`const` values whose type names a type parameter are not supported yet" + .to_string(), + "[2]T".to_string() + )] + ); + } +} diff --git a/crates/kernel/semantic/src/builder.rs b/crates/check/src/builder.rs similarity index 98% rename from crates/kernel/semantic/src/builder.rs rename to crates/check/src/builder.rs index db43a628..74396636 100644 --- a/crates/kernel/semantic/src/builder.rs +++ b/crates/check/src/builder.rs @@ -21,7 +21,7 @@ pub(crate) struct Declared<'p> { /// Building the THIR of one piece of code: a function's body, or a /// constant's value. It checks the code as it builds it. -pub struct ThirBuilder<'a, 'p> { +pub(crate) struct ThirBuilder<'a, 'p> { /// The checker, borrowed for the build: its module, tables and /// diagnostics. pub checker: &'a mut Checker<'p>, diff --git a/crates/check/src/chars.rs b/crates/check/src/chars.rs new file mode 100644 index 00000000..bcd2eff3 --- /dev/null +++ b/crates/check/src/chars.rs @@ -0,0 +1,33 @@ +//! Character literals: `'x'` and `b'x'`. Refused by the checker until a +//! character has a type. + +use crate::builder; +use model::thir; +use source::Span; + +/// A character literal at `span`, which no check exists for yet. +pub(crate) fn check_char_literal( + builder: &mut builder::ThirBuilder<'_, '_>, + span: Span, +) -> thir::Expr { + builder.checker.not_supported(span, "character literals"); + thir::Expr::INVALID +} + +#[cfg(test)] +mod tests { + //! Refusal of character literals until they have a type. + + use crate::testing; + + /// A character has no type yet, so a literal is refused where it is + /// written. + #[test] + fn refused() { + let (_, reported) = testing::bodies("fn f() { 'x'; }"); + let found: Vec<(&str, &str)> = (reported.iter()) + .map(|(_, message, text)| (message.as_str(), text.as_str())) + .collect(); + assert_eq!(found, [("character literals are not supported yet", "'x'")]); + } +} diff --git a/crates/kernel/semantic/src/conformance.rs b/crates/check/src/conformance.rs similarity index 100% rename from crates/kernel/semantic/src/conformance.rs rename to crates/check/src/conformance.rs diff --git a/crates/kernel/semantic/src/declaration.rs b/crates/check/src/declaration.rs similarity index 87% rename from crates/kernel/semantic/src/declaration.rs rename to crates/check/src/declaration.rs index 46155698..08307eec 100644 --- a/crates/kernel/semantic/src/declaration.rs +++ b/crates/check/src/declaration.rs @@ -22,7 +22,7 @@ use model::thir::Body; use model::thir::FactKind; use model::thir::Symbol; use source::Span; -use syntax::ast; +use tree::ast; use crate::Checker; use crate::Checking; @@ -39,7 +39,8 @@ const MOST_HOLDERS: usize = 4_096; impl Checker<'_> { /// The type the module's type declaration or alias `definition` declares: - /// a feature's (`declare_type`), or the type an alias names. One with + /// a struct, interface or enum (`declare_written_type`), or the type an + /// alias names. One with /// type parameters, `struct Box`, declares a type in each copy /// (`copy_type`); its own check, with no type for its `T` /// (`own_arguments`), reports what is wrong whatever its types are and @@ -58,16 +59,13 @@ impl Checker<'_> { } return self.resolve_value_type(written.ty); } - let ast::Type::Feature(ty) = tree.types[written.ty] else { - unreachable!("the parser gives a type declaration only a feature's type") - }; if written.type_parameters.is_empty() || self.in_copy() { - return (self.hooks.declare_type)(self, definition, written, ty); + return self.declare_written_type(definition, written); } let module = definition.module.index(); let reported = self.module_checks[module].diagnostics.len(); // Invalid whenever a field is of a type `T` names, which reports nothing. - (self.hooks.declare_type)(self, definition, written, ty); + self.declare_written_type(definition, written); let found = &self.module_checks[module].diagnostics[reported..]; if found.iter().any(Diagnostic::is_error) { return TypeId::INVALID; @@ -78,6 +76,40 @@ impl Checker<'_> { }) } + /// The type the module's type declaration `definition`, written + /// `written`, declares, by the concept its written type belongs to. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] + fn declare_written_type(&mut self, definition: DefId, written: ast::TypeDecl) -> TypeId { + match self.module().ast.types[written.ty] { + ast::Type::Enum { .. } => crate::enums::declare_enum_type(self, written), + ast::Type::Interface { .. } => { + crate::interfaces::declare_interface_type(self, definition) + } + ast::Type::Struct { fields } => { + crate::structs::declare_struct_type(self, fields, definition, written) + } + ast::Type::Name + | ast::Type::Path(_) + | ast::Type::Generic { .. } + | ast::Type::Bracketed { .. } + | ast::Type::Reference { .. } + | ast::Type::Slice { .. } + | ast::Type::Variadic { .. } + | ast::Type::Function(_) + | ast::Type::Owner + | ast::Type::Type + | ast::Type::Array { .. } + | ast::Type::Optional(_) + | ast::Type::Pointer { .. } + | ast::Type::Invalid => { + unreachable!("only `struct`, `iface` and `enum` begin a type declaration") + } + } + } + /// Reports each attribute of the declaration `definition` but an /// `extern` or a `builtin` on a function, the attributes there are; /// `check_function` checks their shape. @@ -135,7 +167,7 @@ impl Checker<'_> { /// The type of a value whose type is written `ty`: a named type is the /// type its declaration declares, so a value's type is complete (an /// alias names a complete type already). - pub fn resolve_value_type(&mut self, ty: Id) -> TypeId { + pub(crate) fn resolve_value_type(&mut self, ty: Id) -> TypeId { let resolved = self.resolve_type(ty); self.value_type(resolved, ty) } @@ -197,7 +229,7 @@ impl Checker<'_> { /// reference, slice or interface reference, as nothing follows a pointer /// to say what they point into. A struct or an array holding one is /// refused only where it is reached (`reached_through_pointer`). - pub fn written_pointer_target(&mut self, target: TypeId, span: Span) -> Option { + pub(crate) fn written_pointer_target(&mut self, target: TypeId, span: Span) -> Option { self.pointer_target(target, span, |types, target| types[target].borrows()) } @@ -238,7 +270,7 @@ impl Checker<'_> { /// `&target`, or `&mut target` when `mutable` (`element_type`); an /// interface reference to an interface. - pub fn reference_type(&mut self, mutable: bool, target: TypeId) -> TypeId { + pub(crate) fn reference_type(&mut self, mutable: bool, target: TypeId) -> TypeId { if self.is_interface(target) { return self.types.intern(Type::InterfaceReference { mutable, @@ -253,7 +285,7 @@ impl Checker<'_> { /// `[length]element`, written at `span` (`element_type`), holding at /// most `MOST_HOLDERS` references and slices. - pub fn array_type(&mut self, element: TypeId, length: u64, span: Span) -> TypeId { + pub(crate) fn array_type(&mut self, element: TypeId, length: u64, span: Span) -> TypeId { let Some(element) = self.element_type(element) else { return TypeId::INVALID; }; @@ -267,7 +299,12 @@ impl Checker<'_> { /// Whether `ty`, written at `span` and holding `holders` references and /// slices, holds more than `MOST_HOLDERS`, after reporting it there. - pub fn reports_too_many_holders(&mut self, ty: TypeId, holders: usize, span: Span) -> bool { + pub(crate) fn reports_too_many_holders( + &mut self, + ty: TypeId, + holders: usize, + span: Span, + ) -> bool { if holders <= MOST_HOLDERS { return false; } @@ -280,7 +317,7 @@ impl Checker<'_> { /// `ty`, made at `span`, or invalid after an error there when its `size` /// is more bytes than the target allows for a value, which no copy of it /// could count. - pub fn fits_target(&mut self, ty: TypeId, size: u64, span: Span) -> TypeId { + pub(crate) fn fits_target(&mut self, ty: TypeId, size: u64, span: Span) -> TypeId { let largest = self.target.largest_object(); if size <= largest { return ty; @@ -294,7 +331,7 @@ impl Checker<'_> { /// `range[element]`, written or made at `span`: invalid when `element` /// is, reported when it is not an integer. - pub fn range_type(&mut self, element: TypeId, span: Span) -> TypeId { + pub(crate) fn range_type(&mut self, element: TypeId, span: Span) -> TypeId { if element == TypeId::INVALID { return element; } @@ -308,7 +345,7 @@ impl Checker<'_> { /// Whether an array may have `length` elements, as its `len` is a /// `usize` (`check_field`); reported at `span` when not. - pub fn length_fits(&mut self, length: &[u64], span: Span) -> bool { + pub(crate) fn length_fits(&mut self, length: &[u64], span: Span) -> bool { let usize = Integer { signed: false, bits: self.target.pointer_bits, @@ -372,7 +409,7 @@ impl Checker<'_> { TypeId::INVALID } Some(symbol) => self.type_named_by(symbol, span), - None if name == semantic_types::RANGE => { + None if name == semantic_types::builtin::RANGE => { let message = format!("`{name}` needs the type of its values: `{name}[T]`"); self.error(diagnostics::INVALID_TYPE, message, span) } @@ -380,7 +417,7 @@ impl Checker<'_> { None => { let symbols = self.visible_symbols(); let types = symbols.filter(|&(_, symbol)| matches!(symbol, Symbol::Type(_))); - let builtin = semantic_types::builtin_names(); + let builtin = semantic_types::builtin::builtin_names(); let meant = scope::nearest(name, builtin, types.map(|(declared, _)| declared)); let message = format!("unknown type `{name}`"); self.report_unknown(diagnostics::UNDEFINED_NAME, span, message, meant); @@ -452,7 +489,8 @@ impl Checker<'_> { } ast::Expr::Index { value, index } if let ast::Expr::Name = tree.exprs[value] - && tree.file.slice(tree.exprs.span(value)) == semantic_types::RANGE => + && tree.file.slice(tree.exprs.span(value)) + == semantic_types::builtin::RANGE => { let element = self.resolve_type_argument(index); let range = self.range_type(element, span); @@ -475,15 +513,30 @@ impl Checker<'_> { /// its declaration is checked; a value's type is `resolve_value_type`. A /// local never names a type /// (`ThirBuilder::declare`), so only top-level names are looked up. - pub fn resolve_type(&mut self, ty: Id) -> TypeId { + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] + pub(crate) fn resolve_type(&mut self, ty: Id) -> TypeId { // Types written in types, `& & ... i32`, are a deep recursion. source::grow_stack(|| { let tree = &self.module().ast; let span = tree.types.span(ty); let what = match tree.types[ty] { - ast::Type::Feature(feature) => { - return (self.hooks.resolve_type)(self, feature, span); + ast::Type::Array { length, element } => { + return crate::arrays::resolve_array_type(self, length, element, span); + } + ast::Type::Enum { .. } => return crate::enums::resolve_enum_type(self, span), + ast::Type::Interface { .. } => { + return crate::interfaces::resolve_interface_type(self, span); } + ast::Type::Optional(_) => { + return crate::optionals::resolve_optional_type(self, span); + } + ast::Type::Pointer { target } => { + return crate::raw_pointers::resolve_pointer_type(self, target, span); + } + ast::Type::Struct { .. } => return crate::structs::resolve_struct_type(self, span), // `self`'s type: the owner of the function being checked, which // has one (`check_function`). An owner that is not a struct // was reported by `scope::collect`. @@ -506,7 +559,9 @@ impl Checker<'_> { arguments: ConstArguments::NONE, }); } - _ => unreachable!("only a type's function and an interface name `self`"), + ast::Decl::Function(_) | ast::Decl::Const { .. } | ast::Decl::Alias(_) => { + unreachable!("only a type's function and an interface name `self`") + } }; let owner = self .scope() @@ -563,7 +618,7 @@ impl Checker<'_> { } ast::Type::Bracketed { name, inner } => { let written = tree.file.slice(name.span); - if written != semantic_types::RANGE { + if written != semantic_types::builtin::RANGE { let message = format!("`{written}` takes no type in brackets"); return self.error(diagnostics::INVALID_TYPE, message, span); } diff --git a/crates/check/src/enums.rs b/crates/check/src/enums.rs new file mode 100644 index 00000000..71bac198 --- /dev/null +++ b/crates/check/src/enums.rs @@ -0,0 +1,84 @@ +//! Enums: the checker's file for the type `enum { A, B: Payload }` and its +//! declaration, variant literals, `is` tests and `match`. Each is refused +//! until enums are checked. + +use crate::builder; +use model::semantic_types; +use model::thir; +use source::Span; +use tree::ast; + +use crate::Checker; + +/// An enum type at `span`, which no check exists for yet. +pub(crate) fn resolve_enum_type(checker: &mut Checker<'_>, span: Span) -> semantic_types::TypeId { + checker.not_supported(span, "enum types") +} + +/// The declaration of an enum, written `written`, which no check exists +/// for yet. +pub(crate) fn declare_enum_type( + checker: &mut Checker<'_>, + written: ast::TypeDecl, +) -> semantic_types::TypeId { + checker.not_supported(written.name.span, "enum declarations") +} + +/// Variant literals, at `span`, which no check exists for yet. +pub(crate) fn check_variant_literal( + builder: &mut builder::ThirBuilder<'_, '_>, + span: Span, +) -> thir::Expr { + builder.checker.not_supported(span, "variant literals"); + thir::Expr::INVALID +} + +/// `is` tests, at `span`, which no check exists for yet. +pub(crate) fn check_case_test( + builder: &mut builder::ThirBuilder<'_, '_>, + span: Span, +) -> thir::Expr { + builder.checker.not_supported(span, "`is` tests"); + thir::Expr::INVALID +} + +/// A `match` at `span`, which no check exists for yet. +pub(crate) fn check_match( + builder: &mut builder::ThirBuilder<'_, '_>, + span: Span, +) -> Option { + builder.checker.not_supported(span, "`match` statements"); + None +} + +#[cfg(test)] +mod tests { + //! Refusal of enums and `match` until they are checked. + + use crate::testing; + + /// Nothing of an enum is checked yet, so each part is refused where it is + /// written. + #[test] + fn refused() { + let (_, reported) = testing::bodies( + "enum E { A, B: i32 } + fn f(e: E) {} + fn g(a: i32) { E::B with a; } + fn h(a: i32) { a is E::A; } + fn i(a: i32) { match a { _ => { } } }", + ); + let found: Vec<&str> = (reported.iter()) + .map(|(_, message, _)| message.as_str()) + .collect(); + assert_eq!( + found, + [ + "enum declarations are not supported yet", + "variant literals are not supported yet", + "`is` tests are not supported yet", + "`match` statements are not supported yet", + ] + ); + } +} diff --git a/crates/kernel/semantic/src/expression.rs b/crates/check/src/expression.rs similarity index 87% rename from crates/kernel/semantic/src/expression.rs rename to crates/check/src/expression.rs index 5125b39e..63a00643 100644 --- a/crates/kernel/semantic/src/expression.rs +++ b/crates/check/src/expression.rs @@ -18,21 +18,25 @@ use model::semantic_types::TypeId; use model::thir::Expr; use model::thir::ExprKind; use source::Span; -use syntax::ast; -use syntax::operators::Precedence; +use tree::ast; +use tree::operators::Precedence; use crate::builder::ThirBuilder; impl ThirBuilder<'_, '_> { /// `expression` (`check_expr`), added to the body. - pub fn add_expr(&mut self, expression: Id, expected: Option) -> Id { + pub(crate) fn add_expr( + &mut self, + expression: Id, + expected: Option, + ) -> Id { let checked = self.check_expr(expression, expected); self.body .add(checked, self.checker.module().ast.exprs.span(expression)) } /// `expression` (`check_required`), added to the body. - pub fn add_required(&mut self, expression: Id, ty: TypeId) -> Id { + pub(crate) fn add_required(&mut self, expression: Id, ty: TypeId) -> Id { let checked = self.check_required(expression, ty); self.body .add(checked, self.checker.module().ast.exprs.span(expression)) @@ -57,7 +61,7 @@ impl ThirBuilder<'_, '_> { let span = self.checker.module().ast.exprs.span(expression); let found = expr.ty; let conversion = self.checker.types.conversion(found, to); - if conversion != Conversion::NeedsCast + if !matches!(conversion, Conversion::NeedsCast(_)) && let Some(converted) = self.convert(expr, span, to, conversion) { return Ok(converted); @@ -74,7 +78,7 @@ impl ThirBuilder<'_, '_> { |ty| { matches!( types.conversion(ty, to), - Conversion::Same | Conversion::Implicit + Conversion::Same | Conversion::Implicit(_) ) }, )) @@ -92,7 +96,7 @@ impl ThirBuilder<'_, '_> { to: TypeId, ) -> Diagnostic { let types = &self.checker.types; - if types.conversion(found, to) != Conversion::NeedsCast { + if !matches!(types.conversion(found, to), Conversion::NeedsCast(_)) { return mismatch; } // The type itself, as an alias's text is not a type to write. @@ -107,7 +111,7 @@ impl ThirBuilder<'_, '_> { /// `conversion` (`Types::conversion`): given the type, converted (folded /// when it is a constant), lent again as a `&`, or made an interface. /// `None` when it never converts. - pub fn convert( + pub(crate) fn convert( &mut self, expr: Expr, span: Span, @@ -116,10 +120,11 @@ impl ThirBuilder<'_, '_> { ) -> Option { let kind = match conversion { Conversion::Same => expr.kind, - Conversion::Implicit | Conversion::NeedsCast => match expr.kind { + Conversion::Implicit(cast) | Conversion::NeedsCast(cast) => match expr.kind { ExprKind::Constant(constant) => { let types = &self.checker.types; ExprKind::Constant(crate::fold::conversions::convert( + cast, &types[expr.ty], &types[to], &constant, @@ -213,15 +218,42 @@ impl ThirBuilder<'_, '_> { /// operation leaves no nodes for its operands. `expected` is the type a /// number literal without a suffix takes, if any; the value may have /// another type. - pub fn check_expr(&mut self, expression: Id, expected: Option) -> Expr { + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] + pub(crate) fn check_expr( + &mut self, + expression: Id, + expected: Option, + ) -> Expr { // A long chain of operators, calls or parentheses is a deep recursion. source::grow_stack(|| { let tree = &self.checker.module().ast; let span = tree.exprs.span(expression); match tree.exprs[expression] { - ast::Expr::Feature(feature) => { - (self.checker.hooks.check_expr)(self, feature, span, expected) + ast::Expr::ArrayLiteral { ty, entries } => { + crate::arrays::check_array_literal(self, ty, entries, span) + } + ast::Expr::CaseTest { .. } => crate::enums::check_case_test(self, span), + ast::Expr::Char { .. } => crate::chars::check_char_literal(self, span), + ast::Expr::OrElse { .. } => crate::optionals::check_or_else(self, span), + ast::Expr::Pipe { value, target } => { + crate::pipes::check_pipe(self, value, target, span) + } + ast::Expr::Print { newline, values } => { + crate::printing::check_print(self, newline, values, span) + } + ast::Expr::Range(written) => { + crate::ranges::check_range(self, written, span, expected) + } + ast::Expr::RawAddress(place) => { + crate::raw_pointers::check_raw_address(self, place, span) + } + ast::Expr::StructLiteral { ty, fields } => { + crate::structs::check_struct_literal(self, ty, fields, span, expected) } + ast::Expr::VariantLiteral { .. } => crate::enums::check_variant_literal(self, span), ast::Expr::Name => { let symbol = self.resolve(span); self.check_symbol_value(symbol, span) @@ -240,8 +272,9 @@ impl ThirBuilder<'_, '_> { .label(&tree.file, span, ""); // `*p` of a variable `p` reads as C's dereference, which // is written `p.*`. - if let ast::Type::Feature(written) = tree.types[ty] - && let Some(target) = written.pointee() + if let ast::Type::Pointer { + target: Some(target), + } = tree.types[ty] && let ast::Type::Name = tree.types[target] && let name = tree.file.slice(tree.types.span(target)) && self.innermost.contains_key(name) diff --git a/crates/kernel/semantic/src/expression/borrows.rs b/crates/check/src/expression/borrows.rs similarity index 96% rename from crates/kernel/semantic/src/expression/borrows.rs rename to crates/check/src/expression/borrows.rs index 2a4c3f19..a9e1b402 100644 --- a/crates/kernel/semantic/src/expression/borrows.rs +++ b/crates/check/src/expression/borrows.rs @@ -59,7 +59,7 @@ impl ThirBuilder<'_, '_> { /// `@place`, written at `span`: the address of the checked place /// `place`, which must be a place that can be written and not in a /// temporary's own storage. - pub fn check_address(&mut self, place: Id, span: Span) -> Expr { + pub(crate) fn check_address(&mut self, place: Id, span: Span) -> Expr { let target = self.body.exprs[place].ty; let Some(target) = self.checker.reached_through_pointer(target, span) else { return Expr::INVALID; @@ -93,7 +93,7 @@ impl ThirBuilder<'_, '_> { /// a value it starts from that is not in a variable (a call's result, a /// literal) in a temporary: only a place can be lent, indexed or gone /// through. - pub fn make_place(&mut self, place: Id) -> (Id, Option>) { + pub(crate) fn make_place(&mut self, place: Id) -> (Id, Option>) { let (start, decider) = self.place_root(place); if let Some(variable) = self.start_variable(start) { return (variable, decider); @@ -117,7 +117,7 @@ impl ThirBuilder<'_, '_> { /// The variable that `start`, where a place starts (`place_root`), is /// in: its own or a temporary's; `None` for a value in neither. - pub fn start_variable(&self, start: Id) -> Option> { + pub(crate) fn start_variable(&self, start: Id) -> Option> { match self.body.exprs[start].kind { ExprKind::Variable(variable) | ExprKind::Temporary { variable, .. } => Some(variable), _ => None, @@ -129,7 +129,7 @@ impl ThirBuilder<'_, '_> { /// written: up to the nearest raw pointer, a shared reference or slice if /// any, else the nearest reference, slice or that raw pointer. A slice's /// element is behind the slice, as a reference's target is behind it. - pub fn place_root(&self, place: Id) -> (Id, Option>) { + pub(crate) fn place_root(&self, place: Id) -> (Id, Option>) { let pointer = |reference: Id| &self.checker.types[self.body.exprs[reference].ty]; let shared = |reference| pointer(reference).borrows() == Some(false); let mut root = place; @@ -271,7 +271,7 @@ impl ThirBuilder<'_, '_> { /// `&mut []` itself is not moved. A written `&place` or `&a[i..j]`, /// already checked, borrows its place itself as `to`; a slice lends its /// own elements. - pub fn reborrow(&mut self, reference: Expr, span: Span, to: TypeId) -> Expr { + pub(crate) fn reborrow(&mut self, reference: Expr, span: Span, to: TypeId) -> Expr { let place = match (&reference.kind, &self.checker.types[reference.ty]) { (ExprKind::Borrow(_) | ExprKind::Slice { .. }, _) => { return Expr { diff --git a/crates/kernel/semantic/src/expression/literals.rs b/crates/check/src/expression/literals.rs similarity index 98% rename from crates/kernel/semantic/src/expression/literals.rs rename to crates/check/src/expression/literals.rs index 08c9fdda..7517f20a 100644 --- a/crates/kernel/semantic/src/expression/literals.rs +++ b/crates/check/src/expression/literals.rs @@ -14,8 +14,8 @@ use model::thir::Expr; use model::thir::ExprKind; use model::thir::FactKind; use source::Span; -use syntax::ast; -use syntax::operators::Precedence; +use tree::ast; +use tree::operators::Precedence; use crate::builder::ThirBuilder; use crate::expression::unsuffixed_literal; @@ -65,7 +65,7 @@ impl ThirBuilder<'_, '_> { /// program runs, with why. A value that mismatches is reported, with how /// to spread it when it holds `element`s (`help_spread`, given `alone_in`). /// Without an element type, each entry is checked for its own errors. - pub fn check_entries( + pub(crate) fn check_entries( &mut self, entries: impl Iterator>, element: TypeId, @@ -250,8 +250,8 @@ impl ThirBuilder<'_, '_> { /// entries give `known` values now and more when the program runs if a /// spread, first at `later` with why `[_]` cannot count it, is counted /// then; `None` after reporting that they do not fit it - /// (`arrays::check::check_literal`). - pub fn array_literal_type( + /// (`arrays::check_array_literal`). + pub(crate) fn array_literal_type( &mut self, written: Span, element: TypeId, @@ -407,7 +407,7 @@ impl ThirBuilder<'_, '_> { /// A range's or slice's ends `start` and `end`, of one type: a literal /// without a suffix takes the other end's type, or `hint` when both are /// such literals. - pub fn check_range_ends( + pub(crate) fn check_range_ends( &mut self, start: Id, end: Id, diff --git a/crates/kernel/semantic/src/expression/names.rs b/crates/check/src/expression/names.rs similarity index 100% rename from crates/kernel/semantic/src/expression/names.rs rename to crates/check/src/expression/names.rs diff --git a/crates/kernel/semantic/src/expression/operators.rs b/crates/check/src/expression/operators.rs similarity index 99% rename from crates/kernel/semantic/src/expression/operators.rs rename to crates/check/src/expression/operators.rs index 17884b70..095175f6 100644 --- a/crates/kernel/semantic/src/expression/operators.rs +++ b/crates/check/src/expression/operators.rs @@ -12,9 +12,9 @@ use model::thir::Expr; use model::thir::ExprKind; use model::thir::FactKind; use source::Span; -use syntax::ast; -use syntax::operators::BinaryOp; -use syntax::operators::UnaryOp; +use tree::ast; +use tree::operators::BinaryOp; +use tree::operators::UnaryOp; use crate::builder::ThirBuilder; use crate::expression::unsuffixed_literal; diff --git a/crates/kernel/semantic/src/expression/places.rs b/crates/check/src/expression/places.rs similarity index 98% rename from crates/kernel/semantic/src/expression/places.rs rename to crates/check/src/expression/places.rs index d21eef0d..41245346 100644 --- a/crates/kernel/semantic/src/expression/places.rs +++ b/crates/check/src/expression/places.rs @@ -12,9 +12,9 @@ use model::semantic_types::TypeId; use model::thir::Expr; use model::thir::ExprKind; use source::Span; -use syntax::ast; -use syntax::ast::Ident; -use syntax::ast::WrittenRange; +use tree::ast; +use tree::ast::Ident; +use tree::ast::WrittenRange; use crate::builder::ThirBuilder; @@ -366,7 +366,7 @@ impl ThirBuilder<'_, '_> { /// `value`, or what it refers to when it is a reference or a typed raw /// pointer, added at `span`: a field or an element is reached through /// the pointer, and a reference lent again lends what it refers to. - pub fn through_pointer(&mut self, value: Id, span: Span) -> Id { + pub(crate) fn through_pointer(&mut self, value: Id, span: Span) -> Id { let Some(target) = self.checker.types[self.body.exprs[value].ty].pointee() else { return value; }; @@ -400,7 +400,7 @@ impl ThirBuilder<'_, '_> { /// The index of the field `name` of the type `ty`, in declaration order, /// and its type; `None` after reporting that the type has no such field, /// with its nearest field name. - pub fn field_index(&mut self, ty: TypeId, name: Ident) -> Option<(usize, TypeId)> { + pub(crate) fn field_index(&mut self, ty: TypeId, name: Ident) -> Option<(usize, TypeId)> { let Some(Members { definition, fields, .. }) = self.checker.types[ty].members() diff --git a/crates/kernel/semantic/src/fold.rs b/crates/check/src/fold.rs similarity index 100% rename from crates/kernel/semantic/src/fold.rs rename to crates/check/src/fold.rs diff --git a/crates/kernel/semantic/src/fold/conversions.rs b/crates/check/src/fold/conversions.rs similarity index 66% rename from crates/kernel/semantic/src/fold/conversions.rs rename to crates/check/src/fold/conversions.rs index a2218075..ed6dda62 100644 --- a/crates/kernel/semantic/src/fold/conversions.rs +++ b/crates/check/src/fold/conversions.rs @@ -3,20 +3,19 @@ use std::borrow::Cow; use model::constant::Value; -use model::mir::Class; +use model::mir; use model::semantic_types::Type; use eval::operations; use eval::operations::RegisterValue; -use lower::arithmetic::cast_conversion; /// `value` of the type `from` as a value of the type `to`, which it converts -/// to (`Types::conversion`), as LLVM converts it: a wider integer keeps the -/// value (a signed one its sign), a narrower one keeps the low bits, `true` -/// is 1, a float rounds to the nearest value of its new type (ties to even), -/// and a float becomes an integer cut toward zero, saturated at the ends of -/// the integer's range, and 0 when NaN (as Rust's `as`). -pub fn convert(from: &Type, to: &Type, value: &Value) -> Value { +/// to by `cast` (`Types::conversion`), as LLVM converts it: a wider integer +/// keeps the value (a signed one its sign), a narrower one keeps the low +/// bits, `true` is 1, a float rounds to the nearest value of its new type +/// (ties to even), and a float becomes an integer cut toward zero, +/// saturated at the ends of the integer's range, and 0 when NaN. +pub fn convert(cast: mir::Cast, from: &Type, to: &Type, value: &Value) -> Value { let register = match value { Value::Integer(limbs) => { let Type::Integer(from) = from else { @@ -36,14 +35,7 @@ pub fn convert(from: &Type, to: &Type, value: &Value) -> Value { Value::Bytes(_) => unreachable!("check converts no string"), }; let ((from_class, from_bits), (to_class, to_bits)) = (number(from), number(to)); - let converted = operations::convert( - cast_conversion(from, to), - from_class, - from_bits, - to_class, - to_bits, - ®ister, - ); + let converted = operations::convert(cast, from_class, from_bits, to_class, to_bits, ®ister); match to { Type::Float(_) => { Value::Float(operations::float_value(to_class, converted.narrow()).to_bits()) @@ -54,11 +46,11 @@ pub fn convert(from: &Type, to: &Type, value: &Value) -> Value { /// The class and width of a value of the type `ty`, a number or a `bool`; /// an integer at its own width. -fn number(ty: &Type) -> (Class, u32) { +fn number(ty: &Type) -> (mir::Class, u32) { match *ty { - Type::Integer(integer) => (Class::integer(integer.bits), integer.bits), + Type::Integer(integer) => (mir::Class::integer(integer.bits), integer.bits), Type::Float(float) => (float.class(), float.class().bits()), - Type::Bool => (Class::I8, 1), + Type::Bool => (mir::Class::I8, 1), _ => unreachable!("check converts {ty:?} only to and from a raw pointer"), } } diff --git a/crates/kernel/semantic/src/fold/operators.rs b/crates/check/src/fold/operators.rs similarity index 98% rename from crates/kernel/semantic/src/fold/operators.rs rename to crates/check/src/fold/operators.rs index b2e4213f..ecf21bb8 100644 --- a/crates/kernel/semantic/src/fold/operators.rs +++ b/crates/check/src/fold/operators.rs @@ -20,8 +20,8 @@ use model::mir::Class; use model::mir::IntegerOp; use model::semantic_types::Integer; use model::semantic_types::Type; -use syntax::operators::BinaryOp; -use syntax::operators::UnaryOp; +use tree::operators::BinaryOp; +use tree::operators::UnaryOp; use eval::operations; use eval::operations::RegisterValue; @@ -163,7 +163,7 @@ fn shift_count(shifted: Integer, count_type: Integer, count: &Limbs) -> Limbs { /// with the right operand `right`, of the type `right_type`: a division by /// zero or a shift count out of range. Both depend on the right operand /// only, so `op` is tried on a zero left one. -pub fn known_trap( +pub(crate) fn known_trap( op: BinaryOp, left_type: &Type, right_type: &Type, diff --git a/crates/kernel/semantic/src/fold/tests.rs b/crates/check/src/fold/tests.rs similarity index 93% rename from crates/kernel/semantic/src/fold/tests.rs rename to crates/check/src/fold/tests.rs index 99834b17..06ea0501 100644 --- a/crates/kernel/semantic/src/fold/tests.rs +++ b/crates/check/src/fold/tests.rs @@ -1,13 +1,14 @@ use bigint::Limbs; use model::constant::Value; +use model::mir; use model::semantic_types::Float; use model::semantic_types::Integer; use model::semantic_types::Type; use runtime_abi::messages::DIVISION_BY_ZERO; use runtime_abi::messages::shift_count_message; -use syntax::operators::BinaryOp; -use syntax::operators::UnaryOp; +use tree::operators::BinaryOp; +use tree::operators::UnaryOp; use super::conversions::convert; use super::operators::binary; @@ -131,12 +132,21 @@ fn shift_counts_have_their_own_type() { #[test] fn widening_keeps_the_value() { let (i8, u8, i16, i256) = (int(true, 8), int(false, 8), int(true, 16), int(true, 256)); - assert_eq!(convert(&i8, &i16, &value(&i8, -1)), value(&i16, -1)); - assert_eq!(convert(&u8, &i16, &value(&u8, 255)), value(&i16, 255)); - assert_eq!(convert(&i8, &i256, &value(&i8, -128)), value(&i256, -128)); + assert_eq!( + convert(mir::Cast::SignExtend, &i8, &i16, &value(&i8, -1)), + value(&i16, -1) + ); + assert_eq!( + convert(mir::Cast::ZeroExtend, &u8, &i16, &value(&u8, 255)), + value(&i16, 255) + ); + assert_eq!( + convert(mir::Cast::SignExtend, &i8, &i256, &value(&i8, -128)), + value(&i256, -128) + ); let (f32, f64) = (Type::Float(Float::F32), Type::Float(Float::F64)); assert_eq!( - convert(&f32, &f64, &float(&f32, 0.1)), + convert(mir::Cast::FloatWiden, &f32, &f64, &float(&f32, 0.1)), float(&f64, f64::from(0.1f32)) ); } diff --git a/crates/kernel/semantic/src/functions.rs b/crates/check/src/functions.rs similarity index 98% rename from crates/kernel/semantic/src/functions.rs rename to crates/check/src/functions.rs index 112ee605..e177bf27 100644 --- a/crates/kernel/semantic/src/functions.rs +++ b/crates/check/src/functions.rs @@ -11,7 +11,7 @@ use diagnostics::Diagnostic; use model::DefId; use model::semantic_types; use source::Span; -use syntax::ast; +use tree::ast; use crate::Checker; use crate::generics; @@ -21,7 +21,7 @@ use crate::scope; /// body, C, the compiler or each type that implements its interface. Each /// rule reads it (`Checker::signature_type`, and `Checker::check_function` /// for the body). -pub struct FunctionKind { +pub(crate) struct FunctionKind { /// How a message names such a function. pub name: &'static str, /// Who gives its code, as a message says it. @@ -37,7 +37,7 @@ pub struct FunctionKind { } impl FunctionKind { - pub const BODY: FunctionKind = FunctionKind { + pub(crate) const BODY: FunctionKind = FunctionKind { name: "a function", coded_by: "its body", has_body: true, @@ -46,7 +46,7 @@ impl FunctionKind { takes_self_first: false, c_types: false, }; - pub const C: FunctionKind = FunctionKind { + pub(crate) const C: FunctionKind = FunctionKind { name: "an `extern` function", coded_by: "C", has_body: false, @@ -55,7 +55,7 @@ impl FunctionKind { takes_self_first: false, c_types: true, }; - pub const COMPILER: FunctionKind = FunctionKind { + pub(crate) const COMPILER: FunctionKind = FunctionKind { name: "a `#[builtin]` function", coded_by: "the compiler", has_body: false, @@ -64,7 +64,7 @@ impl FunctionKind { takes_self_first: false, c_types: false, }; - pub const INTERFACE_METHOD: FunctionKind = FunctionKind { + pub(crate) const INTERFACE_METHOD: FunctionKind = FunctionKind { name: "an interface method", coded_by: "each type that implements it", has_body: false, @@ -199,7 +199,7 @@ impl Checker<'_> { /// type is reported is invalid inside it. A `const T: type` parameter is /// not among its parameters: each call gives it a type, which makes its /// own copy (`copy_type`). - pub fn signature_type( + pub(crate) fn signature_type( &mut self, name: ast::Ident, signature: ast::Signature, @@ -496,7 +496,7 @@ impl Checker<'_> { mod tests { use model::DefId; use model::semantic_types; - use syntax::ast; + use tree::ast; use crate::testing; diff --git a/crates/kernel/semantic/src/functions/bodies.rs b/crates/check/src/functions/bodies.rs similarity index 100% rename from crates/kernel/semantic/src/functions/bodies.rs rename to crates/check/src/functions/bodies.rs diff --git a/crates/kernel/semantic/src/functions/builtin.rs b/crates/check/src/functions/builtin.rs similarity index 100% rename from crates/kernel/semantic/src/functions/builtin.rs rename to crates/check/src/functions/builtin.rs diff --git a/crates/kernel/semantic/src/functions/calls.rs b/crates/check/src/functions/calls.rs similarity index 99% rename from crates/kernel/semantic/src/functions/calls.rs rename to crates/check/src/functions/calls.rs index 48cfa203..6e8ba9cf 100644 --- a/crates/kernel/semantic/src/functions/calls.rs +++ b/crates/check/src/functions/calls.rs @@ -13,7 +13,7 @@ use model::constant; use model::semantic_types; use model::thir; use source::Span; -use syntax::ast; +use tree::ast; use crate::builder; use crate::generics; @@ -28,7 +28,7 @@ impl builder::ThirBuilder<'_, '_> { /// others (`check_variadic`). A function with `const` parameters is /// called as its copy for what is written in their places /// (`copy_called`). - pub fn check_call( + pub(crate) fn check_call( &mut self, callee: Id, type_arguments: List, diff --git a/crates/kernel/semantic/src/generics.rs b/crates/check/src/generics.rs similarity index 96% rename from crates/kernel/semantic/src/generics.rs rename to crates/check/src/generics.rs index 8d484603..d05c1b26 100644 --- a/crates/kernel/semantic/src/generics.rs +++ b/crates/check/src/generics.rs @@ -14,7 +14,7 @@ use model::DefId; use model::semantic_types; use model::thir; use source::Span; -use syntax::ast; +use tree::ast; use crate::Checker; use crate::builder; @@ -274,11 +274,15 @@ fn written_inside(tree: &ast::Tree, ty: Id) -> Option> | ast::Type::Variadic { element: written, .. } => Some(written), - // shortcut: of a feature's types, only a pointer's target and an - // array's element are looked into; a struct's fields and an - // interface's methods are taken to name no type parameter, as a - // written one is not supported yet. - ast::Type::Feature(ty) => ty.pointee().or_else(|| ty.element()), + ast::Type::Pointer { target } => target, + ast::Type::Array { element, .. } => Some(element), + // shortcut: a struct's fields, an interface's methods and an enum's + // variants are taken to name no type parameter, as a written one is + // not supported yet; an optional is refused when it is checked. + ast::Type::Struct { .. } + | ast::Type::Interface { .. } + | ast::Type::Enum { .. } + | ast::Type::Optional(_) => None, ast::Type::Name | ast::Type::Path(_) | ast::Type::Generic { .. } diff --git a/crates/kernel/semantic/src/generics/constraints.rs b/crates/check/src/generics/constraints.rs similarity index 99% rename from crates/kernel/semantic/src/generics/constraints.rs rename to crates/check/src/generics/constraints.rs index b803e4a0..f62eb6c9 100644 --- a/crates/kernel/semantic/src/generics/constraints.rs +++ b/crates/check/src/generics/constraints.rs @@ -10,7 +10,7 @@ use model::ConstArguments; use model::constant; use model::semantic_types; use model::thir; -use syntax::ast; +use tree::ast; use crate::Checker; use crate::builder; diff --git a/crates/kernel/semantic/src/generics/copies.rs b/crates/check/src/generics/copies.rs similarity index 99% rename from crates/kernel/semantic/src/generics/copies.rs rename to crates/check/src/generics/copies.rs index b95ff441..a64777b8 100644 --- a/crates/kernel/semantic/src/generics/copies.rs +++ b/crates/check/src/generics/copies.rs @@ -16,7 +16,7 @@ use model::ModuleId; use model::semantic_types; use model::thir; use source::Span; -use syntax::ast; +use tree::ast; use crate::COPY_DEPTH_LIMIT; use crate::Checker; diff --git a/crates/check/src/interfaces.rs b/crates/check/src/interfaces.rs new file mode 100644 index 00000000..b3699776 --- /dev/null +++ b/crates/check/src/interfaces.rs @@ -0,0 +1,76 @@ +//! Interfaces: checking `iface { fn name(&self) -> Result, ... }` +//! declarations. The checker gives a `Type::Interface`, so the phases after +//! it know nothing of this file. Interface references, owned interfaces and +//! the conversion of a struct to an interface read that checked type +//! wherever they are checked. + +use crate::functions; +use crate::scope; +use model::DefId; +use model::semantic_types; +use source::Span; +use tree::ast; + +use crate::Checker; + +/// The type an interface type written at `span` names: none yet, as only a +/// declared interface is checked. +pub(crate) fn resolve_interface_type( + checker: &mut Checker<'_>, + span: Span, +) -> semantic_types::TypeId { + checker.not_supported(span, "interface types") +} + +/// The type the module's interface declaration `definition` declares: +/// each method's function type, whose `self` is a reference to the +/// interface (`Type::InterfaceReference`), or the interface taken whole. +/// Invalid when a method has an error or is declared twice, as a struct +/// is when a field has an error. +pub(crate) fn declare_interface_type( + checker: &mut Checker<'_>, + definition: DefId, +) -> semantic_types::TypeId { + let modules = checker.modules; + let tree = &modules[definition.module.index()].ast; + let declared: Vec<&ast::Function> = model::program::interface_methods(modules, definition) + .expect("an interface declaration has methods") + .collect(); + let mut methods = Vec::with_capacity(declared.len()); + for (index, method) in declared.iter().enumerate() { + let text = method.name.text(&tree.file); + // An interface has few methods, so the ones before are searched. + if let Some(first) = declared[..index] + .iter() + .find(|first| first.name.text(&tree.file) == text) + { + let diagnostic = scope::report_redeclared( + &tree.file, + text, + "interface", + method.name.span, + first.name.span, + ); + checker.report(diagnostic); + methods.push(semantic_types::TypeId::INVALID); + continue; + } + let kind = &functions::FunctionKind::INTERFACE_METHOD; + methods.push(checker.signature_type(method.name, method.signature, true, kind)); + } + let invalid = |ty: semantic_types::TypeId| match &checker.types[ty] { + semantic_types::Type::Function { + parameters, result, .. + } => { + parameters.contains(&semantic_types::TypeId::INVALID) + || *result == semantic_types::TypeId::INVALID + } + _ => true, + }; + if methods.iter().any(|&method| invalid(method)) { + return semantic_types::TypeId::INVALID; + } + let named = checker.declared_name(definition); + checker.types.define_interface(named, methods.into()); + named +} diff --git a/crates/kernel/semantic/src/lib.rs b/crates/check/src/lib.rs similarity index 93% rename from crates/kernel/semantic/src/lib.rs rename to crates/check/src/lib.rs index b3ded92e..755ab0ad 100644 --- a/crates/kernel/semantic/src/lib.rs +++ b/crates/check/src/lib.rs @@ -2,16 +2,28 @@ //! the value of each constant, built into THIR in one walk per body //! (docs/ir-design.md). It starts with each module's scope. -pub mod builder; +mod builder; mod conformance; -pub mod declaration; +mod declaration; mod expression; pub mod fold; -pub mod functions; +mod functions; pub mod generics; mod locals; pub mod scope; mod statement; + +// One file per concept, named as the parser's file that reads it. +mod arrays; +mod chars; +mod enums; +mod interfaces; +mod optionals; +mod pipes; +mod printing; +mod ranges; +mod raw_pointers; +mod structs; /// Why a call of `callee` with `given` arguments is wrong, when it takes /// `fixed` of them, or at least that many when `variadic`. pub(crate) fn argument_count_message( @@ -36,7 +48,6 @@ use std::cell::RefCell; use std::sync::Arc; use arena::Id; -use builder::ThirBuilder; use diagnostics::Code; use diagnostics::Diagnostic; use diagnostics::fix::Fix; @@ -53,45 +64,13 @@ use model::semantic_types::ImplementationId; use model::semantic_types::Type; use model::semantic_types::TypeId; use model::semantic_types::Types; -use model::thir; use model::thir::Fact; use model::thir::FactKind; use model::thir::Symbol; use rustc_hash::FxHashMap; use scope::Scope; use source::Span; -use syntax::ast; - -/// How the checker checks the nodes of the features, which the `features` -/// crate gives: one function per kind of node, each a `match` that hands -/// the node to its feature (docs/structure-mapping.md, step 7). -pub struct CheckHooks { - /// The feature expression `expr`, written at `span`, where a value of - /// the type `expected` is wanted, if one is. - pub check_expr: fn( - builder: &mut ThirBuilder<'_, '_>, - expr: ast::FeatureExpr, - span: Span, - expected: Option, - ) -> thir::Expr, - /// The feature statement `stmt`, written at `span`; `None` when it - /// leaves no statement, after an error. - pub check_stmt: fn( - builder: &mut ThirBuilder<'_, '_>, - stmt: ast::FeatureStmt, - span: Span, - ) -> Option, - /// The type the feature type `ty`, written at `span`, names. - pub resolve_type: fn(checker: &mut Checker<'_>, ty: ast::FeatureType, span: Span) -> TypeId, - /// The type the module's type declaration `definition`, written - /// `written`, declares with the feature type `ty`. - pub declare_type: fn( - checker: &mut Checker<'_>, - definition: DefId, - written: ast::TypeDecl, - ty: ast::FeatureType, - ) -> TypeId, -} +use tree::ast; /// Checks a program's declarations. Each module-scope declaration (`DefId`) /// is checked once, the first time anything asks for it, and its result is @@ -108,8 +87,6 @@ pub struct Checker<'p> { /// The machine the program is for: the width of `isize` and `usize` is /// its `pointer_bits`, and a value may take its `largest_object` bytes. pub target: &'static Machine, - /// How the features' nodes are checked. - hooks: &'static CheckHooks, internals: CheckerInternals, } @@ -237,7 +214,6 @@ impl<'p> Checker<'p> { modules: &'p [model::program::Module], target: &'static Machine, record_facts: bool, - hooks: &'static CheckHooks, ) -> Checker<'p> { let module_checks = (0..modules.len()) .map(|index| { @@ -261,7 +237,6 @@ impl<'p> Checker<'p> { types: Types::new(target.pointer_bits), debug_types: ProgramDebugTypes::default(), target, - hooks, internals: CheckerInternals { known_implementations: FxHashMap::default(), records_editor_facts: record_facts, @@ -289,7 +264,7 @@ impl<'p> Checker<'p> { /// The name the type declaration `definition`, being checked, gives its /// type: with what its copy is given, for a type with type parameters /// (`copy_type`). - pub fn declared_name(&mut self, definition: DefId) -> TypeId { + pub(crate) fn declared_name(&mut self, definition: DefId) -> TypeId { let checking = (self.internals.declarations_being_checked.last()) .expect("a declaration is being checked"); debug_assert_eq!(checking.definition, definition); @@ -304,7 +279,7 @@ impl<'p> Checker<'p> { /// for, named at `used_at`. A type declaration makes its type /// (`Type::Named`, a struct's once checked), so naming it checks nothing; /// an alias names its declared type (`Type::Alias`). - pub fn named_type(&mut self, definition: DefId, used_at: Span) -> TypeId { + pub(crate) fn named_type(&mut self, definition: DefId, used_at: Span) -> TypeId { if let ast::Decl::Type(_) = model::program::declaration(self.modules, definition) { return self.types.intern(Type::Named { definition, @@ -406,13 +381,13 @@ impl<'p> Checker<'p> { } /// The type `ty` as a message names it (`Types::text`). - pub fn type_text(&self, ty: TypeId) -> String { + pub(crate) fn type_text(&self, ty: TypeId) -> String { model::program::type_text(self.modules, &self.types, ty) } /// Both types as a message names them, with each one's module when two /// different declarations in them read the same: `a::Point`, `[1]b::Point`. - pub fn type_texts(&self, first: TypeId, second: TypeId) -> (String, String) { + pub(crate) fn type_texts(&self, first: TypeId, second: TypeId) -> (String, String) { let name = |definition: DefId| model::program::declared_text(self.modules, definition); // `Types::text` needs a closure it can copy, so this one cannot own the list. let written = RefCell::new(Vec::new()); @@ -518,24 +493,24 @@ impl<'p> Checker<'p> { } /// The module being checked. - pub fn module(&self) -> &'p model::program::Module { + pub(crate) fn module(&self) -> &'p model::program::Module { &self.modules[self.current_module().index()] } /// The names the module being checked declares and imports. - pub fn scope(&self) -> &Scope<'p> { + pub(crate) fn scope(&self) -> &Scope<'p> { &self.module_checks[self.current_module().index()].scope } /// Adds `diagnostic` to what the module being checked reported. - pub fn report(&mut self, diagnostic: Diagnostic) { + pub(crate) fn report(&mut self, diagnostic: Diagnostic) { let module = self.current_module().index(); self.module_checks[module].diagnostics.push(diagnostic); } /// Reports the error `message` at `span` of the module, and gives the type /// of an error already reported, so nothing more is reported about it. - pub fn error(&mut self, code: Code, message: impl Into, span: Span) -> TypeId { + pub(crate) fn error(&mut self, code: Code, message: impl Into, span: Span) -> TypeId { let diagnostic = Diagnostic::new(code, message).label(&self.module().ast.file, span, ""); self.report(diagnostic); TypeId::INVALID @@ -774,7 +749,7 @@ impl<'p> Checker<'p> { } /// The prelude's scope; `None` while checking the prelude itself. - pub fn prelude(&self) -> Option<&Scope<'p>> { + pub(crate) fn prelude(&self) -> Option<&Scope<'p>> { Some(&self.module_checks[self.scope().parent?.index()].scope) } @@ -803,7 +778,7 @@ impl<'p> Checker<'p> { /// Reports syntax the checker does not handle yet, such as `what` = /// "reference types". - pub fn not_supported(&mut self, span: Span, what: &str) -> TypeId { + pub(crate) fn not_supported(&mut self, span: Span, what: &str) -> TypeId { let message = format!("{what} are not supported yet"); self.error(diagnostics::NOT_SUPPORTED_YET, message, span) } diff --git a/crates/kernel/semantic/src/locals.rs b/crates/check/src/locals.rs similarity index 98% rename from crates/kernel/semantic/src/locals.rs rename to crates/check/src/locals.rs index 9aff204c..1bd65a5a 100644 --- a/crates/kernel/semantic/src/locals.rs +++ b/crates/check/src/locals.rs @@ -7,7 +7,7 @@ use model::layout; use model::semantic_types; use model::thir; use source::Span; -use syntax::ast; +use tree::ast; use crate::builder; use crate::functions; @@ -153,7 +153,7 @@ impl builder::ThirBuilder<'_, '_> { let types = &self.checker.types; let message = if unknown.is_some() { "the value of a constant must be known at compile time" - } else if layout::in_memory(types, checked.ty) + } else if layout::held(types, checked.ty) == layout::Held::Memory || types[checked.ty].borrows() == Some(true) || matches!(types[checked.ty], semantic_types::Type::RawPointer { .. }) { diff --git a/crates/check/src/optionals.rs b/crates/check/src/optionals.rs new file mode 100644 index 00000000..5ae80fb5 --- /dev/null +++ b/crates/check/src/optionals.rs @@ -0,0 +1,45 @@ +//! Optional types and `orelse` in the checker. Both are refused until +//! optional values exist. + +use crate::Checker; +use crate::builder; +use model::semantic_types; +use model::thir; +use source::Span; + +/// `?T` at `span`, which no check exists for yet. +pub(crate) fn resolve_optional_type( + checker: &mut Checker<'_>, + span: Span, +) -> semantic_types::TypeId { + checker.not_supported(span, "optional types") +} + +/// `value orelse fallback` at `span`, which no check exists for yet. +pub(crate) fn check_or_else(builder: &mut builder::ThirBuilder<'_, '_>, span: Span) -> thir::Expr { + builder.checker.not_supported(span, "`orelse` fallbacks"); + thir::Expr::INVALID +} + +#[cfg(test)] +mod tests { + //! Refusing optional types and `orelse` in the checker. + + use crate::testing; + + /// Neither is checked yet, so each is refused where it is written. + #[test] + fn refused() { + let (_, reported) = testing::bodies("fn f(a: ?i32) {}\nfn g(b: i32) { b orelse 1; }"); + let found: Vec<(&str, &str)> = (reported.iter()) + .map(|(_, message, text)| (message.as_str(), text.as_str())) + .collect(); + assert_eq!( + found, + [ + ("optional types are not supported yet", "?i32"), + ("`orelse` fallbacks are not supported yet", "b orelse 1"), + ] + ); + } +} diff --git a/crates/check/src/pipes.rs b/crates/check/src/pipes.rs new file mode 100644 index 00000000..93571ced --- /dev/null +++ b/crates/check/src/pipes.rs @@ -0,0 +1,68 @@ +//! Pipes: `value |> f(arguments)` is checked as the call `f(value, arguments)`. + +use crate::builder; +use arena::Id; +use model::thir; +use source::Span; +use tree::ast; + +/// `value |> target` at `span`: its target must be a call, which is checked +/// with the value as its first written argument, so a method takes it after +/// its `self`. +pub(crate) fn check_pipe( + builder: &mut builder::ThirBuilder<'_, '_>, + value: Id, + target: Id, + span: Span, +) -> thir::Expr { + let tree = &builder.checker.module().ast; + let ast::Expr::Call { + callee, + type_arguments, + arguments, + } = tree.exprs[target] + else { + let message = "a pipe's target must be a call"; + builder.checker.error( + diagnostics::INVALID_OPERATION, + message, + tree.exprs.span(target), + ); + builder.add_expr(value, None); // for its own errors + return thir::Expr::INVALID; + }; + let mut given = vec![value]; + given.extend(tree.children.lists.items(arguments)); + builder.check_call(callee, type_arguments, &given, span) +} + +#[cfg(test)] +mod tests { + //! Checking pipes as calls. + + use crate::testing; + + /// A pipe is checked as the call of its target with the value first. + #[test] + fn checked_as_calls() { + let (found, reported) = + testing::bodies("fn g(a: i32, b: i32) {}\nfn f(a: i32) { a |> g(2); }"); + assert!(reported.is_empty(), "{reported:?}"); + assert!(found[1].contains("(a.0, 2:i32)"), "{found:?}"); + let (_, reported) = testing::bodies( + "fn g(a: i32) -> i32 { return a; }\nfn f(a: bool) { a |> g(); 1 |> g(2); 1 |> g; 1 |> g().x; }", + ); + let found: Vec<(&str, &str)> = (reported.iter()) + .map(|(_, message, text)| (message.as_str(), text.as_str())) + .collect(); + assert_eq!( + found, + [ + ("mismatched types: expected `i32`, found `bool`", "a"), + ("`g` takes 1 argument, but 2 were given", "1 |> g(2)"), + ("a pipe's target must be a call", "g"), + ("a pipe's target must be a call", "g().x"), + ] + ); + } +} diff --git a/crates/features/src/printing.rs b/crates/check/src/printing.rs similarity index 75% rename from crates/features/src/printing.rs rename to crates/check/src/printing.rs index a5475d3b..cfdfe2e4 100644 --- a/crates/features/src/printing.rs +++ b/crates/check/src/printing.rs @@ -1,53 +1,20 @@ -//! Printing: `print(values)` and `println(values)`, read and checked into -//! calls of the prelude's print functions, so no later phase knows of them. +//! Printing: `print(values)` and `println(values)` checked into calls of the +//! prelude's print functions, so no later phase knows of them. +use crate::builder; +use model::constant; +use model::semantic_types; +use model::thir; use source::Span; -use std::num::NonZeroU32; +use std::num; +use tree::ast; use arena::Id; +use arena::List; use bigint::Limbs; -use check::builder::ThirBuilder; use model::Callee; use model::ConstArguments; use model::DeclarationCopy; -use model::constant::Value; -use model::semantic_types::Conversion; -use model::semantic_types::Float; -use model::semantic_types::Integer; -use model::semantic_types::Type; -use model::semantic_types::TypeId; -use model::semantic_types::Types; -use model::thir; -use model::thir::Symbol; -use parser::Parser; -use parser::Rules; -use parser::expr::starts_expression; -use syntax::ast; -use syntax::operators::Precedence; -use token::TokenKind; - -/// Adds the rules that read `print` and `println` to `rules`. -pub(crate) const fn rows(rules: &mut Rules) { - rules.prefix(TokenKind::Print, print); - rules.prefix(TokenKind::Println, print); -} - -/// Reads `print(values)` or `println(values)`, which take any number of -/// values. -fn print(p: &mut Parser) -> Id { - let keyword = p.next(); - let print = ast::FeatureExpr::Print(ast::Print { - newline: keyword.kind == TokenKind::Println, - values: p.delimited( - TokenKind::LeftParen, - TokenKind::RightParen, - false, - starts_expression, - |p| p.expr(Precedence::Lowest), - ), - }); - p.add(keyword.span.start, ast::Expr::Feature(print)) -} /// `print(values)`, or `println(values)` when `newline`: each value of a /// type `printable` takes, with a space between each. A plain string @@ -58,7 +25,7 @@ fn print(p: &mut Parser) -> Id { /// when `newline`, then the one that writes out what they kept back, added /// to `statements`. `None` at the first that cannot be made, reported. fn print_values( - builder: &mut ThirBuilder<'_, '_>, + builder: &mut builder::ThirBuilder<'_, '_>, statements: &mut Vec>, values: &[Id], newline: bool, @@ -80,30 +47,35 @@ fn print_values( /// The calls that print `value`, added to `statements`; `None` when one /// cannot be made, reported. fn print_value( - builder: &mut ThirBuilder<'_, '_>, + builder: &mut builder::ThirBuilder<'_, '_>, statements: &mut Vec>, mut value: Id, span: Span, ) -> Option<()> { // A reference prints what it refers to. A loop, not recursion: // references nest as deep as the source writes. - while let Type::Reference { .. } = builder.checker.types[builder.body.exprs[value].ty] { + while let semantic_types::Type::Reference { .. } = + builder.checker.types[builder.body.exprs[value].ty] + { value = builder.through_pointer(value, span); } let ty = builder.body.exprs[value].ty; let i32_constant = |value: u32| thir::Expr { - ty: TypeId::I32, - kind: thir::ExprKind::Constant(Value::Integer(Limbs::new(32, &[u64::from(value)]))), + ty: semantic_types::TypeId::I32, + kind: thir::ExprKind::Constant(constant::Value::Integer(Limbs::new( + 32, + &[u64::from(value)], + ))), }; - let read = |builder: &ThirBuilder<'_, '_>| builder.body.exprs[value].clone(); + let read = |builder: &builder::ThirBuilder<'_, '_>| builder.body.exprs[value].clone(); match builder.checker.types[ty] { // The runtime reads an integer from memory (`widened`): where it // is kept or referred to, else a temporary. - Type::Integer(integer) => { + semantic_types::Type::Integer(integer) => { let limbs = widened(builder, value, integer); builder.make_place(limbs); let address = thir::Expr { - ty: TypeId::RAWPTR, + ty: semantic_types::TypeId::RAWPTR, kind: thir::ExprKind::Address(limbs), }; let arguments = vec![ @@ -113,20 +85,26 @@ fn print_value( ]; statements.push(library_call(builder, "PrintInt", arguments, span)?); } - Type::Float(float) => { + semantic_types::Type::Float(float) => { let (double, bits) = match float { - Float::F32 => { + semantic_types::Float::F32 => { let own = builder.body.exprs.span(value); - let widened = - builder.convert(read(builder), own, TypeId::F64, Conversion::Implicit); + let conversion = (builder.checker.types) + .conversion(semantic_types::TypeId::F32, semantic_types::TypeId::F64); + let widened = builder.convert( + read(builder), + own, + semantic_types::TypeId::F64, + conversion, + ); (widened.expect("an `f32` converts to an `f64`"), 32) } - Float::F64 => (read(builder), 64), + semantic_types::Float::F64 => (read(builder), 64), }; let arguments = vec![double, i32_constant(bits)]; statements.push(library_call(builder, "PrintFloat", arguments, span)?); } - Type::Bool => { + semantic_types::Type::Bool => { let (print_true, print_false) = ( print_text(builder, b"true", span)?, print_text(builder, b"false", span)?, @@ -141,13 +119,13 @@ fn print_value( }; statements.push(builder.body.add(choice, span)); } - Type::CString => { + semantic_types::Type::CString => { let arguments = vec![read(builder)]; statements.push(library_call(builder, "PrintText", arguments, span)?); } // Its bytes' address and its length, read from one variable: a // temporary is worked out by each expression that holds it. - Type::Str => { + semantic_types::Type::Str => { let text = match builder.body.exprs[value].kind { thir::ExprKind::Variable(_) => value, _ => kept(builder, statements, value, span), @@ -157,12 +135,12 @@ fn print_value( kind: thir::ExprKind::Field { value: text, index }, }; let arguments = vec![ - part(0, TypeId::RAWPTR), + part(0, semantic_types::TypeId::RAWPTR), part(1, builder.checker.types.usize), ]; statements.push(library_call(builder, "PrintBytes", arguments, span)?); } - Type::RawPointer { .. } => { + semantic_types::Type::RawPointer { .. } => { let arguments = vec![read(builder)]; statements.push(library_call(builder, "PrintPointer", arguments, span)?); } @@ -176,21 +154,26 @@ fn print_value( /// every target, all little-endian. So it is widened to a multiple of 64 /// bits. fn widened( - builder: &mut ThirBuilder<'_, '_>, + builder: &mut builder::ThirBuilder<'_, '_>, value: Id, - integer: Integer, + integer: semantic_types::Integer, ) -> Id { let bits = integer.bits.next_multiple_of(64); if bits == integer.bits { return value; } - let wide = (builder.checker.types).intern(Type::Integer(Integer { bits, ..integer })); + let wide = + (builder.checker.types).intern(semantic_types::Type::Integer(semantic_types::Integer { + bits, + ..integer + })); // At its own span, where an error in working it out is reported. let (narrow, span) = ( builder.body.exprs[value].clone(), builder.body.exprs.span(value), ); - let widened = builder.convert(narrow, span, wide, Conversion::Implicit); + let conversion = builder.checker.types.conversion(narrow.ty, wide); + let widened = builder.convert(narrow, span, wide, conversion); builder .body .add(widened.expect("an integer converts to a wider one"), span) @@ -198,7 +181,7 @@ fn widened( /// A hidden variable set to `value` by a statement added to `statements`. fn kept( - builder: &mut ThirBuilder<'_, '_>, + builder: &mut builder::ThirBuilder<'_, '_>, statements: &mut Vec>, value: Id, span: Span, @@ -219,13 +202,13 @@ fn kept( /// The statement that prints `text` (`library_call`). fn print_text( - builder: &mut ThirBuilder<'_, '_>, + builder: &mut builder::ThirBuilder<'_, '_>, text: &[u8], span: Span, ) -> Option> { let text = thir::Expr { - ty: TypeId::CSTR, - kind: thir::ExprKind::Constant(Value::Bytes(text.into())), + ty: semantic_types::TypeId::CSTR, + kind: thir::ExprKind::Constant(constant::Value::Bytes(text.into())), }; library_call(builder, "PrintText", vec![text], span) } @@ -235,7 +218,7 @@ fn print_text( /// it with a parameter of each argument's type and no result, or when its /// declaration has an error, reported there. fn library_call( - builder: &mut ThirBuilder<'_, '_>, + builder: &mut builder::ThirBuilder<'_, '_>, name: &str, arguments: Vec, span: Span, @@ -245,26 +228,26 @@ fn library_call( let checker = &mut *builder.checker; let prelude = checker.prelude().unwrap_or(checker.scope()); let declared = match prelude.get(None, name) { - Some(Symbol::Function(definition)) => { + Some(thir::Symbol::Function(definition)) => { Some((definition, checker.function_type(definition, span))) } _ => None, }; let types = &checker.types; let as_called = declared.filter(|&(_, signature)| match &types[signature] { - Type::Function { + semantic_types::Type::Function { parameters, result, .. } => { - types.same(*result, TypeId::VOID) + types.same(*result, semantic_types::TypeId::VOID) && parameters.len() == arguments.len() && (parameters.iter().zip(&arguments)).all(|(¶meter, argument)| { - types.conversion(argument.ty, parameter) == Conversion::Same + types.conversion(argument.ty, parameter) == semantic_types::Conversion::Same }) } _ => false, }); let Some((definition, signature)) = as_called else { - if declared.is_none_or(|(_, signature)| signature != TypeId::INVALID) { + if declared.is_none_or(|(_, signature)| signature != semantic_types::TypeId::INVALID) { let message = format!("the `core` library does not declare `{name}` as `print` calls it"); checker.error(diagnostics::UNDEFINED_NAME, message, span); @@ -275,11 +258,11 @@ fn library_call( definition, arguments: ConstArguments::NONE, }; - let arguments: Vec = (arguments.into_iter()) + let arguments: Vec = (arguments.into_iter()) .map(|argument| builder.body.add(argument, span).into()) .collect(); let call = thir::Expr { - ty: TypeId::VOID, + ty: semantic_types::TypeId::VOID, kind: thir::ExprKind::Call { callee: Callee::Function(function), signature, @@ -293,33 +276,30 @@ fn library_call( /// Whether `print` writes a value of the type `ty`: a number, `bool`, /// `&cstr`, `&str` or raw pointer, or a reference to one. A struct or array /// prints only once a trait or interface lets its type say how. -fn printable(types: &Types, mut ty: TypeId) -> bool { +fn printable(types: &semantic_types::Types, mut ty: semantic_types::TypeId) -> bool { // A loop, not recursion: references nest as deep as the source writes. loop { match &types[ty] { - Type::Integer(_) - | Type::Float(_) - | Type::Bool - | Type::CString - | Type::Str - | Type::RawPointer { .. } => return true, - Type::Reference { target, .. } => ty = *target, + semantic_types::Type::Integer(_) + | semantic_types::Type::Float(_) + | semantic_types::Type::Bool + | semantic_types::Type::CString + | semantic_types::Type::Str + | semantic_types::Type::RawPointer { .. } => return true, + semantic_types::Type::Reference { target, .. } => ty = *target, _ => return false, } } } -#[cfg(test)] -mod tests; - /// A block of calls of the prelude's print functions, one for each /// value by its type, then one that writes out what they kept back. pub(crate) fn check_print( - builder: &mut ThirBuilder<'_, '_>, - print: ast::Print, + builder: &mut builder::ThirBuilder<'_, '_>, + newline: bool, + values: List, span: Span, ) -> thir::Expr { - let ast::Print { newline, values } = print; let tree = &builder.checker.module().ast; let mut checked = Vec::with_capacity(values.len()); for value in tree.children.lists.items(values) { @@ -329,7 +309,7 @@ pub(crate) fn check_print( let types = &builder.checker.types; // On an error the others are still checked, for their own. if !printable(types, ty) { - if ty != TypeId::INVALID { + if ty != semantic_types::TypeId::INVALID { let message = format!("`{}` cannot be printed", builder.checker.type_text(ty)); (builder.checker).error(diagnostics::INVALID_OPERATION, message, span); } @@ -338,7 +318,7 @@ pub(crate) fn check_print( let mut printed = builder.body.add(expr, span); // Printing reads a value, never takes it: a `&mut` reference in // a place, the one printable value that moves, is lent as `&`. - if let Type::Reference { + if let semantic_types::Type::Reference { mutable: true, target, } = types[ty] @@ -371,7 +351,7 @@ pub(crate) fn check_print( } // An integer is kept even alone, as the runtime reads it: // from memory, which must not be the program's own variable. - if let Type::Integer(integer) = builder.checker.types[*ty] { + if let semantic_types::Type::Integer(integer) = builder.checker.types[*ty] { *value = widened(builder, *value, integer); } else if alone { continue; @@ -385,7 +365,7 @@ pub(crate) fn check_print( return thir::Expr::INVALID; // reported } thir::Expr { - ty: TypeId::VOID, + ty: semantic_types::TypeId::VOID, kind: thir::ExprKind::Block(block), } } diff --git a/crates/check/src/ranges.rs b/crates/check/src/ranges.rs new file mode 100644 index 00000000..8f026529 --- /dev/null +++ b/crates/check/src/ranges.rs @@ -0,0 +1,139 @@ +//! Ranges: the checker's file for `a..b`, `a..=b`, `a..b:step`, and `..b` or +//! `a..` before a `]`, as the parser reads them. A range value is checked into +//! the built-in type `range[T]`, so the phases after it know nothing of this +//! file. + +use crate::builder; +use arena::Id; +use bigint::Limbs; +use model::constant; +use model::semantic_types; +use model::thir; +use source::Span; +use tree::ast; + +/// The step of a range, written `step` or else 1 at `range_span`, of +/// the range type's step type `step_type` (`Types::range`), and not a +/// constant zero. With an invalid `step_type`, after an error in the +/// ends, it is checked only for its own errors. +fn check_range_step( + builder: &mut builder::ThirBuilder<'_, '_>, + step: Option>, + step_type: semantic_types::TypeId, + range_span: Span, +) -> Id { + let Some(step) = step else { + let one = match builder.checker.types[step_type] { + semantic_types::Type::Integer(unsigned) => thir::Expr { + ty: step_type, + kind: thir::ExprKind::Constant(constant::Value::Integer(Limbs::new( + unsigned.bits, + &[1], + ))), + }, + _ => thir::Expr::INVALID, + }; + return builder.body.add(one, range_span); + }; + let step = match step_type { + semantic_types::TypeId::INVALID => builder.add_expr(step, None), + ty => builder.add_required(step, ty), + }; + if let thir::ExprKind::Constant(constant::Value::Integer(limbs)) = + &builder.body.exprs[step].kind + && limbs.as_slice().iter().all(|&limb| limb == 0) + { + let span = builder.body.exprs.span(step); + let message = "a range's step must not be zero"; + builder + .checker + .error(diagnostics::INVALID_OPERATION, message, span); + } + step +} +/// The range `start..end`, or `..=`, stepping by `start..end:step`, at +/// `span`: a `range[T]` of its ends' integer type `T`. A literal end +/// without a suffix takes the other end's type, or `T` when a +/// `range[T]` is `expected`; the step is of the range type's step type +/// and not a constant zero (`check_range_step`). A range without both +/// ends is not supported yet. +pub(crate) fn check_range( + builder: &mut builder::ThirBuilder<'_, '_>, + written: ast::WrittenRange, + span: Span, + expected: Option, +) -> thir::Expr { + let ast::WrittenRange { + inclusive, + start: Some(start), + end: Some(end), + step, + } = written + else { + builder + .checker + .not_supported(span, "ranges without both ends"); + return thir::Expr::INVALID; + }; + let hint = expected.and_then(|ty| match builder.checker.types[ty] { + semantic_types::Type::Range { element, .. } => Some(element), + _ => None, + }); + let (start, end) = builder.check_range_ends(start, end, hint); + let ty = builder + .checker + .range_type(builder.body.exprs[start].ty, span); + let step_type = match builder.checker.types[ty] { + semantic_types::Type::Range { step, .. } => step, + _ => semantic_types::TypeId::INVALID, + }; + let step = check_range_step(builder, step, step_type, span); + if ty == semantic_types::TypeId::INVALID { + return thir::Expr::INVALID; + } + thir::Expr { + ty, + kind: thir::ExprKind::Range { + start, + end, + step, + inclusive, + }, + } +} + +#[cfg(test)] +mod tests { + //! Checking ranges: a loop over a range takes its ends' type, and its step. + + use crate::testing; + + /// A range's literal start takes the end's type; its variables are + /// declared in the body. Its step is the ends' type made unsigned, 1 + /// when not written. + #[test] + fn loops() { + let (bodies, reported) = testing::bodies( + "fn f(n: i64) { + for i in 0..n { let j = i; } + for 0..3 { } + for k in 1..=n { } + for i, m in n..0:2 { } + }", + ); + assert!(reported.is_empty(), "{reported:?}"); + assert_eq!( + bodies, + [" for i.1 in 0:i64..n.0 by 1:u64 { + let j.2 = i.1 + } + for 0:i32..3:i32 by 1:u32 { + } + for k.3 in 1:i64..=n.0 by 1:u64 { + } + for i.4, m.5 in n.0..0:i64 by 2:u64 { + } +"] + ); + } +} diff --git a/crates/check/src/raw_pointers.rs b/crates/check/src/raw_pointers.rs new file mode 100644 index 00000000..59b6d012 --- /dev/null +++ b/crates/check/src/raw_pointers.rs @@ -0,0 +1,46 @@ +//! Raw pointers in the checker. The checker gives a `Type::RawPointer` and an +//! `ExprKind::Address`, so the phases after it know nothing of this file. A +//! pointer's operations (`==`, `rawptr + usize`), `.*` through it and `none` +//! read that checked type wherever they are checked. + +use crate::builder; +use arena::Id; +use model::semantic_types; +use model::thir; +use source::Span; +use tree::ast; + +use crate::Checker; + +/// The type `rawptr`, or `*target`, written at `span`. +pub(crate) fn resolve_pointer_type( + checker: &mut Checker<'_>, + target: Option>, + span: Span, +) -> semantic_types::TypeId { + let Some(written) = target else { + return semantic_types::TypeId::RAWPTR; + }; + // A pointer only names its target, so a struct can point to itself. + // shortcut: `*[2]Node` or `*Alias` of `Node` in `Node` is a cycle, as + // an array's element and an alias's target are complete, and so is + // any cycle through such a pointer; let them stay names too if a + // program needs it. + let pointee = checker.resolve_type(written); + match checker.written_pointer_target(pointee, span) { + Some(target) => checker.types.intern(semantic_types::Type::RawPointer { + target: Some(target), + }), + None => semantic_types::TypeId::INVALID, + } +} + +/// `@place`, written at `span`. +pub(crate) fn check_raw_address( + builder: &mut builder::ThirBuilder<'_, '_>, + place: Id, + span: Span, +) -> thir::Expr { + let checked_place = builder.add_expr(place, None); + builder.check_address(checked_place, span) +} diff --git a/crates/kernel/semantic/src/scope.rs b/crates/check/src/scope.rs similarity index 97% rename from crates/kernel/semantic/src/scope.rs rename to crates/check/src/scope.rs index abf209a4..2dcb34bb 100644 --- a/crates/kernel/semantic/src/scope.rs +++ b/crates/check/src/scope.rs @@ -16,7 +16,7 @@ use model::thir::Symbol; use rustc_hash::FxHashMap; use source::SourceFile; use source::Span; -use syntax::ast; +use tree::ast; /// A place that holds declarations, and where each name is written. A module /// has one for its top-level declarations, imports and type functions. A name @@ -34,7 +34,7 @@ pub struct Scope<'p> { } impl<'p> Scope<'p> { - pub fn new(parent: Option) -> Scope<'p> { + pub(crate) fn new(parent: Option) -> Scope<'p> { Scope { parent, names: FxHashMap::default(), @@ -64,7 +64,7 @@ impl<'p> Scope<'p> { } /// Every name of `owner` with what it stands for, in no order. - pub fn symbols(&self, owner: Option) -> impl Iterator { + pub(crate) fn symbols(&self, owner: Option) -> impl Iterator { (self.names.iter()) .filter(move |((of, _), _)| *of == owner) .map(|(&(_, name), &(symbol, _))| (name, symbol)) @@ -72,7 +72,7 @@ impl<'p> Scope<'p> { /// Brings `name` of `owner` in as `symbol`, written at `span`. A name /// already in keeps its first meaning, and gives where that was written. - pub fn declare( + pub(crate) fn declare( &mut self, owner: Option, name: &'p str, @@ -116,7 +116,7 @@ pub(crate) fn nearest<'d, 'f: 'd>( /// Reports `name` declared again at `again` in the same `place` (a module or /// a block) of `file`, where it was first declared at `first`. -pub fn report_redeclared( +pub(crate) fn report_redeclared( file: &Arc, name: &str, place: &str, diff --git a/crates/kernel/semantic/src/statement.rs b/crates/check/src/statement.rs similarity index 94% rename from crates/kernel/semantic/src/statement.rs rename to crates/check/src/statement.rs index 3807674b..eada483a 100644 --- a/crates/kernel/semantic/src/statement.rs +++ b/crates/check/src/statement.rs @@ -24,8 +24,8 @@ use model::thir::Stmt; use model::thir::Symbol; use model::thir::Variable; use source::Span; -use syntax::ast; -use syntax::ast::Ident; +use tree::ast; +use tree::ast::Ident; use crate::Checker; use crate::Checking; @@ -220,7 +220,7 @@ impl<'a, 'p> ThirBuilder<'a, 'p> { /// statements `build` gives, which declare no name; the hidden /// variables `build` makes end with it. It is added before the blocks /// `build` adds. - pub fn add_block( + pub(crate) fn add_block( &mut self, span: Span, build: impl FnOnce(&mut Self) -> Vec>, @@ -277,7 +277,12 @@ impl<'a, 'p> ThirBuilder<'a, 'p> { /// A variable of the current block with no name, made for the code at /// `span`. - pub fn add_hidden_variable(&mut self, ty: TypeId, mutable: bool, span: Span) -> Id { + pub(crate) fn add_hidden_variable( + &mut self, + ty: TypeId, + mutable: bool, + span: Span, + ) -> Id { let variable = Variable { ty, mutable, @@ -366,6 +371,10 @@ impl<'a, 'p> ThirBuilder<'a, 'p> { /// The THIR of `statement`; `None` for a `const`, which only declares a /// name, and for a statement with an error. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] fn check_statement(&mut self, statement: Id) -> Option> { // Blocks in blocks and long `else if` chains are a deep recursion. source::grow_stack(|| { @@ -390,7 +399,7 @@ impl<'a, 'p> ThirBuilder<'a, 'p> { } ast::Stmt::Return(value) => Stmt::Return(self.check_return_value(span, value)), ast::Stmt::Panic(message) => self.check_panic(message)?, - ast::Stmt::Feature(stmt) => (self.checker.hooks.check_stmt)(self, stmt, span)?, + ast::Stmt::Match { .. } => crate::enums::check_match(self, span)?, ast::Stmt::Expression(value) => Stmt::Expression(self.add_expr(value, None)), ast::Stmt::Assign { target, value } => self.assign(target, value)?, ast::Stmt::If { @@ -400,11 +409,13 @@ impl<'a, 'p> ThirBuilder<'a, 'p> { } => { let condition = self.add_required(condition, TypeId::BOOL); // A copy holds only the branch its constants choose. - let chosen = match self.body.exprs[condition].kind { - ExprKind::Constant(Value::Bool(taken)) if self.checker.in_copy() => { - Some(taken) - } - _ => None, + let chosen = if let ExprKind::Constant(Value::Bool(taken)) = + self.body.exprs[condition].kind + && self.checker.in_copy() + { + Some(taken) + } else { + None }; match chosen { Some(true) => Stmt::Block(self.check_block(then?)), @@ -475,17 +486,17 @@ impl<'a, 'p> ThirBuilder<'a, 'p> { } => { let iterable = self.add_expr(iterable, None); let ty = self.body.exprs[iterable].ty; - match self.checker.types[ty] { - Type::Range { .. } => { - self.check_for_range(index, Some(value), iterable, body?) - } - _ => self.check_for_array(index, value, iterable, body?)?, + if let Type::Range { .. } = self.checker.types[ty] { + self.check_for_range(index, Some(value), iterable, body?) + } else { + self.check_for_array(index, value, iterable, body?)? } } ast::Stmt::Break | ast::Stmt::Continue if self.loops == 0 => { - let jump = match tree.stmts[statement] { - ast::Stmt::Break => "break", - _ => "continue", + let jump = if let ast::Stmt::Break = tree.stmts[statement] { + "break" + } else { + "continue" }; let message = format!("`{jump}` outside a loop"); self.checker diff --git a/crates/kernel/semantic/src/statement/assignments.rs b/crates/check/src/statement/assignments.rs similarity index 99% rename from crates/kernel/semantic/src/statement/assignments.rs rename to crates/check/src/statement/assignments.rs index 92d54e47..9897f98d 100644 --- a/crates/kernel/semantic/src/statement/assignments.rs +++ b/crates/check/src/statement/assignments.rs @@ -11,7 +11,7 @@ use model::thir::Stmt; use model::thir::Symbol; use model::thir::Variable; use source::Span; -use syntax::ast; +use tree::ast; use crate::builder::ThirBuilder; diff --git a/crates/kernel/semantic/src/statement/loops.rs b/crates/check/src/statement/loops.rs similarity index 99% rename from crates/kernel/semantic/src/statement/loops.rs rename to crates/check/src/statement/loops.rs index b93a9f16..c95602b2 100644 --- a/crates/kernel/semantic/src/statement/loops.rs +++ b/crates/check/src/statement/loops.rs @@ -17,8 +17,8 @@ use model::thir::Local; use model::thir::Stmt; use model::thir::Variable; use source::Span; -use syntax::ast; -use syntax::ast::Ident; +use tree::ast; +use tree::ast::Ident; use crate::builder::ThirBuilder; diff --git a/crates/kernel/semantic/src/statement/tests.rs b/crates/check/src/statement/tests.rs similarity index 99% rename from crates/kernel/semantic/src/statement/tests.rs rename to crates/check/src/statement/tests.rs index 76f139ff..ae7dfcf8 100644 --- a/crates/kernel/semantic/src/statement/tests.rs +++ b/crates/check/src/statement/tests.rs @@ -3,7 +3,7 @@ use model::DeclarationCopy; use model::DefId; use model::thir::Body; use source::SourceFile; -use syntax::ast; +use tree::ast; use crate::testing::Reported; use crate::testing::reported; diff --git a/crates/features/src/structs.rs b/crates/check/src/structs.rs similarity index 53% rename from crates/features/src/structs.rs rename to crates/check/src/structs.rs index 0d661055..a9cae137 100644 --- a/crates/features/src/structs.rs +++ b/crates/check/src/structs.rs @@ -1,138 +1,39 @@ -//! Structs: `struct { name: Type, ... }` and `Type.{ name = value, ... }`. -//! The checker gives the core's struct type and struct value, so the phases -//! after it know nothing of them. A field and a field's value are the -//! core's (`ast::Field`, `ast::FieldValue`): the core reads fields too, as -//! in `point.x`. +//! Structs: checking `struct { name: Type, ... }` declarations and +//! `Type.{ name = value, ... }` literals. The checker gives a `Type::Struct` +//! and a `ExprKind::StructLiteral`, so the phases after it know nothing of +//! this file. Reading a field, as in `point.x`, is checked in +//! `expression/places.rs`. +use crate::builder; +use crate::scope; use arena::Id; -use check::Checker; -use check::builder::ThirBuilder; -use check::scope::report_redeclared; +use arena::List; use diagnostics::Diagnostic; use model::DefId; -use model::layout::struct_layout; -use model::semantic_types::Type; -use model::semantic_types::TypeId; +use model::layout; +use model::semantic_types; use model::thir; -use parser::Parser; -use parser::Rules; -use parser::decl::type_decl; -use parser::is_name; use source::Span; -use std::num::NonZeroU32; -use syntax::ast; -use syntax::operators::Precedence; -use token::TokenKind; +use std::num; +use tree::ast; -/// Adds the rules that read struct types, declarations and literals -/// to `rules`. -pub(crate) const fn rows(rules: &mut Rules) { - rules.declaration(TokenKind::Struct, type_decl); - rules.type_start(TokenKind::Struct, struct_type); - rules.prefix(TokenKind::Dot, anonymous_literal); - rules.after_path(TokenKind::Dot, TokenKind::LeftBrace, typed_literal); -} - -/// Reads `{ name: Type, ... }`, the fields of a struct type that starts at -/// `start`. -fn struct_type(p: &mut Parser, start: u32) -> Id { - let fields = p.delimited( - TokenKind::LeftBrace, - TokenKind::RightBrace, - true, - |_, kind| is_name(kind), - |p| { - let start = p.tok().span.start; - let name = p.name(); - p.expect(TokenKind::Colon); - let ty = p.type_expr(); - p.add(start, ast::Field { name, ty }) - }, - ); - p.add( - start, - ast::Type::Feature(ast::FeatureType::Struct(ast::StructType { fields })), - ) -} - -/// Reads `.{ name = value, ... }`, a struct literal without a type. -fn anonymous_literal(p: &mut Parser) -> Id { - let start = p.tok().span.start; - literal(p, None, start) -} - -/// Reads `.{ name = value, ... }` after the type `path`. -fn typed_literal(p: &mut Parser, path: Id) -> Id { - let start = p.tree.types.span(path).start; - literal(p, Some(path), start) -} - -/// Reads `.{ name = value, ... }` after `ty` (none when there is no type), a -/// literal that starts at `start`. A `name: value` field, the colon of a -/// declaration where a field is set, is read as if it were `=`, and all such -/// colons are reported in one error. -fn literal(p: &mut Parser, ty: Option>, start: u32) -> Id { - p.next(); // `.` - let mut colons = Vec::new(); - let fields = p.delimited( - TokenKind::LeftBrace, - TokenKind::RightBrace, - false, - |_, kind| is_name(kind), - |p| { - let field_start = p.tok().span.start; - let name = p.name(); - let t = p.tok(); - if t.kind == TokenKind::Colon { - p.next(); - colons.push(p.fix(t.span, " =")); - } else { - p.expect(TokenKind::Assign); - } - let value = p.expr(Precedence::Lowest); - p.add(field_start, ast::FieldValue { name, value }) - }, - ); - if !colons.is_empty() { - let d = Diagnostic::new( - diagnostics::EXPECTED_TOKEN, - "expected `=` after struct literal field name", - ) - .label(&p.tree.file, colons[0].span, ""); - p.repair(d.help("set a field with `=`", colons)); - } - p.add( - start, - ast::Expr::Feature(ast::FeatureExpr::StructLiteral(ast::StructLiteral { - ty, - fields, - })), - ) -} - -#[cfg(test)] -mod tests; +use crate::Checker; /// The type a struct type written at `span` names: none yet, as only a /// declared struct is checked. -pub(crate) fn resolve_struct_type( - checker: &mut Checker<'_>, - _ty: ast::StructType, - span: Span, -) -> TypeId { +pub(crate) fn resolve_struct_type(checker: &mut Checker<'_>, span: Span) -> semantic_types::TypeId { checker.not_supported(span, "struct types") } -/// The type the struct declaration `definition`, written `written` with the -/// fields of `ty`, declares, its fields laid out for the target. +/// The type the struct declaration `definition`, written `written` with +/// `fields`, declares, its fields laid out for the target. pub(crate) fn declare_struct_type( checker: &mut Checker<'_>, - ty: ast::StructType, + fields: List, definition: DefId, written: ast::TypeDecl, -) -> TypeId { +) -> semantic_types::TypeId { let tree = &checker.module().ast; - let fields = ty.fields; let mut field_types = Vec::with_capacity(fields.len()); let name_of = |field: Id| tree.children.fields[field].name; for (index, field) in tree.children.lists.items(fields).enumerate() { @@ -141,7 +42,8 @@ pub(crate) fn declare_struct_type( // A struct has few fields, so the ones before are searched. let mut before = tree.children.lists.items(fields).take(index).map(name_of); if let Some(first) = before.find(|first| first.text(&tree.file) == text) { - let diagnostic = report_redeclared(&tree.file, text, "struct", name.span, first.span); + let diagnostic = + scope::report_redeclared(&tree.file, text, "struct", name.span, first.span); checker.report(diagnostic); } // A struct held by value is checked here: one that holds @@ -152,17 +54,18 @@ pub(crate) fn declare_struct_type( } // Invalid when a field is, as an array is when its element // is, so no later phase lays out a field it cannot. - if field_types.contains(&TypeId::INVALID) { - return TypeId::INVALID; + if field_types.contains(&semantic_types::TypeId::INVALID) { + return semantic_types::TypeId::INVALID; } - let (offsets, size, align) = struct_layout(&checker.types, &field_types, checker.target); + let (offsets, size, align) = + layout::struct_layout(&checker.types, &field_types, checker.target); let named = checker.declared_name(definition); let mut ty = checker.fits_target(named, size, written.name.span); let holders = checker.types.holders_in_fields(&field_types); if checker.reports_too_many_holders(named, holders, written.name.span) { - ty = TypeId::INVALID; + ty = semantic_types::TypeId::INVALID; } - if ty != TypeId::INVALID { + if ty != semantic_types::TypeId::INVALID { checker .types .define_struct(named, field_types.into(), (offsets, size, align)); @@ -174,26 +77,26 @@ pub(crate) fn declare_struct_type( /// the struct type `expected`: a struct value with each field set once. /// A field that is unknown, set twice or missing is reported. pub(crate) fn check_struct_literal( - builder: &mut ThirBuilder<'_, '_>, - literal: ast::StructLiteral, + builder: &mut builder::ThirBuilder<'_, '_>, + written: Option>, + fields: List, span: Span, - expected: Option, + expected: Option, ) -> thir::Expr { - let ast::StructLiteral { - ty: written, - fields, - } = literal; let tree = &builder.checker.module().ast; let ty = match (written, expected) { (Some(written), _) => builder.checker.resolve_value_type(written), (None, Some(expected)) - if matches!(builder.checker.types[expected], Type::Struct { .. }) => + if matches!( + builder.checker.types[expected], + semantic_types::Type::Struct { .. } + ) => { expected } // Reported where it was written, or a `T` only a copy knows: // `let b: Box = .{ ... }` in a generic function's own body. - (None, Some(TypeId::INVALID)) => TypeId::INVALID, + (None, Some(semantic_types::TypeId::INVALID)) => semantic_types::TypeId::INVALID, (None, _) => { let message = "this struct literal needs its type: write it before `.{`"; builder @@ -201,13 +104,13 @@ pub(crate) fn check_struct_literal( .error(diagnostics::MISSING_TYPE, message, span) } }; - let Type::Struct { + let semantic_types::Type::Struct { definition, fields: field_types, .. } = &builder.checker.types[ty] else { - if ty != TypeId::INVALID { + if ty != semantic_types::TypeId::INVALID { let message = format!( "expected a struct type, found `{}`", builder.checker.type_text(ty) @@ -220,18 +123,18 @@ pub(crate) fn check_struct_literal( // For their own errors; what each field's type is, is not known. for field in tree.children.lists.items(fields) { let value = tree.children.field_values[field].value; - builder.add_expr(value, Some(TypeId::INVALID)); + builder.add_expr(value, Some(semantic_types::TypeId::INVALID)); } return thir::Expr::INVALID; }; let definition = *definition; // Where each field is set, by its index. let mut set: Vec> = vec![None; field_types.len()]; - let mut checked: Vec = Vec::with_capacity(fields.len()); + let mut checked: Vec = Vec::with_capacity(fields.len()); for field in tree.children.lists.items(fields) { let ast::FieldValue { name, value } = tree.children.field_values[field]; let Some((index, field_type)) = builder.field_index(ty, name) else { - builder.add_expr(value, Some(TypeId::INVALID)); // for its own errors + builder.add_expr(value, Some(semantic_types::TypeId::INVALID)); // for its own errors continue; }; if let Some(first) = set[index] { diff --git a/crates/check/src/testing.rs b/crates/check/src/testing.rs new file mode 100644 index 00000000..39ec8449 --- /dev/null +++ b/crates/check/src/testing.rs @@ -0,0 +1,136 @@ +//! What the checking tests share: a one-module program read from text, whose +//! declarations are checked one at a time. + +use std::sync::Arc; + +use model::ConstArguments; +use model::DeclarationCopy; +use model::DefId; +use model::ModuleId; +use model::machine::Machine; +use model::program::ImportKind; +use model::semantic_types::Types; +use model::thir; +use source::SourceFile; +use source::Span; +use tree::ast; + +use crate::Checker; + +/// The module `path`, written as `text`, with `imports`; its text must parse +/// without errors. +pub(crate) fn module( + path: &str, + text: &str, + imports: Vec, +) -> model::program::Module { + let file = Arc::new(SourceFile::new("main.peep", text)); + let (ast, parse) = parser::parse(&file); + assert!(parse.is_empty(), "{parse:?}"); + model::program::Module { + path: path.to_string(), + ast, + imports, + } +} + +/// A diagnostic as its code, message and the text of its first label. +pub(crate) type Reported = (&'static str, String, String); + +/// Runs `work` on a checker of the module `app:main` written as `text`, given +/// its id, which +/// imports `app:utils` as `utils` (an import added after `text`, so the +/// places in `text` stay as written), which declares `Shown` and the private +/// `hidden`. Gives what `work` gives, the program's +/// types and the diagnostics. +pub(crate) fn with_checker( + text: &str, + work: impl FnOnce(&mut Checker, ModuleId) -> T, +) -> (T, Types, Vec) { + let (utils_id, main_id) = (ModuleId::from_index(0), ModuleId::from_index(1)); + let imports = vec![model::program::Import { + kind: ImportKind::Declared(0), + module: utils_id, + }]; + let text = format!("{text}\nimport \"app:utils\";\n"); + let modules = [ + module("app:utils", "fn Shown() {}\nfn hidden() {}", Vec::new()), + module("app:main", &text, imports), + ]; + let file = modules[1].ast.file.clone(); + let mut checker = Checker::new(&modules, Machine::named("x86_64-linux").unwrap(), false); + let result = work(&mut checker, main_id); + let reported = checker + .module_checks + .iter() + .flat_map(|module| &module.diagnostics) + .map(|diagnostic| { + let text = file.slice(diagnostic.labels[0].span).to_string(); + (diagnostic.code.id, diagnostic.message.clone(), text) + }) + .collect(); + (result, checker.types, reported) +} + +/// `expected` as `Reported`s, to compare with what was reported. +pub(crate) fn reported(expected: &[(&'static str, &str, &str)]) -> Vec { + let owned = |&(code, message, text): &(&'static str, &str, &str)| { + (code, message.to_string(), text.to_string()) + }; + expected.iter().map(owned).collect() +} + +/// Runs `work` on a checker of the one module `app:main`, written as +/// `text`, given the functions' declarations in order; gives what `work` +/// gives and the diagnostics. +pub(crate) fn with_functions( + text: &str, + work: impl FnOnce(&mut Checker, &[(DefId, Span)]) -> T, +) -> (T, Vec) { + let modules = [module("app:main", text, Vec::new())]; + let tree = &modules[0].ast; + let file = tree.file.clone(); + let functions: Vec<(DefId, Span)> = (tree.declarations().enumerate()) + .filter_map(|(index, declaration)| match tree.decls[declaration] { + ast::Decl::Function(function) => { + let module = ModuleId::from_index(0); + let index = index as u32; + Some((DefId { module, index }, function.name.span)) + } + _ => None, + }) + .collect(); + let mut checker = Checker::new(&modules, Machine::named("x86_64-linux").unwrap(), false); + let result = work(&mut checker, &functions); + let reported = (checker.module_checks.iter()) + .flat_map(|module| &module.diagnostics) + .map(|diagnostic| { + let label = file.slice(diagnostic.labels[0].span).to_string(); + (diagnostic.code.id, diagnostic.message.clone(), label) + }) + .collect(); + (result, reported) +} + +/// The text of the body of every function of `text`, a called function +/// named by its place among them (`f0`). +pub(crate) fn bodies(text: &str) -> (Vec, Vec) { + let file = SourceFile::new("main.peep", text); + with_functions(text, |checker, functions| { + let names: Vec = (0..functions.len()) + .map(|index| format!("f{index}")) + .collect(); + let name = |function: DefId| names[function.index as usize].as_str(); + (functions.iter()) + .map(|&(definition, span)| { + let copy = DeclarationCopy { + definition, + arguments: ConstArguments::NONE, + }; + let mut body = thir::Body::default(); + assert!(checker.check_body(copy, span, &mut body, true)); + body.text(&checker.types, &file, name) + }) + .collect() + }) +} diff --git a/crates/driver/compile/tests/checks_through_features.rs b/crates/check/tests/declarations.rs similarity index 95% rename from crates/driver/compile/tests/checks_through_features.rs rename to crates/check/tests/declarations.rs index 0734e30f..d0678c42 100644 --- a/crates/driver/compile/tests/checks_through_features.rs +++ b/crates/check/tests/declarations.rs @@ -1,6 +1,5 @@ -//! The checker's tests that need a feature to reach core behaviour. The -//! checker's own tests read the core's rules alone, as the `features` crate -//! depends on `check`; these are written in Peeper, through the checker's +//! The checker's declaration, name-table and body checks over two modules, +//! one importing the other, written in Peeper and run through the checker's //! public calls. use std::sync::Arc; @@ -20,13 +19,13 @@ use model::semantic_types::Types; use model::thir::Body; use model::thir::Symbol; use source::SourceFile; -use syntax::ast; +use tree::ast; /// The module `path`, written as `text`, with `imports`; its text must parse /// without errors. fn module(path: &str, text: &str, imports: Vec) -> model::program::Module { let file = Arc::new(SourceFile::new("main.peep", text)); - let (ast, parse) = parser::parse(&file, &features::RULES); + let (ast, parse) = parser::parse(&file); assert!(parse.is_empty(), "{parse:?}"); model::program::Module { path: path.to_string(), @@ -58,12 +57,7 @@ fn with_checker( module("app:main", &text, imports), ]; let file = modules[1].ast.file.clone(); - let mut checker = Checker::new( - &modules, - Machine::named("x86_64-linux").unwrap(), - false, - &features::CHECK_HOOKS, - ); + let mut checker = Checker::new(&modules, Machine::named("x86_64-linux").unwrap(), false); let result = work(&mut checker, main_id); let reported = checker .module_checks @@ -126,7 +120,7 @@ fn definition(module: usize, index: u32) -> DefId { } } -// From `check::declaration`. +// Declarations. #[test] fn errors_are_located() { @@ -205,7 +199,7 @@ fn a_malformed_extern_is_reported() { assert_eq!(found_reported, expected); } -// From `check::scope`. +// A module's names (`check::scope`). #[test] fn declarations_and_imports() { @@ -302,7 +296,7 @@ fn a_type_function_needs_a_struct_of_its_module() { ); } -// From `check::statement`. +// Function bodies. /// The diagnostics of checking every function body of `text`. fn body_reports(text: &str) -> Vec { diff --git a/crates/kernel/semantic/tests/llvm_parity.rs b/crates/check/tests/llvm_parity.rs similarity index 95% rename from crates/kernel/semantic/tests/llvm_parity.rs rename to crates/check/tests/llvm_parity.rs index 17827cc4..69e5b9c9 100644 --- a/crates/kernel/semantic/tests/llvm_parity.rs +++ b/crates/check/tests/llvm_parity.rs @@ -10,8 +10,8 @@ //! Each binary operator becomes the MIR operation lowering makes of it //! (`lower::arithmetic::binary_operation`), written with the instruction //! the backend writes for that operation (`integer_instruction`, -//! `comparison_instruction`, `signed_division`, `conversion_instruction`, -//! `saturating_conversion`). +//! `comparison_instruction`, `signed_division`, `cast_instruction`, +//! `saturating_cast`). //! //! Runs the `lli` of build/toolchains/native, which scripts/setup.sh puts //! there: `cargo test -p check --test llvm_parity -- --ignored`; scripts/check.sh runs it. The CI pack has it; an installed @@ -25,25 +25,25 @@ use bigint::Limbs; use check::fold::conversions::convert; use check::fold::operators::binary; use check::fold::operators::unary; +use llvm::body::cast_instruction; use llvm::body::comparison_instruction; use llvm::body::constant_text; -use llvm::body::conversion_instruction; use llvm::body::float_instruction; use llvm::body::integer_instruction; -use llvm::body::saturating_conversion; +use llvm::body::saturating_cast; use llvm::body::signed_division; use llvm::link::TOOLCHAIN_FOLDER; use lower::arithmetic::BinaryOperation; use lower::arithmetic::binary_operation; -use lower::arithmetic::cast_conversion; use model::constant::Value; use model::mir::Class; use model::mir::IntegerOp; +use model::semantic_types; use model::semantic_types::Float; use model::semantic_types::Integer; use model::semantic_types::Type; -use syntax::operators::BinaryOp; -use syntax::operators::UnaryOp; +use tree::operators::BinaryOp; +use tree::operators::UnaryOp; const WIDTHS: &[u32] = &[ 1, 2, 3, 5, 7, 8, 9, 15, 16, 17, 24, 31, 32, 33, 63, 64, 65, 100, 127, 128, 129, 192, 200, 255, @@ -456,7 +456,7 @@ define i32 @main() {{ let path = Path::new(env!("CARGO_TARGET_TMPDIR")).join("llvm_parity.ll"); std::fs::write(&path, program).unwrap(); let lli = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../../build") + .join("../../build") .join(TOOLCHAIN_FOLDER) .join("bin/lli"); let output = Command::new(lli) @@ -523,19 +523,27 @@ fn write_conversions( types.push(Type::Integer(Integer { signed, bits })); } } + // The cast check gives each pair, which lowering and the folder use. + let mut table = semantic_types::Types::new(64); + let ids: Vec = + types.iter().map(|ty| table.intern(ty.clone())).collect(); let mut declared = std::collections::HashSet::new(); for (index, from) in types.iter().enumerate() { let function = format!("convert{index}"); writeln!(body, "define void @{function}() {{").unwrap(); writeln!(calls, " call void @{function}()").unwrap(); let from_llvm = llvm_type(from); - for to in &types { + for (to_index, to) in types.iter().enumerate() { + let cast = || match table.conversion(ids[index], ids[to_index]) { + semantic_types::Conversion::Implicit(cast) + | semantic_types::Conversion::NeedsCast(cast) => cast, + other => unreachable!("{from:?} to {to:?} is {other:?}"), + }; let instruction = match (from, to) { _ if from == to => continue, (_, Type::Bool) | (Type::Bool, Type::Float(_)) => continue, (&Type::Float(float), &Type::Integer(integer)) => { - let conversion = cast_conversion(from, to); - let (intrinsic, _) = saturating_conversion(conversion, float.class()); + let (intrinsic, _) = saturating_cast(cast(), float.class()); if declared.insert(intrinsic.clone()) { writeln!( declarations, @@ -553,7 +561,7 @@ fn write_conversions( ) if from == to => "same".to_string(), (Type::Bool, Type::Integer(Integer { bits: 1, .. })) => "same".to_string(), // The conversion lowering makes. - _ => conversion_instruction(cast_conversion(from, to)).to_string(), + _ => cast_instruction(cast()).to_string(), }; for _ in 0..3 { let value = match from { @@ -579,7 +587,7 @@ fn write_conversions( }), _ => unreachable!(), }; - let result = convert(from, to, &value); + let result = convert(cast(), from, to, &value); let k = expected.len(); let source = match &value { Value::Float(bits) => format!("0x{bits:016X}"), diff --git a/crates/driver/browser/Cargo.toml b/crates/driver/browser/Cargo.toml index 1d8ac103..e5977f8b 100644 --- a/crates/driver/browser/Cargo.toml +++ b/crates/driver/browser/Cargo.toml @@ -8,7 +8,6 @@ publish.workspace = true [dependencies] compile.workspace = true -features.workspace = true diagnostics.workspace = true eval.workspace = true lexer.workspace = true diff --git a/crates/driver/browser/src/main.rs b/crates/driver/browser/src/main.rs index 98b05b9e..f81460bd 100644 --- a/crates/driver/browser/src/main.rs +++ b/crates/driver/browser/src/main.rs @@ -93,7 +93,7 @@ fn load(project: &project::Project, files: HashMap) -> model::pr let library_files = (LIBRARY_FILES.iter()) .map(|&(path, text)| (Path::new(LIBRARY_ROOT).join(path), text.to_string())); let open_files: HashMap = page_files.chain(library_files).collect(); - project::load(project, &open_files, &features::RULES) + project::load(project, &open_files) } /// The diagnostics of the program `files` make up, as `peeper check` finds diff --git a/crates/driver/compile/Cargo.toml b/crates/driver/compile/Cargo.toml index d8d90116..95dff85a 100644 --- a/crates/driver/compile/Cargo.toml +++ b/crates/driver/compile/Cargo.toml @@ -10,12 +10,11 @@ publish.workspace = true arena.workspace = true diagnostics.workspace = true model.workspace = true -syntax.workspace = true +tree.workspace = true check.workspace = true eval.workspace = true lower.workspace = true parser.workspace = true -features.workspace = true runtime_abi.workspace = true source.workspace = true diff --git a/crates/driver/compile/src/lib.rs b/crates/driver/compile/src/lib.rs index a1be83d4..beada02f 100644 --- a/crates/driver/compile/src/lib.rs +++ b/crates/driver/compile/src/lib.rs @@ -37,7 +37,7 @@ use runtime_abi::abi::PANIC_EXIT_CODE; use runtime_abi::messages::panic_text; use source::SourceFile; use source::Span; -use syntax::ast; +use tree::ast; /// What a compile found, kept for the next compile of the same program. #[derive(Default)] @@ -248,12 +248,7 @@ pub fn run( return Results::default(); } let modules = program.modules.as_slice(); - let mut checker = Checker::new( - modules, - target, - options.record_facts, - &features::CHECK_HOOKS, - ); + let mut checker = Checker::new(modules, target, options.record_facts); let mut results: Vec = modules .iter() .map(|module| ModuleResults::new(module.ast.file.clone())) diff --git a/crates/driver/compile/src/tests.rs b/crates/driver/compile/src/tests.rs index 560d86f8..872ff469 100644 --- a/crates/driver/compile/src/tests.rs +++ b/crates/driver/compile/src/tests.rs @@ -43,7 +43,7 @@ fn load(modules: &[(&str, &str)]) -> model::program::Program { root: PathBuf::from("/peeper-build-test"), name: "app".to_string(), }; - let program = project::load(&project, &open_files, &features::RULES); + let program = project::load(&project, &open_files); let reported: Vec<&str> = program .diagnostics .iter() diff --git a/crates/driver/compile/tests/parses_the_prelude.rs b/crates/driver/compile/tests/parses_the_prelude.rs index 9e090dd4..5755a524 100644 --- a/crates/driver/compile/tests/parses_the_prelude.rs +++ b/crates/driver/compile/tests/parses_the_prelude.rs @@ -1,10 +1,10 @@ -//! The real prelude is written in Peeper, with every feature, so it is -//! read here, not in the parser's own tests (the core's rules alone). +//! The real prelude, written in Peeper with every feature, parses with no +//! error. use std::sync::Arc; use source::SourceFile; -use syntax::ast; +use tree::ast; /// The real prelude, the first file of every program, parses cleanly. #[test] @@ -15,6 +15,6 @@ fn parses_the_prelude() { ); let text = std::fs::read_to_string(path).unwrap(); let file = Arc::new(SourceFile::new("global.peep", &text)); - let (_, errors): (ast::Tree, _) = parser::parse(&file, &features::RULES); + let (_, errors): (ast::Tree, _) = parser::parse(&file); assert!(errors.is_empty(), "{errors:?}"); } diff --git a/crates/driver/compile/tests/path_check_memory.rs b/crates/driver/compile/tests/path_check_memory.rs index 4e535ec5..45ad9bf3 100644 --- a/crates/driver/compile/tests/path_check_memory.rs +++ b/crates/driver/compile/tests/path_check_memory.rs @@ -36,7 +36,7 @@ fn compile_growth_kb(text: String) -> u64 { }; std::fs::write("/proc/self/clear_refs", "5").unwrap(); // resets `VmHWM` let before = status_kb("VmRSS:"); - let program = project::load(&project, &HashMap::from([(main, text)]), &features::RULES); + let program = project::load(&project, &HashMap::from([(main, text)])); assert!(program.checkable); let target = model::machine::Machine::named("x86_64-linux").unwrap(); let results = compile::run( diff --git a/crates/driver/lsp/Cargo.toml b/crates/driver/lsp/Cargo.toml index 25978f07..4a18cf9f 100644 --- a/crates/driver/lsp/Cargo.toml +++ b/crates/driver/lsp/Cargo.toml @@ -10,11 +10,10 @@ publish.workspace = true source.workspace = true arena.workspace = true model.workspace = true -syntax.workspace = true +tree.workspace = true diagnostics.workspace = true project.workspace = true compile.workspace = true -features.workspace = true lexer.workspace = true lsp-server.workspace = true lsp-types.workspace = true diff --git a/crates/driver/lsp/src/checked.rs b/crates/driver/lsp/src/checked.rs index 6ab9f652..89e49133 100644 --- a/crates/driver/lsp/src/checked.rs +++ b/crates/driver/lsp/src/checked.rs @@ -21,7 +21,7 @@ use model::thir::Local; use model::thir::Symbol; use source::Span; use std::fmt::Write; -use syntax::ast; +use tree::ast; use crate::host; diff --git a/crates/driver/lsp/src/hover.rs b/crates/driver/lsp/src/hover.rs index 1f487678..820e4d74 100644 --- a/crates/driver/lsp/src/hover.rs +++ b/crates/driver/lsp/src/hover.rs @@ -9,7 +9,7 @@ use lsp_types::MarkupContent; use lsp_types::MarkupKind; use source::SourceFile; use source::Span; -use syntax::ast; +use tree::ast; use crate::checked::ConstantText; @@ -70,7 +70,8 @@ pub(crate) fn declaration_hover( let signature = written(tree.blocks.span(*body).start); (format!("{signature} {{ {HIDDEN} }}"), None) } - (ast::Decl::Type(declared), _) if matches!(tree.types[declared.ty], ast::Type::Feature(ty) if ty.fields().is_some()) => + (ast::Decl::Type(declared), _) + if matches!(tree.types[declared.ty], ast::Type::Struct { .. }) => { let mut facts = written(span.end).to_string(); write_functions(tree, declared.name, from_elsewhere, &mut facts); diff --git a/crates/driver/lsp/src/server/requests.rs b/crates/driver/lsp/src/server/requests.rs index be8cf705..1b40e6fa 100644 --- a/crates/driver/lsp/src/server/requests.rs +++ b/crates/driver/lsp/src/server/requests.rs @@ -16,10 +16,9 @@ use lsp_types::CodeActionParams; use lsp_types::Location; use lsp_types::TextDocumentPositionParams; use lsp_types::Url; -use model::semantic_types::builtin_doc; use source::SourceFile; use source::Span; -use syntax::ast; +use tree::ast; use crate::checked::CachedFact; use crate::checked::CachedKind; @@ -33,6 +32,7 @@ use crate::hover::hover_text; use crate::hover::markdown_hover; use crate::server::Server; use crate::server::file_path; +use model::semantic_types; impl Server<'_> { /// Answers go to definition with where the name at the given place is /// declared, and hover with what it is, or what the keyword there does; @@ -65,7 +65,7 @@ impl Server<'_> { return None; // declared nowhere } let written = module.ast.file.slice(name.span); - let doc = builtin_doc(written, host().pointer_bits)?; + let doc = semantic_types::builtin::builtin_doc(written, host().pointer_bits)?; return markdown_hover(doc_hover(written, &doc)); } let (file, declared, hover) = declaration_of(checked, module, name)?; diff --git a/crates/driver/lsp/src/server/sync.rs b/crates/driver/lsp/src/server/sync.rs index e28ead70..fe0c31b4 100644 --- a/crates/driver/lsp/src/server/sync.rs +++ b/crates/driver/lsp/src/server/sync.rs @@ -155,7 +155,7 @@ impl Server<'_> { project: project::Project, file: &Path, ) -> Result<(), BoxError> { - let program = project::load(&project, &self.open_files, &features::RULES); + let program = project::load(&project, &self.open_files); let mut checked = self.checked.remove(&key).unwrap_or_default(); let mut all: Vec<&diagnostics::Diagnostic> = program.diagnostics.iter().collect(); // A program that cannot be checked keeps the last compile for the next. diff --git a/crates/driver/lsp/src/tests.rs b/crates/driver/lsp/src/tests.rs index 1f12bcd8..c2fc4aed 100644 --- a/crates/driver/lsp/src/tests.rs +++ b/crates/driver/lsp/src/tests.rs @@ -21,8 +21,8 @@ use lsp_types::Url; use serde_json::json; use source::SourceFile; use source::Span; -use syntax::operators::BinaryOp; -use syntax::operators::UnaryOp; +use tree::operators::BinaryOp; +use tree::operators::UnaryOp; use crate::DEBOUNCE; use crate::OpenFile; diff --git a/crates/driver/peeper/Cargo.toml b/crates/driver/peeper/Cargo.toml index a7bdfc0e..9f9d531b 100644 --- a/crates/driver/peeper/Cargo.toml +++ b/crates/driver/peeper/Cargo.toml @@ -12,7 +12,6 @@ diagnostics.workspace = true lexer.workspace = true project.workspace = true compile.workspace = true -features.workspace = true eval.workspace = true llvm.workspace = true lsp.workspace = true diff --git a/crates/driver/peeper/benches/compile.rs b/crates/driver/peeper/benches/compile.rs index 3a798191..52564a71 100644 --- a/crates/driver/peeper/benches/compile.rs +++ b/crates/driver/peeper/benches/compile.rs @@ -76,7 +76,7 @@ fn main() { let mut clang = Vec::new(); for _ in 0..runs { let start = Instant::now(); - let program = project::load(&project, &files, &features::RULES); + let program = project::load(&project, &files); load.push(start.elapsed()); assert!(program.checkable, "{:?}", program.diagnostics); let start = Instant::now(); diff --git a/crates/driver/peeper/src/args.rs b/crates/driver/peeper/src/args.rs index 417cb8fa..3f295416 100644 --- a/crates/driver/peeper/src/args.rs +++ b/crates/driver/peeper/src/args.rs @@ -219,4 +219,297 @@ fn value<'a>(values: &[&'a str]) -> Result, String> { } #[cfg(test)] -mod tests; +mod tests { + use super::Args; + use super::parse; + use llvm::BuildMode; + use model::machine::Machine; + + use crate::driver::Goal; + + /// The path and dump extensions `args` ask for, with "fix" added for + /// `peeper fix`, `("lsp", [])` for `peeper lsp`, `("init", [name])` for + /// `peeper init`, or `None`. `build` and + /// `run` give "build" or "run", "release" for -release, then -o's value + /// or the arguments. + fn parsed(args: &[&str]) -> Option<(String, Vec)> { + let args: Vec = args.iter().map(|arg| arg.to_string()).collect(); + let (path, goal) = match parse(&args).ok()? { + Args::Program { path, goal, .. } => (path, goal), + Args::Lsp => return Some(("lsp".to_string(), Vec::new())), + Args::Help => return Some(("help".to_string(), Vec::new())), + Args::Init { name } => return Some(("init".to_string(), name.into_iter().collect())), + }; + match goal { + Goal::Check { + dumps, + apply_fixes, + mode, + } => { + let mut asked: Vec = dumps + .iter() + .map(|dump| dump.extension().to_string()) + .collect(); + asked.extend((mode == BuildMode::Release).then(|| "release".to_string())); + if apply_fixes { + asked.push("fix".to_string()); + } + Some((path.display().to_string(), asked)) + } + Goal::Build { output, mode } => { + let mut asked = vec!["build".to_string()]; + asked.extend((mode == BuildMode::Release).then(|| "release".to_string())); + asked.extend(output.map(|output| output.display().to_string())); + Some((path.display().to_string(), asked)) + } + Goal::Run { arguments, mode } => { + let release = (mode == BuildMode::Release).then(|| "release".to_string()); + let asked = ["run".to_string()] + .into_iter() + .chain(release) + .chain(arguments) + .collect(); + Some((path.display().to_string(), asked)) + } + Goal::Interpret => Some((path.display().to_string(), vec!["interpret".to_string()])), + } + } + + #[test] + fn commands() { + let some = |path: &str, asked: &[&str]| { + Some(( + path.to_string(), + asked.iter().map(|a| a.to_string()).collect(), + )) + }; + assert_eq!(parsed(&["check"]), some(".", &[])); + assert_eq!(parsed(&["check", "app"]), some("app", &[])); + assert_eq!(parsed(&["fix"]), some(".", &["fix"])); + assert_eq!(parsed(&["fix", "app"]), some("app", &["fix"])); + assert_eq!(parsed(&["-dump"]), some(".", &["thir", "mir", "ll"])); + assert_eq!(parsed(&["-dump", "mir"]), some(".", &["mir"])); + assert_eq!( + parsed(&["-dump", "app"]), + some("app", &["thir", "mir", "ll"]) + ); + assert_eq!(parsed(&["-dump", "thir", "app"]), some("app", &["thir"])); + assert_eq!( + parsed(&["-dump", "-release"]), + some(".", &["thir", "mir", "ll", "release"]) + ); + assert_eq!(parsed(&["build"]), some(".", &["build"])); + assert_eq!(parsed(&["build", "app"]), some("app", &["build"])); + assert_eq!( + parsed(&["build", "-o", "out"]), + some(".", &["build", "out"]) + ); + assert_eq!( + parsed(&["build", "-o", "out", "app"]), + some("app", &["build", "out"]) + ); + assert_eq!( + parsed(&["build", "-release", "-o", "out", "app"]), + some("app", &["build", "release", "out"]) + ); + assert_eq!(parsed(&["run"]), some(".", &["run"])); + assert_eq!(parsed(&["run", "--", "x"]), some(".", &["run", "x"])); + assert_eq!(parsed(&["run", "-release"]), some(".", &["run", "release"])); + assert_eq!( + parsed(&["run", "app", "--", "x", "-help"]), + some("app", &["run", "x", "-help"]) + ); + assert_eq!(parsed(&["-help"]), some("help", &[])); + assert_eq!(parsed(&["lsp"]), some("lsp", &[])); + assert_eq!(parsed(&["init"]), some("init", &[])); + assert_eq!(parsed(&["init", "app"]), some("init", &["app"])); + assert_eq!(parsed(&["check", "-target", "i686-linux"]), some(".", &[])); + assert_eq!( + parsed(&["-dump", "ll", "-target", "i686-linux", "app"]), + some("app", &["ll"]) + ); + assert_eq!( + parsed(&["build", "-target", "i686-linux", "-o", "out", "app"]), + some("app", &["build", "out"]) + ); + assert_eq!( + parsed(&["run", "-target", "i686-linux", "-release", "app", "--", "x"]), + some("app", &["run", "release", "x"]) + ); + for wrong in [ + &[][..], + &["build", "-o"], + &["build", "a", "b"], + &["run", "app", "x"], + &["run", "app", "-help"], + &["-help", "app"], + &["-dump", "asm", "app"], + &["check", "a", "b"], + &["fix", "a", "b"], + &["lsp", "app"], + &["init", "a", "b"], + ] { + assert_eq!(parsed(wrong), None, "{wrong:?}"); + } + } + + /// `-target` picks the target it names, and the host is the target + /// without it. + #[test] + fn targets() { + let target = |args: &[&str]| { + let args: Vec = args.iter().map(|arg| arg.to_string()).collect(); + match parse(&args) { + Ok(Args::Program { target, .. }) => target, + _ => panic!("{args:?} names a program"), + } + }; + let i686 = Machine::named("i686-linux").unwrap(); + assert_eq!(target(&["check", "-target", "i686-linux"]), i686); + assert_eq!( + target(&["-dump", "ll", "-target", "i686-linux", "app"]), + i686 + ); + assert_eq!( + target(&["build", "-target", "i686-linux", "-o", "out"]), + i686 + ); + assert_eq!( + target(&["run", "app", "-target", "i686-linux", "--", "x"]), + i686 + ); + assert_eq!(Ok(target(&["run", "app"])), Machine::host()); + } + + /// Flags come anywhere; the words left are the command and its value. + #[test] + fn flags_in_any_order() { + let some = |path: &str, asked: &[&str]| { + Some(( + path.to_string(), + asked.iter().map(|a| a.to_string()).collect(), + )) + }; + let release_build = some("app", &["build", "release", "out"]); + assert_eq!( + parsed(&["build", "-o", "out", "app", "-release"]), + release_build + ); + assert_eq!( + parsed(&["-release", "build", "app", "-o", "out"]), + release_build + ); + assert_eq!( + parsed(&["build", "app", "-release", "-o", "out"]), + release_build + ); + assert_eq!(parsed(&["run", "-release"]), some(".", &["run", "release"])); + assert_eq!( + parsed(&["run", "app", "-release", "--", "a", "b"]), + some("app", &["run", "release", "a", "b"]) + ); + assert_eq!( + parsed(&["-dump", "ll", "-release", "app"]), + some("app", &["ll", "release"]) + ); + assert_eq!( + parsed(&["check", "app", "-dump", "mir"]), + some("app", &["mir"]) + ); + assert_eq!( + parsed(&["-dump", "ll", "-dump", "thir"]), + some(".", &["thir", "ll"]) + ); + assert_eq!( + parsed(&["fix", "-dump", "mir", "app"]), + some("app", &["mir", "fix"]) + ); + } + + /// Each mistake is named. + #[test] + fn errors() { + let error = |args: &[&str]| { + let args: Vec = args.iter().map(|arg| arg.to_string()).collect(); + parse(&args).err() + }; + // It lists every target, so a new one changes it. + let unknown = Machine::named("arm").unwrap_err(); + assert!(unknown.starts_with("unknown target `arm`; the targets are x86_64-linux, ")); + for (args, wanted) in [ + (&[][..], "no command given"), + (&["app"], "unknown command `app`"), + (&["build", "-x"], "unknown flag -x"), + (&["run", "app", "-x"], "unknown flag -x"), + ( + &["build", "app", "-o"], + "-o needs the program's path after it", + ), + ( + &["build", "-o", "-release"], + "-o needs the program's path after it", + ), + (&["build", "-o", "a", "-o", "b"], "-o is given twice"), + ( + &["run", "-target"], + "-target needs a target's name after it", + ), + (&["build", "-target", "arm"], unknown.as_str()), + ( + &["run", "-target", "i686-linux", "-target", "i686-linux"], + "-target is given twice", + ), + ( + &["init", "-target", "i686-linux"], + "`init` does not take -target", + ), + (&["run", "-release", "-release"], "-release is given twice"), + ( + &["run", "-interpret", "-interpret"], + "-interpret is given twice", + ), + ( + &["run", "-interpret", "-release"], + "`run -interpret` does not take -release", + ), + ( + &["run", "-interpret", "--", "x"], + "`run -interpret` does not take --", + ), + ( + &["run", "-interpret", "-o", "out"], + "`run -interpret` does not take -o", + ), + (&["run", "-interpret", "a", "b"], "unexpected `b`"), + (&["build", "-interpret"], "`build` does not take -interpret"), + (&["check", "-interpret"], "`check` does not take -interpret"), + (&["-dump", "-interpret"], "`check` does not take -interpret"), + (&["-help", "-help"], "-help is given twice"), + (&["check", "-o", "out"], "`check` does not take -o"), + (&["check", "-release"], "`check` does not take -release"), + (&["run", "-dump"], "`run` does not take -dump"), + (&["run", "app", "-help"], "`run` does not take -help"), + (&["-help", "-release"], "`-help` does not take -release"), + (&["build", "app", "--", "x"], "`build` does not take --"), + (&["build", "a", "b"], "unexpected `b`"), + (&["run", "a", "b"], "unexpected `b`"), + // `ll` does not follow `-dump`, so it is the path. + (&["-dump", "-release", "ll", "app"], "unexpected `app`"), + (&["lsp", "app"], "unexpected `app`"), + (&["-help", "app"], "unexpected `app`"), + ] { + assert_eq!(error(args).as_deref(), Some(wanted), "{args:?}"); + } + } + + #[test] + fn run_on_the_interpreter() { + let interpreted = |path: &str| Some((path.to_string(), vec!["interpret".to_string()])); + assert_eq!(parsed(&["run", "-interpret"]), interpreted(".")); + assert_eq!(parsed(&["-interpret", "run", "app"]), interpreted("app")); + assert_eq!( + parsed(&["run", "-interpret", "-target", "i686-linux", "app"]), + interpreted("app") + ); + } +} diff --git a/crates/driver/peeper/src/args/tests.rs b/crates/driver/peeper/src/args/tests.rs deleted file mode 100644 index dbdcef79..00000000 --- a/crates/driver/peeper/src/args/tests.rs +++ /dev/null @@ -1,292 +0,0 @@ -use super::Args; -use super::parse; -use llvm::BuildMode; -use model::machine::Machine; - -use crate::driver::Goal; - -/// The path and dump extensions `args` ask for, with "fix" added for -/// `peeper fix`, `("lsp", [])` for `peeper lsp`, `("init", [name])` for -/// `peeper init`, or `None`. `build` and -/// `run` give "build" or "run", "release" for -release, then -o's value -/// or the arguments. -fn parsed(args: &[&str]) -> Option<(String, Vec)> { - let args: Vec = args.iter().map(|arg| arg.to_string()).collect(); - let (path, goal) = match parse(&args).ok()? { - Args::Program { path, goal, .. } => (path, goal), - Args::Lsp => return Some(("lsp".to_string(), Vec::new())), - Args::Help => return Some(("help".to_string(), Vec::new())), - Args::Init { name } => return Some(("init".to_string(), name.into_iter().collect())), - }; - match goal { - Goal::Check { - dumps, - apply_fixes, - mode, - } => { - let mut asked: Vec = dumps - .iter() - .map(|dump| dump.extension().to_string()) - .collect(); - asked.extend((mode == BuildMode::Release).then(|| "release".to_string())); - if apply_fixes { - asked.push("fix".to_string()); - } - Some((path.display().to_string(), asked)) - } - Goal::Build { output, mode } => { - let mut asked = vec!["build".to_string()]; - asked.extend((mode == BuildMode::Release).then(|| "release".to_string())); - asked.extend(output.map(|output| output.display().to_string())); - Some((path.display().to_string(), asked)) - } - Goal::Run { arguments, mode } => { - let release = (mode == BuildMode::Release).then(|| "release".to_string()); - let asked = ["run".to_string()] - .into_iter() - .chain(release) - .chain(arguments) - .collect(); - Some((path.display().to_string(), asked)) - } - Goal::Interpret => Some((path.display().to_string(), vec!["interpret".to_string()])), - } -} - -#[test] -fn commands() { - let some = |path: &str, asked: &[&str]| { - Some(( - path.to_string(), - asked.iter().map(|a| a.to_string()).collect(), - )) - }; - assert_eq!(parsed(&["check"]), some(".", &[])); - assert_eq!(parsed(&["check", "app"]), some("app", &[])); - assert_eq!(parsed(&["fix"]), some(".", &["fix"])); - assert_eq!(parsed(&["fix", "app"]), some("app", &["fix"])); - assert_eq!(parsed(&["-dump"]), some(".", &["thir", "mir", "ll"])); - assert_eq!(parsed(&["-dump", "mir"]), some(".", &["mir"])); - assert_eq!( - parsed(&["-dump", "app"]), - some("app", &["thir", "mir", "ll"]) - ); - assert_eq!(parsed(&["-dump", "thir", "app"]), some("app", &["thir"])); - assert_eq!( - parsed(&["-dump", "-release"]), - some(".", &["thir", "mir", "ll", "release"]) - ); - assert_eq!(parsed(&["build"]), some(".", &["build"])); - assert_eq!(parsed(&["build", "app"]), some("app", &["build"])); - assert_eq!( - parsed(&["build", "-o", "out"]), - some(".", &["build", "out"]) - ); - assert_eq!( - parsed(&["build", "-o", "out", "app"]), - some("app", &["build", "out"]) - ); - assert_eq!( - parsed(&["build", "-release", "-o", "out", "app"]), - some("app", &["build", "release", "out"]) - ); - assert_eq!(parsed(&["run"]), some(".", &["run"])); - assert_eq!(parsed(&["run", "--", "x"]), some(".", &["run", "x"])); - assert_eq!(parsed(&["run", "-release"]), some(".", &["run", "release"])); - assert_eq!( - parsed(&["run", "app", "--", "x", "-help"]), - some("app", &["run", "x", "-help"]) - ); - assert_eq!(parsed(&["-help"]), some("help", &[])); - assert_eq!(parsed(&["lsp"]), some("lsp", &[])); - assert_eq!(parsed(&["init"]), some("init", &[])); - assert_eq!(parsed(&["init", "app"]), some("init", &["app"])); - assert_eq!(parsed(&["check", "-target", "i686-linux"]), some(".", &[])); - assert_eq!( - parsed(&["-dump", "ll", "-target", "i686-linux", "app"]), - some("app", &["ll"]) - ); - assert_eq!( - parsed(&["build", "-target", "i686-linux", "-o", "out", "app"]), - some("app", &["build", "out"]) - ); - assert_eq!( - parsed(&["run", "-target", "i686-linux", "-release", "app", "--", "x"]), - some("app", &["run", "release", "x"]) - ); - for wrong in [ - &[][..], - &["build", "-o"], - &["build", "a", "b"], - &["run", "app", "x"], - &["run", "app", "-help"], - &["-help", "app"], - &["-dump", "asm", "app"], - &["check", "a", "b"], - &["fix", "a", "b"], - &["lsp", "app"], - &["init", "a", "b"], - ] { - assert_eq!(parsed(wrong), None, "{wrong:?}"); - } -} - -/// `-target` picks the target it names, and the host is the target -/// without it. -#[test] -fn targets() { - let target = |args: &[&str]| { - let args: Vec = args.iter().map(|arg| arg.to_string()).collect(); - match parse(&args) { - Ok(Args::Program { target, .. }) => target, - _ => panic!("{args:?} names a program"), - } - }; - let i686 = Machine::named("i686-linux").unwrap(); - assert_eq!(target(&["check", "-target", "i686-linux"]), i686); - assert_eq!( - target(&["-dump", "ll", "-target", "i686-linux", "app"]), - i686 - ); - assert_eq!( - target(&["build", "-target", "i686-linux", "-o", "out"]), - i686 - ); - assert_eq!( - target(&["run", "app", "-target", "i686-linux", "--", "x"]), - i686 - ); - assert_eq!(Ok(target(&["run", "app"])), Machine::host()); -} - -/// Flags come anywhere; the words left are the command and its value. -#[test] -fn flags_in_any_order() { - let some = |path: &str, asked: &[&str]| { - Some(( - path.to_string(), - asked.iter().map(|a| a.to_string()).collect(), - )) - }; - let release_build = some("app", &["build", "release", "out"]); - assert_eq!( - parsed(&["build", "-o", "out", "app", "-release"]), - release_build - ); - assert_eq!( - parsed(&["-release", "build", "app", "-o", "out"]), - release_build - ); - assert_eq!( - parsed(&["build", "app", "-release", "-o", "out"]), - release_build - ); - assert_eq!(parsed(&["run", "-release"]), some(".", &["run", "release"])); - assert_eq!( - parsed(&["run", "app", "-release", "--", "a", "b"]), - some("app", &["run", "release", "a", "b"]) - ); - assert_eq!( - parsed(&["-dump", "ll", "-release", "app"]), - some("app", &["ll", "release"]) - ); - assert_eq!( - parsed(&["check", "app", "-dump", "mir"]), - some("app", &["mir"]) - ); - assert_eq!( - parsed(&["-dump", "ll", "-dump", "thir"]), - some(".", &["thir", "ll"]) - ); - assert_eq!( - parsed(&["fix", "-dump", "mir", "app"]), - some("app", &["mir", "fix"]) - ); -} - -/// Each mistake is named. -#[test] -fn errors() { - let error = |args: &[&str]| { - let args: Vec = args.iter().map(|arg| arg.to_string()).collect(); - parse(&args).err() - }; - // It lists every target, so a new one changes it. - let unknown = Machine::named("arm").unwrap_err(); - assert!(unknown.starts_with("unknown target `arm`; the targets are x86_64-linux, ")); - for (args, wanted) in [ - (&[][..], "no command given"), - (&["app"], "unknown command `app`"), - (&["build", "-x"], "unknown flag -x"), - (&["run", "app", "-x"], "unknown flag -x"), - ( - &["build", "app", "-o"], - "-o needs the program's path after it", - ), - ( - &["build", "-o", "-release"], - "-o needs the program's path after it", - ), - (&["build", "-o", "a", "-o", "b"], "-o is given twice"), - ( - &["run", "-target"], - "-target needs a target's name after it", - ), - (&["build", "-target", "arm"], unknown.as_str()), - ( - &["run", "-target", "i686-linux", "-target", "i686-linux"], - "-target is given twice", - ), - ( - &["init", "-target", "i686-linux"], - "`init` does not take -target", - ), - (&["run", "-release", "-release"], "-release is given twice"), - ( - &["run", "-interpret", "-interpret"], - "-interpret is given twice", - ), - ( - &["run", "-interpret", "-release"], - "`run -interpret` does not take -release", - ), - ( - &["run", "-interpret", "--", "x"], - "`run -interpret` does not take --", - ), - ( - &["run", "-interpret", "-o", "out"], - "`run -interpret` does not take -o", - ), - (&["run", "-interpret", "a", "b"], "unexpected `b`"), - (&["build", "-interpret"], "`build` does not take -interpret"), - (&["check", "-interpret"], "`check` does not take -interpret"), - (&["-dump", "-interpret"], "`check` does not take -interpret"), - (&["-help", "-help"], "-help is given twice"), - (&["check", "-o", "out"], "`check` does not take -o"), - (&["check", "-release"], "`check` does not take -release"), - (&["run", "-dump"], "`run` does not take -dump"), - (&["run", "app", "-help"], "`run` does not take -help"), - (&["-help", "-release"], "`-help` does not take -release"), - (&["build", "app", "--", "x"], "`build` does not take --"), - (&["build", "a", "b"], "unexpected `b`"), - (&["run", "a", "b"], "unexpected `b`"), - // `ll` does not follow `-dump`, so it is the path. - (&["-dump", "-release", "ll", "app"], "unexpected `app`"), - (&["lsp", "app"], "unexpected `app`"), - (&["-help", "app"], "unexpected `app`"), - ] { - assert_eq!(error(args).as_deref(), Some(wanted), "{args:?}"); - } -} - -#[test] -fn run_on_the_interpreter() { - let interpreted = |path: &str| Some((path.to_string(), vec!["interpret".to_string()])); - assert_eq!(parsed(&["run", "-interpret"]), interpreted(".")); - assert_eq!(parsed(&["-interpret", "run", "app"]), interpreted("app")); - assert_eq!( - parsed(&["run", "-interpret", "-target", "i686-linux", "app"]), - interpreted("app") - ); -} diff --git a/crates/driver/peeper/src/driver.rs b/crates/driver/peeper/src/driver.rs index d6026559..c0b3c65e 100644 --- a/crates/driver/peeper/src/driver.rs +++ b/crates/driver/peeper/src/driver.rs @@ -79,11 +79,7 @@ impl Command { } // Read and parse every module, following imports. No editor has // unsaved text here, so every file is read from disk. - let program = project::load( - &project, - &HashMap::::new(), - &features::RULES, - ); + let program = project::load(&project, &HashMap::::new()); match goal { Goal::Check { dumps, @@ -316,4 +312,216 @@ pub fn installation_dir() -> Result { } #[cfg(test)] -mod tests; +mod tests { + use std::path::Path; + use std::path::PathBuf; + + use super::Command; + use super::Goal; + use llvm::BuildMode; + use model::machine::Machine; + use project::path_text; + + fn temp_dir(test: &str) -> PathBuf { + let root = std::env::temp_dir().join(format!("peeper-check-{}-{test}", std::process::id())); + _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + root + } + + fn write(root: &Path, files: &[(&str, &[u8])]) { + for (name, text) in files { + let file = root.join(name); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(file, text).unwrap(); + } + } + + /// Checks `path` with the libraries of `installation`; gives the exit + /// code and what was printed. + fn checked(path: &Path, installation: &Path) -> (u8, String) { + let mut command = Command { + path: path.to_path_buf(), + target: Machine::host().unwrap(), + installation: installation.to_path_buf(), + out: Vec::new(), + colored: false, + }; + let check = Goal::Check { + dumps: Vec::new(), + apply_fixes: false, + mode: BuildMode::Debug, + }; + let code = command.execute(&check); + (code, String::from_utf8(command.out).unwrap()) + } + + /// `peeper fix` writes the suggested fixes, lists them top down, and + /// reports only the errors left, which have no fix. + #[test] + fn fixes_a_file() { + let root = temp_dir("fix"); + let text = b"fn main() {\n let count = 1;\n let a = cout\n let b = gone;\n}\n"; + write(&root, &[("app.peep", text)]); + let file = root.join("app.peep"); + let mut command = Command { + path: file.clone(), + target: Machine::host().unwrap(), + installation: PathBuf::new(), + out: Vec::new(), + colored: false, + }; + let fix = Goal::Check { + dumps: Vec::new(), + apply_fixes: true, + mode: BuildMode::Debug, + }; + let code = command.execute(&fix); + let out = String::from_utf8(command.out).unwrap(); + let fixed = std::fs::read_to_string(&file).unwrap(); + assert_eq!( + fixed, + "fn main() {\n let count = 1;\n let a = cout;\n let b = gone;\n}\n" + ); + let first = format!("fixed {}:3:17: ", path_text(&file)); + assert!(out.starts_with(&first), "{out}"); + assert!(out.contains("unknown name `gone`"), "{out}"); + assert_eq!(code, 1, "`gone` has no fix"); + } + + #[test] + fn checks_a_project() { + let root = temp_dir("project"); + write( + &root, + &[ + ("app/peeper.toml", b"name = \"myapp\""), + ( + "app/src/main.peep", + b"import \"myapp:util\";\nimport \"myapp:gone\";\nfn main() {}", + ), + ("app/src/util.peep", b"fn Util() {}"), + ("libs/core/peeper.toml", b"name = \"core\"\nbuild = \"lib\""), + ("libs/core/src/global.peep", b""), + ], + ); + let (code, out) = checked(&root.join("app"), &root); + let gone = root.join("app/src/gone.peep"); + let main = root.join("app/src/main.peep"); + let want = format!( + "[M0001]: module not found: {}\n --> {}:2:1\n", + path_text(&gone), + path_text(&main) + ); + assert_eq!(code, 1); + assert!( + out.starts_with(&want) && out.ends_with("Compilation failed with 1 error(s)\n"), + "{out}" + ); + + write( + &root, + &[("app/src/main.peep", b"import \"myapp:util\";\nfn main() {}")], + ); + assert_eq!(checked(&root.join("app"), &root), (0, String::new())); + } + + #[test] + fn checks_a_single_file() { + let root = temp_dir("single"); + write( + &root, + &[ + ("tool.peep", b"fn main() {}"), + ("bad.peep", b"fn main() { a $ b; }\n"), + ], + ); + assert_eq!( + checked(&root.join("tool.peep"), Path::new("")), + (0, String::new()) + ); + let (code, out) = checked(&root.join("bad.peep"), Path::new("")); + assert_eq!(code, 1); + assert!( + out.starts_with("[L0001]: illegal character \"$\"\n"), + "{out}" + ); + + write(&root, &[("invalid.peep", b"fn f() {}\n// \xff\n")]); + let (code, out) = checked(&root.join("invalid.peep"), Path::new("")); + assert_eq!(code, 1); + assert!( + out.starts_with("[L0001]: file is not valid UTF-8\n") && out.contains(":2:4\n"), + "{out}" + ); + assert_eq!(checked(&root.join("missing.peep"), Path::new("")).0, 1); + } + + #[test] + fn folder_errors() { + let root = temp_dir("folders"); + write( + &root, + &[ + ("core/peeper.toml", b"name = \"core\""), + ("libs/core/peeper.toml", b"name = \"core\"\nbuild = \"lib\""), + ("libs/core/src/x.peep", b""), + ("empty/x", b""), + ], + ); + for (folder, want) in [ + ("empty", "no peeper.toml in this folder"), + ("core", "project name `core` is taken by a bundled library"), + ] { + let (code, out) = checked(&root.join(folder), &root); + assert!(code == 1 && out.contains(want), "{folder}: {code} {out}"); + } + } + + /// `build` and `run` need the entry file's `fn main()` or `fn main() -> + /// i32`, and report it before linking; `check` does not. + #[test] + fn needs_an_entry_point() { + let root = temp_dir("entry"); + write( + &root, + &[ + ("none.peep", b"fn helper() {}\n"), + ("bodyless.peep", b"#[extern(\"start\")]\nfn main();\n"), + ("takes.peep", b"fn main(x: i32) {}\n"), + ("wide.peep", b"fn main() -> i64 { return 0; }\n"), + ], + ); + for (file, at) in [ + ("none.peep", ":1:1"), + ("bodyless.peep", ":1:1"), + ("takes.peep", ":1:4"), + ("wide.peep", ":1:4"), + ] { + let path = root.join(file); + let mut command = Command { + path: path.clone(), + target: Machine::host().unwrap(), + installation: PathBuf::new(), + out: Vec::new(), + colored: false, + }; + let code = command.execute(&Goal::Build { + output: None, + mode: BuildMode::Debug, + }); + let out = String::from_utf8(command.out).unwrap(); + assert_eq!(code, 1, "{file}: {out}"); + assert!( + out.starts_with("[M0006]: program entrypoint must be") + && out.contains(&format!("{}{at}\n", path_text(&path))), + "{file}: {out}" + ); + assert_eq!( + checked(&path, Path::new("")).0, + 0, + "{file}: check needs no main" + ); + } + } +} diff --git a/crates/driver/peeper/src/driver/tests.rs b/crates/driver/peeper/src/driver/tests.rs deleted file mode 100644 index bba7acfc..00000000 --- a/crates/driver/peeper/src/driver/tests.rs +++ /dev/null @@ -1,211 +0,0 @@ -use std::path::Path; -use std::path::PathBuf; - -use super::Command; -use super::Goal; -use llvm::BuildMode; -use model::machine::Machine; -use project::path_text; - -fn temp_dir(test: &str) -> PathBuf { - let root = std::env::temp_dir().join(format!("peeper-check-{}-{test}", std::process::id())); - _ = std::fs::remove_dir_all(&root); - std::fs::create_dir_all(&root).unwrap(); - root -} - -fn write(root: &Path, files: &[(&str, &[u8])]) { - for (name, text) in files { - let file = root.join(name); - std::fs::create_dir_all(file.parent().unwrap()).unwrap(); - std::fs::write(file, text).unwrap(); - } -} - -/// Checks `path` with the libraries of `installation`; gives the exit -/// code and what was printed. -fn checked(path: &Path, installation: &Path) -> (u8, String) { - let mut command = Command { - path: path.to_path_buf(), - target: Machine::host().unwrap(), - installation: installation.to_path_buf(), - out: Vec::new(), - colored: false, - }; - let check = Goal::Check { - dumps: Vec::new(), - apply_fixes: false, - mode: BuildMode::Debug, - }; - let code = command.execute(&check); - (code, String::from_utf8(command.out).unwrap()) -} - -/// `peeper fix` writes the suggested fixes, lists them top down, and -/// reports only the errors left, which have no fix. -#[test] -fn fixes_a_file() { - let root = temp_dir("fix"); - let text = b"fn main() {\n let count = 1;\n let a = cout\n let b = gone;\n}\n"; - write(&root, &[("app.peep", text)]); - let file = root.join("app.peep"); - let mut command = Command { - path: file.clone(), - target: Machine::host().unwrap(), - installation: PathBuf::new(), - out: Vec::new(), - colored: false, - }; - let fix = Goal::Check { - dumps: Vec::new(), - apply_fixes: true, - mode: BuildMode::Debug, - }; - let code = command.execute(&fix); - let out = String::from_utf8(command.out).unwrap(); - let fixed = std::fs::read_to_string(&file).unwrap(); - assert_eq!( - fixed, - "fn main() {\n let count = 1;\n let a = cout;\n let b = gone;\n}\n" - ); - let first = format!("fixed {}:3:17: ", path_text(&file)); - assert!(out.starts_with(&first), "{out}"); - assert!(out.contains("unknown name `gone`"), "{out}"); - assert_eq!(code, 1, "`gone` has no fix"); -} - -#[test] -fn checks_a_project() { - let root = temp_dir("project"); - write( - &root, - &[ - ("app/peeper.toml", b"name = \"myapp\""), - ( - "app/src/main.peep", - b"import \"myapp:util\";\nimport \"myapp:gone\";\nfn main() {}", - ), - ("app/src/util.peep", b"fn Util() {}"), - ("libs/core/peeper.toml", b"name = \"core\"\nbuild = \"lib\""), - ("libs/core/src/global.peep", b""), - ], - ); - let (code, out) = checked(&root.join("app"), &root); - let gone = root.join("app/src/gone.peep"); - let main = root.join("app/src/main.peep"); - let want = format!( - "[M0001]: module not found: {}\n --> {}:2:1\n", - path_text(&gone), - path_text(&main) - ); - assert_eq!(code, 1); - assert!( - out.starts_with(&want) && out.ends_with("Compilation failed with 1 error(s)\n"), - "{out}" - ); - - write( - &root, - &[("app/src/main.peep", b"import \"myapp:util\";\nfn main() {}")], - ); - assert_eq!(checked(&root.join("app"), &root), (0, String::new())); -} - -#[test] -fn checks_a_single_file() { - let root = temp_dir("single"); - write( - &root, - &[ - ("tool.peep", b"fn main() {}"), - ("bad.peep", b"fn main() { a $ b; }\n"), - ], - ); - assert_eq!( - checked(&root.join("tool.peep"), Path::new("")), - (0, String::new()) - ); - let (code, out) = checked(&root.join("bad.peep"), Path::new("")); - assert_eq!(code, 1); - assert!( - out.starts_with("[L0001]: illegal character \"$\"\n"), - "{out}" - ); - - write(&root, &[("invalid.peep", b"fn f() {}\n// \xff\n")]); - let (code, out) = checked(&root.join("invalid.peep"), Path::new("")); - assert_eq!(code, 1); - assert!( - out.starts_with("[L0001]: file is not valid UTF-8\n") && out.contains(":2:4\n"), - "{out}" - ); - assert_eq!(checked(&root.join("missing.peep"), Path::new("")).0, 1); -} - -#[test] -fn folder_errors() { - let root = temp_dir("folders"); - write( - &root, - &[ - ("core/peeper.toml", b"name = \"core\""), - ("libs/core/peeper.toml", b"name = \"core\"\nbuild = \"lib\""), - ("libs/core/src/x.peep", b""), - ("empty/x", b""), - ], - ); - for (folder, want) in [ - ("empty", "no peeper.toml in this folder"), - ("core", "project name `core` is taken by a bundled library"), - ] { - let (code, out) = checked(&root.join(folder), &root); - assert!(code == 1 && out.contains(want), "{folder}: {code} {out}"); - } -} - -/// `build` and `run` need the entry file's `fn main()` or `fn main() -> -/// i32`, and report it before linking; `check` does not. -#[test] -fn needs_an_entry_point() { - let root = temp_dir("entry"); - write( - &root, - &[ - ("none.peep", b"fn helper() {}\n"), - ("bodyless.peep", b"#[extern(\"start\")]\nfn main();\n"), - ("takes.peep", b"fn main(x: i32) {}\n"), - ("wide.peep", b"fn main() -> i64 { return 0; }\n"), - ], - ); - for (file, at) in [ - ("none.peep", ":1:1"), - ("bodyless.peep", ":1:1"), - ("takes.peep", ":1:4"), - ("wide.peep", ":1:4"), - ] { - let path = root.join(file); - let mut command = Command { - path: path.clone(), - target: Machine::host().unwrap(), - installation: PathBuf::new(), - out: Vec::new(), - colored: false, - }; - let code = command.execute(&Goal::Build { - output: None, - mode: BuildMode::Debug, - }); - let out = String::from_utf8(command.out).unwrap(); - assert_eq!(code, 1, "{file}: {out}"); - assert!( - out.starts_with("[M0006]: program entrypoint must be") - && out.contains(&format!("{}{at}\n", path_text(&path))), - "{file}: {out}" - ); - assert_eq!( - checked(&path, Path::new("")).0, - 0, - "{file}: check needs no main" - ); - } -} diff --git a/crates/driver/project/Cargo.toml b/crates/driver/project/Cargo.toml index 42a1c8ff..83d9d83a 100644 --- a/crates/driver/project/Cargo.toml +++ b/crates/driver/project/Cargo.toml @@ -11,12 +11,11 @@ source.workspace = true diagnostics.workspace = true literal.workspace = true model.workspace = true -syntax.workspace = true +tree.workspace = true parser.workspace = true toml_edit.workspace = true [dev-dependencies] -features.workspace = true [lints] workspace = true diff --git a/crates/driver/project/src/lib.rs b/crates/driver/project/src/lib.rs index 3d372e6f..3e999b26 100644 --- a/crates/driver/project/src/lib.rs +++ b/crates/driver/project/src/lib.rs @@ -27,7 +27,6 @@ use packages::SOURCE_EXTENSION; use packages::file_of; use packages::import_path_of; use packages::is_source_file; -use parser::Rules; use crate::loading::Job; use crate::loading::load_module; @@ -257,13 +256,8 @@ pub fn library_packages( /// reads as text, such as a `String`), read instead of what is on disk. Its /// keys, like `project`'s paths, are spelled as `canonical_path` spells them. /// Each `.peep` file of a package in it is loaded too, imported or not, so an -/// editor checks the file it has open. `rules` are the core's and each -/// feature's, which every module is parsed with. -pub fn load( - project: &Project, - open_files: &HashMap + Sync>, - rules: &'static Rules, -) -> Program { +/// editor checks the file it has open. +pub fn load(project: &Project, open_files: &HashMap + Sync>) -> Program { let with_prelude = file_of(&project.packages, PRELUDE_PATH) .is_some_and(|file| file.is_file() || open_files.contains_key(&file)); let workers = if cfg!(target_family = "wasm") { @@ -313,7 +307,7 @@ pub fn load( // A panic goes to the main thread, which would // otherwise wait for this module forever. let loaded = std::panic::catch_unwind(AssertUnwindSafe(|| { - load_module(&project.packages, open_files, rules, job, with_prelude) + load_module(&project.packages, open_files, job, with_prelude) })); _ = send_module.send(loaded); } @@ -348,7 +342,7 @@ pub fn load( let loaded = if workers == 0 { let job = jobs.lock().expect("no worker holds the lock").try_recv(); let job = job.expect("each pending module has a job"); - load_module(&project.packages, open_files, rules, job, with_prelude) + load_module(&project.packages, open_files, job, with_prelude) } else { // This thread holds `send_module`, so a receive always ends. let loaded = done.recv().expect("this thread holds a sender"); diff --git a/crates/driver/project/src/loading.rs b/crates/driver/project/src/loading.rs index 95b0d6b2..90d9b445 100644 --- a/crates/driver/project/src/loading.rs +++ b/crates/driver/project/src/loading.rs @@ -15,10 +15,9 @@ use model::program::Import; use model::program::ImportKind; use model::program::Module; use model::program::default_alias; -use parser::Rules; use source::SourceFile; use source::Span; -use syntax::ast::Tree; +use tree::ast::Tree; use crate::PRELUDE_PATH; use crate::packages::SOURCE_EXTENSION; @@ -41,13 +40,12 @@ pub(crate) struct Job { pub(crate) standalone: bool, // a file in no package, checked on its own: it cannot import } -/// Reads, parses with `rules` and resolves the imports of one module, taking +/// Reads, parses and resolves the imports of one module, taking /// its text from `open_files` when it is open there. A file that cannot be /// read, or is not UTF-8, gets an empty tree and one error. pub(crate) fn load_module( packages: &HashMap, open_files: &HashMap>, - rules: &'static Rules, job: Job, with_prelude: bool, ) -> Loaded { @@ -64,7 +62,7 @@ pub(crate) fn load_module( text => text, }; let (ast, diagnostics) = match text.map(String::from_utf8) { - Ok(Ok(text)) => parser::parse(&Arc::new(SourceFile::new(path, text)), rules), + Ok(Ok(text)) => parser::parse(&Arc::new(SourceFile::new(path, text))), Ok(Err(error)) => { // The text up to the bad byte is kept as is, so the error points at it. let at = error.utf8_error().valid_up_to(); diff --git a/crates/driver/project/src/tests.rs b/crates/driver/project/src/tests.rs index 88382b36..f73cedc5 100644 --- a/crates/driver/project/src/tests.rs +++ b/crates/driver/project/src/tests.rs @@ -192,11 +192,7 @@ fn a_library_loads_each_of_its_files() { std::os::unix::fs::symlink(&root, root.join("src/back")).unwrap(); let project = find(&root, &root.join("libs")).unwrap(); assert_eq!(project.entry, None); - let program = load( - &project, - &HashMap::::new(), - &features::RULES, - ); + let program = load(&project, &HashMap::::new()); assert_eq!(messages(&program), Vec::::new()); assert_eq!(order(&program), ["tools:a", "tools:deep/b"]); assert_eq!(program.entry, None); @@ -214,7 +210,7 @@ fn a_library_without_files_is_an_error() { .root; let project = find(&root, &root.join("libs")).unwrap(); let none = HashMap::::new(); - let missing = load(&project, &none, &features::RULES); + let missing = load(&project, &none); let got = messages(&missing); assert!( got.len() == 1 && got[0].starts_with("program: M0001 read library: "), @@ -223,14 +219,14 @@ fn a_library_without_files_is_an_error() { assert!(!missing.checkable); std::fs::create_dir(root.join("src")).unwrap(); let source = path_text(&root.join("src")); - let empty = load(&project, &none, &features::RULES); + let empty = load(&project, &none); assert_eq!( messages(&empty), [format!("program: M0001 no source files in {source}")] ); std::fs::remove_dir(root.join("src")).unwrap(); let open = HashMap::from([(root.join("src/a.peep"), "fn A() {}".to_string())]); - let program = load(&project, &open, &features::RULES); + let program = load(&project, &open); assert_eq!(messages(&program), Vec::::new()); assert_eq!(order(&program), ["tools:a"]); } @@ -343,11 +339,7 @@ fn loads_nested_imports() { ("libs/core/src/global.peep", "fn Exit(code: i32) {}"), ], ); - let program = load( - &project, - &HashMap::::new(), - &features::RULES, - ); + let program = load(&project, &HashMap::::new()); assert_eq!(messages(&program), Vec::::new()); assert_eq!( order(&program).join(" "), @@ -373,11 +365,7 @@ fn loads_a_module_with_a_dot_in_its_name() { ("src/a.b.peep", "fn X() {}"), ], ); - let program = load( - &project, - &HashMap::::new(), - &features::RULES, - ); + let program = load(&project, &HashMap::::new()); assert_eq!(messages(&program), Vec::::new()); assert_eq!(order(&program).join(" "), "myapp:a.b myapp:main"); } @@ -409,11 +397,7 @@ fn import_errors() { ("src/c.peep", ""), ], ); - let program = load( - &project, - &HashMap::::new(), - &features::RULES, - ); + let program = load(&project, &HashMap::::new()); let missing = project.root.join("src/missing.peep"); let parts = "myapp:main: M0003 import path parts cannot be empty, `.` or `..`, or hold `\\` or `:`" @@ -452,11 +436,7 @@ fn import_errors() { fn guesses_a_missing_module_but_not_itself() { let main = "import \"myapp:shapez\";\nimport \"myapp:mainn\";\nfn main() {}"; let project = write("guess", &[("src/main.peep", main), ("src/shapes.peep", "")]); - let program = load( - &project, - &HashMap::::new(), - &features::RULES, - ); + let program = load(&project, &HashMap::::new()); let guesses: Vec<&str> = program .diagnostics .iter() @@ -471,11 +451,7 @@ fn reports_imports_at_their_line() { "line", &[("src/main.peep", "fn main() {}\nimport \"myapp:missing\";\n")], ); - let program = load( - &project, - &HashMap::::new(), - &features::RULES, - ); + let program = load(&project, &HashMap::::new()); let main = module_named(&program, "myapp:main"); assert_eq!(program.diagnostics.len(), 1, "{:?}", messages(&program)); let label = &program.diagnostics[0].labels[0]; @@ -513,11 +489,7 @@ fn reports_a_cycle_with_each_import() { ("src/b.peep", r#"import "myapp:a";"#), ], ); - let program = load( - &project, - &HashMap::::new(), - &features::RULES, - ); + let program = load(&project, &HashMap::::new()); assert_eq!( messages(&program), ["myapp:a: M0002 modules import each other in a cycle"] @@ -543,11 +515,7 @@ fn a_cycle_through_the_prelude_is_reported_once() { ("libs/core/src/x.peep", r#"import "core:global";"#), ], ); - let program = load( - &project, - &HashMap::::new(), - &features::RULES, - ); + let program = load(&project, &HashMap::::new()); assert_eq!( cycle_steps(&program), [ @@ -568,11 +536,7 @@ fn a_cycle_through_the_implicit_prelude_import_notes_it() { ("libs/core/src/x.peep", "fn F() {}"), ], ); - let program = load( - &project, - &HashMap::::new(), - &features::RULES, - ); + let program = load(&project, &HashMap::::new()); assert_eq!( cycle_steps(&program), [ @@ -591,11 +555,7 @@ fn redundant_prelude_import() { ("libs/core/src/global.peep", ""), ], ); - let program = load( - &project, - &HashMap::::new(), - &features::RULES, - ); + let program = load(&project, &HashMap::::new()); assert_eq!( messages(&program), ["myapp:main: S0004 `core:global` is imported automatically"] @@ -617,11 +577,7 @@ fn a_single_file_cannot_import() { ], ); project.entry = Some(project.root.join("tool.peep")); - let program = load( - &project, - &HashMap::::new(), - &features::RULES, - ); + let program = load(&project, &HashMap::::new()); assert_eq!( messages(&program), ["tool: M0003 a single file cannot import; check its project folder instead"] @@ -637,22 +593,14 @@ fn a_single_file_cannot_import() { fn unreadable_and_non_utf8_entries() { let mut project = write("unreadable", &[("src/bad.peep", "fn \u{0} main")]); std::fs::write(project.root.join("src/bad.peep"), b"fn \xff main() {}").unwrap(); - let program = load( - &project, - &HashMap::::new(), - &features::RULES, - ); + let program = load(&project, &HashMap::::new()); let got = messages(&program); assert!( got.len() == 1 && got[0].starts_with("program: M0001 read module: "), "{got:?}" ); project.entry = Some(project.root.join("src/bad.peep")); - let program = load( - &project, - &HashMap::::new(), - &features::RULES, - ); + let program = load(&project, &HashMap::::new()); assert_eq!( messages(&program), ["myapp:bad: L0001 file is not valid UTF-8"] @@ -678,7 +626,7 @@ fn orders_a_long_import_chain() { project.root.join("src/main.peep"), "import \"myapp:m0\";".to_string(), ); - let program = load(&project, &open_files, &features::RULES); + let program = load(&project, &open_files); assert_eq!(messages(&program), Vec::::new()); assert_eq!(order(&program).last(), Some(&"myapp:main")); } @@ -703,11 +651,7 @@ fn loads_many_modules_in_a_stable_order() { .map(|(n, t)| (n.as_str(), t.as_str())) .collect(); let project = write("many", &files); - let first = load( - &project, - &HashMap::::new(), - &features::RULES, - ); + let first = load(&project, &HashMap::::new()); assert!(messages(&first).is_empty()); assert_eq!(first.modules.len(), 202); for (index, module) in first.modules.iter().enumerate() { @@ -722,11 +666,7 @@ fn loads_many_modules_in_a_stable_order() { } for _ in 0..5 { assert_eq!( - order(&load( - &project, - &HashMap::::new(), - &features::RULES - )), + order(&load(&project, &HashMap::::new())), order(&first), "order differs between runs" ); @@ -749,7 +689,7 @@ fn open_files_win_over_disk() { ), (project.root.join("src/b.peep"), "fn B() {}".to_string()), // not on disk ]); - let program = load(&project, &open_files, &features::RULES); + let program = load(&project, &open_files); assert_eq!(messages(&program), Vec::::new()); assert_eq!(module_named(&program, "myapp:b").ast.file.text, "fn B() {}"); } diff --git a/crates/kernel/eval/Cargo.toml b/crates/eval/Cargo.toml similarity index 100% rename from crates/kernel/eval/Cargo.toml rename to crates/eval/Cargo.toml diff --git a/crates/kernel/eval/src/interpreter.rs b/crates/eval/src/interpreter.rs similarity index 100% rename from crates/kernel/eval/src/interpreter.rs rename to crates/eval/src/interpreter.rs diff --git a/crates/kernel/eval/src/interpreter/instructions.rs b/crates/eval/src/interpreter/instructions.rs similarity index 69% rename from crates/kernel/eval/src/interpreter/instructions.rs rename to crates/eval/src/interpreter/instructions.rs index 23c3ee8f..3bdc7ece 100644 --- a/crates/kernel/eval/src/interpreter/instructions.rs +++ b/crates/eval/src/interpreter/instructions.rs @@ -5,17 +5,9 @@ use std::borrow::Cow; use arena::Id; use bigint::Limbs; -use model::mir::Class; -use model::mir::Conversion; -use model::mir::Instruction; -use model::mir::InstructionKind; -use model::mir::Operand; -use model::mir::Place; -use model::mir::Root; -use model::mir::Step; +use model::mir; use crate::operations; -use crate::operations::RegisterValue; use super::ADDRESS_NOT_KNOWN; use super::Halt; @@ -24,18 +16,25 @@ use super::Interpreter; impl Interpreter<'_, '_> { /// Runs the instruction `id`, giving its value, if it has one. - pub(super) fn run_instruction(&mut self, id: Id) -> Result, Halt> { + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] + pub(super) fn run_instruction( + &mut self, + id: Id, + ) -> Result, Halt> { let body = self.frame().body; let at = self.first_value + id.index(); let value = match &body.instructions[id].kind { - &InstructionKind::Integer { + &mir::InstructionKind::Integer { operation, class, left, right, } => { // Only `rawptr + usize` works on the pointer class. - if class == Class::Pointer && self.memory.is_constant() { + if class == mir::Class::Pointer && self.memory.is_constant() { let message = "a pointer offset cannot run at compile time, \ as it could read an address"; return Err(self.fail(message, self.span_of(id))); @@ -45,19 +44,19 @@ impl Interpreter<'_, '_> { let value = value.map_err(|message| self.fail(message, self.span_of(id)))?; self.hold(at, value) } - &InstructionKind::Float { + &mir::InstructionKind::Float { operation, class, left, right, } => operations::float(operation, class, self.operand(left), self.operand(right)), - &InstructionKind::Compare { + &mir::InstructionKind::Compare { comparison, class, left, right, } => { - if class == Class::Pointer + if class == mir::Class::Pointer && self.memory.is_constant() && self.operand(left) != 0 && self.operand(right) != 0 @@ -68,15 +67,15 @@ impl Interpreter<'_, '_> { let bits = self.class_bits(class); u128::from(operations::compare(comparison, class, bits, &left, &right)) } - &InstructionKind::Convert { - conversion, + &mir::InstructionKind::Convert { + cast, from, to, value, } => { // `none` stays `none`; any other address could reach an // address's bytes. - if conversion == Conversion::PointerCast + if cast == mir::Cast::PointerCast && self.memory.is_constant() && self.operand(value) != 0 { @@ -86,20 +85,20 @@ impl Interpreter<'_, '_> { } let (from_bits, to_bits) = (self.class_bits(from), self.class_bits(to)); let value = self.register(from, value); - let value = operations::convert(conversion, from, from_bits, to, to_bits, &value); + let value = operations::convert(cast, from, from_bits, to, to_bits, &value); self.hold(at, value) } - InstructionKind::Load { class, place } => { + mir::InstructionKind::Load { class, place } => { let address = self.address(place, id)?; - if let Class::Wide(bits) = *class { + if let mir::Class::Wide(bits) = *class { let size = u64::from(bits.div_ceil(8)); // as `store` keeps it let value = Limbs::from_le_bytes(bits, self.read_bytes(address, size, id)?); - self.hold(at, RegisterValue::Wide(Cow::Owned(value))) + self.hold(at, operations::RegisterValue::Wide(Cow::Owned(value))) } else { self.load(*class, address, id)? } } - InstructionKind::Store { + mir::InstructionKind::Store { class, place, value, @@ -109,25 +108,24 @@ impl Interpreter<'_, '_> { self.store(*class, address, value, id)?; return Ok(None); } - InstructionKind::Copy { to, from, size } => { + mir::InstructionKind::Copy { to, from, size } => { let (to, from) = (self.address(to, id)?, self.address(from, id)?); self.count_copy(*size, id)?; let copied = self.memory.copy(from, to, *size); copied.ok_or_else(|| self.fail(INVALID_ACCESS, self.span_of(id)))?; return Ok(None); } - InstructionKind::Address { place, .. } | InstructionKind::Borrow { place, .. } => { - u128::from(self.address(place, id)?) - } - InstructionKind::Call { .. } => unreachable!("`run_frames` runs a call"), - InstructionKind::Check { failed, message } => { + mir::InstructionKind::Address { place, .. } + | mir::InstructionKind::Borrow { place, .. } => u128::from(self.address(place, id)?), + mir::InstructionKind::Call { .. } => unreachable!("`run_frames` runs a call"), + mir::InstructionKind::Check { failed, message } => { if self.operand(*failed) != 0 { return Err(self.fail(&**message, self.span_of(id))); } return Ok(None); } - InstructionKind::Moved { .. } => return Ok(None), - InstructionKind::Dead(slot) => { + mir::InstructionKind::Moved { .. } => return Ok(None), + mir::InstructionKind::Dead(slot) => { // A program's frame keeps no slot starts: its slots stay put. let started = self.frame_mut().slots.get_mut(slot.index()); if let Some(started) = started.and_then(Option::take) { @@ -140,21 +138,21 @@ impl Interpreter<'_, '_> { } /// What `operand`, of `class`, holds. - fn register(&self, class: Class, operand: Operand) -> RegisterValue<'_> { + fn register(&self, class: mir::Class, operand: mir::Operand) -> operations::RegisterValue<'_> { match class { - Class::Wide(_) => { - RegisterValue::Wide(Cow::Borrowed(&self.wides[self.operand(operand) as usize])) - } - _ => RegisterValue::Narrow(self.operand(operand)), + mir::Class::Wide(_) => operations::RegisterValue::Wide(Cow::Borrowed( + &self.wides[self.operand(operand) as usize], + )), + _ => operations::RegisterValue::Narrow(self.operand(operand)), } } /// The register at `at` holding `value`: a wide value is kept in /// `wides` at `at`. - pub(super) fn hold(&mut self, at: usize, value: RegisterValue) -> u128 { + pub(super) fn hold(&mut self, at: usize, value: operations::RegisterValue) -> u128 { match value { - RegisterValue::Narrow(value) => value, - RegisterValue::Wide(limbs) => { + operations::RegisterValue::Narrow(value) => value, + operations::RegisterValue::Wide(limbs) => { if self.wides.len() <= at { self.wides.resize(at + 1, Limbs::new(0, &[])); } @@ -168,18 +166,22 @@ impl Interpreter<'_, '_> { /// pointer at each `Through`. A sum wraps at the pointer's width, as /// any number a raw pointer holds may be wrong: the access that follows /// is what refuses it. - pub(super) fn address(&mut self, place: &Place, id: Id) -> Result { + pub(super) fn address( + &mut self, + place: &mir::Place, + id: Id, + ) -> Result { let mut address = match place.root { - Root::Slot(slot) => self.slot_address(slot, id)?, - Root::At(operand) => self.operand(operand) as u64, - Root::Result => self.registers[self.first_register] as u64, + mir::Root::Slot(slot) => self.slot_address(slot, id)?, + mir::Root::At(operand) => self.operand(operand) as u64, + mir::Root::Result => self.registers[self.first_register] as u64, }; let wrap = operations::mask(self.target.pointer_bits) as u64; for &step in &place.steps { address = match step { - Step::Offset(bytes) => address.wrapping_add(bytes) & wrap, - Step::Through => self.load(Class::Pointer, address, id)? as u64, - Step::Index { index, size, .. } => { + mir::Step::Offset(bytes) => address.wrapping_add(bytes) & wrap, + mir::Step::Through => self.load(mir::Class::Pointer, address, id)? as u64, + mir::Step::Index { index, size, .. } => { let offset = (self.operand(index) as u64).wrapping_mul(size); address.wrapping_add(offset) & wrap } @@ -193,14 +195,19 @@ impl Interpreter<'_, '_> { &self, address: u64, length: u64, - id: Id, + id: Id, ) -> Result<&[u8], Halt> { let bytes = self.memory.bytes(address, length); bytes.ok_or_else(|| self.fail(INVALID_ACCESS, self.span_of(id))) } /// The register of `class`, not `Wide`, kept at `address`. - fn load(&self, class: Class, address: u64, id: Id) -> Result { + fn load( + &self, + class: mir::Class, + address: u64, + id: Id, + ) -> Result { let size = class.bytes(self.target.pointer_bytes()); let bytes = self.read_bytes(address, size, id)?; let mut word = [0; 16]; @@ -211,21 +218,21 @@ impl Interpreter<'_, '_> { /// Keeps `value`, a register of `class`, at `address`. fn store( &mut self, - class: Class, + class: mir::Class, address: u64, value: u128, - id: Id, + id: Id, ) -> Result<(), Halt> { // A wide integer covers its own bytes, not the padding of its slot. let size = match class { - Class::Wide(bits) => u64::from(bits.div_ceil(8)), + mir::Class::Wide(bits) => u64::from(bits.div_ceil(8)), _ => class.bytes(self.target.pointer_bytes()), }; let Some(bytes) = self.memory.bytes_mut(address, size) else { return Err(self.fail(INVALID_ACCESS, self.span_of(id))); }; match class { - Class::Wide(_) => self.wides[value as usize].write_le_bytes(bytes), + mir::Class::Wide(_) => self.wides[value as usize].write_le_bytes(bytes), _ => bytes.copy_from_slice(&value.to_le_bytes()[..size as usize]), } Ok(()) diff --git a/crates/kernel/eval/src/interpreter/memory.rs b/crates/eval/src/interpreter/memory.rs similarity index 100% rename from crates/kernel/eval/src/interpreter/memory.rs rename to crates/eval/src/interpreter/memory.rs diff --git a/crates/kernel/eval/src/interpreter/program.rs b/crates/eval/src/interpreter/program.rs similarity index 100% rename from crates/kernel/eval/src/interpreter/program.rs rename to crates/eval/src/interpreter/program.rs diff --git a/crates/kernel/eval/src/lib.rs b/crates/eval/src/lib.rs similarity index 100% rename from crates/kernel/eval/src/lib.rs rename to crates/eval/src/lib.rs diff --git a/crates/kernel/eval/src/operations.rs b/crates/eval/src/operations.rs similarity index 60% rename from crates/kernel/eval/src/operations.rs rename to crates/eval/src/operations.rs index 7e06411b..6e31a608 100644 --- a/crates/kernel/eval/src/operations.rs +++ b/crates/eval/src/operations.rs @@ -12,13 +12,8 @@ use std::borrow::Cow; use std::cmp::Ordering; use bigint::Limbs; -use model::mir::Class; -use model::mir::Comparison; -use model::mir::Conversion; -use model::mir::FloatOp; -use model::mir::IntegerOp; -use runtime_abi::messages::DIVISION_BY_ZERO; -use runtime_abi::messages::shift_count_message; +use model::mir; +use runtime_abi::messages; /// What a register holds: up to 128 bits (an integer, a float's bits or an /// address), or the limbs of an integer wider than that. @@ -60,7 +55,7 @@ impl<'l> RegisterValue<'l> { /// lowest signed value over -1 wraps to itself. `Err` when it traps: a /// divisor of zero, or a shift count not below `bits`. pub fn integer( - operation: IntegerOp, + operation: mir::IntegerOp, bits: u32, left: &RegisterValue, right: &RegisterValue, @@ -78,8 +73,8 @@ pub fn integer( /// Whether `left` and `right`, of `class` and `bits` bits, compare as /// `comparison` says. pub fn compare( - comparison: Comparison, - class: Class, + comparison: mir::Comparison, + class: mir::Class, bits: u32, left: &RegisterValue, right: &RegisterValue, @@ -97,15 +92,15 @@ pub fn compare( /// when outside it, and NaN to 0, as Rust's `as` does at each width; it is /// saturated at the integer's own width, which may be below its class's. pub fn convert( - conversion: Conversion, - from: Class, + cast: mir::Cast, + from: mir::Class, from_bits: u32, - to: Class, + to: mir::Class, to_bits: u32, value: &RegisterValue, ) -> RegisterValue<'static> { - if let Conversion::FloatToSigned { bits } | Conversion::FloatToUnsigned { bits } = conversion { - let signed = matches!(conversion, Conversion::FloatToSigned { .. }); + if let mir::Cast::FloatToSigned { bits } | mir::Cast::FloatToUnsigned { bits } = cast { + let signed = matches!(cast, mir::Cast::FloatToSigned { .. }); let integer = bigint::from_float(bits, signed, float_value(from, value.narrow())); return RegisterValue::of_limbs( to_bits, @@ -113,24 +108,24 @@ pub fn convert( ); } if from_bits <= 128 && to_bits <= 128 { - let converted = narrow_convert(conversion, from, from_bits, to, to_bits, value.narrow()); + let converted = narrow_convert(cast, from, from_bits, to, to_bits, value.narrow()); return RegisterValue::Narrow(converted); } // A wide integer on either side goes through limbs. let limbs = value.limbs(from_bits); - match conversion { - Conversion::SignExtend | Conversion::ZeroExtend => { - let signed = conversion == Conversion::SignExtend; + match cast { + mir::Cast::SignExtend | mir::Cast::ZeroExtend => { + let signed = cast == mir::Cast::SignExtend; RegisterValue::of_limbs( to_bits, Cow::Owned(bigint::extend(from_bits, signed, &limbs, to_bits)), ) } - Conversion::Truncate => { + mir::Cast::Truncate => { RegisterValue::of_limbs(to_bits, Cow::Owned(Limbs::new(to_bits, limbs.as_slice()))) } - Conversion::SignedToFloat | Conversion::UnsignedToFloat => { - let signed = conversion == Conversion::SignedToFloat; + mir::Cast::SignedToFloat | mir::Cast::UnsignedToFloat => { + let signed = cast == mir::Cast::SignedToFloat; RegisterValue::Narrow(float_bits( to, bigint::to_float(from_bits, signed, &limbs, to_bits), @@ -160,43 +155,43 @@ fn signed(bits: u32, value: u128) -> i128 { /// pointer wrote are not checked, so those trap here, though a machine's /// shift would not. fn narrow_integer( - operation: IntegerOp, + operation: mir::IntegerOp, bits: u32, left: u128, right: u128, ) -> Result { let nonzero = || { if right == 0 { - return Err(DIVISION_BY_ZERO.to_owned()); + return Err(messages::DIVISION_BY_ZERO.to_owned()); } Ok(right) }; let count = || { if right >= u128::from(bits) { - return Err(shift_count_message(bits)); + return Err(messages::shift_count_message(bits)); } Ok(right as u32) }; let value = match operation { - IntegerOp::Add => left.wrapping_add(right), - IntegerOp::Subtract => left.wrapping_sub(right), - IntegerOp::Multiply => left.wrapping_mul(right), - IntegerOp::SignedDivide => { + mir::IntegerOp::Add => left.wrapping_add(right), + mir::IntegerOp::Subtract => left.wrapping_sub(right), + mir::IntegerOp::Multiply => left.wrapping_mul(right), + mir::IntegerOp::SignedDivide => { nonzero()?; signed(bits, left).wrapping_div(signed(bits, right)) as u128 } - IntegerOp::UnsignedDivide => left / nonzero()?, - IntegerOp::SignedRemainder => { + mir::IntegerOp::UnsignedDivide => left / nonzero()?, + mir::IntegerOp::SignedRemainder => { nonzero()?; signed(bits, left).wrapping_rem(signed(bits, right)) as u128 } - IntegerOp::UnsignedRemainder => left % nonzero()?, - IntegerOp::ShiftLeft => left << count()?, - IntegerOp::SignedShiftRight => (signed(bits, left) >> count()?) as u128, - IntegerOp::UnsignedShiftRight => left >> count()?, - IntegerOp::And => left & right, - IntegerOp::Or => left | right, - IntegerOp::Xor => left ^ right, + mir::IntegerOp::UnsignedRemainder => left % nonzero()?, + mir::IntegerOp::ShiftLeft => left << count()?, + mir::IntegerOp::SignedShiftRight => (signed(bits, left) >> count()?) as u128, + mir::IntegerOp::UnsignedShiftRight => left >> count()?, + mir::IntegerOp::And => left & right, + mir::IntegerOp::Or => left | right, + mir::IntegerOp::Xor => left ^ right, }; Ok(value & mask(bits)) } @@ -204,7 +199,7 @@ fn narrow_integer( /// `left operation right` on integers of `bits` bits, more than 128, which /// trap as `integer`'s do. fn wide_integer( - operation: IntegerOp, + operation: mir::IntegerOp, bits: u32, left: &Limbs, right: &Limbs, @@ -213,46 +208,47 @@ fn wide_integer( let count = bigint::to_u64(bits, false, right).filter(|&count| count < u64::from(bits)); count .map(|count| count as u32) - .ok_or_else(|| shift_count_message(bits)) + .ok_or_else(|| messages::shift_count_message(bits)) }; - let divided = |quotient: Option| quotient.ok_or_else(|| DIVISION_BY_ZERO.to_owned()); + let divided = + |quotient: Option| quotient.ok_or_else(|| messages::DIVISION_BY_ZERO.to_owned()); Ok(match operation { - IntegerOp::Add => bigint::add(bits, left, right), - IntegerOp::Subtract => bigint::subtract(bits, left, right), - IntegerOp::Multiply => bigint::multiply(bits, left, right), - IntegerOp::SignedDivide => divided(bigint::divide(bits, true, left, right))?, - IntegerOp::UnsignedDivide => divided(bigint::divide(bits, false, left, right))?, - IntegerOp::SignedRemainder => divided(bigint::remainder(bits, true, left, right))?, - IntegerOp::UnsignedRemainder => divided(bigint::remainder(bits, false, left, right))?, - IntegerOp::ShiftLeft => bigint::shift_left(bits, left, count()?), - IntegerOp::SignedShiftRight => bigint::shift_right(bits, true, left, count()?), - IntegerOp::UnsignedShiftRight => bigint::shift_right(bits, false, left, count()?), - IntegerOp::And => bigint::bit_and(bits, left, right), - IntegerOp::Or => bigint::bit_or(bits, left, right), - IntegerOp::Xor => bigint::bit_xor(bits, left, right), + mir::IntegerOp::Add => bigint::add(bits, left, right), + mir::IntegerOp::Subtract => bigint::subtract(bits, left, right), + mir::IntegerOp::Multiply => bigint::multiply(bits, left, right), + mir::IntegerOp::SignedDivide => divided(bigint::divide(bits, true, left, right))?, + mir::IntegerOp::UnsignedDivide => divided(bigint::divide(bits, false, left, right))?, + mir::IntegerOp::SignedRemainder => divided(bigint::remainder(bits, true, left, right))?, + mir::IntegerOp::UnsignedRemainder => divided(bigint::remainder(bits, false, left, right))?, + mir::IntegerOp::ShiftLeft => bigint::shift_left(bits, left, count()?), + mir::IntegerOp::SignedShiftRight => bigint::shift_right(bits, true, left, count()?), + mir::IntegerOp::UnsignedShiftRight => bigint::shift_right(bits, false, left, count()?), + mir::IntegerOp::And => bigint::bit_and(bits, left, right), + mir::IntegerOp::Or => bigint::bit_or(bits, left, right), + mir::IntegerOp::Xor => bigint::bit_xor(bits, left, right), }) } /// The float of `class` whose bits a register holds, as an `f64`, which /// holds an `f32` exactly. -pub fn float_value(class: Class, bits: u128) -> f64 { +pub fn float_value(class: mir::Class, bits: u128) -> f64 { match class { - Class::F32 => f64::from(f32::from_bits(bits as u32)), + mir::Class::F32 => f64::from(f32::from_bits(bits as u32)), _ => f64::from_bits(bits as u64), } } /// The bits of `value` as a float of `class`, rounded to it. -pub fn float_bits(class: Class, value: f64) -> u128 { +pub fn float_bits(class: mir::Class, value: f64) -> u128 { match class { - Class::F32 => u128::from((value as f32).to_bits()), + mir::Class::F32 => u128::from((value as f32).to_bits()), _ => u128::from(value.to_bits()), } } /// `left operation right` on floats of `class`, each in its own /// precision. Which NaN one gives is not specified, as in LLVM. -pub fn float(operation: FloatOp, class: Class, left: u128, right: u128) -> u128 { +pub fn float(operation: mir::FloatOp, class: mir::Class, left: u128, right: u128) -> u128 { fn apply< F: std::ops::Add + std::ops::Sub @@ -260,19 +256,19 @@ pub fn float(operation: FloatOp, class: Class, left: u128, right: u128) -> u128 + std::ops::Div + std::ops::Rem, >( - operation: FloatOp, + operation: mir::FloatOp, left: F, right: F, ) -> F { match operation { - FloatOp::Add => left + right, - FloatOp::Subtract => left - right, - FloatOp::Multiply => left * right, - FloatOp::Divide => left / right, - FloatOp::Remainder => left % right, + mir::FloatOp::Add => left + right, + mir::FloatOp::Subtract => left - right, + mir::FloatOp::Multiply => left * right, + mir::FloatOp::Divide => left / right, + mir::FloatOp::Remainder => left % right, } } - if class == Class::F32 { + if class == mir::Class::F32 { let (left, right) = (f32::from_bits(left as u32), f32::from_bits(right as u32)); return u128::from(apply(operation, left, right).to_bits()); } @@ -284,30 +280,30 @@ pub fn float(operation: FloatOp, class: Class, left: u128, right: u128) -> u128 /// compare as `comparison` says. A float's `Equal` and `NotEqual` are a /// float's: NaN equals nothing, and `-0.0` equals `0.0`. fn narrow_compare( - comparison: Comparison, - class: Class, + comparison: mir::Comparison, + class: mir::Class, bits: u32, left: u128, right: u128, ) -> bool { - if matches!(class, Class::F32 | Class::F64) { + if matches!(class, mir::Class::F32 | mir::Class::F64) { let (left, right) = (float_value(class, left), float_value(class, right)); return match comparison { - Comparison::Equal => left == right, - Comparison::NotEqual => left != right, - Comparison::FloatLess => left < right, - Comparison::FloatLessOrEqual => left <= right, + mir::Comparison::Equal => left == right, + mir::Comparison::NotEqual => left != right, + mir::Comparison::FloatLess => left < right, + mir::Comparison::FloatLessOrEqual => left <= right, _ => unreachable!("floats compare as floats"), }; } match comparison { - Comparison::Equal => left == right, - Comparison::NotEqual => left != right, - Comparison::SignedLess => signed(bits, left) < signed(bits, right), - Comparison::SignedLessOrEqual => signed(bits, left) <= signed(bits, right), - Comparison::UnsignedLess => left < right, - Comparison::UnsignedLessOrEqual => left <= right, - Comparison::FloatLess | Comparison::FloatLessOrEqual => { + mir::Comparison::Equal => left == right, + mir::Comparison::NotEqual => left != right, + mir::Comparison::SignedLess => signed(bits, left) < signed(bits, right), + mir::Comparison::SignedLessOrEqual => signed(bits, left) <= signed(bits, right), + mir::Comparison::UnsignedLess => left < right, + mir::Comparison::UnsignedLessOrEqual => left <= right, + mir::Comparison::FloatLess | mir::Comparison::FloatLessOrEqual => { unreachable!("only floats compare as floats") } } @@ -315,16 +311,16 @@ fn narrow_compare( /// Whether `left` and `right`, integers of `bits` bits, more than 128, /// compare as `comparison` says. -fn wide_compare(comparison: Comparison, bits: u32, left: &Limbs, right: &Limbs) -> bool { +fn wide_compare(comparison: mir::Comparison, bits: u32, left: &Limbs, right: &Limbs) -> bool { let order = |signed| bigint::compare(bits, signed, left, right); match comparison { - Comparison::Equal => left == right, - Comparison::NotEqual => left != right, - Comparison::SignedLess => order(true) == Ordering::Less, - Comparison::SignedLessOrEqual => order(true) != Ordering::Greater, - Comparison::UnsignedLess => order(false) == Ordering::Less, - Comparison::UnsignedLessOrEqual => order(false) != Ordering::Greater, - Comparison::FloatLess | Comparison::FloatLessOrEqual => { + mir::Comparison::Equal => left == right, + mir::Comparison::NotEqual => left != right, + mir::Comparison::SignedLess => order(true) == Ordering::Less, + mir::Comparison::SignedLessOrEqual => order(true) != Ordering::Greater, + mir::Comparison::UnsignedLess => order(false) == Ordering::Less, + mir::Comparison::UnsignedLessOrEqual => order(false) != Ordering::Greater, + mir::Comparison::FloatLess | mir::Comparison::FloatLessOrEqual => { unreachable!("only floats compare as floats") } } @@ -333,32 +329,32 @@ fn wide_compare(comparison: Comparison, bits: u32, left: &Limbs, right: &Limbs) /// `value`, a register of `from` of `from_bits` bits, as `to` of `to_bits` /// bits; neither is wide, and it is no float becoming an integer. fn narrow_convert( - conversion: Conversion, - from: Class, + cast: mir::Cast, + from: mir::Class, from_bits: u32, - to: Class, + to: mir::Class, to_bits: u32, value: u128, ) -> u128 { let float = || float_value(from, value); - let converted = match conversion { - Conversion::SignExtend => signed(from_bits, value) as u128, - Conversion::ZeroExtend | Conversion::Truncate | Conversion::PointerCast => value, - Conversion::SignedToFloat => { + let converted = match cast { + mir::Cast::SignExtend => signed(from_bits, value) as u128, + mir::Cast::ZeroExtend | mir::Cast::Truncate | mir::Cast::PointerCast => value, + mir::Cast::SignedToFloat => { let value = signed(from_bits, value); match to { - Class::F32 => u128::from((value as f32).to_bits()), + mir::Class::F32 => u128::from((value as f32).to_bits()), _ => u128::from((value as f64).to_bits()), } } - Conversion::UnsignedToFloat => match to { - Class::F32 => u128::from((value as f32).to_bits()), + mir::Cast::UnsignedToFloat => match to { + mir::Class::F32 => u128::from((value as f32).to_bits()), _ => u128::from((value as f64).to_bits()), }, - Conversion::FloatToSigned { .. } | Conversion::FloatToUnsigned { .. } => { + mir::Cast::FloatToSigned { .. } | mir::Cast::FloatToUnsigned { .. } => { unreachable!("`convert` turns a float into an integer through limbs") } - Conversion::FloatWiden | Conversion::FloatNarrow => float_bits(to, float()), + mir::Cast::FloatWiden | mir::Cast::FloatNarrow => float_bits(to, float()), }; converted & mask(to_bits) } diff --git a/crates/features/Cargo.toml b/crates/features/Cargo.toml deleted file mode 100644 index 566e1cc7..00000000 --- a/crates/features/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "features" -description = "Peeper: the list of its features, and each feature's reading and checking" -version.workspace = true -edition.workspace = true -license-file.workspace = true -publish.workspace = true - -[dependencies] -arena.workspace = true -check.workspace = true -diagnostics.workspace = true -model.workspace = true -parser.workspace = true -source.workspace = true -syntax.workspace = true -token.workspace = true -bigint.workspace = true -literal.workspace = true - -[lints] -workspace = true diff --git a/crates/features/src/arrays.rs b/crates/features/src/arrays.rs deleted file mode 100644 index f3e50417..00000000 --- a/crates/features/src/arrays.rs +++ /dev/null @@ -1,192 +0,0 @@ -//! Arrays: `[N]T` and the array literals `[N]T{ ... }` and `[_]T{ ... }`. -//! The checker gives the core's array type and literal (`Type::Array`, -//! `ExprKind::ArrayLiteral`), so the phases after it know nothing of -//! them. A literal's entries and their `...` spreads are the core's, as a -//! call to a `...` parameter checks them too; so are slices, read after the -//! core's `&`, and indexing. - -use arena::Id; -use check::Checker; -use check::builder::ThirBuilder; -use diagnostics::Diagnostic; -use model::semantic_types::Type; -use model::semantic_types::TypeId; -use model::thir; -use parser::Parser; -use parser::Rules; -use parser::expr::spreadable; -use parser::expr::starts_expression; -use source::Span; -use syntax::ast; -use token::Token; -use token::TokenKind; - -/// Adds the rules that read array types and array literals to `rules`. -pub(crate) const fn rows(rules: &mut Rules) { - rules.type_start(TokenKind::LeftBracket, array_type); - rules.prefix(TokenKind::LeftBracket, array_literal); -} - -/// Reads the `N]T` of `[N]T`, a type that starts at `start`, with its `[`; -/// a `[]T` alone is reported, as it has no fixed size. -fn array_type(p: &mut Parser, start: u32) -> Id { - let open = Token { - kind: TokenKind::LeftBracket, - span: Span { - start, - end: start + 1, - }, - }; - let t = p.tok(); - // `[]T` alone, read whole so the message names it and parsing goes on. - if t.kind == TokenKind::RightBracket { - p.next(); - let element = p.type_expr(); - let ty = p.add(start, ast::Type::Invalid); - // An element reported already, as `[]i32` in `[][]i32`, is the - // one mistake: its fix fixes the whole. - if let ast::Type::Invalid = p.tree.types[element] { - return ty; - } - let element = p.tree.file.slice(p.tree.types.span(element)); - let message = - format!("`[]{element}` is any number of `{element}`s, so it has no fixed size"); - let label = format!("use `[N]{element}` for a fixed array or `&[]{element}` for a slice"); - let span = p.tree.types.span(ty); - p.repair(Diagnostic::new(diagnostics::INVALID_TYPE, message).label( - &p.tree.file, - span, - label, - )); - return ty; - } - if t.kind != TokenKind::Number { - p.fail( - Diagnostic::new(diagnostics::INVALID_TYPE, "expected array length").label( - &p.tree.file, - t.span, - "use `[N]T` for fixed arrays or `&[]T` for slices", - ), - ); - return p.add(start, ast::Type::Invalid); - } - p.next(); - p.check_number(t); - p.close(TokenKind::RightBracket, open); - let element = p.type_expr(); - let length = t.span; - p.add( - start, - ast::Type::Feature(ast::FeatureType::Array(ast::ArrayType { length, element })), - ) -} - -/// Reads `[N]T{ entries }` or `[_]T{ entries }` (the length is the number of -/// values they give); an entry is a value, or `values...`, which spreads an -/// array or a range: `(0..3)...` or `0..3...`. Without `{` after it, `[N]T` -/// is the type alone. -fn array_literal(p: &mut Parser) -> Id { - let start = p.tok().span.start; - let ty = if p.ahead(1).kind == TokenKind::Underscore { - let open = p.next(); - p.next(); - p.close(TokenKind::RightBracket, open); - let element = p.type_expr(); - ast::ArrayLiteralType::Counted { element } - } else { - let ty = p.type_expr(); - // Without entries `[N]T` is the type alone, as an argument that - // takes one; `[_]T` needs its entries to have a length. - if !p.at(TokenKind::LeftBrace) { - return p.add(start, ast::Expr::Type(ty)); - } - ast::ArrayLiteralType::Written(ty) - }; - let entries = p.delimited( - TokenKind::LeftBrace, - TokenKind::RightBrace, - false, - starts_expression, - spreadable, - ); - p.add( - start, - ast::Expr::Feature(ast::FeatureExpr::ArrayLiteral(ast::ArrayLiteral { - ty, - entries, - })), - ) -} - -#[cfg(test)] -mod tests; - -/// The type `[length]element`, written at `span`: the length is a whole -/// number without a suffix that an array can hold. -pub(crate) fn resolve_array_type( - checker: &mut Checker<'_>, - ty: ast::ArrayType, - span: Span, -) -> TypeId { - let ast::ArrayType { length, element } = ty; - let literal = literal::numeric::split(checker.module().ast.file.slice(length)); - let value = literal.integer_value(); - if !literal.suffix.is_empty() || literal.is_float() { - let message = "an array length is a whole number without a suffix"; - return checker.error(diagnostics::INVALID_TYPE, message, length); - } - if !checker.length_fits(&value, length) { - return TypeId::INVALID; - } - let element = checker.resolve_value_type(element); - checker.array_type(element, value[0], span) -} - -/// `[N]T{ entries }`, written at `span`, or `[_]T{ entries }`, whose -/// length is the number of values its entries give: each entry a `T`, or -/// a spread of a range, an array or a slice (`count_spread`). They must -/// give exactly its length. A slice, or a range whose count is not known -/// now, is counted when the program runs, so its literal needs a written -/// length, which the entries known now must not already pass. -pub(crate) fn check_array_literal( - builder: &mut ThirBuilder<'_, '_>, - literal: ast::ArrayLiteral, - span: Span, -) -> thir::Expr { - let tree = &builder.checker.module().ast; - let (element, length, written) = match literal.ty { - ast::ArrayLiteralType::Counted { element } => { - // `[_]T`, from its `[` to its element's end - let written = Span { - start: span.start, - end: tree.types.span(element).end, - }; - (builder.checker.resolve_value_type(element), None, written) - } - ast::ArrayLiteralType::Written(written) => { - let span = tree.types.span(written); - match builder.checker.resolve_value_type(written) { - ty if ty == TypeId::INVALID => (TypeId::INVALID, None, span), - ty => match builder.checker.types[ty] { - Type::Array { - element, length, .. - } => (element, Some((ty, length)), span), - _ => unreachable!("an array literal's written type is an array type"), - }, - } - } - }; - let entries = tree.children.lists.items(literal.entries); - let (parts, known, later) = builder.check_entries(entries, element, None); - let Some(known) = known.filter(|_| element != TypeId::INVALID) else { - return thir::Expr::INVALID; - }; - let Some(ty) = builder.array_literal_type(written, element, length, (known, later), span) - else { - return thir::Expr::INVALID; - }; - thir::Expr { - ty, - kind: thir::ExprKind::ArrayLiteral(builder.body.children.lists.add(&parts)), - } -} diff --git a/crates/features/src/arrays/tests.rs b/crates/features/src/arrays/tests.rs deleted file mode 100644 index 9f99e0d2..00000000 --- a/crates/features/src/arrays/tests.rs +++ /dev/null @@ -1,211 +0,0 @@ -//! Reading and checking arrays. The parser's tree dump and the checker's -//! test program are those crates' own, so these build what they need. - -use arena::Id; -use syntax::ast; - -use crate::testing::Tree; -use crate::testing::bodies; -use crate::testing::messages; -use crate::testing::parse_text; -use crate::testing::with_checker; - -/// The messages of the errors in `text`. -/// The written type `ty` with `[N]` for each array, `&[]` for each slice -/// and the innermost type's text. -fn shape(tree: &Tree, ty: Id) -> String { - match tree.types[ty] { - ast::Type::Feature(ast::FeatureType::Array(ast::ArrayType { length, element })) => { - format!("[{}]{}", tree.file.slice(length), shape(tree, element)) - } - ast::Type::Slice { element, .. } => format!("&[]{}", shape(tree, element)), - _ => tree.file.slice(tree.types.span(ty)).to_string(), - } -} - -/// `[N]T` is a type wherever a type goes, an array's element too, and -/// where a value could go when no `{` follows; `[N]T{ }` and `[_]T{ }` are -/// literals, whose entries may spread. -#[test] -fn parses_types_and_literals() { - let text = "fn f(a: [4]u8, b: [2][3]i32, c: &[][2]u8) { - g([4]i32); - [2]i32{ 1, 2 }; - [_]u8{ 1, (b)..., a... }; - }"; - let (tree, errors) = parse_text(text); - assert!(errors.is_empty(), "{errors:?}"); - let decl = tree.declarations().next().unwrap(); - let ast::Decl::Function(function) = tree.decls[decl] else { - panic!("not a function") - }; - let parameters: Vec = (tree.children.lists.items(function.signature.parameters)) - .map(|parameter| shape(&tree, tree.children.params[parameter].ty)) - .collect(); - assert_eq!(parameters, ["[4]u8", "[2][3]i32", "&[][2]u8"]); - let mut literals = Vec::new(); - for id in tree.exprs.ids() { - match tree.exprs[id] { - ast::Expr::Type(ty) => literals.push(format!("type {}", shape(&tree, ty))), - ast::Expr::Feature(ast::FeatureExpr::ArrayLiteral(ast::ArrayLiteral { - ty, - entries, - })) => { - let ty = match ty { - ast::ArrayLiteralType::Written(ty) => shape(&tree, ty), - ast::ArrayLiteralType::Counted { element } => { - format!("[_]{}", shape(&tree, element)) - } - }; - let entries: Vec<&str> = (tree.children.lists.items(entries)) - .map(|entry| match tree.exprs[entry] { - ast::Expr::Spread(_) => "spread", - _ => "value", - }) - .collect(); - literals.push(format!("{ty} {}", entries.join(" "))); - } - _ => {} - } - } - assert_eq!( - literals, - [ - "type [4]i32", - "[2]i32 value value", - "[_]u8 value spread spread" - ] - ); -} - -/// A `[]T` alone has no fixed size, and is read whole, so the parser stays -/// in step and reports the next one too; an element so reported is the -/// one mistake. -#[test] -fn type_errors() { - for (text, want) in [ - ("fn f(a: [n]i32) {}", &["expected array length"][..]), - ( - "fn f(a: []i32) {}", - &["`[]i32` is any number of `i32`s, so it has no fixed size"], - ), - ( - "fn f(a: [][]i32) {}", - &["`[]i32` is any number of `i32`s, so it has no fixed size"], - ), - ( - "fn f(a: []i32, b: []u8) {}", - &[ - "`[]i32` is any number of `i32`s, so it has no fixed size", - "`[]u8` is any number of `u8`s, so it has no fixed size", - ], - ), - ("fn f() { [x]i32{}; }", &["expected array length"]), - ( - "fn f() { []i32{}; }", - &["`[]i32` is any number of `i32`s, so it has no fixed size"], - ), - ("fn f() { [_]i32; }", &["expected `{`, found `;`"]), - ] { - assert_eq!(messages(text), want, "{text}"); - } -} - -/// A `;` for a `,` in a literal's `{ }` is repaired with one error per -/// list; a `;` after an unclosed literal ends the statement, so its `}` is -/// missing. -#[test] -fn separators() { - let text = "fn f() { let v = [2]i32{1; 2}; }"; - let (_, errors) = parse_text(text); - assert_eq!(errors.len(), 1, "{errors:?}"); - assert_eq!(errors[0].message, "expected `,` between items, found `;`"); - let mut fixed = text.to_string(); - for fix in errors[0].notes[0].fixes().iter().rev() { - fixed.replace_range(fix.span.range(), &fix.new_text); - } - assert_eq!(fixed, "fn f() { let v = [2]i32{1, 2}; }"); - assert_eq!( - messages("fn f() {\n let v = [3]i32{4, 5, 6;\n return;\n}"), - ["expected `}`, found `;`"] - ); -} - -/// `[_]T` takes its length from its entries, a spread's too; `[N]T` needs -/// that many. -#[test] -fn literals() { - let (bodies, reported) = bodies( - "fn f(a: [2]i32) { - let b = [_]i32{ 1, a..., 4 }; - let c = [3]i32{ 1, 2 }; - }", - ); - assert_eq!( - reported, - [( - "T0001", - "`[3]i32` needs 3 values, found 2".to_string(), - "[3]i32{ 1, 2 }".to_string() - )] - ); - assert_eq!( - bodies, - [" let b.1 = [4]i32{ 1:i32, (a.0)..., 4:i32 }\n let c.2 = invalid\n"] - ); -} - -/// A temporary is stored where it is computed, and each one a `let`'s -/// value makes is marked to last with it; one in a plain statement is not. -/// An array's temporary is indexed and looped over as a variable is. -#[test] -fn temporaries() { - let (bodies, reported) = bodies( - "fn make() -> [2]i32 { return [2]i32{1, 2}; } - fn id(r: &mut i32) -> &mut i32 in r { return r; } - fn sum(values: &[]i32) -> i32 { return values[0]; } - fn f() { - let total = sum(&make()); - let kept = &make(); - let first = make()[0]; - let mut x = 1; - id(&mut x).* = 2; - for v in &make() { } - }", - ); - assert!(reported.is_empty(), "{reported:?}"); - assert_eq!( - bodies[3], - " let total.1 = call f2(&(kept _.0 = call f0():[2]i32)):i32 - let kept.3 = &(kept _.2 = call f0():[2]i32) - let first.5 = (kept _.4 = call f0():[2]i32)[at 0:u64] - let mut x.6 = 1:i32 - (_.7 = call f1(&mut x.6):&mut i32).* = 2:i32 - { - let _.9 = &(kept _.8 = call f0():[2]i32) - for _.10 in 0:u64..2:u64 by 1:u64 { - let v.11 = &_.9.*[at _.10] - } - } -" - ); -} - -/// A `const` value's type is read again at each call, which cannot know a -/// type parameter yet, so one naming it through an array is refused. -#[test] -fn const_array_of_a_type_parameter() { - let text = "fn Typed(const T: type, const a: [2]T) {}"; - let ((), reported) = with_checker(text, |checker, functions| { - let (definition, name) = functions[0]; - checker.function_type(definition, name); - }); - assert_eq!( - reported, - [( - "T0043", - "`const` values whose type names a type parameter are not supported yet".to_string(), - "[2]T".to_string() - )] - ); -} diff --git a/crates/features/src/chars.rs b/crates/features/src/chars.rs deleted file mode 100644 index a1f51fe4..00000000 --- a/crates/features/src/chars.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! Character literals: `'x'` and `b'x'`. Read, and refused by the checker -//! until a character has a type. - -use arena::Id; -use check::builder::ThirBuilder; -use model::thir; -use parser::Parser; -use parser::Rules; -use source::Span; -use syntax::ast; -use token::TokenKind; - -/// Adds the rules that read character literals to `rules`. -pub(crate) const fn rows(rules: &mut Rules) { - rules.prefix(TokenKind::Char, char_literal); - rules.prefix(TokenKind::ByteChar, char_literal); -} - -/// Reads `'x'` or `b'x'`. -fn char_literal(p: &mut Parser) -> Id { - let token = p.next(); - let byte = token.kind == TokenKind::ByteChar; - p.add( - token.span.start, - ast::Expr::Feature(ast::FeatureExpr::Char(ast::CharLiteral { byte })), - ) -} - -#[cfg(test)] -mod tests; - -/// A character literal at `span`, which no check exists for yet. -pub(crate) fn check_char_literal( - builder: &mut ThirBuilder<'_, '_>, - _literal: ast::CharLiteral, - span: Span, -) -> thir::Expr { - builder.checker.not_supported(span, "character literals"); - thir::Expr::INVALID -} diff --git a/crates/features/src/chars/tests.rs b/crates/features/src/chars/tests.rs deleted file mode 100644 index a6298df0..00000000 --- a/crates/features/src/chars/tests.rs +++ /dev/null @@ -1,33 +0,0 @@ -//! Reading character literals, and their refusal. - -use syntax::ast; - -use crate::testing::bodies; -use crate::testing::parse_text; - -/// `'x'` is a character and `b'y'` a byte, each spanning its quotes. -#[test] -fn parses_literals() { - let (tree, errors) = parse_text("fn f() { 'x'; b'y'; }"); - assert!(errors.is_empty(), "{errors:?}"); - let literals: Vec<(bool, &str)> = (tree.exprs.ids()) - .filter_map(|id| match tree.exprs[id] { - ast::Expr::Feature(ast::FeatureExpr::Char(ast::CharLiteral { byte })) => { - Some((byte, tree.file.slice(tree.exprs.span(id)))) - } - _ => None, - }) - .collect(); - assert_eq!(literals, [(false, "'x'"), (true, "b'y'")]); -} - -/// A character has no type yet, so a literal is refused where it is -/// written. -#[test] -fn refused() { - let (_, reported) = bodies("fn f() { 'x'; }"); - let found: Vec<(&str, &str)> = (reported.iter()) - .map(|(_, message, text)| (message.as_str(), text.as_str())) - .collect(); - assert_eq!(found, [("character literals are not supported yet", "'x'")]); -} diff --git a/crates/features/src/enums.rs b/crates/features/src/enums.rs deleted file mode 100644 index 07d9cee5..00000000 --- a/crates/features/src/enums.rs +++ /dev/null @@ -1,265 +0,0 @@ -//! Enums: the type `enum { A, B: Payload }` and its declaration, a variant -//! literal (`Enum::Case with payload`), a case test (`x is Enum::Case`) and -//! `match`. All are read, and refused by the checker until enums exist. - -use std::num::NonZeroU32; - -use arena::Id; -use arena::List; -use check::Checker; -use check::builder::ThirBuilder; -use diagnostics::Diagnostic; -use model::semantic_types::TypeId; -use model::thir; -use parser::Parser; -use parser::Rules; -use parser::decl::type_decl; -use parser::is_name; -use source::Span; -use syntax::ast; -use syntax::operators::Precedence; -use token::TokenKind; - -/// Adds the rules that read enum types and declarations, variant -/// literals, `is` tests and `match` to `rules`. -pub(crate) const fn rows(rules: &mut Rules) { - rules.declaration(TokenKind::Enum, type_decl); - rules.type_start(TokenKind::Enum, enum_type); - rules.infix(TokenKind::With, Precedence::Call, variant_literal); - rules.infix(TokenKind::Is, Precedence::Equality, case_test); - rules.statement(TokenKind::Match, match_statement); -} - -/// Reads `{ Name, Name: Payload, ... }`, the variants of an enum type that -/// starts at `start`. -fn enum_type(p: &mut Parser, start: u32) -> Id { - let variants = p.delimited( - TokenKind::LeftBrace, - TokenKind::RightBrace, - true, - |_, kind| is_name(kind), - |p| { - let start = p.tok().span.start; - let name = p.name(); - let payload = p.at(TokenKind::Colon).then(|| { - p.next(); - p.type_expr() - }); - p.add(start, ast::Variant { name, payload }) - }, - ); - let ty = ast::FeatureType::Enum(ast::EnumType { variants }); - p.add(start, ast::Type::Feature(ty)) -} - -/// Reports `case` unless it is a full path `Enum::Case` (or a type already -/// reported as invalid). -fn require_path(p: &mut Parser, case: Id) { - if !matches!(p.tree.types[case], ast::Type::Path(_) | ast::Type::Invalid) { - let span = p.tree.types.span(case); - p.repair( - Diagnostic::new( - diagnostics::INVALID_EXPRESSION, - "enum case must use a fully named path", - ) - .label(&p.tree.file, span, "write `Enum::Variant`"), - ); - } -} - -/// Reads `with payload` after `case`, which is a full path `Enum::Case`. -fn variant_literal(p: &mut Parser, case: Id) -> Id { - p.next(); - let payload = p.expr(Precedence::Lowest); - let path = match p.tree.exprs[case] { - ast::Expr::Path(path) if matches!(p.tree.types[path], ast::Type::Path(_)) => path, - _ => { - let span = p.tree.exprs.span(case); - p.repair( - Diagnostic::new( - diagnostics::INVALID_EXPRESSION, - "enum case must use a fully named path", - ) - .label(&p.tree.file, span, "write `Enum::Variant`"), - ); - return case; - } - }; - let literal = ast::FeatureExpr::VariantLiteral(ast::VariantLiteral { - case: path, - payload, - }); - p.add(p.start_of(case), ast::Expr::Feature(literal)) -} - -/// Reads `is Enum::Case` after `value`; the case is a full path. -fn case_test(p: &mut Parser, value: Id) -> Id { - p.next(); - let case = p.type_expr(); - require_path(p, case); - let test = ast::FeatureExpr::CaseTest(ast::CaseTest { value, case }); - p.add(p.start_of(value), ast::Expr::Feature(test)) -} - -/// Reads `match subject { arms }`. An arm is `_ => { }`, `Enum::Case => { }` -/// or `Enum::Case with pattern => { }`; arms are not separated by commas. -fn match_statement(p: &mut Parser) -> Id { - let start = p.next().span.start; - let subject = p.expr(Precedence::Lowest); - let mut arms = List::EMPTY; - if let Some(open) = p.expect(TokenKind::LeftBrace) { - let mut read: Vec = Vec::new(); - // Every arm begins with `_` or a path and reads at least it, so the - // loop always moves on. - while p.at(TokenKind::Underscore) || p.at(TokenKind::Ident) { - let arm_start = p.tok().span.start; - let (pattern, body) = match_arm(p); - read.push(p.add(arm_start, ast::MatchArm { pattern, body }).into()); - let t = p.tok(); - if t.kind == TokenKind::Comma { - p.next(); - let fix = p.fix(t.span, ""); - p.repair( - Diagnostic::new(diagnostics::EXPECTED_TOKEN, "match arms do not use commas") - .label(&p.tree.file, t.span, "") - .help("remove this comma", vec![fix]), - ); - } - } - arms = p.tree.children.lists.add(&read); - p.close(TokenKind::RightBrace, open); - } - let statement = ast::FeatureStmt::Match(ast::Match { subject, arms }); - p.add(start, ast::Stmt::Feature(statement)) -} - -/// Reads one arm's pattern, its `=>` and its block. A missing `=>` before -/// the block is read as if it were there. -fn match_arm(p: &mut Parser) -> (Id, Id) { - let t = p.tok(); - let pattern = if t.kind == TokenKind::Underscore { - let start = p.next().span.start; - p.add(start, ast::Pattern::Wildcard) - } else { - case_pattern(p) - }; - if p.at(TokenKind::LeftBrace) { - let at = p.here(); - let fix = p.fix(at, " =>"); - p.repair( - Diagnostic::new( - diagnostics::EXPECTED_TOKEN, - "expected `=>` after match case", - ) - .label(&p.tree.file, at, "") - .help("add missing `=>`", vec![fix]), - ); - } else if p.expect(TokenKind::FatArrow).is_none() { - p.sync(); - } - (pattern, p.block()) -} - -/// Reads `Enum::Case`, perhaps followed by `with` and the pattern of its -/// payload. The case is a full path. -fn case_pattern(p: &mut Parser) -> Id { - // Cases in cases, `A::B with C::D with ...`, are a deep recursion. - source::grow_stack(|| { - let start = p.tok().span.start; - let case = p.type_expr(); - require_path(p, case); - let inner = p.at(TokenKind::With).then(|| { - p.next(); - payload_pattern(p) - }); - p.add(start, ast::Pattern::Case { case, inner }) - }) -} - -/// Reads the pattern after `with`: `none`, `_`, a name to bind, -/// `.{ fields }`, or another case. -fn payload_pattern(p: &mut Parser) -> Id { - let t = p.tok(); - match t.kind { - TokenKind::None => { - p.next(); - p.add(t.span.start, ast::Pattern::None) - } - TokenKind::Underscore => { - p.next(); - p.add(t.span.start, ast::Pattern::Wildcard) - } - TokenKind::Dot => p.struct_pattern(), - TokenKind::Ident if !matches!(p.ahead(1).kind, TokenKind::ColonColon | TokenKind::Less) => { - let name = p.name(); - p.tree.add(ast::Pattern::Binding, name.span) - } - TokenKind::Ident => case_pattern(p), - _ => { - p.fail( - Diagnostic::new( - diagnostics::EXPECTED_TOKEN, - "expected a pattern after `with`", - ) - .label(&p.tree.file, t.span, "") - .help( - "write `none`, `_`, a name, `.{ field }`, or a case of the payload's enum", - Vec::new(), - ), - ); - p.add(p.here().start, ast::Pattern::Invalid) - } - } -} - -#[cfg(test)] -mod tests; - -/// An enum type at `span`, which no check exists for yet. -pub(crate) fn resolve_enum_type( - checker: &mut Checker<'_>, - _ty: ast::EnumType, - span: Span, -) -> TypeId { - checker.not_supported(span, "enum types") -} - -/// The declaration of an enum, written `written`, which no check exists -/// for yet. -pub(crate) fn declare_enum_type( - checker: &mut Checker<'_>, - _ty: ast::EnumType, - written: ast::TypeDecl, -) -> TypeId { - checker.not_supported(written.name.span, "enum declarations") -} - -/// Variant literals, at `span`, which no check exists for yet. -pub(crate) fn check_variant_literal( - builder: &mut ThirBuilder<'_, '_>, - _literal: ast::VariantLiteral, - span: Span, -) -> thir::Expr { - builder.checker.not_supported(span, "variant literals"); - thir::Expr::INVALID -} - -/// `is` tests, at `span`, which no check exists for yet. -pub(crate) fn check_case_test( - builder: &mut ThirBuilder<'_, '_>, - _test: ast::CaseTest, - span: Span, -) -> thir::Expr { - builder.checker.not_supported(span, "`is` tests"); - thir::Expr::INVALID -} - -/// A `match` at `span`, which no check exists for yet. -pub(crate) fn check_match( - builder: &mut ThirBuilder<'_, '_>, - _statement: ast::Match, - span: Span, -) -> Option { - builder.checker.not_supported(span, "`match` statements"); - None -} diff --git a/crates/features/src/enums/tests.rs b/crates/features/src/enums/tests.rs deleted file mode 100644 index d36faaef..00000000 --- a/crates/features/src/enums/tests.rs +++ /dev/null @@ -1,199 +0,0 @@ -//! Reading enums and `match`, and their refusal. - -use arena::Id; -use syntax::ast; - -use crate::testing::Tree; -use crate::testing::bodies; -use crate::testing::messages; -use crate::testing::parse_text; -use crate::testing::statements; - -/// The pattern `pattern` as written, a case's payload pattern in -/// parentheses. -fn shape(tree: &Tree, pattern: Id) -> String { - match tree.patterns[pattern] { - ast::Pattern::Case { case, inner } => { - let case = tree.file.slice(tree.types.span(case)); - match inner { - Some(inner) => format!("{case}({})", shape(tree, inner)), - None => case.to_string(), - } - } - ast::Pattern::Wildcard => "_".to_string(), - ast::Pattern::None => "none".to_string(), - ast::Pattern::Binding => format!("bind {}", tree.file.slice(tree.patterns.span(pattern))), - ast::Pattern::Struct(fields) => format!("struct of {}", fields.len()), - other => panic!("not a match pattern: {other:?}"), - } -} - -/// An enum's variants are names, each perhaps with a payload type; a -/// trailing or doubled comma is style. -#[test] -fn parses_declarations() { - let (tree, errors) = parse_text("enum Status { Ready, Waiting: Pair,, Done, }"); - assert!(errors.is_empty(), "{errors:?}"); - let decl = tree.declarations().next().unwrap(); - let ast::Decl::Type(declared) = tree.decls[decl] else { - panic!("not a type declaration") - }; - let ast::Type::Feature(ast::FeatureType::Enum(ast::EnumType { variants })) = - tree.types[declared.ty] - else { - panic!("not an enum") - }; - let found: Vec<(&str, Option<&str>)> = (tree.children.lists.items(variants)) - .map(|variant| { - let variant = tree.children.variants[variant]; - let payload = variant - .payload - .map(|ty| tree.file.slice(tree.types.span(ty))); - (tree.file.slice(variant.name.span), payload) - }) - .collect(); - assert_eq!( - found, - [ - ("Ready", None), - ("Waiting", Some("Pair")), - ("Done", None) - ] - ); - assert_eq!(messages("enum E { A B }").len(), 1); - assert_eq!(messages("enum E { A: }").len(), 1); -} - -/// A variant literal takes the whole expression after `with`, and a case -/// test binds as `==` does. -#[test] -fn parses_expressions() { - let (tree, errors) = parse_text("fn f() { Shape::Line with 1 + 2; a is E::B && c; }"); - assert!(errors.is_empty(), "{errors:?}"); - let found = statements(&tree); - let text = |span| tree.file.slice(span); - let ast::Expr::Feature(ast::FeatureExpr::VariantLiteral(literal)) = tree.exprs[found[0]] else { - panic!("not a variant literal: {:?}", tree.exprs[found[0]]) - }; - assert_eq!(text(tree.types.span(literal.case)), "Shape::Line"); - assert_eq!(text(tree.exprs.span(literal.payload)), "1 + 2"); - let ast::Expr::Binary { left, .. } = tree.exprs[found[1]] else { - panic!("not a binary operation: {:?}", tree.exprs[found[1]]) - }; - let ast::Expr::Feature(ast::FeatureExpr::CaseTest(test)) = tree.exprs[left] else { - panic!("not a case test: {:?}", tree.exprs[left]) - }; - assert_eq!(text(tree.exprs.span(test.value)), "a"); - assert_eq!(text(tree.types.span(test.case)), "E::B"); -} - -/// An arm is `_`, a case, or a case with the pattern of its payload: -/// `none`, `_`, a name, a struct pattern or another case. -#[test] -fn parses_matches() { - let (tree, errors) = parse_text( - "fn f() { - match shape { - Shape::Dot => { } - Shape::Line with .{ end } => { } - Shape::Maybe with none => { } - Shape::Wrap with Inner::Leaf with value => { } - Shape::Any with _ => { } - _ => { } - } - }", - ); - assert!(errors.is_empty(), "{errors:?}"); - let arms = (tree.stmts.ids()) - .find_map(|id| match tree.stmts[id] { - ast::Stmt::Feature(ast::FeatureStmt::Match(ast::Match { arms, .. })) => Some(arms), - _ => None, - }) - .unwrap(); - let found: Vec = (tree.children.lists.items(arms)) - .map(|arm| shape(&tree, tree.children.match_arms[arm].pattern)) - .collect(); - assert_eq!( - found, - [ - "Shape::Dot", - "Shape::Line(struct of 1)", - "Shape::Maybe(none)", - "Shape::Wrap(Inner::Leaf(bind value))", - "Shape::Any(_)", - "_" - ] - ); -} - -/// Each mistake is one error. -#[test] -fn errors() { - let path = "enum case must use a fully named path"; - for (text, message) in [ - ("a is b;", path), - ("a with 1;", path), - ("match x { a => {} }", path), - ("match x { A::B {} }", "expected `=>` after match case"), - ( - "match x { A::B => {}, _ => {} }", - "match arms do not use commas", - ), - ( - "match x { A::B with => {} }", - "expected a pattern after `with`", - ), - ] { - assert_eq!( - messages(&format!("fn f() {{ {text} }}")), - [message], - "{text}" - ); - } -} - -/// Broken input still gives a tree, and nesting far deeper than the -/// thread's stack would hold still parses. -#[test] -fn broken_and_deep_input() { - for text in [ - "fn f() { A::B with ; }", - "fn f() { match }", - "fn f() { match x { }", - "fn f() { match x { let } }", - ] { - let (tree, errors) = parse_text(text); - assert_eq!(tree.top_level.len(), 1, "{text}"); - assert!(!errors.is_empty(), "{text}"); - } - let deep = format!( - "fn f() {{ match x {{ {}c => {{}} }} }}", - "A::B with ".repeat(100_000) - ); - assert_eq!(parse_text(&deep).0.top_level.len(), 1); -} - -/// Nothing of an enum is checked yet, so each part is refused where it is -/// written. -#[test] -fn refused() { - let (_, reported) = bodies( - "enum E { A, B: i32 } - fn f(e: E) {} - fn g(a: i32) { E::B with a; } - fn h(a: i32) { a is E::A; } - fn i(a: i32) { match a { _ => { } } }", - ); - let found: Vec<&str> = (reported.iter()) - .map(|(_, message, _)| message.as_str()) - .collect(); - assert_eq!( - found, - [ - "enum declarations are not supported yet", - "variant literals are not supported yet", - "`is` tests are not supported yet", - "`match` statements are not supported yet", - ] - ); -} diff --git a/crates/features/src/interfaces.rs b/crates/features/src/interfaces.rs deleted file mode 100644 index bec0b842..00000000 --- a/crates/features/src/interfaces.rs +++ /dev/null @@ -1,118 +0,0 @@ -//! Interfaces: `iface { fn name(&self) -> Result, ... }`. The checker gives -//! the core's interface type, so the phases after it know nothing of -//! them. Interface references, owned interfaces and the conversion of a -//! struct to an interface are the core's: they read the checked type. - -use arena::Id; -use check::Checker; -use check::functions; -use check::scope::report_redeclared; -use model::DefId; -use model::semantic_types::Type; -use model::semantic_types::TypeId; -use parser::Parser; -use parser::Rules; -use parser::decl::type_decl; -use source::Span; -use syntax::ast; -use token::TokenKind; - -/// Adds the rules that read interfaces to `rules`. -pub(crate) const fn rows(rules: &mut Rules) { - rules.declaration(TokenKind::Iface, type_decl); - rules.type_start(TokenKind::Iface, interface_type); -} - -/// Reads `{ fn name(parameters) -> Result, ... }`, the methods of an -/// interface type that starts at `start`: function signatures without -/// bodies. A method takes no default values. -fn interface_type(p: &mut Parser, start: u32) -> Id { - let methods = p.delimited( - TokenKind::LeftBrace, - TokenKind::RightBrace, - true, - |_, kind| kind == TokenKind::Fn, - |p| { - let start = p.next().span.start; - let (name, signature) = p.named_signature(); - p.add( - start, - ast::Decl::Function(ast::Function { - metadata: ast::Metadata::NONE, - owner: None, - name, - signature, - body: None, - }), - ) - }, - ); - p.add( - start, - ast::Type::Feature(ast::FeatureType::Interface(ast::InterfaceType { methods })), - ) -} - -#[cfg(test)] -mod tests; - -/// The type an interface type written at `span` names: none yet, as only a -/// declared interface is checked. -pub(crate) fn resolve_interface_type( - checker: &mut Checker<'_>, - _ty: ast::InterfaceType, - span: Span, -) -> TypeId { - checker.not_supported(span, "interface types") -} - -/// The type the module's interface declaration `definition` declares: -/// each method's function type, whose `self` is a reference to the -/// interface (`Type::InterfaceReference`), or the interface taken whole. -/// Invalid when a method has an error or is declared twice, as a struct -/// is when a field has an error. -pub(crate) fn declare_interface_type( - checker: &mut Checker<'_>, - _ty: ast::InterfaceType, - definition: DefId, -) -> TypeId { - let modules = checker.modules; - let tree = &modules[definition.module.index()].ast; - let declared: Vec<&ast::Function> = model::program::interface_methods(modules, definition) - .expect("an interface declaration has methods") - .collect(); - let mut methods = Vec::with_capacity(declared.len()); - for (index, method) in declared.iter().enumerate() { - let text = method.name.text(&tree.file); - // An interface has few methods, so the ones before are searched. - if let Some(first) = declared[..index] - .iter() - .find(|first| first.name.text(&tree.file) == text) - { - let diagnostic = report_redeclared( - &tree.file, - text, - "interface", - method.name.span, - first.name.span, - ); - checker.report(diagnostic); - methods.push(TypeId::INVALID); - continue; - } - let kind = &functions::FunctionKind::INTERFACE_METHOD; - methods.push(checker.signature_type(method.name, method.signature, true, kind)); - } - let invalid = |ty: TypeId| match &checker.types[ty] { - Type::Function { - parameters, result, .. - } => parameters.contains(&TypeId::INVALID) || *result == TypeId::INVALID, - _ => true, - }; - if methods.iter().any(|&method| invalid(method)) { - return TypeId::INVALID; - } - let named = checker.declared_name(definition); - checker.types.define_interface(named, methods.into()); - named -} diff --git a/crates/features/src/interfaces/tests.rs b/crates/features/src/interfaces/tests.rs deleted file mode 100644 index 78343099..00000000 --- a/crates/features/src/interfaces/tests.rs +++ /dev/null @@ -1,108 +0,0 @@ -//! Reading interfaces. The parser's tree dump is its own tests', so these -//! look at the tree. - -use arena::Id; -use syntax::ast; - -use crate::testing::Tree; -use crate::testing::parse_text; - -/// The written type `ty` in short: `&self`, `&mut self`, or its text. -fn written_type(tree: &Tree, ty: Id) -> String { - match tree.types[ty] { - ast::Type::Reference { mutable, target } - if matches!(tree.types[target], ast::Type::Owner) => - { - if mutable { "&mut self" } else { "&self" }.to_string() - } - _ => tree.file.slice(tree.types.span(ty)).to_string(), - } -} - -/// Each method of the interface type `ty` as `name(name: type, ...) -> result`. -fn methods(tree: &Tree, ty: Id) -> Vec { - let ast::Type::Feature(ast::FeatureType::Interface(ast::InterfaceType { methods })) = - tree.types[ty] - else { - panic!("not an interface type: {:?}", tree.types[ty]) - }; - let method = |id| { - let ast::Decl::Function(function) = tree.decls[id] else { - panic!("an interface holds functions") - }; - assert!(function.body.is_none(), "a method has no body"); - let signature = function.signature; - let names = tree.children.lists.items(signature.type_parameters); - let names: Vec<_> = names - .map(|name| tree.file.slice(tree.children.names.span(name))) - .collect(); - let parameters: Vec<_> = (tree.children.lists.items(signature.parameters)) - .map(|parameter| { - let ast::Param { name, ty, .. } = tree.children.params[parameter]; - let name = name.map_or("_", |name| name.text(&tree.file)); - format!("{name}: {}", written_type(tree, ty)) - }) - .collect(); - let result = signature - .result - .map(|result| format!(" -> {}", written_type(tree, result))); - format!( - "{}<{}>({}){}", - function.name.text(&tree.file), - names.join(", "), - parameters.join(", "), - result.unwrap_or_default() - ) - }; - tree.children.lists.items(methods).map(method).collect() -} - -/// An interface declaration's type is an interface type, whose methods are -/// signatures without bodies. -#[test] -fn parses_declarations() { - let text = "iface Summer {\n fn sum(&self) -> i32,\n fn add(&mut self, value: T)\n}\n"; - let (tree, errors) = parse_text(text); - assert!(errors.is_empty(), "{errors:?}"); - let declarations: Vec<_> = tree.declarations().collect(); - assert_eq!(declarations.len(), 1); - let ast::Decl::Type(declared) = tree.decls[declarations[0]] else { - panic!("not a type declaration") - }; - assert_eq!(declared.name.text(&tree.file), "Summer"); - assert_eq!( - methods(&tree, declared.ty), - [ - "sum<>(self: &self) -> i32", - "add(self: &mut self, value: T)" - ] - ); -} - -/// A method's default value is read as any function's: checking a -/// signature refuses it, for every function alike. -#[test] -fn default_values_are_read() { - let (tree, errors) = parse_text("iface I { fn f(&self, a: i32 = 1) }"); - assert!(errors.is_empty()); - let ast::Decl::Type(declared) = tree.decls[tree.declarations().next().unwrap()] else { - panic!("not a type declaration") - }; - assert_eq!(methods(&tree, declared.ty), ["f<>(self: &self, a: i32)"]); -} - -/// Every span of a tree read from broken interfaces lies in the text and -/// starts before it ends. -#[test] -fn spans_lie_in_the_text() { - for text in ["iface I { fn", "iface I { fn (", "iface", "iface I {"] { - let (tree, _) = parse_text(text); - let spans = (tree.types.ids().map(|id| tree.types.span(id))) - .chain(tree.decls.ids().map(|id| tree.decls.span(id))) - .chain((tree.children.params.ids()).map(|id| tree.children.params.span(id))); - for span in spans { - let (start, end) = (span.start as usize, span.end as usize); - assert!(start <= end && end <= text.len(), "{text:?}: {span:?}"); - } - } -} diff --git a/crates/features/src/lib.rs b/crates/features/src/lib.rs deleted file mode 100644 index 674b20bc..00000000 --- a/crates/features/src/lib.rs +++ /dev/null @@ -1,135 +0,0 @@ -//! Peeper's features, one file each: a feature reads its own nodes (the -//! tree's `FeatureExpr`, `FeatureStmt` and `FeatureType`) and checks them. -//! This is the one place that names every feature: its parse rules -//! (`RULES`) and how the checker checks its nodes (`CHECK_HOOKS`), which -//! the driver hands to the phases (docs/structure-mapping.md, step 7). - -use check::CheckHooks; -use check::Checker; -use check::builder; -use model::DefId; -use model::semantic_types; -use model::thir; -use parser::Rules; -use source::Span; -use syntax::ast; - -mod arrays; -mod chars; -mod enums; -mod interfaces; -mod optionals; -mod pipes; -mod printing; -mod ranges; -mod raw_pointers; -mod structs; - -#[cfg(test)] -mod testing; - -/// Built once, when the compiler is: two rules for one token fail the build. -pub static RULES: Rules = { - let mut rules = Rules::core(); - arrays::rows(&mut rules); - chars::rows(&mut rules); - enums::rows(&mut rules); - interfaces::rows(&mut rules); - optionals::rows(&mut rules); - pipes::rows(&mut rules); - printing::rows(&mut rules); - ranges::rows(&mut rules); - raw_pointers::rows(&mut rules); - structs::rows(&mut rules); - rules -}; - -/// How the checker checks each feature's nodes: by its feature's file. -pub static CHECK_HOOKS: CheckHooks = CheckHooks { - check_expr, - check_stmt, - resolve_type, - declare_type, -}; - -/// The feature expression `expr`, written at `span`, where a value of the -/// type `expected` is wanted, if one is. -fn check_expr( - builder: &mut builder::ThirBuilder<'_, '_>, - expr: ast::FeatureExpr, - span: Span, - expected: Option, -) -> thir::Expr { - match expr { - ast::FeatureExpr::ArrayLiteral(literal) => { - arrays::check_array_literal(builder, literal, span) - } - ast::FeatureExpr::CaseTest(test) => enums::check_case_test(builder, test, span), - ast::FeatureExpr::Char(literal) => chars::check_char_literal(builder, literal, span), - ast::FeatureExpr::OrElse(or_else) => optionals::check_or_else(builder, or_else, span), - ast::FeatureExpr::Pipe(pipe) => pipes::check_pipe(builder, pipe, span), - ast::FeatureExpr::Print(print) => printing::check_print(builder, print, span), - ast::FeatureExpr::Range(range) => ranges::check_range(builder, range, span, expected), - ast::FeatureExpr::RawAddress(address) => { - raw_pointers::check_raw_address(builder, address, span) - } - ast::FeatureExpr::StructLiteral(literal) => { - structs::check_struct_literal(builder, literal, span, expected) - } - ast::FeatureExpr::VariantLiteral(literal) => { - enums::check_variant_literal(builder, literal, span) - } - } -} - -/// The feature statement `stmt`, written at `span`; `None` when it leaves -/// no statement, after an error. -fn check_stmt( - builder: &mut builder::ThirBuilder<'_, '_>, - stmt: ast::FeatureStmt, - span: Span, -) -> Option { - match stmt { - ast::FeatureStmt::Match(statement) => enums::check_match(builder, statement, span), - } -} - -/// The type the feature type `ty`, written at `span`, names. -fn resolve_type( - checker: &mut Checker<'_>, - ty: ast::FeatureType, - span: Span, -) -> semantic_types::TypeId { - match ty { - ast::FeatureType::Array(ty) => arrays::resolve_array_type(checker, ty, span), - ast::FeatureType::Enum(ty) => enums::resolve_enum_type(checker, ty, span), - ast::FeatureType::Interface(ty) => interfaces::resolve_interface_type(checker, ty, span), - ast::FeatureType::Optional(ty) => optionals::resolve_optional_type(checker, ty, span), - ast::FeatureType::Pointer(ty) => raw_pointers::resolve_pointer_type(checker, ty, span), - ast::FeatureType::Struct(ty) => structs::resolve_struct_type(checker, ty, span), - } -} - -/// The type the module's type declaration `definition`, written `written`, -/// declares with the feature type `ty`. -fn declare_type( - checker: &mut Checker<'_>, - definition: DefId, - written: ast::TypeDecl, - ty: ast::FeatureType, -) -> semantic_types::TypeId { - match ty { - ast::FeatureType::Enum(ty) => enums::declare_enum_type(checker, ty, written), - ast::FeatureType::Interface(ty) => { - interfaces::declare_interface_type(checker, ty, definition) - } - ast::FeatureType::Struct(ty) => { - structs::declare_struct_type(checker, ty, definition, written) - } - ast::FeatureType::Array(_) - | ast::FeatureType::Optional(_) - | ast::FeatureType::Pointer(_) => { - unreachable!("only `struct`, `iface` and `enum` begin a type declaration") - } - } -} diff --git a/crates/features/src/optionals.rs b/crates/features/src/optionals.rs deleted file mode 100644 index e518e3bd..00000000 --- a/crates/features/src/optionals.rs +++ /dev/null @@ -1,73 +0,0 @@ -//! Optional values: the type `?T` and `value orelse fallback`. Both are -//! read, and refused by the checker until optional values exist. - -use arena::Id; -use check::Checker; -use check::builder::ThirBuilder; -use model::semantic_types::TypeId; -use model::thir; -use parser::Parser; -use parser::Rules; -use source::Span; -use syntax::ast; -use syntax::operators::Precedence; -use token::TokenKind; - -/// Adds the rules that read optional types and `orelse` to `rules`. -pub(crate) const fn rows(rules: &mut Rules) { - rules.type_start(TokenKind::Question, optional_type); - rules.type_start(TokenKind::QuestionQuestion, doubled_optional_type); - rules.infix(TokenKind::Orelse, Precedence::OrElse, or_else); -} - -/// Reads the type after a `?` that starts at `start`. -fn optional_type(p: &mut Parser, start: u32) -> Id { - let inner = p.type_expr(); - let optional = ast::FeatureType::Optional(ast::OptionalType { inner }); - p.add(start, ast::Type::Feature(optional)) -} - -/// Reads the type after a `??`, one token holding two markers. The second -/// changes nothing (`??T` is `?T`); it is kept in the tree as written and -/// left to a lint to report. -fn doubled_optional_type(p: &mut Parser, start: u32) -> Id { - let inner = optional_type(p, start + 1); - let optional = ast::FeatureType::Optional(ast::OptionalType { inner }); - p.add(start, ast::Type::Feature(optional)) -} - -/// Reads `orelse fallback` or `orelse { block }` after `value`. The fallback -/// may itself end in `orelse`: a orelse b orelse c is a orelse (b orelse c). -fn or_else(p: &mut Parser, value: Id) -> Id { - p.next(); - let fallback = if p.at(TokenKind::LeftBrace) { - ast::OrElseFallback::Block(p.block()) - } else { - // One below OrElse: groups to the right. - ast::OrElseFallback::Value(p.expr(Precedence::Lowest)) - }; - let or_else = ast::FeatureExpr::OrElse(ast::OrElse { value, fallback }); - p.add(p.start_of(value), ast::Expr::Feature(or_else)) -} - -#[cfg(test)] -mod tests; - -/// `?T` at `span`, which no check exists for yet. -pub(crate) fn resolve_optional_type( - checker: &mut Checker<'_>, - _ty: ast::OptionalType, - span: Span, -) -> TypeId { - checker.not_supported(span, "optional types") -} - -/// `value orelse fallback` at `span`, which no check exists for yet. -pub(crate) fn check_or_else( - builder: &mut ThirBuilder<'_, '_>, - _or_else: ast::OrElse, - span: Span, -) -> thir::Expr { - builder.checker.not_supported(span, "`orelse` fallbacks"); - thir::Expr::INVALID -} diff --git a/crates/features/src/optionals/tests.rs b/crates/features/src/optionals/tests.rs deleted file mode 100644 index 40cca7bd..00000000 --- a/crates/features/src/optionals/tests.rs +++ /dev/null @@ -1,106 +0,0 @@ -//! Reading optional types and `orelse`, and their refusal. - -use arena::Id; -use syntax::ast; - -use crate::testing::Tree; -use crate::testing::bodies; -use crate::testing::messages; -use crate::testing::parse_text; -use crate::testing::statements; - -/// `expr` with each `orelse` in parentheses; a block fallback as `{}`. -fn grouped(tree: &Tree, expr: Id) -> String { - match tree.exprs[expr] { - ast::Expr::Feature(ast::FeatureExpr::OrElse(ast::OrElse { value, fallback })) => { - let fallback = match fallback { - ast::OrElseFallback::Value(fallback) => grouped(tree, fallback), - ast::OrElseFallback::Block(_) => "{}".to_string(), - }; - format!("({} orelse {fallback})", grouped(tree, value)) - } - _ => tree.file.slice(tree.exprs.span(expr)).to_string(), - } -} - -/// `orelse` groups to the right and binds looser than `||` and `..`; its -/// fallback may be a block. -#[test] -fn parses_or_else() { - let text = - "fn f() { a orelse b orelse c; a || b orelse { return; }; d orelse e..f; g..h orelse i; }"; - let (tree, errors) = parse_text(text); - assert!(errors.is_empty(), "{errors:?}"); - let found: Vec = (statements(&tree).into_iter()) - .map(|statement| grouped(&tree, statement)) - .collect(); - assert_eq!( - found, - [ - "(a orelse (b orelse c))", - "(a || b orelse {})", - "(d orelse e..f)", - "g..h orelse i" - ] - ); - // The last one is a range whose end is the `orelse`. - let last = (tree.exprs.ids()) - .filter(|&id| { - matches!( - tree.exprs[id], - ast::Expr::Feature(ast::FeatureExpr::OrElse(_)) - ) - }) - .last() - .unwrap(); - assert_eq!(tree.file.slice(tree.exprs.span(last)), "h orelse i"); -} - -/// Each `?` is one optional type, and `??` is two; a missing fallback is -/// one error. -#[test] -fn parses_types() { - let (tree, errors) = parse_text("fn f(a: ?i32, b: ??i32, c: ? ??u8);"); - assert!(errors.is_empty(), "{errors:?}"); - let optionals = (tree.types.ids()) - .filter(|&id| { - matches!( - tree.types[id], - ast::Type::Feature(ast::FeatureType::Optional(_)) - ) - }) - .map(|id| tree.file.slice(tree.types.span(id))) - .collect::>(); - assert_eq!(optionals.len(), 6, "{optionals:?}"); - assert!(optionals.contains(&"?i32") && optionals.contains(&"??i32")); - assert_eq!(messages("fn f() { a orelse ; }").len(), 1); -} - -/// Nesting far deeper than the thread's stack would hold still parses. -#[test] -fn deep_nesting_does_not_overflow() { - let n = 100_000; - for text in [ - format!("fn f() {{ let a = b{}", " orelse { c".repeat(n)), - format!("fn f(a: {}i32) {{}}", "?".repeat(n)), - ] { - let (tree, _) = parse_text(&text); - assert_eq!(tree.top_level.len(), 1); - } -} - -/// Neither is checked yet, so each is refused where it is written. -#[test] -fn refused() { - let (_, reported) = bodies("fn f(a: ?i32) {}\nfn g(b: i32) { b orelse 1; }"); - let found: Vec<(&str, &str)> = (reported.iter()) - .map(|(_, message, text)| (message.as_str(), text.as_str())) - .collect(); - assert_eq!( - found, - [ - ("optional types are not supported yet", "?i32"), - ("`orelse` fallbacks are not supported yet", "b orelse 1"), - ] - ); -} diff --git a/crates/features/src/pipes.rs b/crates/features/src/pipes.rs deleted file mode 100644 index 87fc7c1f..00000000 --- a/crates/features/src/pipes.rs +++ /dev/null @@ -1,57 +0,0 @@ -//! Pipes: `value |> f(arguments)` is the call `f(value, arguments)`. - -use arena::Id; -use check::builder::ThirBuilder; -use model::thir; -use parser::Parser; -use parser::Rules; -use source::Span; -use syntax::ast; -use syntax::operators::Precedence; -use token::TokenKind; - -/// Adds the rule that reads pipes to `rules`. -pub(crate) const fn rows(rules: &mut Rules) { - rules.infix(TokenKind::PipeArrow, Precedence::Pipe, pipe); -} - -/// Reads `|> target` after `value`. The target takes only what binds -/// tighter than a prefix operator, so `a |> len() as i32` is -/// (a |> len()) as i32. -fn pipe(p: &mut Parser, value: Id) -> Id { - p.next(); - let target = p.expr(Precedence::Prefix); - let pipe = ast::FeatureExpr::Pipe(ast::Pipe { value, target }); - p.add(p.start_of(value), ast::Expr::Feature(pipe)) -} - -#[cfg(test)] -mod tests; - -/// `value |> target` at `span`: its target must be a call, which is checked -/// with the value as its first written argument, so a method takes it after -/// its `self`. -pub(crate) fn check_pipe( - builder: &mut ThirBuilder<'_, '_>, - pipe: ast::Pipe, - span: Span, -) -> thir::Expr { - let tree = &builder.checker.module().ast; - let ast::Expr::Call { - callee, - type_arguments, - arguments, - } = tree.exprs[pipe.target] - else { - let target = tree.exprs.span(pipe.target); - let message = "a pipe's target must be a call"; - builder - .checker - .error(diagnostics::INVALID_OPERATION, message, target); - builder.add_expr(pipe.value, None); // for its own errors - return thir::Expr::INVALID; - }; - let mut given = vec![pipe.value]; - given.extend(tree.children.lists.items(arguments)); - builder.check_call(callee, type_arguments, &given, span) -} diff --git a/crates/features/src/pipes/tests.rs b/crates/features/src/pipes/tests.rs deleted file mode 100644 index 0be712dc..00000000 --- a/crates/features/src/pipes/tests.rs +++ /dev/null @@ -1,69 +0,0 @@ -//! Reading pipes, and checking them as calls. - -use arena::Id; -use syntax::ast; - -use crate::testing::Tree; -use crate::testing::bodies; -use crate::testing::parse_text; -use crate::testing::statements; - -/// `expr` with each pipe in parentheses. -fn grouped(tree: &Tree, expr: Id) -> String { - match tree.exprs[expr] { - ast::Expr::Feature(ast::FeatureExpr::Pipe(ast::Pipe { value, target })) => { - format!("({} |> {})", grouped(tree, value), grouped(tree, target)) - } - _ => tree.file.slice(tree.exprs.span(expr)).to_string(), - } -} - -/// A pipe groups to the left and binds looser than `+`; what is written -/// after its target, as `as`, takes the whole pipe. Any target is read: -/// the checker says what one may be. -#[test] -fn parses_pipes() { - let (tree, errors) = - parse_text("fn f() { a |> f(b) |> g(); a + b |> f(); a |> b; c |> len() as i32; }"); - assert!(errors.is_empty(), "{errors:?}"); - let found: Vec = (statements(&tree).into_iter()) - .map(|statement| grouped(&tree, statement)) - .collect(); - assert_eq!( - found[..3], - ["((a |> f(b)) |> g())", "(a + b |> f())", "(a |> b)"] - ); - let last = (tree.exprs.ids()) - .filter(|&id| { - matches!( - tree.exprs[id], - ast::Expr::Feature(ast::FeatureExpr::Pipe(_)) - ) - }) - .last() - .unwrap(); - assert_eq!(tree.file.slice(tree.exprs.span(last)), "c |> len()"); -} - -/// A pipe is checked as the call of its target with the value first. -#[test] -fn checked_as_calls() { - let (found, reported) = bodies("fn g(a: i32, b: i32) {}\nfn f(a: i32) { a |> g(2); }"); - assert!(reported.is_empty(), "{reported:?}"); - assert!(found[1].contains("(a.0, 2:i32)"), "{found:?}"); - let (_, reported) = bodies( - "fn g(a: i32) -> i32 { return a; }\nfn f(a: bool) { a |> g(); 1 |> g(2); 1 |> g; 1 |> g().x; }", - ); - let found: Vec<(&str, &str)> = (reported.iter()) - .map(|(_, message, text)| (message.as_str(), text.as_str())) - .collect(); - assert_eq!( - found, - [ - ("mismatched types: expected `i32`, found `bool`", "a"), - ("`g` takes 1 argument, but 2 were given", "1 |> g(2)"), - ("a pipe's target must be a call", "g"), - ("a pipe's target must be a call", "g().x"), - ] - ); -} diff --git a/crates/features/src/printing/tests.rs b/crates/features/src/printing/tests.rs deleted file mode 100644 index f5cf31bc..00000000 --- a/crates/features/src/printing/tests.rs +++ /dev/null @@ -1,33 +0,0 @@ -//! Reading `print` and `println`. What they accept is the test programs' -//! to show. - -use syntax::ast; - -use crate::testing::messages; -use crate::testing::parse_text; - -/// Each takes any number of values, none too; `println` is the one with a -/// newline. -#[test] -fn parses_prints() { - let (tree, errors) = parse_text("fn f() { print(); println(items[n], 1); }"); - assert!(errors.is_empty(), "{errors:?}"); - let prints: Vec<(bool, usize)> = (tree.exprs.ids()) - .filter_map(|id| match tree.exprs[id] { - ast::Expr::Feature(ast::FeatureExpr::Print(ast::Print { newline, values })) => { - Some((newline, values.len())) - } - _ => None, - }) - .collect(); - assert_eq!(prints, [(false, 0), (true, 2)]); -} - -/// An unclosed list is one error, and the statement after it is read. -#[test] -fn unclosed_values() { - assert_eq!( - messages("fn f() { print(; return; }"), - ["expected `)`, found `;`"] - ); -} diff --git a/crates/features/src/ranges.rs b/crates/features/src/ranges.rs deleted file mode 100644 index 16f781f7..00000000 --- a/crates/features/src/ranges.rs +++ /dev/null @@ -1,168 +0,0 @@ -//! Ranges: `a..b`, `a..=b`, `a..b:step`, and `..b` or `a..` before a `]`. -//! The written parts are the core's `WrittenRange`, as slicing reads them -//! (`Tree::written_range`); this file reads them and checks a range -//! value into the core's `range[T]`, so the phases after it know nothing of -//! them. - -use arena::Id; -use bigint::Limbs; -use check::builder::ThirBuilder; -use diagnostics::Diagnostic; -use model::constant::Value; -use model::semantic_types::Type; -use model::semantic_types::TypeId; -use model::thir; -use parser::Parser; -use parser::Rules; -use source::Span; -use syntax::ast; -use syntax::ast::WrittenRange; -use syntax::operators::Precedence; -use token::TokenKind; - -/// Adds the rules that read ranges to `rules`. -pub(crate) const fn rows(rules: &mut Rules) { - rules.prefix(TokenKind::DotDot, open_range); - rules.prefix(TokenKind::DotDotEqual, open_range); - rules.infix(TokenKind::DotDot, Precedence::Range, range); - rules.infix(TokenKind::DotDotEqual, Precedence::Range, range); -} - -/// Reads a range with no start: `..b`, `..=b`, or `..` before `]`. -fn open_range(p: &mut Parser) -> Id { - let start = p.tok().span.start; - range_from(p, start, None) -} - -/// Reads a range from `low`: `a..b`, `a..=b`, or `a..` before `]`. -fn range(p: &mut Parser, low: Id) -> Id { - range_from(p, p.start_of(low), Some(low)) -} - -/// Reads `..` or `..=` and what follows it: an end, then `:step` to step by -/// more than one. Only right before the `]` may a range leave out its end. -fn range_from(p: &mut Parser, start: u32, low: Option>) -> Id { - let op = p.next(); - let mut high = None; - if !p.at(TokenKind::RightBracket) { - high = Some(p.expr(Precedence::Range)); - } else if op.kind == TokenKind::DotDotEqual { - p.repair( - Diagnostic::new( - diagnostics::INVALID_EXPRESSION, - "inclusive range requires an end bound", - ) - .label( - &p.tree.file, - op.span, - "add the inclusive end bound after `..=`", - ), - ); - } - let mut step = None; - if high.is_some() && p.at(TokenKind::Colon) { - p.next(); - step = Some(p.expr(Precedence::Range)); - } - let inclusive = op.kind == TokenKind::DotDotEqual; - let written = WrittenRange { - inclusive, - start: low, - end: high, - step, - }; - p.add( - start, - ast::Expr::Feature(ast::FeatureExpr::Range(ast::Range { written })), - ) -} - -/// The step of a range, written `step` or else 1 at `range_span`, of -/// the range type's step type `step_type` (`Types::range`), and not a -/// constant zero. With an invalid `step_type`, after an error in the -/// ends, it is checked only for its own errors. -fn check_range_step( - builder: &mut ThirBuilder<'_, '_>, - step: Option>, - step_type: TypeId, - range_span: Span, -) -> Id { - let Some(step) = step else { - let one = match builder.checker.types[step_type] { - Type::Integer(unsigned) => thir::Expr { - ty: step_type, - kind: thir::ExprKind::Constant(Value::Integer(Limbs::new(unsigned.bits, &[1]))), - }, - _ => thir::Expr::INVALID, - }; - return builder.body.add(one, range_span); - }; - let step = match step_type { - TypeId::INVALID => builder.add_expr(step, None), - ty => builder.add_required(step, ty), - }; - if let thir::ExprKind::Constant(Value::Integer(limbs)) = &builder.body.exprs[step].kind - && limbs.as_slice().iter().all(|&limb| limb == 0) - { - let span = builder.body.exprs.span(step); - let message = "a range's step must not be zero"; - builder - .checker - .error(diagnostics::INVALID_OPERATION, message, span); - } - step -} - -#[cfg(test)] -mod tests; - -/// The range `start..end`, or `..=`, stepping by `start..end:step`, at -/// `span`: a `range[T]` of its ends' integer type `T`. A literal end -/// without a suffix takes the other end's type, or `T` when a -/// `range[T]` is `expected`; the step is of the range type's step type -/// and not a constant zero (`check_range_step`). A range without both -/// ends is not supported yet. -pub(crate) fn check_range( - builder: &mut ThirBuilder<'_, '_>, - range: ast::Range, - span: Span, - expected: Option, -) -> thir::Expr { - let WrittenRange { - inclusive, - start: Some(start), - end: Some(end), - step, - } = range.written - else { - builder - .checker - .not_supported(span, "ranges without both ends"); - return thir::Expr::INVALID; - }; - let hint = expected.and_then(|ty| match builder.checker.types[ty] { - Type::Range { element, .. } => Some(element), - _ => None, - }); - let (start, end) = builder.check_range_ends(start, end, hint); - let ty = builder - .checker - .range_type(builder.body.exprs[start].ty, span); - let step_type = match builder.checker.types[ty] { - Type::Range { step, .. } => step, - _ => TypeId::INVALID, - }; - let step = check_range_step(builder, step, step_type, span); - if ty == TypeId::INVALID { - return thir::Expr::INVALID; - } - thir::Expr { - ty, - kind: thir::ExprKind::Range { - start, - end, - step, - inclusive, - }, - } -} diff --git a/crates/features/src/ranges/tests.rs b/crates/features/src/ranges/tests.rs deleted file mode 100644 index 26f5ab14..00000000 --- a/crates/features/src/ranges/tests.rs +++ /dev/null @@ -1,115 +0,0 @@ -//! Reading and checking ranges. The parser's tree dump and the checker's -//! test program are those crates' own, so these build what they need. - -use arena::Id; -use syntax::ast; -use syntax::ast::WrittenRange; - -use crate::testing::Tree; -use crate::testing::bodies; -use crate::testing::parse_text; - -/// The expression `id` with each range and binary operation in -/// parentheses, and the rest as written. -fn grouped(tree: &Tree, id: Id) -> String { - let text = |span| tree.file.slice(span).to_string(); - match tree.exprs[id] { - ast::Expr::Feature(ast::FeatureExpr::Range(ast::Range { written })) => { - let WrittenRange { - inclusive, - start, - end, - step, - } = written; - let part = |part: Option>| { - part.map_or(String::new(), |part| grouped(tree, part)) - }; - let op = if inclusive { "..=" } else { ".." }; - let step = step.map_or(String::new(), |step| format!(":{}", grouped(tree, step))); - format!("({}{op}{}{step})", part(start), part(end)) - } - ast::Expr::Binary { op, left, right } => { - let (left, right) = (grouped(tree, left), grouped(tree, right)); - format!("({left} {} {right})", op.symbol()) - } - ast::Expr::Index { value, index } => { - format!("{}[{}]", grouped(tree, value), grouped(tree, index)) - } - _ => text(tree.exprs.span(id)), - } -} - -/// A range binds looser than every binary operator, its step is read as an end is, and ranges group to the left. -#[test] -fn precedence() { - for (text, want) in [ - ("x.y.z[0][i..j]", "x.y.z[0][(i..j)]"), - ("a + b..c * d", "((a + b)..(c * d))"), - ("a..=b:c + d", "(a..=b:(c + d))"), - ("a..b..c", "((a..b)..c)"), - ("a[..b]", "a[(..b)]"), - ("a[b..]", "a[(b..)]"), - ] { - let (tree, errors) = parse_text(&format!("fn f() {{ {text}; }}")); - assert!(errors.is_empty(), "{text}: {errors:?}"); - let decl = tree.declarations().next().unwrap(); - let ast::Decl::Function(function) = tree.decls[decl] else { - panic!("not a function") - }; - let statements = tree.blocks[function.body.unwrap()].statements; - let statement = tree.children.lists.items(statements).next().unwrap(); - let ast::Stmt::Expression(expr) = tree.stmts[statement] else { - panic!("not an expression statement") - }; - assert_eq!(grouped(&tree, expr), want, "{text}"); - } -} - -/// Only right before a `]` may a range leave out its end, and an inclusive -/// one never. -#[test] -fn open_ends() { - for (text, message) in [ - ( - "fn f() { a[1..=]; }", - "inclusive range requires an end bound", - ), - ( - "fn f() { for i in 0.. { } }", - "expected expression, found `{`", - ), - ] { - let (_, errors) = parse_text(text); - let got: Vec<_> = errors.iter().map(|e| e.message.as_str()).collect(); - assert_eq!(got, [message], "{text}"); - } -} - -/// A range's literal start takes the end's type; its variables are -/// declared in the body. Its step is the ends' type made unsigned, 1 -/// when not written. -#[test] -fn loops() { - let (bodies, reported) = bodies( - "fn f(n: i64) { - for i in 0..n { let j = i; } - for 0..3 { } - for k in 1..=n { } - for i, m in n..0:2 { } - }", - ); - assert!(reported.is_empty(), "{reported:?}"); - assert_eq!( - bodies, - [" for i.1 in 0:i64..n.0 by 1:u64 { - let j.2 = i.1 - } - for 0:i32..3:i32 by 1:u32 { - } - for k.3 in 1:i64..=n.0 by 1:u64 { - } - for i.4, m.5 in n.0..0:i64 by 2:u64 { - } -"] - ); -} diff --git a/crates/features/src/raw_pointers.rs b/crates/features/src/raw_pointers.rs deleted file mode 100644 index 8051916e..00000000 --- a/crates/features/src/raw_pointers.rs +++ /dev/null @@ -1,99 +0,0 @@ -//! Raw pointers: `rawptr`, `*T` and `@x`. The checker gives the core's raw -//! pointer type and address (`Type::RawPointer`, `ExprKind::Address`), so -//! the phases after it know nothing of them. A pointer's operations -//! (`==`, `rawptr + usize`), `.*` through it and `none` are the core's: they -//! read the checked type. - -use arena::Id; -use check::Checker; -use check::builder::ThirBuilder; -use model::semantic_types::Type; -use model::semantic_types::TypeId; -use model::thir; -use parser::Parser; -use parser::Rules; -use source::Span; -use syntax::ast; -use syntax::operators::Precedence; -use token::TokenKind; - -/// Adds the rules that read raw pointer types and `@place` to `rules`. -pub(crate) const fn rows(rules: &mut Rules) { - rules.type_start(TokenKind::Asterisk, typed_pointer); - rules.type_start(TokenKind::Rawptr, raw_pointer); - // types that cannot be values - rules.prefix(TokenKind::Asterisk, type_value); - rules.prefix(TokenKind::Rawptr, type_value); - rules.prefix(TokenKind::At, raw_address); -} - -/// Reads the `T` of `*T`, a pointer type that starts at `start`. -fn typed_pointer(p: &mut Parser, start: u32) -> Id { - let target = Some(p.type_expr()); - p.add( - start, - ast::Type::Feature(ast::FeatureType::Pointer(ast::PointerType { target })), - ) -} - -/// `rawptr`, which starts at `start`. -fn raw_pointer(p: &mut Parser, start: u32) -> Id { - p.add( - start, - ast::Type::Feature(ast::FeatureType::Pointer(ast::PointerType { target: None })), - ) -} - -/// Reads a type that cannot be a value (`*T`, `rawptr`) where a value could -/// go. -fn type_value(p: &mut Parser) -> Id { - let start = p.tok().span.start; - let ty = p.type_expr(); - p.add(start, ast::Expr::Type(ty)) -} - -/// Reads `@x`. -fn raw_address(p: &mut Parser) -> Id { - let start = p.next().span.start; - let place = p.expr(Precedence::Prefix); - p.add( - start, - ast::Expr::Feature(ast::FeatureExpr::RawAddress(ast::RawAddress { place })), - ) -} - -#[cfg(test)] -mod tests; - -/// The type `rawptr`, or `*target`, written at `span`. -pub(crate) fn resolve_pointer_type( - checker: &mut Checker<'_>, - ty: ast::PointerType, - span: Span, -) -> TypeId { - let Some(target) = ty.target else { - return TypeId::RAWPTR; - }; - // A pointer only names its target, so a struct can point to itself. - // shortcut: `*[2]Node` or `*Alias` of `Node` in `Node` is a cycle, as - // an array's element and an alias's target are complete, and so is - // any cycle through such a pointer; let them stay names too if a - // program needs it. - let pointee = checker.resolve_type(target); - match checker.written_pointer_target(pointee, span) { - Some(target) => checker.types.intern(Type::RawPointer { - target: Some(target), - }), - None => TypeId::INVALID, - } -} - -/// `@place`, written at `span`. -pub(crate) fn check_raw_address( - builder: &mut ThirBuilder<'_, '_>, - address: ast::RawAddress, - span: Span, -) -> thir::Expr { - let place = builder.add_expr(address.place, None); - builder.check_address(place, span) -} diff --git a/crates/features/src/raw_pointers/tests.rs b/crates/features/src/raw_pointers/tests.rs deleted file mode 100644 index 2703b07d..00000000 --- a/crates/features/src/raw_pointers/tests.rs +++ /dev/null @@ -1,93 +0,0 @@ -//! Reading raw pointers. The parser's tree dump is its own tests', so these -//! look at the tree. - -use arena::Id; -use syntax::ast; - -use crate::testing::Tree; -use crate::testing::parse_text; -use crate::testing::statements; - -/// The written type `ty` as `*` for each pointer to a pointer, then -/// `rawptr` or the innermost type's text. -fn shape(tree: &Tree, ty: Id) -> String { - match tree.types[ty] { - ast::Type::Feature(ast::FeatureType::Pointer(ast::PointerType { - target: Some(target), - })) => format!("*{}", shape(tree, target)), - ast::Type::Feature(ast::FeatureType::Pointer(ast::PointerType { target: None })) => { - "rawptr".to_string() - } - ast::Type::Reference { target, .. } => format!("&{}", shape(tree, target)), - _ => tree.file.slice(tree.types.span(ty)).to_string(), - } -} - -/// The types of the parameters of the first function of `tree`. -fn parameter_types(tree: &Tree) -> Vec { - let decl = tree.declarations().next().unwrap(); - let ast::Decl::Function(function) = tree.decls[decl] else { - panic!("not a function") - }; - (tree.children.lists.items(function.signature.parameters)) - .map(|parameter| shape(tree, tree.children.params[parameter].ty)) - .collect() -} - -/// A pointer's target is any type, a pointer or `rawptr` too, and a -/// pointer is any type's part. -#[test] -fn parses_types() { - let (tree, errors) = parse_text("fn f(a: *u8, b: **u8, c: *rawptr, d: rawptr, e: &*rawptr);"); - assert!(errors.is_empty(), "{errors:?}"); - assert_eq!( - parameter_types(&tree), - ["*u8", "**u8", "*rawptr", "rawptr", "&*rawptr"] - ); -} - -/// A spelling that can only be a type is read as one where a value could -/// go, for an argument that takes a type; `@` takes the place after it. -#[test] -fn parses_expressions() { - let (tree, errors) = parse_text("fn f() { g(*Node, rawptr); @a.b; }"); - assert!(errors.is_empty(), "{errors:?}"); - let found = statements(&tree); - let ast::Expr::Call { arguments, .. } = tree.exprs[found[0]] else { - panic!("not a call: {:?}", tree.exprs[found[0]]) - }; - let types: Vec = (tree.children.lists.items(arguments)) - .map(|argument| match tree.exprs[argument] { - ast::Expr::Type(ty) => shape(&tree, ty), - other => panic!("not a type: {other:?}"), - }) - .collect(); - assert_eq!(types, ["*Node", "rawptr"]); - let ast::Expr::Feature(ast::FeatureExpr::RawAddress(ast::RawAddress { place })) = - tree.exprs[found[1]] - else { - panic!("not a raw address: {:?}", tree.exprs[found[1]]) - }; - assert_eq!(tree.file.slice(tree.exprs.span(place)), "a.b"); -} - -/// Every span of a tree read from broken pointers lies in the text and -/// starts before it ends. -#[test] -fn spans_lie_in_the_text() { - for text in [ - "fn f(a: *", - "fn f(a: *) {}", - "fn f() { @ }", - "fn f() { g(*); }", - ] { - let (tree, _) = parse_text(text); - let spans = (tree.types.ids().map(|id| tree.types.span(id))) - .chain(tree.exprs.ids().map(|id| tree.exprs.span(id))) - .chain(tree.decls.ids().map(|id| tree.decls.span(id))); - for span in spans { - let (start, end) = (span.start as usize, span.end as usize); - assert!(start <= end && end <= text.len(), "{text:?}: {span:?}"); - } - } -} diff --git a/crates/features/src/structs/tests.rs b/crates/features/src/structs/tests.rs deleted file mode 100644 index bb791cf2..00000000 --- a/crates/features/src/structs/tests.rs +++ /dev/null @@ -1,222 +0,0 @@ -//! Reading structs. The parser's tree dump is its own tests', so these look -//! at the tree. - -use arena::Id; -use diagnostics::Diagnostic; -use source::Span; -use syntax::ast; - -use crate::testing::Tree; -use crate::testing::messages; -use crate::testing::parse_text; -use crate::testing::statements; - -/// `text` with the fixes of the first help of `d` applied. -fn fixed(text: &str, d: &Diagnostic) -> String { - let mut text = text.to_string(); - for fix in d.notes[0].fixes().iter().rev() { - text.replace_range(fix.span.range(), &fix.new_text); - } - text -} - -/// Checks that `text` gives exactly one error, `message`, and that its fix -/// (when `want_fixed` is given) gives `want_fixed`. -fn one_error(text: &str, message: &str, want_fixed: Option<&str>) { - let (_, errors) = parse_text(text); - let got: Vec<_> = errors.iter().map(|e| e.message.as_str()).collect(); - assert_eq!(got, [message], "{text:?}"); - if let Some(want) = want_fixed { - assert_eq!(fixed(text, &errors[0]), want, "{text:?}"); - } -} - -fn written(tree: &Tree, span: Span) -> &str { - tree.file.slice(span) -} - -/// The fields of the struct type `ty`: each as `name: type`, the type as -/// written, and the type. -fn fields(tree: &Tree, ty: Id) -> Vec<(String, Id)> { - let ast::Type::Feature(ast::FeatureType::Struct(ast::StructType { fields })) = tree.types[ty] - else { - panic!("not a struct type: {:?}", tree.types[ty]) - }; - let field = |id| { - let ast::Field { name, ty } = tree.children.fields[id]; - let field = format!( - "{}: {}", - name.text(&tree.file), - written(tree, tree.types.span(ty)) - ); - (field, ty) - }; - tree.children.lists.items(fields).map(field).collect() -} - -/// The struct literal `expr`: its type as written, if any, and each field -/// as `name = value`, the value as written. -fn literal(tree: &Tree, expr: Id) -> (Option<&str>, Vec) { - let ast::Expr::Feature(ast::FeatureExpr::StructLiteral(ast::StructLiteral { ty, fields })) = - tree.exprs[expr] - else { - panic!("not a struct literal: {:?}", tree.exprs[expr]) - }; - let field = |id| { - let ast::FieldValue { name, value } = tree.children.field_values[id]; - format!( - "{} = {}", - name.text(&tree.file), - written(tree, tree.exprs.span(value)) - ) - }; - let ty = ty.map(|ty| written(tree, tree.types.span(ty))); - (ty, tree.children.lists.items(fields).map(field).collect()) -} - -/// A struct declaration's type is a struct type, which a field's type can -/// be too; a `;` after its `}` is allowed. -#[test] -fn parses_declarations() { - let text = "struct Pair {\n first: T,\n second: struct { flag: bool },\n};\n"; - let (tree, errors) = parse_text(text); - assert!(errors.is_empty(), "{errors:?}"); - let declarations: Vec<_> = tree.declarations().collect(); - assert_eq!(declarations.len(), 1); - let ast::Decl::Type(declared) = tree.decls[declarations[0]] else { - panic!("not a type declaration") - }; - assert_eq!(declared.name.text(&tree.file), "Pair"); - assert_eq!(declared.type_parameters.len(), 1); - let found = fields(&tree, declared.ty); - let names: Vec<_> = found.iter().map(|(field, _)| field.as_str()).collect(); - assert_eq!(names, ["first: T", "second: struct { flag: bool }"]); - let nested = fields(&tree, found[1].1); - assert_eq!(nested[0].0, "flag: bool"); - assert_eq!(nested.len(), 1); -} - -#[test] -fn declaration_errors() { - one_error( - "struct S { a i32 }", - "expected `:`, found `identifier`", - None, - ); -} - -/// A literal with a type, without one, and as an argument. -#[test] -fn parses_expressions() { - let text = "fn f() {\n Point.{ x = 1, y = -2 };\n .{ a = &mut v, b = !flag };\n line(.{ end = Box::::new(1) });\n}\n"; - let (tree, errors) = parse_text(text); - assert!(errors.is_empty(), "{errors:?}"); - let found = statements(&tree); - assert_eq!( - literal(&tree, found[0]), - (Some("Point"), vec!["x = 1".into(), "y = -2".into()]) - ); - assert_eq!( - literal(&tree, found[1]), - (None, vec!["a = &mut v".into(), "b = !flag".into()]) - ); - let ast::Expr::Call { arguments, .. } = tree.exprs[found[2]] else { - panic!("not a call") - }; - let argument = tree.children.lists.items(arguments).next().unwrap(); - assert_eq!( - literal(&tree, argument), - (None, vec!["end = Box::::new(1)".into()]) - ); -} - -#[test] -fn expression_errors() { - one_error( - "fn f() { .{ a: 1, b: 2 }; }", - "expected `=` after struct literal field name", - None, - ); -} - -/// In an expression, type arguments follow `::`, before `.{` too. -#[test] -fn comparison_is_not_type_arguments() { - let (tree, errors) = parse_text("fn f() { Pair::.{}; }"); - assert!(errors.is_empty(), "{errors:?}"); - assert_eq!( - literal(&tree, statements(&tree)[0]), - (Some("Pair::"), Vec::new()) - ); -} - -/// Every span of a tree read from broken structs lies in the text and -/// starts before it ends. -#[test] -fn spans_lie_in_the_text() { - for text in [ - "fn f() { .{ a = }; }", - "fn f() { .{ a: 1, b: 2 }; }", - "fn f() { a::.{}; }", - "struct", - "struct S {", - "struct S { a: }", - "struct S {} struct", - "fn f() {\nstruct S {}", - ] { - let (tree, _) = parse_text(text); - let spans = (tree.exprs.ids().map(|id| tree.exprs.span(id))) - .chain(tree.types.ids().map(|id| tree.types.span(id))) - .chain(tree.decls.ids().map(|id| tree.decls.span(id))) - .chain(tree.stmts.ids().map(|id| tree.stmts.span(id))) - .chain(tree.blocks.ids().map(|id| tree.blocks.span(id))) - .chain( - tree.children - .fields - .ids() - .map(|id| tree.children.fields.span(id)), - ) - .chain( - (tree.children.field_values.ids()).map(|id| tree.children.field_values.span(id)), - ); - for span in spans { - let (start, end) = (span.start as usize, span.end as usize); - assert!(start <= end && end <= text.len(), "{text:?}: {span:?}"); - } - } -} - -/// A closer that comes later means what stands before it does not belong: -/// that is reported once, and the list ends at its own closer. -#[test] -fn missing_token_place() { - let (tree, errors) = parse_text("fn f() { let p = Point.{ .x = 1, y = 2 }; }\nfn g() {}"); - let got: Vec<_> = errors.iter().map(|e| e.message.as_str()).collect(); - assert_eq!(got, ["expected `}`, found `.`"]); - assert_eq!(tree.top_level.len(), 2); -} - -/// Extra and trailing commas are left to a lint; a `;` for a `,` is -/// repaired with one error per list. -#[test] -fn separators() { - for text in [ - "struct S { a: i32, b: i32, }", - "fn f() { let p = .{ a = 1,, }; }", - ] { - assert!(messages(text).is_empty(), "{text:?}"); - } - for (text, want) in [ - ("struct S { a: i32; b: i32 }", "struct S { a: i32, b: i32 }"), - ( - "struct S { a: i32; b: i32; }", - "struct S { a: i32, b: i32 }", - ), - ( - "fn f() { let p = .{ a = 1; b = 2 }; }", - "fn f() { let p = .{ a = 1, b = 2 }; }", - ), - ] { - one_error(text, "expected `,` between items, found `;`", Some(want)); - } -} diff --git a/crates/features/src/testing.rs b/crates/features/src/testing.rs deleted file mode 100644 index 16ed4668..00000000 --- a/crates/features/src/testing.rs +++ /dev/null @@ -1,117 +0,0 @@ -//! What the features' tests share: a text read as Peeper, and a checker of -//! a one-module program. - -use std::sync::Arc; - -use arena::Id; -use check::Checker; -use diagnostics::Diagnostic; -use model::ConstArguments; -use model::DeclarationCopy; -use model::DefId; -use model::ModuleId; -use model::machine::Machine; -use model::thir::Body; -use source::SourceFile; -use source::Span; -use syntax::ast; - -pub(crate) type Tree = ast::Tree; - -/// The tree of `text` and its syntax errors. -pub(crate) fn parse_text(text: &str) -> (Tree, Vec) { - parser::parse(&Arc::new(SourceFile::new("t.peep", text)), &crate::RULES) -} - -/// The message of each syntax error of `text`. -pub(crate) fn messages(text: &str) -> Vec { - let (_, errors) = parse_text(text); - errors.into_iter().map(|error| error.message).collect() -} - -/// A diagnostic as its code, message and the text of its first label. -pub(crate) type Reported = (&'static str, String, String); - -/// Runs `work` on a checker of the one module `app:main`, written as -/// `text`, given the functions' declarations in order; gives what `work` -/// gives and the diagnostics. -pub(crate) fn with_checker( - text: &str, - work: impl FnOnce(&mut Checker, &[(DefId, Span)]) -> T, -) -> (T, Vec) { - let file = Arc::new(SourceFile::new("main.peep", text)); - let (ast, parse) = parser::parse(&file, &crate::RULES); - assert!(parse.is_empty(), "{parse:?}"); - let modules = [model::program::Module { - path: "app:main".to_string(), - ast, - imports: Vec::new(), - }]; - let tree = &modules[0].ast; - let functions: Vec<(DefId, Span)> = (tree.declarations().enumerate()) - .filter_map(|(index, declaration)| match tree.decls[declaration] { - ast::Decl::Function(function) => { - let module = ModuleId::from_index(0); - let index = index as u32; - Some((DefId { module, index }, function.name.span)) - } - _ => None, - }) - .collect(); - let mut checker = Checker::new( - &modules, - Machine::named("x86_64-linux").unwrap(), - false, - &crate::CHECK_HOOKS, - ); - let result = work(&mut checker, &functions); - let reported = (checker.module_checks.iter()) - .flat_map(|module| &module.diagnostics) - .map(|diagnostic| { - let label = file.slice(diagnostic.labels[0].span).to_string(); - (diagnostic.code.id, diagnostic.message.clone(), label) - }) - .collect(); - (result, reported) -} - -/// The expressions of the statements of the first function of `tree`. -pub(crate) fn statements(tree: &Tree) -> Vec> { - let decl = tree.declarations().next().unwrap(); - let ast::Decl::Function(function) = tree.decls[decl] else { - panic!("not a function") - }; - let statements = tree.blocks[function.body.unwrap()].statements; - let expression = |statement| match tree.stmts[statement] { - ast::Stmt::Expression(expr) => expr, - other => panic!("not an expression statement: {other:?}"), - }; - tree.children - .lists - .items(statements) - .map(expression) - .collect() -} - -/// The text of the body of every function of `text`, a called function -/// named by its place among them (`f0`). -pub(crate) fn bodies(text: &str) -> (Vec, Vec) { - let file = SourceFile::new("main.peep", text); - with_checker(text, |checker, functions| { - let names: Vec = (0..functions.len()) - .map(|index| format!("f{index}")) - .collect(); - let name = |function: DefId| names[function.index as usize].as_str(); - (functions.iter()) - .map(|&(definition, span)| { - let copy = DeclarationCopy { - definition, - arguments: ConstArguments::NONE, - }; - let mut body = Body::default(); - assert!(checker.check_body(copy, span, &mut body, true)); - body.text(&checker.types, &file, name) - }) - .collect() - }) -} diff --git a/crates/kernel/flow/Cargo.toml b/crates/flow/Cargo.toml similarity index 100% rename from crates/kernel/flow/Cargo.toml rename to crates/flow/Cargo.toml diff --git a/crates/kernel/flow/src/lib.rs b/crates/flow/src/lib.rs similarity index 100% rename from crates/kernel/flow/src/lib.rs rename to crates/flow/src/lib.rs diff --git a/crates/kernel/flow/src/loans/errors.rs b/crates/flow/src/loans/errors.rs similarity index 100% rename from crates/kernel/flow/src/loans/errors.rs rename to crates/flow/src/loans/errors.rs diff --git a/crates/kernel/flow/src/loans/holders.rs b/crates/flow/src/loans/holders.rs similarity index 100% rename from crates/kernel/flow/src/loans/holders.rs rename to crates/flow/src/loans/holders.rs diff --git a/crates/kernel/flow/src/loans/mod.rs b/crates/flow/src/loans/mod.rs similarity index 100% rename from crates/kernel/flow/src/loans/mod.rs rename to crates/flow/src/loans/mod.rs diff --git a/crates/kernel/flow/src/loans/passes.rs b/crates/flow/src/loans/passes.rs similarity index 100% rename from crates/kernel/flow/src/loans/passes.rs rename to crates/flow/src/loans/passes.rs diff --git a/crates/kernel/flow/src/loans/places.rs b/crates/flow/src/loans/places.rs similarity index 100% rename from crates/kernel/flow/src/loans/places.rs rename to crates/flow/src/loans/places.rs diff --git a/crates/kernel/flow/src/loans/two_phase.rs b/crates/flow/src/loans/two_phase.rs similarity index 100% rename from crates/kernel/flow/src/loans/two_phase.rs rename to crates/flow/src/loans/two_phase.rs diff --git a/crates/kernel/flow/src/missing_return.rs b/crates/flow/src/missing_return.rs similarity index 100% rename from crates/kernel/flow/src/missing_return.rs rename to crates/flow/src/missing_return.rs diff --git a/crates/kernel/flow/src/unreachable.rs b/crates/flow/src/unreachable.rs similarity index 100% rename from crates/kernel/flow/src/unreachable.rs rename to crates/flow/src/unreachable.rs diff --git a/crates/kernel/flow/src/variable_state.rs b/crates/flow/src/variable_state.rs similarity index 100% rename from crates/kernel/flow/src/variable_state.rs rename to crates/flow/src/variable_state.rs diff --git a/crates/kernel/model/src/layout.rs b/crates/kernel/model/src/layout.rs deleted file mode 100644 index 9defb4d1..00000000 --- a/crates/kernel/model/src/layout.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! How values are laid out in memory for the target: each type's size and -//! alignment. The checker rejects a type too big for the target with it; the -//! backend places and copies values with it, and LLVM sees only the bytes. - -use crate::machine::Machine; -use crate::mir::Class; -use crate::semantic_types::Float; -use crate::semantic_types::Type; -use crate::semantic_types::TypeId; -use crate::semantic_types::Types; -use crate::semantic_types::range_fields; - -/// The size and alignment in bytes of a value of type `ty` in memory for -/// `target`: an integer is aligned as the next of 8, 16, 32, 64 and 128 bits -/// that holds it, a 64-bit one as `target` says, and wider ones as 128; its -/// size is rounded up to that. LLVM loads and stores a scalar itself, so a -/// scalar's must match LLVM's; a value kept in memory is bytes to LLVM, so -/// this alone says where its parts are. A size past `u64` is `u64::MAX`, more -/// than any machine's `largest_object`: the checker rejects such a type, so -/// no later phase lays it out. -pub fn layout(types: &Types, ty: TypeId, target: &Machine) -> (u64, u64) { - match &types[ty] { - Type::Bool => (1, 1), - Type::Integer(integer) => { - let align: u64 = match integer.bits { - 1..=8 => 1, - 9..=16 => 2, - 17..=32 => 4, - 33..=64 => target.i64_align, - _ => 16, - }; - // The class's bytes: its own, rounded up to the alignment. - let bytes = Class::integer(integer.bits).bytes(target.pointer_bytes()); - (bytes, align) - } - Type::Float(Float::F32) => (4, 4), - Type::Float(Float::F64) => (8, target.i64_align), - Type::CString | Type::Reference { .. } | Type::RawPointer { .. } => { - let bytes = target.pointer_bytes(); - (bytes, bytes) - } - Type::Slice { .. } - | Type::Str - | Type::InterfaceReference { .. } - | Type::Interface { .. } => { - let bytes = target.pointer_bytes(); - (2 * bytes, bytes) - } - Type::Struct { internals, .. } => (internals.size, internals.align), - Type::Range { element, step } => { - let fields = range_fields(*element, *step).map(|(_, ty)| ty); - let (_, size, align) = struct_layout(types, &fields, target); - (size, align) - } - Type::Array { internals, .. } => { - let (size, align) = layout(types, internals.base, target); - (size.saturating_mul(internals.count), align) - } - Type::Invalid | Type::Void | Type::Function { .. } | Type::Named { .. } => { - unreachable!("no value is laid out with this type") - } - Type::Alias { .. } => unreachable!("indexing looks through aliases"), - } -} - -/// Whether a value of type `ty` is kept in memory, not held whole as one -/// number: a struct, an array or a range. LLVM splits a value of such a type -/// into one operation per part, so a big array as one value made clang slow, -/// then crash; the interpreter copies such a value as its bytes. -pub fn in_memory(types: &Types, ty: TypeId) -> bool { - matches!( - types[ty], - Type::Struct { .. } | Type::Array { .. } | Type::Range { .. } - ) -} - -/// Field `index` of the struct, range or `str` type `ty`: where it is from -/// the value's start, in bytes, and its type. A struct's offsets are kept -/// (`StructInternals`); a range's two or three fields are laid out here; a -/// `str` is its bytes' address, then its length. -pub fn field_placed(types: &Types, ty: TypeId, index: usize, target: &Machine) -> (u64, TypeId) { - match &types[ty] { - ty if let Some(members) = ty.members() => (members.offsets[index], members.fields[index]), - Type::Str => [(0, TypeId::RAWPTR), (target.pointer_bytes(), types.usize)][index], - Type::Range { element, step } => { - let fields = range_fields(*element, *step).map(|(_, ty)| ty); - let (offsets, ..) = struct_layout(types, &fields, target); - (offsets[index], fields[index]) - } - _ => unreachable!("only a struct, a range and a `str` have fields"), - } -} - -/// The offset of each of `fields` in a struct holding them in order, and the -/// struct's size and alignment, in bytes (`layout`): each field at the next -/// multiple of its alignment, the size rounded up to the largest. -pub fn struct_layout(types: &Types, fields: &[TypeId], target: &Machine) -> (Vec, u64, u64) { - let (mut offsets, mut end, mut align) = (Vec::with_capacity(fields.len()), 0u64, 1); - for &field in fields { - let (size, field_align) = layout(types, field, target); - let offset = end - .checked_next_multiple_of(field_align) - .unwrap_or(u64::MAX); - offsets.push(offset); - end = offset.saturating_add(size); - align = align.max(field_align); - } - let size = end.checked_next_multiple_of(align).unwrap_or(u64::MAX); - (offsets, size, align) -} - -#[cfg(test)] -mod tests; diff --git a/crates/kernel/model/src/layout/tests.rs b/crates/kernel/model/src/layout/tests.rs deleted file mode 100644 index 15844d9c..00000000 --- a/crates/kernel/model/src/layout/tests.rs +++ /dev/null @@ -1,53 +0,0 @@ -use crate::machine::Machine; -use crate::semantic_types::TypeId; -use crate::semantic_types::Types; - -use super::struct_layout; - -/// Each struct's field offsets and size match what LLVM gives on x86-64 -/// and AArch64, and with 32-bit pointers on i686 (measured with -/// `getelementptr` folded by clang `-O1`, `-m32` for i686). -#[test] -fn struct_layout_matches_llvm() { - let mut types = Types::new(64); - let mut integer = |name: &str| types.builtin(name).unwrap(); - let (i8, i24, i40, i128, i200) = ( - integer("i8"), - integer("i24"), - integer("i40"), - integer("i128"), - integer("i200"), - ); - let layout = |fields: &[TypeId]| { - let (offsets, size, _) = - struct_layout(&types, fields, Machine::named("x86_64-linux").unwrap()); - (offsets, size) - }; - assert_eq!(layout(&[TypeId::I32, TypeId::I64]), (vec![0, 8], 16)); - assert_eq!( - layout(&[TypeId::BOOL, i128, TypeId::I32]), - (vec![0, 16, 32], 48) - ); - assert_eq!(layout(&[i8, i24, i8]), (vec![0, 4, 8], 12)); - assert_eq!(layout(&[i8, i200, i8]), (vec![0, 16, 48], 64)); - assert_eq!(layout(&[i8, i40]), (vec![0, 8], 16)); - assert_eq!( - layout(&[i8, TypeId::F64, TypeId::CSTR]), - (vec![0, 8, 16], 24) - ); - assert_eq!(layout(&[]), (vec![], 0)); - let i686 = |fields: &[TypeId]| { - let (offsets, size, _) = - struct_layout(&types, fields, Machine::named("i686-linux").unwrap()); - (offsets, size) - }; - assert_eq!(i686(&[TypeId::I32, TypeId::I64]), (vec![0, 4], 12)); - assert_eq!( - i686(&[TypeId::BOOL, i128, TypeId::I32]), - (vec![0, 16, 32], 48) - ); - assert_eq!(i686(&[i8, i24, i8]), (vec![0, 4, 8], 12)); - assert_eq!(i686(&[i8, i200, i8]), (vec![0, 16, 48], 64)); - assert_eq!(i686(&[i8, i40]), (vec![0, 4], 12)); - assert_eq!(i686(&[i8, TypeId::F64, TypeId::CSTR]), (vec![0, 4, 12], 16)); -} diff --git a/crates/kernel/semantic/src/testing.rs b/crates/kernel/semantic/src/testing.rs deleted file mode 100644 index a7e7188f..00000000 --- a/crates/kernel/semantic/src/testing.rs +++ /dev/null @@ -1,94 +0,0 @@ -//! What the checking tests share: a one-module program read from text, whose -//! declarations are checked one at a time. - -use std::sync::Arc; - -use model::ModuleId; -use model::machine::Machine; -use model::program::ImportKind; -use model::semantic_types::Types; -use parser::Rules; -use source::SourceFile; - -use crate::CheckHooks; -use crate::Checker; - -/// The core's rules alone: the checking tests read no feature, since the -/// `features` crate depends on this one. -static RULES: Rules = Rules::core(); - -/// The core's rules make no feature node, so no hook is ever asked. -static HOOKS: CheckHooks = CheckHooks { - check_expr: |_, _, _, _| unreachable!("the core rules read no feature expression"), - check_stmt: |_, _, _| unreachable!("the core rules read no feature statement"), - resolve_type: |_, _, _| unreachable!("the core rules read no feature type"), - declare_type: |_, _, _, _| unreachable!("the core rules read no feature type"), -}; - -/// The module `path`, written as `text`, with `imports`; its text must parse -/// without errors. -pub(crate) fn module( - path: &str, - text: &str, - imports: Vec, -) -> model::program::Module { - let file = Arc::new(SourceFile::new("main.peep", text)); - let (ast, parse) = parser::parse(&file, &RULES); - assert!(parse.is_empty(), "{parse:?}"); - model::program::Module { - path: path.to_string(), - ast, - imports, - } -} - -/// A diagnostic as its code, message and the text of its first label. -pub(crate) type Reported = (&'static str, String, String); - -/// Runs `work` on a checker of the module `app:main` written as `text`, given -/// its id, which -/// imports `app:utils` as `utils` (an import added after `text`, so the -/// places in `text` stay as written), which declares `Shown` and the private -/// `hidden`. Gives what `work` gives, the program's -/// types and the diagnostics. -pub(crate) fn with_checker( - text: &str, - work: impl FnOnce(&mut Checker, ModuleId) -> T, -) -> (T, Types, Vec) { - let (utils_id, main_id) = (ModuleId::from_index(0), ModuleId::from_index(1)); - let imports = vec![model::program::Import { - kind: ImportKind::Declared(0), - module: utils_id, - }]; - let text = format!("{text}\nimport \"app:utils\";\n"); - let modules = [ - module("app:utils", "fn Shown() {}\nfn hidden() {}", Vec::new()), - module("app:main", &text, imports), - ]; - let file = modules[1].ast.file.clone(); - let mut checker = Checker::new( - &modules, - Machine::named("x86_64-linux").unwrap(), - false, - &HOOKS, - ); - let result = work(&mut checker, main_id); - let reported = checker - .module_checks - .iter() - .flat_map(|module| &module.diagnostics) - .map(|diagnostic| { - let text = file.slice(diagnostic.labels[0].span).to_string(); - (diagnostic.code.id, diagnostic.message.clone(), text) - }) - .collect(); - (result, checker.types, reported) -} - -/// `expected` as `Reported`s, to compare with what was reported. -pub(crate) fn reported(expected: &[(&'static str, &str, &str)]) -> Vec { - let owned = |&(code, message, text): &(&'static str, &str, &str)| { - (code, message.to_string(), text.to_string()) - }; - expected.iter().map(owned).collect() -} diff --git a/crates/kernel/syntax/parser/src/decl/tests.rs b/crates/kernel/syntax/parser/src/decl/tests.rs deleted file mode 100644 index 51312c71..00000000 --- a/crates/kernel/syntax/parser/src/decl/tests.rs +++ /dev/null @@ -1,265 +0,0 @@ -use crate::tests::dump_of; -use crate::tests::messages; -use crate::tests::one_error; - -#[test] -fn parses_variadic_parameters() { - let text = "fn f(first: i32, rest: ...mut i32);\nfn g(_: ...i32);\n"; - let want = "module - function declaration - declared name f - parameter - declared name first - type name i32 - variadic parameter - declared name rest - variadic type mut - type name i32 - function declaration - declared name g - variadic parameter - variadic type - type name i32 -"; - assert!(messages(text).is_empty()); - assert_eq!(dump_of(text), want); -} - -/// `const T: type` takes a type; `type` is a type only there, which the -/// checker decides, so the parser reads it in any parameter. -#[test] -fn parses_type_parameters() { - let text = "fn f(x: i32, const T: type, t: type);\n"; - let want = "module - function declaration - declared name f - parameter - declared name x - type name i32 - const parameter - declared name T - type of a type type - parameter - declared name t - type of a type type -"; - assert!(messages(text).is_empty()); - assert_eq!(dump_of(text), want); -} - -/// The lexer reads `&&` as one token; in a type it is two references. -#[test] -fn parses_two_references_written_as_one_token() { - let text = "fn f(a: &&i32, b: &&mut []u8);\n"; - let want = "module - function declaration - declared name f - parameter - declared name a - reference type - reference type - type name i32 - parameter - declared name b - reference type - slice type mut - type name u8 -"; - assert!(messages(text).is_empty()); - assert_eq!(dump_of(text), want); -} - -#[test] -fn parses_signatures() { - let text = "fn Counter::Add(&mut self, mut delta: i32, scale: f64 = 1, &Counter) -> &T in (self, delta) where T: Shape, U: Sized(8) {} -fn Counter::Get(&self) {} -fn Counter::Into(self) {} -fn Counter::Doubled(mut self) {} -fn exit(code: i32); -fn Use(callback: fn(value: &Box, i32) -> &Box in value, view: &[]u8, edit: &mut []u8) -> a::Box>; -"; - let want = "module - function declaration - owner type Counter - declared name Add - declared name T - declared name U - parameter - declared name self - reference type mut - self type self - parameter mut - declared name delta - type name i32 - parameter - declared name scale - type name f64 - number literal 1 - parameter - reference type - type name Counter - reference type - type name T - name reference self - name reference delta - constraint - name reference T - name reference Shape - constraint - name reference U - name reference Sized - number literal 8 - block {} - function declaration - owner type Counter - declared name Get - parameter - declared name self - reference type - self type self - block {} - function declaration - owner type Counter - declared name Into - parameter - declared name self - self type self - block {} - function declaration - owner type Counter - declared name Doubled - parameter mut - declared name self - self type self - block {} - function declaration - declared name exit - parameter - declared name code - type name i32 - function declaration - declared name Use - parameter - declared name callback - function type - parameter - declared name value - reference type - type name Box - parameter - type name i32 - reference type - type name Box - name reference value - parameter - declared name view - slice type - type name u8 - parameter - declared name edit - slice type mut - type name u8 - path - type name a - generic type - type name Box - generic type - type name Box - type name T -"; - assert!(messages(text).is_empty()); - assert_eq!(dump_of(text), want); -} - -#[test] -fn signature_errors() { - for (text, message, fixed) in [ - ( - "fn f() i32 {}", - "expected `->` before the return type", - Some("fn f() -> i32 {}"), - ), - ( - "fn f(mut mut a: i32) {}", - "`mut` is repeated", - Some("fn f(mut a: i32) {}"), - ), - ( - "fn f(mut i32) {}", - "mutable parameter requires a named binding", - None, - ), - ("fn f(a: ) {}", "expected type, found `)`", None), - ("fn f() -> i32", "missing function body", None), - ("fn f() {}", "expected `,`", Some("fn f() {}")), - ] { - one_error(text, message, fixed); - } -} - -#[test] -fn parses_declarations() { - let text = r#"/// The answer. -/// Twice checked. -const Answer: i32 = 42; -const Untyped = 1; -#[extern(rt_exit)] -fn exit(code: i32); -type Alias = T; -fn Pair::new() {} -"#; - let want = r#"module - const declaration - metadata - doc comment /// The answer. -/// Twice checked. - declared name Answer - type name i32 - number literal 42 - const declaration - declared name Untyped - number literal 1 - function declaration - metadata - attribute - name reference extern - name reference rt_exit - declared name exit - parameter - declared name code - type name i32 - type alias declaration - declared name Alias - declared name T - type name T - function declaration - owner type Pair - declared name new - block {} -"#; - assert!(messages(text).is_empty()); - assert_eq!(dump_of(text), want); -} - -#[test] -fn declaration_errors() { - for (text, message) in [ - ("let a = 1;", "top-level `let` not allowed"), - ("a + 1;", "module scope expects declaration"), - ( - "#[a, b] fn f();", - "only one attribute is allowed per `#[...]` block", - ), - ("fn (p: Point) f() {}", "expected `identifier`, found `(`"), - ("type A i32;", "expected `=`, found `identifier`"), - ] { - one_error(text, message, None); - } -} - -/// A `///` on the line of earlier code is not the next declaration's -/// documentation. -#[test] -fn doc_comment_after_code() { - assert!(!dump_of("const a = 1; /// about a\nconst b = 2;").contains("metadata")); -} diff --git a/crates/kernel/syntax/parser/src/expr.rs b/crates/kernel/syntax/parser/src/expr.rs deleted file mode 100644 index 62fe8717..00000000 --- a/crates/kernel/syntax/parser/src/expr.rs +++ /dev/null @@ -1,360 +0,0 @@ -//! Expressions, read by a Pratt parser. A prefix rule reads an expression that -//! a token begins (a name, a literal, `(`); an infix rule reads what a token -//! adds after an expression on its left (an operator and its right side, a -//! call). Each token with an infix rule has a precedence: it joins the expression being read only when it -//! binds tighter than the operator before it, so precedence and associativity -//! live in the table below and not in nested grammar rules. - -use arena::Id; -use arena::List; -use diagnostics::Diagnostic; -use source::Span; -use syntax::ast::Expr; -use syntax::ast::Type; -use syntax::operators::BinaryOp; -use syntax::operators::Precedence; -use syntax::operators::UnaryOp; -use token::TokenKind; - -use crate::Parser; -use crate::Rules; -use crate::literals; - -/// Reads the expression the current token begins. -pub type PrefixRule = fn(&mut Parser) -> Id; - -/// Reads what continues the path `path` in an expression, from the token -/// after it. -pub type AfterPathRule = fn(&mut Parser, Id) -> Id; - -/// Reads what the current token adds to the expression `left`. -pub type InfixRule = fn(&mut Parser, Id) -> Id; - -impl Rules { - pub const fn prefix(&mut self, kind: TokenKind, read: PrefixRule) { - assert!( - self.prefix[kind as usize].is_none(), - "two rules begin an expression with one token" - ); - self.prefix[kind as usize] = Some(read); - } - - pub const fn infix(&mut self, kind: TokenKind, precedence: Precedence, read: InfixRule) { - assert!( - self.infix[kind as usize].is_none(), - "two rules continue an expression with one token" - ); - self.infix[kind as usize] = Some((precedence, read)); - } - - /// The rule that reads what continues a path when the two tokens after - /// it are `first` and `second`. - fn after_path_rule(&self, first: TokenKind, second: TokenKind) -> Option { - let (paired, read) = self.after_path[first as usize]?; - (paired == second).then_some(read) - } - - const fn binary_operator(&mut self, kind: TokenKind, op: BinaryOp) { - self.infix(kind, op.precedence(), binary); - self.binary[kind as usize] = Some(op); - } -} - -/// Adds the core's expression rules to `rules`. -pub(crate) const fn expression_rows(rules: &mut Rules) { - // values - rules.prefix(TokenKind::Ident, name_or_path); - rules.prefix(TokenKind::SelfValue, self_name); - rules.prefix(TokenKind::Number, literals::number_literal); - rules.prefix(TokenKind::None, literals::none_literal); - rules.prefix(TokenKind::True, literals::bool_literal); - rules.prefix(TokenKind::False, literals::bool_literal); - rules.prefix(TokenKind::String, literals::string_literal); - rules.prefix(TokenKind::CString, literals::string_literal); - rules.prefix(TokenKind::LeftParen, parentheses); - - // prefix operators - rules.prefix(TokenKind::Plus, leading_plus); - rules.prefix(TokenKind::Minus, unary); - rules.prefix(TokenKind::Bang, unary); - rules.prefix(TokenKind::Tilde, unary); - rules.prefix(TokenKind::Ampersand, reference); - - // logical - rules.binary_operator(TokenKind::OrOr, BinaryOp::LogicalOr); - rules.binary_operator(TokenKind::AndAnd, BinaryOp::LogicalAnd); - - // bitwise - rules.binary_operator(TokenKind::Pipe, BinaryOp::BitOr); - rules.binary_operator(TokenKind::Caret, BinaryOp::BitXor); - rules.binary_operator(TokenKind::Ampersand, BinaryOp::BitAnd); - - // equality and comparison - rules.binary_operator(TokenKind::EqualEqual, BinaryOp::EqualTo); - rules.binary_operator(TokenKind::BangEqual, BinaryOp::NotEqualTo); - rules.binary_operator(TokenKind::Less, BinaryOp::LessThan); - rules.binary_operator(TokenKind::LessEqual, BinaryOp::LessOrEqual); - rules.binary_operator(TokenKind::Greater, BinaryOp::GreaterThan); - rules.binary_operator(TokenKind::GreaterEqual, BinaryOp::GreaterOrEqual); - - // arithmetic - rules.binary_operator(TokenKind::ShiftLeft, BinaryOp::ShiftLeft); - rules.binary_operator(TokenKind::ShiftRight, BinaryOp::ShiftRight); - rules.binary_operator(TokenKind::Plus, BinaryOp::Add); - rules.binary_operator(TokenKind::Minus, BinaryOp::Subtract); - rules.binary_operator(TokenKind::Asterisk, BinaryOp::Multiply); - rules.binary_operator(TokenKind::Slash, BinaryOp::Divide); - rules.binary_operator(TokenKind::Percent, BinaryOp::Remainder); - - // call, index and selector - rules.infix(TokenKind::LeftParen, Precedence::Call, call); - rules.infix(TokenKind::LeftBracket, Precedence::Call, index); - rules.infix(TokenKind::Dot, Precedence::Call, selector); - - rules.infix(TokenKind::As, Precedence::Cast, cast); -} - -/// Whether an expression can begin with `kind`. -pub fn starts_expression(p: &Parser, kind: TokenKind) -> bool { - p.rules.prefix[kind as usize].is_some() -} - -impl Parser { - /// Reads an expression whose operators bind tighter than `min`. - pub fn expr(&mut self, min: Precedence) -> Id { - source::grow_stack(|| { - let t = self.tok(); - let Some(read) = self.rules.prefix[t.kind as usize] else { - self.fail( - Diagnostic::new( - diagnostics::EXPECTED_TOKEN, - format!("expected expression, found `{}`", t.kind.text()), - ) - .label( - &self.tree.file, - t.span, - "expected an expression here", - ), - ); - return self.add(self.last_end, Expr::Invalid); - }; - let mut left = read(self); - while let Some((precedence, read)) = self.rules.infix[self.tok().kind as usize] - && precedence > min - { - left = read(self, left); - } - left - }) - } - - /// Reads the current token as an expression without children. - pub(crate) fn leaf(&mut self, node: Expr) -> Id { - let start = self.next().span.start; - self.add(start, node) - } - - /// The start of expression `id`, where an infix expression on it starts. - pub fn start_of(&self, id: Id) -> u32 { - self.tree.exprs.span(id).start - } - - /// Whether the name at the current token begins a path or a type rather - /// than standing alone: `::` follows it, or `.{`, or type arguments that - /// `::` or `.{` follow. - fn starts_path(&self) -> bool { - match self.ahead(1).kind { - TokenKind::ColonColon => true, - first => self - .rules - .after_path_rule(first, self.ahead(2).kind) - .is_some(), - } - } -} - -/// Reads `self`, the name of a type's function's first parameter. -fn self_name(p: &mut Parser) -> Id { - p.leaf(Expr::Name) -} - -/// Reads a name; or, when a path or type arguments follow it, a path -/// (`a::B`, `Box::::new`) or what a feature reads after one -/// (`Point.{...}`). -pub(crate) fn name_or_path(p: &mut Parser) -> Id { - if !p.starts_path() { - return p.leaf(Expr::Name); - } - let path = p.expression_path(); - let start = p.tree.types.span(path).start; - if let Some(read) = p.rules.after_path_rule(p.tok().kind, p.ahead(1).kind) { - return read(p, path); - } - p.add(start, Expr::Path(path)) -} - -/// Reads `as Type` after `value`. -fn cast(p: &mut Parser, value: Id) -> Id { - p.next(); - let ty = p.type_expr(); - p.add(p.start_of(value), Expr::Cast { value, ty }) -} - -/// Reads `( expression )`. -fn parentheses(p: &mut Parser) -> Id { - let open = p.next(); - let inner = p.expr(Precedence::Lowest); - p.close(TokenKind::RightParen, open); - p.add(open.span.start, Expr::Parentheses(inner)) -} - -/// Reads a binary operator and its right side. The right side takes only -/// operators that bind tighter, so operators of one precedence group to the -/// left: a - b - c is (a - b) - c. -fn binary(p: &mut Parser, left: Id) -> Id { - let kind = p.next().kind; - let op = p.rules.binary[kind as usize].expect("binary is the rule of operator tokens only"); - let right = p.expr(op.precedence()); - p.add(p.start_of(left), Expr::Binary { op, left, right }) -} - -/// Reads the arguments of a call to `callee`. The type arguments of a -/// callee written `f::` or `a::f::` are the call's, and the callee -/// is the name or path without them. -fn call(p: &mut Parser, callee: Id) -> Id { - let start = p.start_of(callee); - let mut callee = callee; - let mut type_arguments = List::EMPTY; - if let Expr::Path(path) = p.tree.exprs[callee] { - let segments: Vec> = match p.tree.types[path] { - Type::Path(segments) => p.tree.children.lists.items(segments).collect(), - _ => vec![path], - }; - let (&last, before) = segments.split_last().expect("a path has a name"); - if let Type::Generic { name, arguments } = p.tree.types[last] { - type_arguments = arguments; - callee = if before.is_empty() { - p.tree.add(Expr::Name, name.span) - } else { - let last = p.tree.add(Type::Name, name.span); - let items: Vec<_> = before.iter().chain([&last]).map(|&s| s.into()).collect(); - let segments = p.tree.children.lists.add(&items); - let span = Span::new(start as usize, name.span.end as usize); - let path = p.tree.add(Type::Path(segments), span); - p.tree.add(Expr::Path(path), span) - }; - } - } - let arguments = p.delimited( - TokenKind::LeftParen, - TokenKind::RightParen, - false, - starts_expression, - spreadable, - ); - p.add( - start, - Expr::Call { - callee, - type_arguments, - arguments, - }, - ) -} - -/// Reads an entry of an array literal or an argument of a call: `value` or -/// `value...`. -pub fn spreadable(p: &mut Parser) -> Id { - let start = p.tok().span.start; - let value = p.expr(Precedence::Lowest); - if !p.at(TokenKind::Ellipsis) { - return value; - } - p.next(); - p.add(start, Expr::Spread(value)) -} - -/// Reads `+x` as `x`, reporting the `+`: there is no unary `+`, as it would -/// change nothing. -fn leading_plus(p: &mut Parser) -> Id { - let plus = p.next().span; - let fix = p.fix(plus, ""); - p.repair( - Diagnostic::new( - diagnostics::INVALID_EXPRESSION, - "`+` is not a prefix operator", - ) - .label(&p.tree.file, plus, "") - .help("remove it; `+x` is just `x`", vec![fix]), - ); - p.expr(Precedence::Prefix) -} - -/// Reads `-x`, `!x` or `~x`. -fn unary(p: &mut Parser) -> Id { - let token = p.next(); - let op = match token.kind { - TokenKind::Minus => UnaryOp::Negate, - TokenKind::Bang => UnaryOp::LogicalNot, - TokenKind::Tilde => UnaryOp::BitNot, - _ => unreachable!("unary is the rule of operator tokens only"), - }; - let value = p.expr(Precedence::Prefix); - p.add(token.span.start, Expr::Unary { op, value }) -} - -/// Reads `&x` or `&mut x`. -fn reference(p: &mut Parser) -> Id { - let start = p.next().span.start; - // `&[]T` and `&mut []T` are slice types; nothing after `&` reads `[]`. - let after_mut = usize::from(p.at(TokenKind::Mut)); - let open = p.ahead(after_mut); - if open.kind == TokenKind::LeftBracket && p.ahead(after_mut + 1).kind == TokenKind::RightBracket - { - let ty = p.reference_type(start); - if p.at(TokenKind::LeftBrace) { - let written = p.tree.file.slice(p.tree.types.span(ty)); - let fix = p.fix(Span::at(open.span.end as usize), "_"); - p.fail( - Diagnostic::new( - diagnostics::INVALID_EXPRESSION, - format!("`{written}` is a slice type, so it takes no values"), - ) - .label(&p.tree.file, p.tree.types.span(ty), "") - .help( - "write `[_]` to lend an array's values as a slice", - vec![fix], - ), - ); - } - return p.add(start, Expr::Type(ty)); - } - let mutable = p.at(TokenKind::Mut); - if mutable { - p.next(); - } - let value = p.expr(Precedence::Prefix); - p.add(start, Expr::Reference { mutable, value }) -} - -/// Reads `[index]` after `value`. -fn index(p: &mut Parser, value: Id) -> Id { - let open = p.next(); - let index = p.expr(Precedence::Lowest); - p.close(TokenKind::RightBracket, open); - p.add(p.start_of(value), Expr::Index { value, index }) -} - -/// Reads `.name` or `.*` after `value`. -fn selector(p: &mut Parser, value: Id) -> Id { - p.next(); - if p.at(TokenKind::Asterisk) { - p.next(); - return p.add(p.start_of(value), Expr::Dereference(value)); - } - let field = p.name(); - p.add(p.start_of(value), Expr::Selector { value, field }) -} - -#[cfg(test)] -mod tests; diff --git a/crates/kernel/syntax/parser/src/expr/tests.rs b/crates/kernel/syntax/parser/src/expr/tests.rs deleted file mode 100644 index 406bcf36..00000000 --- a/crates/kernel/syntax/parser/src/expr/tests.rs +++ /dev/null @@ -1,359 +0,0 @@ -use syntax::ast::Decl; -use syntax::ast::Stmt; -use syntax::ast::StringKind; -use syntax::ast::Tree; - -use super::*; -use crate::tests::dump_of; -use crate::tests::messages; -use crate::tests::one_error; -use crate::tests::parse_text; - -/// There is no unary `+`: a leading one is reported, and its fix removes it. -#[test] -fn leading_plus() { - one_error( - "fn f() { let a = +5; }", - "`+` is not a prefix operator", - Some("fn f() { let a = 5; }"), - ); -} - -/// An operator is written as the token it is read from: each binary and -/// unary operator comes from exactly one operator token, whose text is -/// the operator's symbol. -#[test] -fn operators_are_written_as_their_tokens() { - let (mut binary, mut unary) = (0, 0); - for &kind in token::OPERATORS { - for text in [ - format!("fn f() {{ a {} b; }}", kind.text()), - format!("fn f() {{ {}a; }}", kind.text()), - ] { - let (tree, errors) = parse_text(&text); - if !errors.is_empty() { - continue; - } - for id in tree.exprs.ids() { - match tree.exprs[id] { - Expr::Binary { op, .. } => { - assert_eq!(op.symbol(), kind.text(), "{text}"); - binary += 1; - } - Expr::Unary { op, .. } => { - assert_eq!(op.symbol(), kind.text(), "{text}"); - unary += 1; - } - _ => {} - } - } - } - } - assert_eq!((binary, unary), (18, 3)); -} - -/// The expression of the first statement of the first function. -fn first_expression(tree: &Tree) -> Id { - let decl = tree.declarations().next().unwrap(); - let Decl::Function(f) = tree.decls[decl] else { - panic!("not a function") - }; - let statement = tree - .children - .lists - .items(tree.blocks[f.body.unwrap()].statements) - .next() - .unwrap(); - let Stmt::Expression(e) = tree.stmts[statement] else { - panic!("not an expression statement") - }; - e -} - -/// An expression with each binary operation and cast in parentheses. -fn grouped(t: &Tree, id: Id) -> String { - let text = |span| t.file.slice(span).to_string(); - match t.exprs[id] { - Expr::Cast { value, ty } => { - format!("({} as {})", grouped(t, value), text(t.types.span(ty))) - } - Expr::Binary { op, left, right } => { - format!( - "({} {} {})", - grouped(t, left), - op.symbol(), - grouped(t, right) - ) - } - Expr::Unary { value, .. } | Expr::Reference { value, .. } => { - let (span, inner) = (t.exprs.span(id), t.exprs.span(value)); - let prefix = t.file.text[span.start as usize..inner.start as usize].trim(); - let space = if let Expr::Reference { mutable: true, .. } = t.exprs[id] { - " " - } else { - "" - }; - format!("{prefix}{space}{}", grouped(t, value)) - } - Expr::Selector { value, field } => { - format!("{}.{}", grouped(t, value), text(field.span)) - } - Expr::Dereference(value) => format!("{}.*", grouped(t, value)), - Expr::Index { value, index } => { - format!("{}[{}]", grouped(t, value), text(t.exprs.span(index))) - } - Expr::Call { - callee, arguments, .. - } => { - let arguments: Vec<_> = t - .children - .lists - .items(arguments) - .map(|a| grouped(t, a)) - .collect(); - format!("{}({})", grouped(t, callee), arguments.join(", ")) - } - _ => text(t.exprs.span(id)), - } -} - -/// How operators group, from loosest to tightest, and that operators of -/// one precedence group to the left. A cast binds tighter than every binary -/// operator. -#[test] -fn precedence() { - for (text, want) in [ - ("a || b && c", "(a || (b && c))"), - ("a | b ^ c & d", "(a | (b ^ (c & d)))"), - ("a & b == c", "(a & (b == c))"), - ("a == b < c", "(a == (b < c))"), - ("a < b << c", "(a < (b << c))"), - ("a << b + c", "(a << (b + c))"), - ("a + b * c", "(a + (b * c))"), - ("a - b - c", "((a - b) - c)"), - ("a * b % c / d", "(((a * b) % c) / d)"), - ("(a + b) * f(c, d + e)", "((a + b) * f(c, (d + e)))"), - ("a != b >= c > d <= e", "(a != (((b >= c) > d) <= e))"), - ("-a * b", "(-a * b)"), - ("-a.b(c)[d]", "-a.b(c)[d]"), - ("!a && b", "(!a && b)"), - ("&mut a + b", "(&mut a + b)"), - ("x.y.z[0][i]", "x.y.z[0][i]"), - ("-r.* * r.x.*", "(-r.* * r.x.*)"), - ("&mut r.*.x", "&mut r.*.x"), - ("a + b as i64", "(a + (b as i64))"), - ("a as i32 * b", "((a as i32) * b)"), - ] { - let (tree, errors) = parse_text(&format!("fn f() {{ {text}; }}")); - assert!(errors.is_empty(), "{text}: {errors:?}"); - assert_eq!(grouped(&tree, first_expression(&tree)), want, "{text}"); - } -} - -#[test] -fn parses_expressions() { - let text = r#"fn f() { - none; - Box::::new(1); - Max::(1); - list::Sum::(); - sum(1, (a)..., &mut b...); - items[n]; -} -"#; - let want = r#"module - function declaration - declared name f - block - expression statement - none literal none - expression statement - call expression - path - generic type - type name Box - type name i32 - type name new - number literal 1 - expression statement - call expression - name reference Max - type name f64 - type name i32 - number literal 1 - expression statement - call expression - path - type name list - type name Sum - type name u8 - expression statement - call expression - name reference sum - number literal 1 - spread - parentheses - name reference a - spread - reference expression mut - name reference b - expression statement - index expression - name reference items - name reference n -"#; - assert!(messages(text).is_empty()); - assert_eq!(dump_of(text), want); -} - -#[test] -fn expression_errors() { - one_error("fn f() { a.; }", "expected `identifier`, found `;`", None); -} - -/// Values after a slice type are an array's, lent: `&[_]i32{ 1, 2 }`. -#[test] -fn slice_type_with_values() { - one_error( - "fn f() { let s = &[]i32{ 1, 2 }; }", - "`&[]i32` is a slice type, so it takes no values", - Some("fn f() { let s = &[_]i32{ 1, 2 }; }"), - ); -} - -/// A spelling that can only be a type is read as one where a value could go, -/// for an argument that takes a type. -#[test] -fn type_expressions() { - let text = "fn f() { g(&[]i32, &mut []u8, &x); }\n"; - let want = r#"module - function declaration - declared name f - block - expression statement - call expression - name reference g - type expression - slice type - type name i32 - type expression - slice type mut - type name u8 - reference expression - name reference x -"#; - assert!(messages(text).is_empty()); - assert_eq!(dump_of(text), want); -} - -/// In an expression `<` compares; type arguments follow `::`. -#[test] -fn comparison_is_not_type_arguments() { - for (text, want) in [ - ("a < b && c > d;", "binary"), - ("Box::::new();", "call"), - ("a < b;", "binary"), - ("f(a < b, c > d);", "call"), - ("Max::(1);", "call"), - ("a < b > (c);", "binary"), - ("a < b && c > (d);", "binary"), - ] { - let (tree, errors) = parse_text(&format!("fn f() {{ {text} }}")); - assert!(errors.is_empty(), "{text}: {errors:?}"); - let got = match tree.exprs[first_expression(&tree)] { - Expr::Binary { .. } => "binary", - Expr::Call { .. } => "call", - other => panic!("{text}: {other:?}"), - }; - assert_eq!(got, want, "{text}"); - } -} - -/// Number literal suffixes, with the old compiler's messages. Digits outside -/// the base are the lexer's to report; a leading zero (007) is left to a -/// later lint pass. -#[test] -fn number_checks() { - for (literal, message) in [ - ("1i", "invalid numeric literal suffix i"), - ("1i_32", "invalid numeric literal suffix i_32"), - ("1i8_", "invalid numeric literal suffix i8_"), - ("1u", "invalid numeric literal suffix u"), - ("1f", "invalid numeric literal suffix f"), - ("0b1i", "invalid numeric literal suffix i"), - ("0o7u", "invalid numeric literal suffix u"), - ( - "2.4i32", - "integer suffix i32 cannot be used on a float literal", - ), - ( - "1e3u8", - "integer suffix u8 cannot be used on a float literal", - ), - ("0", ""), - ("0.5", ""), - ("007", ""), - ("01i32", ""), - ("01f32", ""), - ("1.5f32", ""), - ("0x1f_u8", ""), - ("0xffu24", ""), - ("1_000i64", ""), - ("1e3f64", ""), - ] { - let text = format!("fn f() {{ {literal}; }}"); - let (_, errors) = parse_text(&text); - if message.is_empty() { - assert!(errors.is_empty(), "{literal}: {errors:?}"); - continue; - } - let start = text.find(literal).unwrap(); - assert!( - errors.len() == 1 - && errors[0].message == message - && errors[0].labels[0].span.range() == (start..start + literal.len()), - "{literal}: {errors:?}" - ); - } -} - -/// `true` and `false` are bool literals, each spanning its word, and an -/// operand like any value. -#[test] -fn bool_literals() { - let (tree, errors) = parse_text("fn f() { true; false; !true == false; }"); - assert!(errors.is_empty(), "{errors:?}"); - let literals: Vec<(bool, &str)> = (tree.exprs.ids()) - .filter_map(|id| match tree.exprs[id] { - Expr::Bool(value) => Some((value, tree.file.slice(tree.exprs.span(id)))), - _ => None, - }) - .collect(); - assert_eq!( - literals, - [ - (true, "true"), - (false, "false"), - (true, "true"), - (false, "false") - ] - ); -} - -/// `"..."` is a plain string literal and `c"..."` a C one, each spanning -/// its quotes. -#[test] -fn string_literals() { - let (tree, errors) = parse_text(r#"fn f() { g("a", c"b"); }"#); - assert!(errors.is_empty(), "{errors:?}"); - let literals: Vec<(StringKind, &str)> = (tree.exprs.ids()) - .filter_map(|id| match tree.exprs[id] { - Expr::String(kind) => Some((kind, tree.file.slice(tree.exprs.span(id)))), - _ => None, - }) - .collect(); - assert_eq!( - literals, - [(StringKind::Plain, "\"a\""), (StringKind::C, "c\"b\"")] - ); -} diff --git a/crates/kernel/syntax/parser/src/stmt/tests.rs b/crates/kernel/syntax/parser/src/stmt/tests.rs deleted file mode 100644 index 96d67a39..00000000 --- a/crates/kernel/syntax/parser/src/stmt/tests.rs +++ /dev/null @@ -1,167 +0,0 @@ -use syntax::ast::Stmt; - -use crate::tests::dump_of; -use crate::tests::messages; -use crate::tests::one_error; -use crate::tests::parse_text; - -/// A `return` without a value needs only its `;`: one missing at a line -/// end is read past with a fix, one missing inside a line is reported. -#[test] -fn lone_return() { - one_error( - "fn f() {\n return\n}", - "expected `;`, found `}`", - Some("fn f() {\n return;\n}"), - ); - one_error("fn f() { return }", "expected `;`, found `}`", None); -} - -#[test] -fn parses_statements() { - let text = "fn f() { - let mut n: i32 = 0; - let .{ x, y as z, _ } = point; - const limit = 10; - n = n + 1; - if n == 1 { } else if n == 2 { } else { } - for { break; } - for n < limit { continue; } - for item in items { } - for i, item in items { } - for n { } - for v in values { } - { } -} -"; - let want = "module - function declaration - declared name f - block - let statement mut - declared name n - type name i32 - number literal 0 - destructure statement - struct pattern - field pattern - field name x - field pattern - field name y - declared name z - rest pattern _ - name reference point - const declaration - declared name limit - number literal 10 - assign statement - name reference n - binary expression + - name reference n - number literal 1 - if statement - binary expression == - name reference n - number literal 1 - block { } - if statement - binary expression == - name reference n - number literal 2 - block { } - block { } - loop statement - block - break statement break; - loop statement - binary expression < - name reference n - name reference limit - block - continue statement continue; - for in statement - declared name item - name reference items - block { } - for in statement - declared name i - declared name item - name reference items - block { } - loop statement - name reference n - block { } - for in statement - declared name v - name reference values - block { } - block { } -"; - assert!(messages(text).is_empty()); - assert_eq!(dump_of(text), want); -} - -/// `if a = b` is read as the comparison it was meant to be. -#[test] -fn assignment_in_condition_is_read_as_equal_to() { - let (tree, _) = crate::tests::parse_text("fn f() { if a = b {} }"); - let condition = tree - .stmts - .ids() - .find_map(|statement| match tree.stmts[statement] { - syntax::ast::Stmt::If { condition, .. } => Some(condition), - _ => None, - }) - .expect("an if statement"); - assert!(matches!( - tree.exprs[condition], - syntax::ast::Expr::Binary { - op: syntax::operators::BinaryOp::EqualTo, - .. - } - )); -} - -#[test] -fn statement_errors() { - for (text, message, fixed) in [ - ( - "if a = b {}", - "expected `==` in condition, found `=`", - Some("if a == b {}"), - ), - ("if a", "missing if body", None), - ("if a {} else", "missing else body", None), - ("for x in items", "missing for body", None), - ("for a.b in x {}", "invalid loop variable", None), - ("break outer;", "labeled break is not supported yet", None), - ( - "let .{ a = b } = v;", - "a destructure field is renamed with `as`", - Some("let .{ a as b } = v;"), - ), - ( - "let .{ _, a } = v;", - "`_` must be the last destructure item", - None, - ), - ] { - let fixed = fixed.map(|f| format!("fn f() {{ {f} }}")); - one_error(&format!("fn f() {{ {text} }}"), message, fixed.as_deref()); - } -} - -/// `panic` takes one expression and ends with `;`. -#[test] -fn panics() { - let (tree, errors) = parse_text("fn f() { panic \"stop\"; panic (message); }"); - assert!(errors.is_empty(), "{errors:?}"); - let found: Vec<&str> = (tree.stmts.ids()) - .filter_map(|id| match tree.stmts[id] { - Stmt::Panic(message) => Some(tree.file.slice(tree.exprs.span(message))), - _ => None, - }) - .collect(); - assert_eq!(found, ["\"stop\"", "(message)"]); - assert_eq!(messages("fn f() { panic ; }").len(), 1); -} diff --git a/crates/kernel/lower/Cargo.toml b/crates/lower/Cargo.toml similarity index 90% rename from crates/kernel/lower/Cargo.toml rename to crates/lower/Cargo.toml index aec3393b..50287693 100644 --- a/crates/kernel/lower/Cargo.toml +++ b/crates/lower/Cargo.toml @@ -10,14 +10,13 @@ publish.workspace = true arena.workspace = true bigint.workspace = true model.workspace = true -syntax.workspace = true +tree.workspace = true runtime_abi.workspace = true rustc-hash.workspace = true source.workspace = true [dev-dependencies] check.workspace = true -features.workspace = true parser.workspace = true project.workspace = true diff --git a/crates/kernel/lower/src/aggregates.rs b/crates/lower/src/aggregates.rs similarity index 66% rename from crates/kernel/lower/src/aggregates.rs rename to crates/lower/src/aggregates.rs index e8048486..60544905 100644 --- a/crates/kernel/lower/src/aggregates.rs +++ b/crates/lower/src/aggregates.rs @@ -4,32 +4,17 @@ use arena::Id; use arena::List; use bigint::Limbs; -use model::layout::layout; -use model::mir::Class; -use model::mir::Comparison; -use model::mir::Conversion; -use model::mir::InstructionKind; -use model::mir::IntegerOp; -use model::mir::Operand; -use model::mir::Place; -use model::mir::SLICE_WORDS; -use model::mir::Step; -use model::mir::Terminator; -use model::semantic_types::Integer; -use model::semantic_types::Type; -use model::semantic_types::TypeId; -use model::semantic_types::range_field; +use model::layout; +use model::mir; +use model::semantic_types; use model::thir; -use runtime_abi::messages::RANGE_STEP_MESSAGE; -use runtime_abi::messages::SLICE_BOUNDS_MESSAGE; -use runtime_abi::messages::SLICE_ORDER_MESSAGE; -use runtime_abi::messages::array_parts_message; +use runtime_abi::messages; use source::Span; use crate::Loop; use crate::Lowering; use crate::Value; -use crate::expression::Length; +use crate::expression; use crate::slot_of; /// A range's walk: the five fields of a range value (`range_fields`). Its @@ -38,22 +23,22 @@ use crate::slot_of; /// counted when `inclusive`, an `I8`. Each is a constant when known while /// lowering, else a register. struct RangeWalk { - start: Operand, - left: Operand, - step: Operand, - delta: Operand, - inclusive: Operand, + start: mir::Operand, + left: mir::Operand, + step: mir::Operand, + delta: mir::Operand, + inclusive: mir::Operand, } impl RangeWalk { - /// Each field with where it is in a range value (`range_field`). - fn fields(self) -> [(usize, Operand); 5] { + /// Each field with where it is in a range value (`ranges::field`). + fn fields(self) -> [(usize, mir::Operand); 5] { [ - (range_field::START, self.start), - (range_field::LEFT, self.left), - (range_field::STEP, self.step), - (range_field::DELTA, self.delta), - (range_field::INCLUSIVE, self.inclusive), + (semantic_types::ranges::field::START, self.start), + (semantic_types::ranges::field::LEFT, self.left), + (semantic_types::ranges::field::STEP, self.step), + (semantic_types::ranges::field::DELTA, self.delta), + (semantic_types::ranges::field::INCLUSIVE, self.inclusive), ] } } @@ -72,8 +57,8 @@ impl Lowering<'_> { pub(super) fn lower_struct_literal( &mut self, fields: List, - ty: TypeId, - place: Place, + ty: semantic_types::TypeId, + place: mir::Place, ) -> Option<()> { for field in self.thir.children.lists.items(fields) { let thir::FieldValue { index, value } = self.thir.children.field_values[field]; @@ -90,18 +75,18 @@ impl Lowering<'_> { pub(super) fn lower_array_literal( &mut self, parts: List, - ty: TypeId, - place: Place, + ty: semantic_types::TypeId, + place: mir::Place, span: Span, ) -> Option<()> { - let Type::Array { + let semantic_types::Type::Array { element, length, .. } = self.types[ty] else { unreachable!("an array literal makes an array") }; let element = self.types.real(element); - let (size, _) = layout(self.types, element, self.target); + let (size, _) = layout::layout(self.types, element, self.target); let parts: Vec> = self.thir.children.lists.items(parts).collect(); // Each part's value, and how many elements it gives: a number when // known now, else a register counted when the program runs. @@ -110,8 +95,8 @@ impl Lowering<'_> { // Counted in an integer wider than a range's element and at least // as wide as a pointer, so a count never overflows. let wide = match self.types[element] { - Type::Integer(integer) => { - Class::integer((integer.bits + 1).max(self.target.pointer_bits)) + semantic_types::Type::Integer(integer) => { + mir::Class::integer((integer.bits + 1).max(self.target.pointer_bits)) } _ => self.usize, }; @@ -121,7 +106,7 @@ impl Lowering<'_> { // An element may itself be a slice or a range: one part, not a spread. let spread = !self.types.same(part_type, element); let value = match self.types[part_type] { - Type::Range { .. } if spread => Part::Range(self.walk_range(part)?), + semantic_types::Type::Range { .. } if spread => Part::Range(self.walk_range(part)?), _ => { let called_later = last_call.is_some_and(|last| index < last); let value = self.lower_expr(part)?; @@ -130,9 +115,9 @@ impl Lowering<'_> { }; let count = match self.types[part_type] { _ if !spread => Ok(1), - Type::Array { length, .. } => Ok(length), + semantic_types::Type::Array { length, .. } => Ok(length), _ => match self.part_count(&value, part_type, wide, span) { - Operand::Constant { bits, .. } => Ok(bits[0]), + mir::Operand::Constant { bits, .. } => Ok(bits[0]), counted => { counted_at_run_time = true; Err(counted) @@ -145,33 +130,34 @@ impl Lowering<'_> { let fixed: u64 = lowered.iter().filter_map(|(.., count)| count.ok()).sum(); let mut remaining = self.class_constant(wide, &Limbs::new(wide.bits(), &[length - fixed]), span); - let mut failed = Operand::integer(Class::I8, 0); + let mut failed = mir::Operand::integer(mir::Class::I8, 0); for (.., count) in &lowered { let Err(count) = count else { continue }; - let over = self.compare(Comparison::UnsignedLess, wide, remaining, *count, span); - failed = self.integer(IntegerOp::Or, Class::I8, failed, over, span); - remaining = self.integer(IntegerOp::Subtract, wide, remaining, *count, span); + let over = + self.compare(mir::Comparison::UnsignedLess, wide, remaining, *count, span); + failed = self.integer(mir::IntegerOp::Or, mir::Class::I8, failed, over, span); + remaining = self.integer(mir::IntegerOp::Subtract, wide, remaining, *count, span); } let zero = self.class_constant(wide, &Limbs::new(wide.bits(), &[]), span); - let short = self.compare(Comparison::NotEqual, wide, remaining, zero, span); - let failed = self.integer(IntegerOp::Or, Class::I8, failed, short, span); - self.emit_check(failed, &array_parts_message(length), span); + let short = self.compare(mir::Comparison::NotEqual, wide, remaining, zero, span); + let failed = self.integer(mir::IntegerOp::Or, mir::Class::I8, failed, short, span); + self.emit_check(failed, &messages::array_parts_message(length), span); } // Where the next part goes, in elements: a number until a part // counted when the program runs, then a register. - let mut position: Result = Ok(0); + let mut position: Result = Ok(0); for (&part, (spread, part_type, value, count)) in parts.iter().zip(lowered) { // A position counted when the program runs is already a `usize`. // Also how many elements there are from it to the end: at most // the length when only the program knows the position. - let at = |position: &Result| match *position { + let at = |position: &Result| match *position { Ok(index) => ( - place.clone().then(Step::Offset(index * size)), + place.clone().then(mir::Step::Offset(index * size)), length - index, ), Err(index) => { let count = Some(length); - let step = Step::Index { index, size, count }; + let step = mir::Step::Index { index, size, count }; (place.clone().then(step), length) } }; @@ -179,18 +165,19 @@ impl Lowering<'_> { Part::Range(walk) => { let (to, room) = at(&position); let count = match count { - Ok(count) => Operand::integer(self.usize, count), + Ok(count) => mir::Operand::integer(self.usize, count), Err(count) => self.as_usize(count, wide, span), }; self.fill_range(to, room, walk, part_type, count, span); } Part::Value(value) - if spread && matches!(self.types[part_type], Type::Slice { .. }) => + if spread + && matches!(self.types[part_type], semantic_types::Type::Slice { .. }) => { let (to, room) = at(&position); let count = count.expect_err("a slice is counted when the program runs"); let count = self.as_usize(count, wide, span); - let from = value.memory().then(Step::Through); + let from = value.memory().then(mir::Step::Through); self.copy_elements(to, room, from, count, size, span); } // A value in memory is read by its copy, at the part's own @@ -209,16 +196,16 @@ impl Lowering<'_> { (Ok(index), Ok(count)) => Ok(index + count), (Ok(index), Err(count)) => { let count = self.as_usize(count, wide, span); - let index = Operand::integer(self.usize, index); - Err(self.integer(IntegerOp::Add, self.usize, index, count, span)) + let index = mir::Operand::integer(self.usize, index); + Err(self.integer(mir::IntegerOp::Add, self.usize, index, count, span)) } (Err(index), Ok(count)) => { - let count = Operand::integer(self.usize, count); - Err(self.integer(IntegerOp::Add, self.usize, index, count, span)) + let count = mir::Operand::integer(self.usize, count); + Err(self.integer(mir::IntegerOp::Add, self.usize, index, count, span)) } (Err(index), Err(count)) => { let count = self.as_usize(count, wide, span); - Err(self.integer(IntegerOp::Add, self.usize, index, count, span)) + Err(self.integer(mir::IntegerOp::Add, self.usize, index, count, span)) } }; } @@ -227,11 +214,11 @@ impl Lowering<'_> { /// `count`, a number of the class `wide`, as a `usize`: it was checked /// to fit the array. - fn as_usize(&mut self, count: Operand, wide: Class, span: Span) -> Operand { + fn as_usize(&mut self, count: mir::Operand, wide: mir::Class, span: Span) -> mir::Operand { if wide == self.usize { return count; } - self.convert(Conversion::Truncate, wide, self.usize, count, span) + self.convert(mir::Cast::Truncate, wide, self.usize, count, span) } /// How many elements the spread part `part`, of the type `part_type`, @@ -239,20 +226,26 @@ impl Lowering<'_> { /// `left` over its `step`, one more when it includes its end or when /// that leaves a rest (`Integer::count_over`). A constant when the /// range's fields are. - fn part_count(&mut self, part: &Part, part_type: TypeId, wide: Class, span: Span) -> Operand { + fn part_count( + &mut self, + part: &Part, + part_type: semantic_types::TypeId, + wide: mir::Class, + span: Span, + ) -> mir::Operand { match (part, &self.types[part_type]) { - (Part::Value(value), Type::Slice { .. }) => { + (Part::Value(value), semantic_types::Type::Slice { .. }) => { let length = self.second_word(value.clone().memory()); let length = self.load(self.usize, length, span); self.widen_unsigned(length, self.usize, wide, span) } - (Part::Range(walk), Type::Range { .. }) => { + (Part::Range(walk), semantic_types::Type::Range { .. }) => { let (_, size) = self.range_integers(part_type); let (left, step, inclusive) = (walk.left, walk.step, walk.inclusive); if let ( - Operand::Constant { bits: left, .. }, - Operand::Constant { bits: step, .. }, - Operand::Constant { + mir::Operand::Constant { bits: left, .. }, + mir::Operand::Constant { bits: step, .. }, + mir::Operand::Constant { bits: inclusive, .. }, ) = (left, step, inclusive) @@ -263,15 +256,15 @@ impl Lowering<'_> { let count = bigint::extend(size.bits + 1, false, &count, wide.bits()); return self.class_constant(wide, &count, span); } - let class = Class::integer(size.bits); - let whole = self.integer(IntegerOp::UnsignedDivide, class, left, step, span); + let class = mir::Class::integer(size.bits); + let whole = self.integer(mir::IntegerOp::UnsignedDivide, class, left, step, span); let whole = self.widen_unsigned(whole, class, wide, span); - let rest = self.integer(IntegerOp::UnsignedRemainder, class, left, step, span); + let rest = self.integer(mir::IntegerOp::UnsignedRemainder, class, left, step, span); let zero = self.class_constant(class, &Limbs::new(class.bits(), &[]), span); - let more = self.compare(Comparison::NotEqual, class, rest, zero, span); - let last = self.integer(IntegerOp::Or, Class::I8, inclusive, more, span); - let extra = self.widen_unsigned(last, Class::I8, wide, span); - self.integer(IntegerOp::Add, wide, whole, extra, span) + let more = self.compare(mir::Comparison::NotEqual, class, rest, zero, span); + let last = self.integer(mir::IntegerOp::Or, mir::Class::I8, inclusive, more, span); + let extra = self.widen_unsigned(last, mir::Class::I8, wide, span); + self.integer(mir::IntegerOp::Add, wide, whole, extra, span) } _ => unreachable!("only a slice and a range are counted when the program runs"), } @@ -279,11 +272,17 @@ impl Lowering<'_> { /// `value` of the class `from` as the class `to`, no narrower, read /// unsigned. - fn widen_unsigned(&mut self, value: Operand, from: Class, to: Class, span: Span) -> Operand { + fn widen_unsigned( + &mut self, + value: mir::Operand, + from: mir::Class, + to: mir::Class, + span: Span, + ) -> mir::Operand { if from == to { return value; } - self.convert(Conversion::ZeroExtend, from, to, value, span) + self.convert(mir::Cast::ZeroExtend, from, to, value, span) } /// Copies `count` elements of `size` bytes from `from`, a slice's @@ -291,21 +290,21 @@ impl Lowering<'_> { /// loop, so the code does not grow with the count. fn copy_elements( &mut self, - to: Place, + to: mir::Place, room: u64, - from: Place, - count: Operand, + from: mir::Place, + count: mir::Operand, size: u64, span: Span, ) { self.for_each_index(count, span, |lowering, at| { - let kind = InstructionKind::Copy { - to: to.clone().then(Step::Index { + let kind = mir::InstructionKind::Copy { + to: to.clone().then(mir::Step::Index { index: at, size, count: Some(room), }), - from: from.clone().then(Step::Index { + from: from.clone().then(mir::Step::Index { index: at, size, count: None, @@ -321,34 +320,34 @@ impl Lowering<'_> { /// its array's end: its `start`, then each `delta` more, wrapping. fn fill_range( &mut self, - to: Place, + to: mir::Place, room: u64, walk: RangeWalk, - range_type: TypeId, - count: Operand, + range_type: semantic_types::TypeId, + count: mir::Operand, span: Span, ) { - let Type::Range { element, .. } = self.types[range_type] else { + let semantic_types::Type::Range { element, .. } = self.types[range_type] else { unreachable!("only a range fills elements") }; - let Type::Integer(integer) = self.types[element] else { + let semantic_types::Type::Integer(integer) = self.types[element] else { unreachable!("a range is of integers") }; - let class = Class::integer(integer.bits); - let (size, _) = layout(self.types, element, self.target); + let class = mir::Class::integer(integer.bits); + let (size, _) = layout::layout(self.types, element, self.target); let RangeWalk { start, delta, .. } = walk; let value = self.register_slot(class, span); - self.store(class, Place::whole(value), start, span); + self.store(class, mir::Place::whole(value), start, span); self.for_each_index(count, span, |lowering, at| { - let current = lowering.load(class, Place::whole(value), span); - let element = to.clone().then(Step::Index { + let current = lowering.load(class, mir::Place::whole(value), span); + let element = to.clone().then(mir::Step::Index { index: at, size, count: Some(room), }); lowering.store(class, element, current, span); - let next = lowering.arithmetic(IntegerOp::Add, integer, current, delta, span); - lowering.store(class, Place::whole(value), next, span); + let next = lowering.arithmetic(mir::IntegerOp::Add, integer, current, delta, span); + lowering.store(class, mir::Place::whole(value), next, span); }); } @@ -356,19 +355,19 @@ impl Lowering<'_> { /// kept in a hidden slot in scope until the statement ends. fn for_each_index( &mut self, - count: Operand, + count: mir::Operand, span: Span, - body: impl FnOnce(&mut Self, Operand), + body: impl FnOnce(&mut Self, mir::Operand), ) { let index = self.register_slot(self.usize, span); - let zero = Operand::integer(self.usize, 0); - self.store(self.usize, Place::whole(index), zero, span); + let zero = mir::Operand::integer(self.usize, 0); + self.store(self.usize, mir::Place::whole(index), zero, span); let [test, body_block, done] = [(); 3].map(|()| self.new_block(span)); - self.finish(Terminator::Jump(test)); + self.finish(mir::Terminator::Jump(test)); self.block = test; - let at = self.load(self.usize, Place::whole(index), span); - let more = self.compare(Comparison::UnsignedLess, self.usize, at, count, span); - self.finish(Terminator::Branch { + let at = self.load(self.usize, mir::Place::whole(index), span); + let more = self.compare(mir::Comparison::UnsignedLess, self.usize, at, count, span); + self.finish(mir::Terminator::Branch { condition: more, span, then: body_block, @@ -376,16 +375,16 @@ impl Lowering<'_> { }); self.block = body_block; body(self, at); - let one = Operand::integer(self.usize, 1); - let next = self.integer(IntegerOp::Add, self.usize, at, one, span); - self.store(self.usize, Place::whole(index), next, span); - self.finish(Terminator::Jump(test)); + let one = mir::Operand::integer(self.usize, 1); + let next = self.integer(mir::IntegerOp::Add, self.usize, at, one, span); + self.store(self.usize, mir::Place::whole(index), next, span); + self.finish(mir::Terminator::Jump(test)); self.block = done; } /// A range value written as `start..end:step`, at `place`: its walk's /// five fields. - pub(super) fn lower_range(&mut self, range: Id, place: Place) -> Option<()> { + pub(super) fn lower_range(&mut self, range: Id, place: mir::Place) -> Option<()> { let span = self.thir.exprs.span(range); let ty = self.types.real(self.thir.exprs[range].ty); let walk = self.walk_range(range)?; @@ -403,7 +402,7 @@ impl Lowering<'_> { /// written: `start`, `end`, `step` and `inclusive`, after stopping the /// program when its step is zero; a constant zero step the checker /// rejected. - fn lower_range_parts(&mut self, range: Id) -> Option<[Operand; 4]> { + fn lower_range_parts(&mut self, range: Id) -> Option<[mir::Operand; 4]> { let thir::ExprKind::Range { start, end, @@ -420,16 +419,16 @@ impl Lowering<'_> { let start = self.lower_expr(start)?.register(); let end = self.lower_expr(end)?.register(); let step = self.lower_expr(step)?.register(); - if !matches!(step, Operand::Constant { .. }) { - let Type::Integer(step_integer) = self.types[size] else { + if !matches!(step, mir::Operand::Constant { .. }) { + let semantic_types::Type::Integer(step_integer) = self.types[size] else { unreachable!("a step is an integer") }; let zero = self.integer_constant(step_integer, 0, step_span); - let class = Class::integer(step_integer.bits); - let failed = self.compare(Comparison::Equal, class, step, zero, step_span); - self.emit_check(failed, RANGE_STEP_MESSAGE, step_span); + let class = mir::Class::integer(step_integer.bits); + let failed = self.compare(mir::Comparison::Equal, class, step, zero, step_span); + self.emit_check(failed, messages::RANGE_STEP_MESSAGE, step_span); } - let inclusive = Operand::integer(Class::I8, u64::from(inclusive)); + let inclusive = mir::Operand::integer(mir::Class::I8, u64::from(inclusive)); Some([start, end, step, inclusive]) } @@ -445,8 +444,8 @@ impl Lowering<'_> { let range_type = self.thir.exprs[range].ty; let (integer, step_integer) = self.range_integers(range_type); let (class, size_class) = ( - Class::integer(integer.bits), - Class::integer(step_integer.bits), + mir::Class::integer(integer.bits), + mir::Class::integer(step_integer.bits), ); if !matches!(self.thir.exprs[range].kind, thir::ExprKind::Range { .. }) { let place = self.lower_expr(range)?.memory(); @@ -458,16 +457,16 @@ impl Lowering<'_> { lowering.load(class, at, span) }; return Some(RangeWalk { - start: field(self, range_field::START), - left: field(self, range_field::LEFT), - step: field(self, range_field::STEP), - delta: field(self, range_field::DELTA), - inclusive: field(self, range_field::INCLUSIVE), + start: field(self, semantic_types::ranges::field::START), + left: field(self, semantic_types::ranges::field::LEFT), + step: field(self, semantic_types::ranges::field::STEP), + delta: field(self, semantic_types::ranges::field::DELTA), + inclusive: field(self, semantic_types::ranges::field::INCLUSIVE), }); } let [start, end, step, inclusive] = self.lower_range_parts(range)?; - let known = |operand: Operand, bits: u32| match operand { - Operand::Constant { bits: value, .. } => Some(Limbs::new(bits, &value)), + let known = |operand: mir::Operand, bits: u32| match operand { + mir::Operand::Constant { bits: value, .. } => Some(Limbs::new(bits, &value)), _ => None, }; let delta = |lowering: &mut Self, up: bool| match known(step, step_integer.bits) { @@ -485,7 +484,7 @@ impl Lowering<'_> { None => { let delta = lowering.convert_integer(step, step_integer, integer, span); let zero = lowering.integer_constant(integer, 0, span); - lowering.arithmetic(IntegerOp::Subtract, integer, zero, delta, span) + lowering.arithmetic(mir::IntegerOp::Subtract, integer, zero, delta, span) } }; if let (Some(first), Some(last)) = (known(start, integer.bits), known(end, integer.bits)) { @@ -507,16 +506,16 @@ impl Lowering<'_> { let delta_slot = self.register_slot(class, span); let way = |lowering: &mut Self, up: bool| { let (near, far) = if up { (start, end) } else { (end, start) }; - let distance = lowering.arithmetic(IntegerOp::Subtract, integer, far, near, span); + let distance = lowering.arithmetic(mir::IntegerOp::Subtract, integer, far, near, span); let left = lowering.convert_integer(distance, integer, step_integer, span); - lowering.store(size_class, Place::whole(left_slot), left, span); + lowering.store(size_class, mir::Place::whole(left_slot), left, span); let delta = delta(lowering, up); - lowering.store(class, Place::whole(delta_slot), delta, span); + lowering.store(class, mir::Place::whole(delta_slot), delta, span); }; - let (_, less_or_equal) = Comparison::integer_less(integer.signed); + let (_, less_or_equal) = mir::Comparison::integer_less(integer.signed); let up = self.compare(less_or_equal, class, start, end, span); let [upward, downward, counted] = [(); 3].map(|()| self.new_block(span)); - self.finish(Terminator::Branch { + self.finish(mir::Terminator::Branch { condition: up, span, then: upward, @@ -524,13 +523,13 @@ impl Lowering<'_> { }); self.block = upward; way(self, true); - self.finish(Terminator::Jump(counted)); + self.finish(mir::Terminator::Jump(counted)); self.block = downward; way(self, false); - self.finish(Terminator::Jump(counted)); + self.finish(mir::Terminator::Jump(counted)); self.block = counted; - let left = self.load(size_class, Place::whole(left_slot), span); - let delta = self.load(class, Place::whole(delta_slot), span); + let left = self.load(size_class, mir::Place::whole(left_slot), span); + let delta = self.load(class, mir::Place::whole(delta_slot), span); Some(RangeWalk { start, left, @@ -542,11 +541,14 @@ impl Lowering<'_> { /// The integer types of the values and of the step of the range type /// `range_type`. - fn range_integers(&self, range_type: TypeId) -> (Integer, Integer) { - let Type::Range { element, step } = self.types[range_type] else { + fn range_integers( + &self, + range_type: semantic_types::TypeId, + ) -> (semantic_types::Integer, semantic_types::Integer) { + let semantic_types::Type::Range { element, step } = self.types[range_type] else { unreachable!("only a range has a walk") }; - let (&Type::Integer(integer), &Type::Integer(step_integer)) = + let (&semantic_types::Type::Integer(integer), &semantic_types::Type::Integer(step_integer)) = (&self.types[element], &self.types[step]) else { unreachable!("a range is of integers") @@ -574,8 +576,8 @@ impl Lowering<'_> { let range_span = self.thir.exprs.span(range); let (integer, step_integer) = self.range_integers(self.thir.exprs[range].ty); let (class, size_class) = ( - Class::integer(integer.bits), - Class::integer(step_integer.bits), + mir::Class::integer(integer.bits), + mir::Class::integer(step_integer.bits), ); let RangeWalk { start, @@ -587,7 +589,7 @@ impl Lowering<'_> { // Whether the range includes its end, when that is known now: a // range written here; `None` for a range value. let included = match inclusive { - Operand::Constant { bits, .. } => Some(bits[0] != 0), + mir::Operand::Constant { bits, .. } => Some(bits[0] != 0), _ => None, }; let first = if included == Some(true) { @@ -596,7 +598,7 @@ impl Lowering<'_> { let zero = self.class_constant(size_class, &Limbs::new(size_class.bits(), &[]), range_span); let away = self.compare( - Comparison::NotEqual, + mir::Comparison::NotEqual, size_class, left_first, zero, @@ -604,12 +606,18 @@ impl Lowering<'_> { ); match included { Some(_) => away, - None => self.integer(IntegerOp::Or, Class::I8, inclusive, away, range_span), + None => self.integer( + mir::IntegerOp::Or, + mir::Class::I8, + inclusive, + away, + range_span, + ), } }; let counter = self.register_slot(class, range_span); let left = self.register_slot(size_class, range_span); - let going = self.register_slot(Class::I8, range_span); + let going = self.register_slot(mir::Class::I8, range_span); let index_slot = index.map(slot_of); let passes_class = index.map(|index| { let passes_type = self.thir.variables[index].ty; @@ -617,47 +625,47 @@ impl Lowering<'_> { .expect("a count is a register") }); let passes = passes_class.map(|class| self.register_slot(class, range_span)); - self.store(class, Place::whole(counter), start, range_span); - self.store(size_class, Place::whole(left), left_first, range_span); - self.store(Class::I8, Place::whole(going), first, range_span); + self.store(class, mir::Place::whole(counter), start, range_span); + self.store(size_class, mir::Place::whole(left), left_first, range_span); + self.store(mir::Class::I8, mir::Place::whole(going), first, range_span); if let (Some(passes), Some(passes_class)) = (passes, passes_class) { let zero = self.class_constant( passes_class, &Limbs::new(passes_class.bits(), &[]), range_span, ); - self.store(passes_class, Place::whole(passes), zero, range_span); + self.store(passes_class, mir::Place::whole(passes), zero, range_span); } let test = self.new_block(span); - self.finish(Terminator::Jump(test)); + self.finish(mir::Terminator::Jump(test)); self.block = test; - let going_now = self.load(Class::I8, Place::whole(going), range_span); + let going_now = self.load(mir::Class::I8, mir::Place::whole(going), range_span); let pass = self.new_block(self.thir.blocks.span(body)); let exit = self.new_block(span); - self.finish(Terminator::Branch { + self.finish(mir::Terminator::Branch { condition: going_now, span: range_span, then: pass, otherwise: exit, }); self.block = pass; - let counter_now = self.load(class, Place::whole(counter), range_span); - let left_now = self.load(size_class, Place::whole(left), range_span); + let counter_now = self.load(class, mir::Place::whole(counter), range_span); + let left_now = self.load(size_class, mir::Place::whole(left), range_span); let declared = self.declared.len(); // the pass's variables, then its body's if let Some(value) = value { let slot = slot_of(value); let value_span = self.mir.slots.span(slot); - self.store(class, Place::whole(slot), counter_now, value_span); + self.store(class, mir::Place::whole(slot), counter_now, value_span); self.declare(slot); } if let (Some(index_slot), Some(passes), Some(passes_class)) = (index_slot, passes, passes_class) { - let passes_now = self.load(passes_class, Place::whole(passes), range_span); + let passes_now = self.load(passes_class, mir::Place::whole(passes), range_span); let index_span = self.mir.slots.span(index_slot); self.store( passes_class, - Place::whole(index_slot), + mir::Place::whole(index_slot), passes_now, index_span, ); @@ -667,31 +675,49 @@ impl Lowering<'_> { &Limbs::new(passes_class.bits(), &[1]), range_span, ); - let next = self.integer(IntegerOp::Add, passes_class, passes_now, one, range_span); - self.store(passes_class, Place::whole(passes), next, range_span); + let next = self.integer( + mir::IntegerOp::Add, + passes_class, + passes_now, + one, + range_span, + ); + self.store(passes_class, mir::Place::whole(passes), next, range_span); } - let (less, less_or_equal) = Comparison::integer_less(step_integer.signed); + let (less, less_or_equal) = mir::Comparison::integer_less(step_integer.signed); let more = match included { Some(true) => self.compare(less_or_equal, size_class, step, left_now, range_span), Some(false) => self.compare(less, size_class, step, left_now, range_span), None => { let beyond = self.compare(less, size_class, step, left_now, range_span); - let at = self.compare(Comparison::Equal, size_class, left_now, step, range_span); - let last = self.integer(IntegerOp::And, Class::I8, inclusive, at, range_span); - self.integer(IntegerOp::Or, Class::I8, beyond, last, range_span) + let at = self.compare( + mir::Comparison::Equal, + size_class, + left_now, + step, + range_span, + ); + let last = self.integer( + mir::IntegerOp::And, + mir::Class::I8, + inclusive, + at, + range_span, + ); + self.integer(mir::IntegerOp::Or, mir::Class::I8, beyond, last, range_span) } }; - let next = self.arithmetic(IntegerOp::Add, integer, counter_now, delta, range_span); + let next = self.arithmetic(mir::IntegerOp::Add, integer, counter_now, delta, range_span); let left_next = self.arithmetic( - IntegerOp::Subtract, + mir::IntegerOp::Subtract, step_integer, left_now, step, range_span, ); - self.store(class, Place::whole(counter), next, range_span); - self.store(size_class, Place::whole(left), left_next, range_span); - self.store(Class::I8, Place::whole(going), more, range_span); + self.store(class, mir::Place::whole(counter), next, range_span); + self.store(size_class, mir::Place::whole(left), left_next, range_span); + self.store(mir::Class::I8, mir::Place::whole(going), more, range_span); // Every pass ends here, then tests again. let step_block = self.new_block(span); let targets = Loop { @@ -701,7 +727,7 @@ impl Lowering<'_> { }; self.lower_loop_body(body, targets)?; self.block = step_block; - self.finish(Terminator::Jump(test)); + self.finish(mir::Terminator::Jump(test)); self.block = exit; Some(()) } @@ -713,7 +739,7 @@ impl Lowering<'_> { /// known at compile time for an array, so they get no check; a slice's /// length is known only when the program runs, so each of its ends but /// a start of 0 is checked. Its two words go at `to`. - pub(super) fn lower_slice(&mut self, expression: Id, to: Place) -> Option<()> { + pub(super) fn lower_slice(&mut self, expression: Id, to: mir::Place) -> Option<()> { let span = self.thir.exprs.span(expression); let thir::Expr { ty, @@ -735,22 +761,22 @@ impl Lowering<'_> { let mut place = self.place_of(array)?; let viewed = self.types.real(self.thir.exprs[array].ty); let (element, length) = match self.types[viewed] { - Type::Array { + semantic_types::Type::Array { element, length, .. - } => (element, Length::Known(length)), + } => (element, expression::Length::Known(length)), // Its elements are behind its first word. - Type::Slice { element, .. } => { + semantic_types::Type::Slice { element, .. } => { let length = self.second_word(place.clone()); let read = self.load(self.usize, length, span); - place = place.then(Step::Through); - (element, Length::Read(read)) + place = place.then(mir::Step::Through); + (element, expression::Length::Read(read)) } _ => unreachable!("the checker slices only an array or a slice"), }; - let (size, _) = layout(self.types, self.types.real(element), self.target); + let (size, _) = layout::layout(self.types, self.types.real(element), self.target); let known_length = match length { - Length::Known(length) => Some(length), - Length::Read(_) => None, + expression::Length::Known(length) => Some(length), + expression::Length::Read(_) => None, }; // How many elements come before each end when known at compile // time: a missing start is 0, a missing end the length. @@ -764,9 +790,9 @@ impl Lowering<'_> { |known: Option| known.is_none() || known_length.is_none() && known != Some(0); let start_operand = match start { Some(start) if checked(known_start) => { - self.lower_slice_end(start, Comparison::UnsignedLess, length)? + self.lower_slice_end(start, mir::Comparison::UnsignedLess, length)? } - _ => Operand::integer( + _ => mir::Operand::integer( self.usize, known_start.expect("an unchecked start is known"), ), @@ -775,23 +801,23 @@ impl Lowering<'_> { (Some(end), known) if checked(known) => { // A `..=` end is below the length, so one past it fits. let outside = if inclusive { - Comparison::UnsignedLessOrEqual + mir::Comparison::UnsignedLessOrEqual } else { - Comparison::UnsignedLess + mir::Comparison::UnsignedLess }; let end = self.lower_slice_end(end, outside, length)?; if inclusive { - let one = Operand::integer(self.usize, 1); - self.integer(IntegerOp::Add, self.usize, end, one, span) + let one = mir::Operand::integer(self.usize, 1); + self.integer(mir::IntegerOp::Add, self.usize, end, one, span) } else { end } } - (_, Some(known)) => Operand::integer(self.usize, known), + (_, Some(known)) => mir::Operand::integer(self.usize, known), // A slice's missing end is its length. (_, None) => match length { - Length::Read(length) => length, - Length::Known(_) => unreachable!("an array's missing end is known"), + expression::Length::Read(length) => length, + expression::Length::Known(_) => unreachable!("an array's missing end is known"), }, }; // Each end is inside the elements, so a start of 0 or an end at the @@ -801,19 +827,19 @@ impl Lowering<'_> { known_start == Some(0) || at_length || known_start.is_some() && known_end.is_some(); if !in_order { let failed = self.compare( - Comparison::UnsignedLess, + mir::Comparison::UnsignedLess, self.usize, end_operand, start_operand, span, ); - self.emit_check(failed, SLICE_ORDER_MESSAGE, span); + self.emit_check(failed, messages::SLICE_ORDER_MESSAGE, span); } let count = match (known_start, known_end) { - (Some(start), Some(end)) => Operand::integer(self.usize, end - start), + (Some(start), Some(end)) => mir::Operand::integer(self.usize, end - start), (Some(0), None) => end_operand, _ => self.integer( - IntegerOp::Subtract, + mir::IntegerOp::Subtract, self.usize, end_operand, start_operand, @@ -822,13 +848,13 @@ impl Lowering<'_> { }; // The loan runs from the start to the array's end, so a write // before the start may happen while the slice is in use. - let elements = place.then(Step::Index { + let elements = place.then(mir::Step::Index { index: start_operand, size, count: known_length, }); let covered = known_length.map(|length| (length - known_start.unwrap_or(0)) * size); - let address = self.borrow(elements, covered, mutable, &SLICE_WORDS, span); + let address = self.borrow(elements, covered, mutable, &mir::SLICE_WORDS, span); self.slice_words(address, count, to, span); Some(()) } @@ -839,12 +865,19 @@ impl Lowering<'_> { fn lower_slice_end( &mut self, end: Id, - outside: Comparison, - length: Length, - ) -> Option { + outside: mir::Comparison, + length: expression::Length, + ) -> Option { let span = self.thir.exprs.span(end); let ty = self.types.real(self.thir.exprs[end].ty); let value = self.lower_expr(end)?.register(); - Some(self.checked_usize(value, ty, outside, length, SLICE_BOUNDS_MESSAGE, span)) + Some(self.checked_usize( + value, + ty, + outside, + length, + messages::SLICE_BOUNDS_MESSAGE, + span, + )) } } diff --git a/crates/kernel/lower/src/arithmetic.rs b/crates/lower/src/arithmetic.rs similarity index 66% rename from crates/kernel/lower/src/arithmetic.rs rename to crates/lower/src/arithmetic.rs index a1969d5a..277fd05a 100644 --- a/crates/kernel/lower/src/arithmetic.rs +++ b/crates/lower/src/arithmetic.rs @@ -1,15 +1,13 @@ -//! The MIR operation lowering makes of each operator and `as` on -//! numbers; check's folder computes constants with the same -//! (`check::fold`). +//! The MIR operation lowering makes of each operator on numbers; the +//! checker's constant folder (`check::fold`) computes constants with the +//! same. use model::mir::Comparison; -use model::mir::Conversion; use model::mir::FloatOp; use model::mir::IntegerOp; -use model::semantic_types::Float; use model::semantic_types::Integer; use model::semantic_types::Type; -use syntax::operators::BinaryOp; +use tree::operators::BinaryOp; /// The MIR operation of a binary operator on two numbers. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -70,25 +68,3 @@ pub fn binary_operation(op: BinaryOp, number: &Type) -> BinaryOperation { _ => unreachable!("the checker allows no other operator on numbers"), } } - -/// The conversion `value as to` makes of a value of the type `from`, as -/// check allows it: between numbers, from a `bool` to an integer, and -/// between raw pointers; integers at their own widths. Check drops an `as` -/// to the same type. -pub fn cast_conversion(from: &Type, to: &Type) -> Conversion { - match (from, to) { - (Type::Integer(from), Type::Integer(to)) if to.bits < from.bits => Conversion::Truncate, - (Type::Integer(from), Type::Integer(_)) if from.signed => Conversion::SignExtend, - (Type::Integer(_) | Type::Bool, Type::Integer(_)) => Conversion::ZeroExtend, - (Type::Integer(from), Type::Float(_)) if from.signed => Conversion::SignedToFloat, - (Type::Integer(_), Type::Float(_)) => Conversion::UnsignedToFloat, - (Type::Float(_), Type::Integer(to)) if to.signed => { - Conversion::FloatToSigned { bits: to.bits } - } - (Type::Float(_), Type::Integer(to)) => Conversion::FloatToUnsigned { bits: to.bits }, - (Type::Float(Float::F32), Type::Float(Float::F64)) => Conversion::FloatWiden, - (Type::Float(Float::F64), Type::Float(Float::F32)) => Conversion::FloatNarrow, - (Type::RawPointer { .. }, Type::RawPointer { .. }) => Conversion::PointerCast, - _ => unreachable!("check converts no {from:?} to {to:?}"), - } -} diff --git a/crates/kernel/lower/src/c_abi.rs b/crates/lower/src/c_abi.rs similarity index 100% rename from crates/kernel/lower/src/c_abi.rs rename to crates/lower/src/c_abi.rs diff --git a/crates/kernel/lower/src/expression.rs b/crates/lower/src/expression.rs similarity index 67% rename from crates/kernel/lower/src/expression.rs rename to crates/lower/src/expression.rs index 4714275f..c2bf1a55 100644 --- a/crates/kernel/lower/src/expression.rs +++ b/crates/lower/src/expression.rs @@ -3,47 +3,21 @@ use arena::Id; use bigint::Limbs; -use model::Callee; use model::ConstArguments; use model::DeclarationCopy; -use model::constant::Value as Constant; -use model::layout::layout; -use model::mir::Callee as MirCallee; -use model::mir::Class; -use model::mir::Comparison; -use model::mir::Conversion; -use model::mir::Global; -use model::mir::InstructionKind; -use model::mir::IntegerOp; -use model::mir::LoanWords; -use model::mir::Operand; -use model::mir::Passing; -use model::mir::Place; -use model::mir::REFERENCE_WORDS; -use model::mir::Root; -use model::mir::SLICE_WORDS; -use model::mir::Signature; -use model::mir::Step; -use model::semantic_types::Float; -use model::semantic_types::ImplementationId; -use model::semantic_types::Integer; -use model::semantic_types::Type; -use model::semantic_types::TypeId; +use model::constant; +use model::layout; +use model::mir; +use model::semantic_types; use model::thir; -use runtime_abi::messages::DIVISION_BY_ZERO; -use runtime_abi::messages::SLICE_INDEX_MESSAGE; -use runtime_abi::messages::array_index_message; -use runtime_abi::messages::shift_count_message; +use runtime_abi::messages; use source::Span; -use syntax::operators::BinaryOp; -use syntax::operators::UnaryOp; +use tree::operators; use crate::Lowering; use crate::Value; -use crate::arithmetic::BinaryOperation; -use crate::arithmetic::binary_operation; -use crate::arithmetic::cast_conversion; -use crate::c_abi::c_signature; +use crate::arithmetic; +use crate::c_abi; use crate::slot_of; /// The length of what an index or a slice is taken of: an array's, from @@ -51,11 +25,15 @@ use crate::slot_of; #[derive(Clone, Copy)] pub(super) enum Length { Known(u64), - Read(Operand), + Read(mir::Operand), } impl Lowering<'_> { /// The value of `expression`, computed in the block being filled. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] pub(super) fn lower_expr(&mut self, expression: Id) -> Option { // A long chain of operators, calls or parentheses is a deep recursion. source::grow_stack(|| { @@ -63,16 +41,18 @@ impl Lowering<'_> { let thir::Expr { ty, kind } = &self.thir.exprs[expression]; let ty = self.types.real(*ty); Some(match kind { - _ if ty == TypeId::INVALID => return None, + _ if ty == semantic_types::TypeId::INVALID => return None, thir::ExprKind::Invalid => { unreachable!("a body with an invalid value has errors and is not lowered") } - thir::ExprKind::Constant(Constant::Bytes(_)) if ty == TypeId::STR => { + thir::ExprKind::Constant(constant::Value::Bytes(_)) + if ty == semantic_types::TypeId::STR => + { self.in_temporary(expression, ty, span)? } thir::ExprKind::Constant(value) => self.constant(value, ty, span), thir::ExprKind::Variable(variable) => { - self.read(Place::whole(slot_of(*variable)), ty, span) + self.read(mir::Place::whole(slot_of(*variable)), ty, span) } thir::ExprKind::Temporary { .. } | thir::ExprKind::Field { .. } @@ -83,7 +63,7 @@ impl Lowering<'_> { } thir::ExprKind::Length(value) => self.lower_length(*value, span)?, thir::ExprKind::Binary { - op: op @ (BinaryOp::LogicalAnd | BinaryOp::LogicalOr), + op: op @ (operators::BinaryOp::LogicalAnd | operators::BinaryOp::LogicalOr), left, right, } => self.lower_short_circuit(*op, *left, *right, span)?, @@ -103,8 +83,14 @@ impl Lowering<'_> { }; let place = self.place_of(*borrowed)?; let borrowed_type = self.types.real(self.thir.exprs[*borrowed].ty); - let (size, _) = layout(self.types, borrowed_type, self.target); - Value::Register(self.borrow(place, Some(size), mutable, &REFERENCE_WORDS, span)) + let (size, _) = layout::layout(self.types, borrowed_type, self.target); + Value::Register(self.borrow( + place, + Some(size), + mutable, + &mir::REFERENCE_WORDS, + span, + )) } thir::ExprKind::ToInterface { .. } | thir::ExprKind::StructLiteral(_) @@ -115,8 +101,8 @@ impl Lowering<'_> { thir::ExprKind::Address(addressed) => { let place = self.place_of(*addressed)?; let addressed_type = self.types.real(self.thir.exprs[*addressed].ty); - let (size, _) = layout(self.types, addressed_type, self.target); - Value::Register(self.emit(InstructionKind::Address { place, size }, span)) + let (size, _) = layout::layout(self.types, addressed_type, self.target); + Value::Register(self.emit(mir::InstructionKind::Address { place, size }, span)) } thir::ExprKind::Block(block) => { self.lower_block(*block, self.declared.len())?; @@ -132,40 +118,45 @@ impl Lowering<'_> { fn in_temporary( &mut self, expression: Id, - ty: TypeId, + ty: semantic_types::TypeId, span: Span, ) -> Option { let slot = self.temporary(ty, span); - self.lower_into(expression, Place::whole(slot))?; - Some(Value::Memory(Place::whole(slot))) + self.lower_into(expression, mir::Place::whole(slot))?; + Some(Value::Memory(mir::Place::whole(slot))) } /// The constant `value`, of the type `ty`, as a register; a `&str` is /// in memory (`lower_into`). - fn constant(&mut self, value: &Constant, ty: TypeId, span: Span) -> Value { + fn constant( + &mut self, + value: &constant::Value, + ty: semantic_types::TypeId, + span: Span, + ) -> Value { match value { - Constant::Bool(value) => { - Value::Register(Operand::integer(Class::I8, u64::from(*value))) + constant::Value::Bool(value) => { + Value::Register(mir::Operand::integer(mir::Class::I8, u64::from(*value))) } - Constant::Integer(limbs) => { - let Type::Integer(integer) = self.types[ty] else { + constant::Value::Integer(limbs) => { + let semantic_types::Type::Integer(integer) = self.types[ty] else { unreachable!("an integer constant has an integer type") }; Value::Register(self.integer_operand(integer, limbs, span)) } - Constant::Float(bits) => Value::Register(match self.types[ty] { - Type::Float(Float::F32) => { + constant::Value::Float(bits) => Value::Register(match self.types[ty] { + semantic_types::Type::Float(semantic_types::Float::F32) => { let bits = (f64::from_bits(*bits) as f32).to_bits(); - Operand::integer(Class::F32, u64::from(bits)) + mir::Operand::integer(mir::Class::F32, u64::from(bits)) } - _ => Operand::integer(Class::F64, *bits), + _ => mir::Operand::integer(mir::Class::F64, *bits), }), - Constant::Null => Value::Register(Operand::integer(Class::Pointer, 0)), - Constant::Bytes(bytes) => { + constant::Value::Null => Value::Register(mir::Operand::integer(mir::Class::Pointer, 0)), + constant::Value::Bytes(bytes) => { // C reads a `&cstr` up to its first zero byte, so it ends in one. let mut text = bytes.to_vec(); text.push(0); - Value::Register(self.global(Global::Bytes(text.into()))) + Value::Register(self.global(mir::Global::Bytes(text.into()))) } } } @@ -175,11 +166,11 @@ impl Lowering<'_> { /// register of a narrow type holds its value (`narrow`). pub(super) fn integer_operand( &mut self, - integer: Integer, + integer: semantic_types::Integer, value: &Limbs, span: Span, - ) -> Operand { - let class = Class::integer(integer.bits); + ) -> mir::Operand { + let class = mir::Class::integer(integer.bits); let extended = bigint::extend(integer.bits, integer.signed, value, class.bits()); self.class_constant(class, &extended, span) } @@ -187,19 +178,24 @@ impl Lowering<'_> { /// The integer `value`, of `class`'s width, as an operand: a wide one is /// read-only data, loaded here, as a constant operand holds at most 128 /// bits. - pub(super) fn class_constant(&mut self, class: Class, value: &Limbs, span: Span) -> Operand { - if let Class::Wide(_) = class { + pub(super) fn class_constant( + &mut self, + class: mir::Class, + value: &Limbs, + span: Span, + ) -> mir::Operand { + if let mir::Class::Wide(_) = class { let mut bytes = vec![0; class.bytes(self.target.pointer_bytes()) as usize]; value.write_le_bytes(&mut bytes); - let global = self.global(Global::Bytes(bytes.into())); - let place = Place { - root: Root::At(global), + let global = self.global(mir::Global::Bytes(bytes.into())); + let place = mir::Place { + root: mir::Root::At(global), steps: Box::default(), }; return self.load(class, place, span); } let limbs = value.as_slice(); - Operand::Constant { + mir::Operand::Constant { class, bits: [limbs[0], limbs.get(1).copied().unwrap_or(0)], } @@ -208,7 +204,12 @@ impl Lowering<'_> { /// The integer `value`, of one limb, of the type `integer` as an /// operand, cut to the type's width: `value` must fit it. A `usize` one /// is `Operand::integer(self.usize, value)`. - pub(super) fn integer_constant(&mut self, integer: Integer, value: u64, span: Span) -> Operand { + pub(super) fn integer_constant( + &mut self, + integer: semantic_types::Integer, + value: u64, + span: Span, + ) -> mir::Operand { self.integer_operand(integer, &Limbs::new(integer.bits, &[value]), span) } @@ -216,20 +217,25 @@ impl Lowering<'_> { /// may carry into the bits above its width, cut back to its width: the /// bits above are made its sign bit's, or zero. Nothing for a type as /// wide as its class. - pub(super) fn narrow(&mut self, value: Operand, integer: Integer, span: Span) -> Operand { - let class = Class::integer(integer.bits); + pub(super) fn narrow( + &mut self, + value: mir::Operand, + integer: semantic_types::Integer, + span: Span, + ) -> mir::Operand { + let class = mir::Class::integer(integer.bits); let extra = class.bits() - integer.bits; if extra == 0 { return value; } if integer.signed { - let count = Operand::integer(class, u64::from(extra)); - let up = self.integer(IntegerOp::ShiftLeft, class, value, count, span); - self.integer(IntegerOp::SignedShiftRight, class, up, count, span) + let count = mir::Operand::integer(class, u64::from(extra)); + let up = self.integer(mir::IntegerOp::ShiftLeft, class, value, count, span); + self.integer(mir::IntegerOp::SignedShiftRight, class, up, count, span) } else { let ones = Limbs::new(integer.bits, &[u64::MAX, u64::MAX]); let mask = self.integer_operand(integer, &ones, span); - self.integer(IntegerOp::And, class, value, mask, span) + self.integer(mir::IntegerOp::And, class, value, mask, span) } } @@ -241,17 +247,17 @@ impl Lowering<'_> { // copied, and a `&mut []` stays usable. let place = self.place_of(value)?; if !self.types[value_type].is_slice_shaped() { - let Type::Array { length, .. } = self.types[value_type] else { + let semantic_types::Type::Array { length, .. } = self.types[value_type] else { unreachable!("`.len` is the length of an array, slice or `&str`") }; // A register, not a constant: the checker took this length as // known only when the program runs, after the call, so a // division, shift, step or count using it is checked then. - let slot = Place::whole(self.register_slot(self.usize, span)); + let slot = mir::Place::whole(self.register_slot(self.usize, span)); self.store( self.usize, slot.clone(), - Operand::integer(self.usize, length), + mir::Operand::integer(self.usize, length), span, ); return Some(Value::Register(self.load(self.usize, slot, span))); @@ -265,7 +271,7 @@ impl Lowering<'_> { /// (`s.start.x` is one place), each element's index computed here, in /// the order written; or, for a value not in a variable, the memory /// its value is computed into. - pub(super) fn place_of(&mut self, expression: Id) -> Option { + pub(super) fn place_of(&mut self, expression: Id) -> Option { // From the last step: each one, or the index expression of an element. let mut steps = Vec::new(); let mut outer = expression; @@ -275,11 +281,11 @@ impl Lowering<'_> { let ty = self.thir.exprs[value].ty; let (offset, _) = model::layout::field_placed(self.types, ty, index as usize, self.target); - steps.push(Ok(Step::Offset(offset))); + steps.push(Ok(mir::Step::Offset(offset))); outer = value; } thir::ExprKind::Dereference(reference) => { - steps.push(Ok(Step::Through)); + steps.push(Ok(mir::Step::Through)); outer = reference; } thir::ExprKind::Index { array, .. } => { @@ -287,11 +293,11 @@ impl Lowering<'_> { // A slice's elements are behind its first word. let array_type = self.types.real(self.thir.exprs[array].ty); if self.types[array_type].is_slice_shaped() { - steps.push(Ok(Step::Through)); + steps.push(Ok(mir::Step::Through)); } outer = array; } - thir::ExprKind::Variable(variable) => break Place::whole(slot_of(variable)), + thir::ExprKind::Variable(variable) => break mir::Place::whole(slot_of(variable)), thir::ExprKind::Temporary { variable, value, @@ -301,12 +307,12 @@ impl Lowering<'_> { let ty = self.types.real(self.thir.exprs[value].ty); let value = self.lower_expr(value)?; let temporary = slot_of(variable); - self.put(Place::whole(temporary), value, ty, span); + self.put(mir::Place::whole(temporary), value, ty, span); // A kept one is in `declared` with its variable (`declare`). if kept_by.is_none() { self.declared.push(temporary); // until its statement ends } - break Place::whole(temporary); + break mir::Place::whole(temporary); } // A value not in a variable: computed into memory, or a // reference in a register, gone through. @@ -314,11 +320,11 @@ impl Lowering<'_> { Value::Memory(place) => break place, Value::Moving(..) => unreachable!("a variable's value is read in place"), Value::Register(address) => { - let Some(Ok(Step::Through)) = steps.pop() else { + let Some(Ok(mir::Step::Through)) = steps.pop() else { unreachable!("only a reference's value is a register here") }; - break Place { - root: Root::At(address), + break mir::Place { + root: mir::Root::At(address), steps: Box::default(), }; } @@ -342,39 +348,43 @@ impl Lowering<'_> { /// stopping the program when it is outside them. A constant index into /// an array is inside, as the checker made sure. A slice's length is /// read after its index is computed, as the element itself is. - fn lower_index(&mut self, indexing: Id, elements: &Place) -> Option { + fn lower_index( + &mut self, + indexing: Id, + elements: &mir::Place, + ) -> Option { let span = self.thir.exprs.span(indexing); let thir::ExprKind::Index { array, index } = self.thir.exprs[indexing].kind else { unreachable!("the caller found an index") }; let viewed = self.types.real(self.thir.exprs[array].ty); let (element, checked, count) = match self.types[viewed] { - Type::Array { + semantic_types::Type::Array { element, length, .. } if let Some(at) = self.known_position(index) => { - let at = Operand::integer(self.usize, at); + let at = mir::Operand::integer(self.usize, at); (element, at, Some(length)) } - Type::Array { + semantic_types::Type::Array { element, length, .. } => { let value = self.lower_expr(index)?.register(); - let message = array_index_message(length); + let message = messages::array_index_message(length); let index_type = self.types.real(self.thir.exprs[index].ty); let checked = self.checked_usize( value, index_type, - Comparison::UnsignedLessOrEqual, + mir::Comparison::UnsignedLessOrEqual, Length::Known(length), &message, span, ); (element, checked, Some(length)) } - Type::Slice { element, .. } => { + semantic_types::Type::Slice { element, .. } => { let value = self.lower_expr(index)?.register(); // The slice's words are the place before its elements' step. - let slice = Place { + let slice = mir::Place { root: elements.root, steps: elements.steps[..elements.steps.len() - 1].into(), }; @@ -384,17 +394,17 @@ impl Lowering<'_> { let checked = self.checked_usize( value, index_type, - Comparison::UnsignedLessOrEqual, + mir::Comparison::UnsignedLessOrEqual, Length::Read(read), - SLICE_INDEX_MESSAGE, + messages::SLICE_INDEX_MESSAGE, span, ); (element, checked, None) } _ => unreachable!("the checker indexes only an array or a slice"), }; - let (size, _) = layout(self.types, self.types.real(element), self.target); - Some(Step::Index { + let (size, _) = layout::layout(self.types, self.types.real(element), self.target); + Some(mir::Step::Index { index: checked, size, count, @@ -405,11 +415,13 @@ impl Lowering<'_> { /// constant: the checker took only those that fit a `usize`, and an /// index into an array only one inside it. pub(super) fn known_position(&self, position: Id) -> Option { - let thir::ExprKind::Constant(Constant::Integer(value)) = &self.thir.exprs[position].kind + let thir::ExprKind::Constant(constant::Value::Integer(value)) = + &self.thir.exprs[position].kind else { return None; }; - let Type::Integer(integer) = self.types[self.types.real(self.thir.exprs[position].ty)] + let semantic_types::Type::Integer(integer) = + self.types[self.types.real(self.thir.exprs[position].ty)] else { unreachable!("a position is an integer") }; @@ -426,14 +438,14 @@ impl Lowering<'_> { /// type before it is cut to one. pub(super) fn checked_usize( &mut self, - value: Operand, - ty: TypeId, - outside: Comparison, + value: mir::Operand, + ty: semantic_types::TypeId, + outside: mir::Comparison, length: Length, message: &str, span: Span, - ) -> Operand { - let (&Type::Integer(integer), &Type::Integer(size)) = + ) -> mir::Operand { + let (&semantic_types::Type::Integer(integer), &semantic_types::Type::Integer(size)) = (&self.types[ty], &self.types[self.types.usize]) else { unreachable!("a position and `usize` are integers") @@ -441,8 +453,8 @@ impl Lowering<'_> { let wide = integer.bits > size.bits; if wide && integer.signed { let zero = self.integer_constant(integer, 0, span); - let class = Class::integer(integer.bits); - let failed = self.compare(Comparison::SignedLess, class, value, zero, span); + let class = mir::Class::integer(integer.bits); + let failed = self.compare(mir::Comparison::SignedLess, class, value, zero, span); self.emit_check(failed, message, span); } let compared = if wide || ty == self.types.usize { @@ -451,7 +463,7 @@ impl Lowering<'_> { self.convert_integer(value, integer, size, span) }; let compared_type = if wide { integer } else { size }; - let compared_class = Class::integer(compared_type.bits); + let compared_class = mir::Class::integer(compared_type.bits); let limit = match length { Length::Known(length) => self.integer_constant(compared_type, length, span), Length::Read(length) if wide => self.convert_integer(length, size, integer, span), @@ -470,17 +482,17 @@ impl Lowering<'_> { pub(super) fn convert_integer( &mut self, - value: Operand, - from: Integer, - to: Integer, + value: mir::Operand, + from: semantic_types::Integer, + to: semantic_types::Integer, span: Span, - ) -> Operand { - let (from_class, to_class) = (Class::integer(from.bits), Class::integer(to.bits)); + ) -> mir::Operand { + let (from_class, to_class) = (mir::Class::integer(from.bits), mir::Class::integer(to.bits)); let converted = if from_class == to_class { value } else { - let conversion = cast_conversion(&Type::Integer(from), &Type::Integer(to)); - self.convert(conversion, from_class, to_class, value, span) + let cast = from.cast_to(to); + self.convert(cast, from_class, to_class, value, span) }; // To a type narrower than its class, or one read with the other sign. if to.bits < from.bits || to.bits < to_class.bits() && from.signed != to.signed { @@ -492,7 +504,7 @@ impl Lowering<'_> { fn lower_binary( &mut self, - op: BinaryOp, + op: operators::BinaryOp, left: Id, right: Id, span: Span, @@ -501,15 +513,15 @@ impl Lowering<'_> { let right_type = self.types.real(self.thir.exprs[right].ty); let left_value = self.lower_expr(left)?.register(); let right_value = self.lower_expr(right)?.register(); - let right_constant = matches!(right_value, Operand::Constant { .. }); + let right_constant = matches!(right_value, mir::Operand::Constant { .. }); let number = &self.types[left_type]; let value = match *number { - Type::Integer(_) | Type::Float(_) => { + semantic_types::Type::Integer(_) | semantic_types::Type::Float(_) => { let Some(class) = self.class(left_type) else { unreachable!("a number is a register") }; - match binary_operation(op, number) { - BinaryOperation::Compare { + match arithmetic::binary_operation(op, number) { + arithmetic::BinaryOperation::Compare { comparison, swapped, } => { @@ -520,8 +532,8 @@ impl Lowering<'_> { }; self.compare(comparison, class, left, right, span) } - BinaryOperation::Float(operation) => { - let kind = InstructionKind::Float { + arithmetic::BinaryOperation::Float(operation) => { + let kind = mir::InstructionKind::Float { operation, class, left: left_value, @@ -529,33 +541,35 @@ impl Lowering<'_> { }; self.emit(kind, span) } - BinaryOperation::Integer(operation) => { - let Type::Integer(integer) = *number else { + arithmetic::BinaryOperation::Integer(operation) => { + let semantic_types::Type::Integer(integer) = *number else { unreachable!("an integer operation is on integers") }; let right = match operation { - IntegerOp::SignedDivide - | IntegerOp::UnsignedDivide - | IntegerOp::SignedRemainder - | IntegerOp::UnsignedRemainder => { + mir::IntegerOp::SignedDivide + | mir::IntegerOp::UnsignedDivide + | mir::IntegerOp::SignedRemainder + | mir::IntegerOp::UnsignedRemainder => { if !right_constant { let zero = Limbs::new(class.bits(), &[]); let zero = self.class_constant(class, &zero, span); let failed = self.compare( - Comparison::Equal, + mir::Comparison::Equal, class, right_value, zero, span, ); - self.emit_check(failed, DIVISION_BY_ZERO, span); + self.emit_check(failed, messages::DIVISION_BY_ZERO, span); } right_value } - IntegerOp::ShiftLeft - | IntegerOp::SignedShiftRight - | IntegerOp::UnsignedShiftRight => { - let Type::Integer(count_type) = self.types[right_type] else { + mir::IntegerOp::ShiftLeft + | mir::IntegerOp::SignedShiftRight + | mir::IntegerOp::UnsignedShiftRight => { + let semantic_types::Type::Integer(count_type) = + self.types[right_type] + else { unreachable!("a shift count is an integer") }; self.shift_count( @@ -572,37 +586,43 @@ impl Lowering<'_> { } } } - Type::Bool => { - let class = Class::I8; + semantic_types::Type::Bool => { + let class = mir::Class::I8; match op { - BinaryOp::EqualTo => { - self.compare(Comparison::Equal, class, left_value, right_value, span) - } - BinaryOp::NotEqualTo => { - self.compare(Comparison::NotEqual, class, left_value, right_value, span) + operators::BinaryOp::EqualTo => { + self.compare(mir::Comparison::Equal, class, left_value, right_value, span) } + operators::BinaryOp::NotEqualTo => self.compare( + mir::Comparison::NotEqual, + class, + left_value, + right_value, + span, + ), _ => unreachable!("the checker allows no other `bool` operator"), } } - Type::RawPointer { .. } | Type::CString | Type::Reference { .. } => match op { + semantic_types::Type::RawPointer { .. } + | semantic_types::Type::CString + | semantic_types::Type::Reference { .. } => match op { // `rawptr + usize`: the address that many bytes on. - BinaryOp::Add => self.integer( - IntegerOp::Add, - Class::Pointer, + operators::BinaryOp::Add => self.integer( + mir::IntegerOp::Add, + mir::Class::Pointer, left_value, right_value, span, ), - BinaryOp::EqualTo => self.compare( - Comparison::Equal, - Class::Pointer, + operators::BinaryOp::EqualTo => self.compare( + mir::Comparison::Equal, + mir::Class::Pointer, left_value, right_value, span, ), - BinaryOp::NotEqualTo => self.compare( - Comparison::NotEqual, - Class::Pointer, + operators::BinaryOp::NotEqualTo => self.compare( + mir::Comparison::NotEqual, + mir::Class::Pointer, left_value, right_value, span, @@ -621,72 +641,72 @@ impl Lowering<'_> { /// checker already refused when outside. fn shift_count( &mut self, - count: Operand, - count_type: Integer, - shifted: Integer, + count: mir::Operand, + count_type: semantic_types::Integer, + shifted: semantic_types::Integer, constant: bool, span: Span, - ) -> Operand { - let count_class = Class::integer(count_type.bits); + ) -> mir::Operand { + let count_class = mir::Class::integer(count_type.bits); if !constant { // The bits a count needs to reach the width, besides a sign bit. let width_bits = u32::BITS - shifted.bits.leading_zeros(); let failed = if count_type.bits - u32::from(count_type.signed) >= width_bits { let width = self.integer_constant(count_type, u64::from(shifted.bits), span); - let failed = Comparison::UnsignedLessOrEqual; + let failed = mir::Comparison::UnsignedLessOrEqual; Some(self.compare(failed, count_class, width, count, span)) } else if count_type.signed { // No count of its type reaches the width: only a negative // one is outside. let zero = self.integer_constant(count_type, 0, span); - Some(self.compare(Comparison::SignedLess, count_class, count, zero, span)) + Some(self.compare(mir::Comparison::SignedLess, count_class, count, zero, span)) } else { None // an unsigned count too narrow to reach the width }; if let Some(failed) = failed { - self.emit_check(failed, &shift_count_message(shifted.bits), span); + self.emit_check(failed, &messages::shift_count_message(shifted.bits), span); } } - let shifted_class = Class::integer(shifted.bits); + let shifted_class = mir::Class::integer(shifted.bits); if count_class == shifted_class { return count; } // Inside the width, so it fits any class. - if let Operand::Constant { bits, .. } = count { + if let mir::Operand::Constant { bits, .. } = count { let count = Limbs::new(shifted.bits, &bits); return self.integer_operand(shifted, &count, span); } - let conversion = if count_class.bits() > shifted_class.bits() { - Conversion::Truncate + let cast = if count_class.bits() > shifted_class.bits() { + mir::Cast::Truncate } else { - Conversion::ZeroExtend + mir::Cast::ZeroExtend }; - self.convert(conversion, count_class, shifted_class, count, span) + self.convert(cast, count_class, shifted_class, count, span) } fn lower_unary( &mut self, - op: UnaryOp, + op: operators::UnaryOp, value: Id, - ty: TypeId, + ty: semantic_types::TypeId, span: Span, ) -> Option { let operand = self.lower_expr(value)?.register(); let result = match (op, &self.types[ty]) { - (UnaryOp::Negate, &Type::Integer(integer)) => { + (operators::UnaryOp::Negate, &semantic_types::Type::Integer(integer)) => { let zero = self.integer_constant(integer, 0, span); - self.arithmetic(IntegerOp::Subtract, integer, zero, operand, span) + self.arithmetic(mir::IntegerOp::Subtract, integer, zero, operand, span) } - (UnaryOp::Negate, &Type::Float(float)) => { + (operators::UnaryOp::Negate, &semantic_types::Type::Float(float)) => { let class = float.class(); // From -0.0, so that -(0.0) is -0.0 and -(-0.0) is 0.0. - let sign = if float == Float::F32 { + let sign = if float == semantic_types::Float::F32 { 1 << 31 } else { 1 << 63 }; - let zero = Operand::integer(class, sign); - let kind = InstructionKind::Float { + let zero = mir::Operand::integer(class, sign); + let kind = mir::InstructionKind::Float { operation: model::mir::FloatOp::Subtract, class, left: zero, @@ -696,16 +716,16 @@ impl Lowering<'_> { } // All ones of the type, extended as its values are, so the bits // above the width flip to what they should be. - (UnaryOp::BitNot, &Type::Integer(integer)) => { - let class = Class::integer(integer.bits); + (operators::UnaryOp::BitNot, &semantic_types::Type::Integer(integer)) => { + let class = mir::Class::integer(integer.bits); let ones = vec![u64::MAX; integer.bits.div_ceil(64) as usize]; let ones = Limbs::new(integer.bits, &ones); let ones = self.integer_operand(integer, &ones, span); - self.integer(IntegerOp::Xor, class, operand, ones, span) + self.integer(mir::IntegerOp::Xor, class, operand, ones, span) } - (UnaryOp::LogicalNot, Type::Bool) => { - let zero = Operand::integer(Class::I8, 0); - self.compare(Comparison::Equal, Class::I8, operand, zero, span) + (operators::UnaryOp::LogicalNot, semantic_types::Type::Bool) => { + let zero = mir::Operand::integer(mir::Class::I8, 0); + self.compare(mir::Comparison::Equal, mir::Class::I8, operand, zero, span) } _ => unreachable!("the checker allows no other unary operator"), }; @@ -713,24 +733,29 @@ impl Lowering<'_> { } /// The number, `bool` or raw pointer `value` converted to the type `to`. - fn lower_convert(&mut self, value: Id, to: TypeId, span: Span) -> Option { + fn lower_convert( + &mut self, + value: Id, + to: semantic_types::TypeId, + span: Span, + ) -> Option { let from = self.types.real(self.thir.exprs[value].ty); let operand = self.lower_expr(value)?.register(); let converted = match (&self.types[from], &self.types[to]) { - (&Type::Integer(from), &Type::Integer(to)) => { + (&semantic_types::Type::Integer(from), &semantic_types::Type::Integer(to)) => { self.convert_integer(operand, from, to, span) } - (Type::Bool, &Type::Integer(to)) => { - let bit = Integer { - signed: false, - bits: 1, - }; - self.convert_integer(operand, bit, to, span) + (semantic_types::Type::Bool, &semantic_types::Type::Integer(to)) => { + self.convert_integer(operand, semantic_types::Integer::BOOL, to, span) } - (from_type, to_type) => { - let conversion = cast_conversion(from_type, to_type); + _ => { + let (semantic_types::Conversion::Implicit(cast) + | semantic_types::Conversion::NeedsCast(cast)) = self.types.conversion(from, to) + else { + unreachable!("check converts only a pair that converts") + }; let class = |ty| self.class(ty).expect("a converted value is a register"); - self.convert(conversion, class(from), class(to), operand, span) + self.convert(cast, class(from), class(to), operand, span) } }; Some(Value::Register(converted)) @@ -738,14 +763,14 @@ impl Lowering<'_> { pub(super) fn convert( &mut self, - conversion: Conversion, - from: Class, - to: Class, - value: Operand, + cast: mir::Cast, + from: mir::Class, + to: mir::Class, + value: mir::Operand, span: Span, - ) -> Operand { - let kind = InstructionKind::Convert { - conversion, + ) -> mir::Operand { + let kind = mir::InstructionKind::Convert { + cast, from, to, value, @@ -758,21 +783,27 @@ impl Lowering<'_> { /// result, or a field of one of them. A literal, or a call giving its /// value in memory, is built right there, with no copy; an assignment's /// target may be read by its value, so it is not such a place. - pub(super) fn lower_into(&mut self, expression: Id, place: Place) -> Option<()> { + pub(super) fn lower_into( + &mut self, + expression: Id, + place: mir::Place, + ) -> Option<()> { // Literals nest as deep as the source. source::grow_stack(|| { let span = self.thir.exprs.span(expression); let thir::Expr { ty, kind } = &self.thir.exprs[expression]; let ty = self.types.real(*ty); match kind { - _ if ty == TypeId::INVALID => None, + _ if ty == semantic_types::TypeId::INVALID => None, thir::ExprKind::StructLiteral(fields) => { self.lower_struct_literal(*fields, ty, place) } // Its address and length. - thir::ExprKind::Constant(Constant::Bytes(bytes)) if ty == TypeId::STR => { - let address = self.global(Global::Bytes(bytes.clone())); - let length = Operand::integer(self.usize, bytes.len() as u64); + thir::ExprKind::Constant(constant::Value::Bytes(bytes)) + if ty == semantic_types::TypeId::STR => + { + let address = self.global(mir::Global::Bytes(bytes.clone())); + let length = mir::Operand::integer(self.usize, bytes.len() as u64); self.slice_words(address, length, place, span); Some(()) } @@ -796,7 +827,7 @@ impl Lowering<'_> { callee, signature, arguments, - } if matches!(self.result_passing(ty), Some(Passing::Memory { .. })) => { + } if matches!(self.result_passing(ty), Some(mir::Passing::Memory { .. })) => { let destination = Some(place); self.lower_call(*callee, *signature, *arguments, ty, destination, span)?; Some(()) @@ -818,28 +849,31 @@ impl Lowering<'_> { /// a new temporary. fn lower_call( &mut self, - callee: Callee, - signature: TypeId, + callee: model::Callee, + signature: semantic_types::TypeId, arguments: arena::List, - ty: TypeId, - destination: Option, + ty: semantic_types::TypeId, + destination: Option, span: Span, ) -> Option { - let Type::Function { origins, .. } = &self.types[self.types.real(signature)] else { + let semantic_types::Type::Function { origins, .. } = + &self.types[self.types.real(signature)] + else { unreachable!("a call's signature is a function type") }; let mut passed = Vec::with_capacity(arguments.len()); let mut parameters = Vec::with_capacity(arguments.len()); let c_symbol = match callee { - Callee::Function(function) => { + model::Callee::Function(function) => { model::program::c_symbol(self.modules, function.definition) } - Callee::Method(_) => None, + model::Callee::Method(_) => None, }; let result = self.result_passing(ty); let result_place = match result { - Some(Passing::Memory { size, .. }) => { - let place = destination.unwrap_or_else(|| Place::whole(self.temporary(ty, span))); + Some(mir::Passing::Memory { size, .. }) => { + let place = + destination.unwrap_or_else(|| mir::Place::whole(self.temporary(ty, span))); Some((place, size)) } _ => None, @@ -848,10 +882,10 @@ impl Lowering<'_> { // one runs: a value in memory is copied then. let mut pending = self.thir.children.lists.items(arguments); let callee = match callee { - Callee::Function(function) => MirCallee::Function(function), + model::Callee::Function(function) => mir::Callee::Function(function), // The receiver, the first argument, is an interface value: its // address is passed, and its table holds the method at `slot`. - Callee::Method(slot) => { + model::Callee::Method(slot) => { let receiver = pending.next().expect("a method call has its receiver"); let receiver_type = self.types.real(self.thir.exprs[receiver].ty); // An owned interface taken by value moves once its words @@ -860,41 +894,43 @@ impl Lowering<'_> { Value::Moving(place, read) => (place, Some(read)), value => (value.memory(), None), }; - let address = self.load(Class::Pointer, view.clone(), span); + let address = self.load(mir::Class::Pointer, view.clone(), span); let table_place = self.second_word(view.clone()); - let table = self.load(Class::Pointer, table_place, span); + let table = self.load(mir::Class::Pointer, table_place, span); if let Some(read) = moved_at { self.mark_moved(view, receiver_type, read); } - let method_place = Place { - root: Root::At(table), - steps: Box::new([Step::Offset(u64::from(slot) * self.target.pointer_bytes())]), + let method_place = mir::Place { + root: mir::Root::At(table), + steps: Box::new([mir::Step::Offset( + u64::from(slot) * self.target.pointer_bytes(), + )]), }; - let method = self.load(Class::Pointer, method_place, span); + let method = self.load(mir::Class::Pointer, method_place, span); passed.push(address); - parameters.push(Passing::Register { - class: Class::Pointer, + parameters.push(mir::Passing::Register { + class: mir::Class::Pointer, signed: false, }); - MirCallee::Pointer(method) + mir::Callee::Pointer(method) } }; for argument in pending { let argument_type = self.types.real(self.thir.exprs[argument].ty); // An argument to a parameter whose type has an error, reported // where it was written, which may be another module. - if argument_type == TypeId::INVALID { + if argument_type == semantic_types::TypeId::INVALID { return None; } let passing = self.passing(argument_type); parameters.push(passing); match passing { - Passing::Register { .. } => passed.push(self.lower_expr(argument)?.register()), - Passing::Memory { size, .. } => { + mir::Passing::Register { .. } => passed.push(self.lower_expr(argument)?.register()), + mir::Passing::Memory { size, .. } => { let copy = self.temporary(argument_type, span); - self.lower_into(argument, Place::whole(copy))?; - let kind = InstructionKind::Address { - place: Place::whole(copy), + self.lower_into(argument, mir::Place::whole(copy))?; + let kind = mir::InstructionKind::Address { + place: mir::Place::whole(copy), size, }; passed.push(self.emit(kind, span)); @@ -905,15 +941,15 @@ impl Lowering<'_> { let c = c_symbol.map(|symbol| { let argument_types = (self.thir.children.lists.items(arguments)) .map(|argument| self.types.real(self.thir.exprs[argument].ty)); - c_signature(self.types, self.target, symbol, ty, argument_types) + c_abi::c_signature(self.types, self.target, symbol, ty, argument_types) }); - self.mir.signatures.push(Signature { + self.mir.signatures.push(mir::Signature { parameters: parameters.into(), result, c, origins: origins.clone(), }); - let kind = InstructionKind::Call { + let kind = mir::InstructionKind::Call { callee, signature: (self.mir.signatures.len() - 1) as u32, arguments: passed.into(), @@ -921,12 +957,14 @@ impl Lowering<'_> { }; let mut called = self.emit(kind, span); // C leaves the bits of a register above a narrow integer unset. - if let (true, &Type::Integer(integer)) = (c_function, &self.types[self.types.real(ty)]) { + if let (true, &semantic_types::Type::Integer(integer)) = + (c_function, &self.types[self.types.real(ty)]) + { called = self.narrow(called, integer, span); } Some(match (result, result_place) { - (Some(Passing::Register { .. }), _) => Value::Register(called), - (Some(Passing::Memory { .. }), Some((place, _))) => Value::Memory(place), + (Some(mir::Passing::Register { .. }), _) => Value::Register(called), + (Some(mir::Passing::Memory { .. }), Some((place, _))) => Value::Memory(place), _ => Value::Nothing, }) } @@ -936,18 +974,18 @@ impl Lowering<'_> { /// `place`. fn lower_to_interface( &mut self, - reference: Operand, - implementation: ImplementationId, - ty: TypeId, - place: Place, + reference: mir::Operand, + implementation: semantic_types::ImplementationId, + ty: semantic_types::TypeId, + place: mir::Place, span: Span, ) { let methods = self.types.implementation(implementation); let interface = match self.types[ty] { - Type::InterfaceReference { interface, .. } => interface, + semantic_types::Type::InterfaceReference { interface, .. } => interface, _ => ty, // an owned interface }; - let Type::Interface { + let semantic_types::Type::Interface { methods: signatures, .. } = &self.types[interface] @@ -965,7 +1003,7 @@ impl Lowering<'_> { (copy, self.signature(signature)) }) .collect(); - let table = self.global(Global::Functions(table)); + let table = self.global(mir::Global::Functions(table)); self.interface_words(reference, table, place, span); } @@ -976,8 +1014,8 @@ impl Lowering<'_> { fn lower_borrow( &mut self, borrowed: Id, - ty: TypeId, - to: Place, + ty: semantic_types::TypeId, + to: mir::Place, span: Span, ) -> Option<()> { let Some(mutable) = self.types[ty].borrows() else { @@ -987,39 +1025,42 @@ impl Lowering<'_> { let borrowed_type = self.types.real(self.thir.exprs[borrowed].ty); match (&self.types[borrowed_type], &self.types[ty]) { // A slice of an array's elements, or a slice's elements lent again. - (_, Type::Slice { .. }) => { + (_, semantic_types::Type::Slice { .. }) => { let (elements, size, length) = - if let Type::Array { length, .. } = self.types[borrowed_type] { - let (size, _) = layout(self.types, borrowed_type, self.target); - let length = Operand::integer(self.usize, length); + if let semantic_types::Type::Array { length, .. } = self.types[borrowed_type] { + let (size, _) = layout::layout(self.types, borrowed_type, self.target); + let length = mir::Operand::integer(self.usize, length); (place, Some(size), length) } else { let length = self.second_word(place.clone()); let length = self.load(self.usize, length, span); - (place.then(Step::Through), None, length) + (place.then(mir::Step::Through), None, length) }; - let address = self.borrow(elements, size, mutable, &SLICE_WORDS, span); + let address = self.borrow(elements, size, mutable, &mir::SLICE_WORDS, span); self.slice_words(address, length, to, span); } // An interface's struct lent again as an interface reference, under a // new loan: what an interface reference views (the place ends by // going through it, so its two words are before that), or what an // owned interface took (behind its own two words). - (Type::Interface { .. }, Type::InterfaceReference { .. }) => { + ( + semantic_types::Type::Interface { .. }, + semantic_types::Type::InterfaceReference { .. }, + ) => { let (words, struct_place) = match place.steps.last() { - Some(Step::Through) => ( - Place { + Some(mir::Step::Through) => ( + mir::Place { root: place.root, steps: place.steps[..place.steps.len() - 1].into(), }, place, ), - _ => (place.clone(), place.then(Step::Through)), + _ => (place.clone(), place.then(mir::Step::Through)), }; // Only the program knows which struct it views. - let address = self.borrow(struct_place, None, mutable, &REFERENCE_WORDS, span); + let address = self.borrow(struct_place, None, mutable, &mir::REFERENCE_WORDS, span); let table_place = self.second_word(words); - let table = self.load(Class::Pointer, table_place, span); + let table = self.load(mir::Class::Pointer, table_place, span); self.interface_words(address, table, to, span); } _ => unreachable!("a reference is one register"), @@ -1031,13 +1072,13 @@ impl Lowering<'_> { /// named by `words` in messages: its address. pub(super) fn borrow( &mut self, - place: Place, + place: mir::Place, size: Option, mutable: bool, - words: &'static LoanWords, + words: &'static mir::LoanWords, span: Span, - ) -> Operand { - let kind = InstructionKind::Borrow { + ) -> mir::Operand { + let kind = mir::InstructionKind::Borrow { place, size, mutable, @@ -1048,21 +1089,27 @@ impl Lowering<'_> { /// An interface reference or owned interface at `place`: `address` and /// its methods' `table` as its two words. - fn interface_words(&mut self, address: Operand, table: Operand, place: Place, span: Span) { - self.store(Class::Pointer, place.clone(), address, span); + fn interface_words( + &mut self, + address: mir::Operand, + table: mir::Operand, + place: mir::Place, + span: Span, + ) { + self.store(mir::Class::Pointer, place.clone(), address, span); let table_place = self.second_word(place); - self.store(Class::Pointer, table_place, table, span); + self.store(mir::Class::Pointer, table_place, table, span); } /// A slice value at `place`: `address` and `length` as its two words. pub(super) fn slice_words( &mut self, - address: Operand, - length: Operand, - place: Place, + address: mir::Operand, + length: mir::Operand, + place: mir::Place, span: Span, ) { - self.store(Class::Pointer, place.clone(), address, span); + self.store(mir::Class::Pointer, place.clone(), address, span); let length_place = self.second_word(place); self.store(self.usize, length_place, length, span); } @@ -1072,25 +1119,28 @@ impl Lowering<'_> { /// both meet. fn lower_short_circuit( &mut self, - op: BinaryOp, + op: operators::BinaryOp, left: Id, right: Id, span: Span, ) -> Option { let (left_span, right_span) = (self.thir.exprs.span(left), self.thir.exprs.span(right)); - let result = self.register_slot(Class::I8, span); + let result = self.register_slot(mir::Class::I8, span); // Each side's temporaries end with it: a `bool` holds no reference, // and `right` may not run. let temporaries = self.declared.len(); let left = self.lower_expr(left)?.register(); self.close_scopes(temporaries, left_span); // When `left` decides, `&&` is false and `||` is true. - let decided = Operand::integer(Class::I8, u64::from(op == BinaryOp::LogicalOr)); - self.store(Class::I8, Place::whole(result), decided, span); + let decided = mir::Operand::integer( + mir::Class::I8, + u64::from(op == operators::BinaryOp::LogicalOr), + ); + self.store(mir::Class::I8, mir::Place::whole(result), decided, span); let right_block = self.new_block(right_span); let join = self.new_block(span); let (then, otherwise) = match op { - BinaryOp::LogicalAnd => (right_block, join), + operators::BinaryOp::LogicalAnd => (right_block, join), _ => (join, right_block), }; self.finish(model::mir::Terminator::Branch { @@ -1101,13 +1151,13 @@ impl Lowering<'_> { }); self.block = right_block; let right = self.lower_expr(right)?.register(); - self.store(Class::I8, Place::whole(result), right, span); + self.store(mir::Class::I8, mir::Place::whole(result), right, span); self.close_scopes(temporaries, right_span); self.finish(model::mir::Terminator::Jump(join)); self.block = join; Some(Value::Register(self.load( - Class::I8, - Place::whole(result), + mir::Class::I8, + mir::Place::whole(result), span, ))) } diff --git a/crates/kernel/lower/src/lib.rs b/crates/lower/src/lib.rs similarity index 66% rename from crates/kernel/lower/src/lib.rs rename to crates/lower/src/lib.rs index 0d65d282..6b5c07f0 100644 --- a/crates/kernel/lower/src/lib.rs +++ b/crates/lower/src/lib.rs @@ -17,39 +17,11 @@ use std::num::NonZeroU32; use arena::Arena; use arena::Id; use arena::Lists; -use model::layout::field_placed; -use model::layout::layout; -use model::machine::Machine; -use model::mir::Block; -use model::mir::Body; -use model::mir::Class; -use model::mir::Comparison; -use model::mir::DebugMember; -use model::mir::DebugScope; -use model::mir::DebugType; -use model::mir::DebugTypeId; -use model::mir::DebugTypes; -use model::mir::Global; -use model::mir::Holder; -use model::mir::InstructionKind; -use model::mir::IntegerOp; -use model::mir::Operand; -use model::mir::Passing; -use model::mir::Place; -use model::mir::REFERENCE_WORDS; -use model::mir::Root; -use model::mir::SLICE_WORDS; -use model::mir::Signature; -use model::mir::Slot; -use model::mir::Step; -use model::mir::Terminator; -use model::program::Module; -use model::semantic_types::Float; -use model::semantic_types::Integer; -use model::semantic_types::Type; -use model::semantic_types::TypeId; -use model::semantic_types::Types; -use model::semantic_types::range_fields; +use model::layout; +use model::machine; +use model::mir; +use model::program; +use model::semantic_types; use model::thir; use rustc_hash::FxHashMap; use source::Span; @@ -58,8 +30,8 @@ use source::Span; /// type each was made for, so each is made once. #[derive(Default)] pub struct ProgramDebugTypes { - pub table: DebugTypes, - of_type: FxHashMap, + pub table: mir::DebugTypes, + of_type: FxHashMap, } /// The MIR of the checked body `body` of a function of the type @@ -68,16 +40,16 @@ pub struct ProgramDebugTypes { /// debugger (`debug_types`, shared by the program's bodies). pub fn lower( body: &thir::Body, - function: TypeId, - types: &Types, - target: &'static Machine, - modules: &[Module], + function: semantic_types::TypeId, + types: &semantic_types::Types, + target: &'static machine::Machine, + modules: &[program::Module], debug_types: &mut ProgramDebugTypes, -) -> Option { +) -> Option { if body.has_errors { return None; } - let Type::Function { + let semantic_types::Type::Function { parameters, result, .. } = &types[function] else { @@ -89,19 +61,19 @@ pub fn lower( target, modules, debug_types, - mir: Body { + mir: mir::Body { blocks: Arena::default(), instructions: Arena::default(), slots: Arena::default(), - signature: Signature { + signature: mir::Signature { parameters: Box::default(), // below, once passing can be asked result: None, c: None, origins: Box::default(), }, returned: match &types[*result] { - Type::Interface { .. } => Some("an interface holding"), - Type::Slice { .. } => Some("a slice of"), + semantic_types::Type::Interface { .. } => Some("an interface holding"), + semantic_types::Type::Slice { .. } => Some("a slice of"), _ if types.holds_loans(*result).is_some() => Some("a reference into"), _ => None, }, @@ -117,11 +89,11 @@ pub fn lower( loops: Vec::new(), declared: Vec::new(), kept: vec![Vec::new(); body.variables.len()], - usize: Class::integer(target.pointer_bits), + usize: mir::Class::integer(target.pointer_bits), }; lowering.mir.signature = lowering.signature(function); - lowering.mir.result_debug_type = - (types.real(*result) != TypeId::VOID).then(|| lowering.debug_type(*result, 0)); + lowering.mir.result_debug_type = (types.real(*result) != semantic_types::TypeId::VOID) + .then(|| lowering.debug_type(*result, 0)); // One debug scope per block and one slot per THIR variable, in order: // block `i` is debug scope `i`, and the ids of variables match. for block in body.blocks.ids() { @@ -129,18 +101,21 @@ pub fn lower( .parent .map(|parent| Id::from_index(parent.index())); let span = body.blocks.span(block); - lowering.mir.debug_scopes.push(DebugScope { parent }, span); + lowering + .mir + .debug_scopes + .push(mir::DebugScope { parent }, span); } for id in body.variables.ids() { let variable = body.variables[id]; - if variable.ty == TypeId::INVALID { + if variable.ty == semantic_types::TypeId::INVALID { return None; } let ty = types.real(variable.ty); - let (size, align) = layout(types, ty, target); + let (size, align) = layout::layout(types, ty, target); let debug_type = (!variable.hidden).then(|| lowering.debug_type(ty, 0)); lowering.mir.slots.push( - Slot { + mir::Slot { size, align, holders: lowering.holders(ty).into(), @@ -169,11 +144,11 @@ pub fn lower( // (`Body::parameter_in_memory`). for index in 0..parameters.len() { let slot = Id::from_index(index); - if let Passing::Register { class, .. } = lowering.mir.signature.parameters[index] { - let kind = InstructionKind::Store { + if let mir::Passing::Register { class, .. } = lowering.mir.signature.parameters[index] { + let kind = mir::InstructionKind::Store { class, - place: Place::whole(slot), - value: Operand::Parameter(index as u32), + place: mir::Place::whole(slot), + value: mir::Operand::Parameter(index as u32), }; lowering.emit(kind, lowering.mir.slots.span(slot)); } @@ -181,41 +156,41 @@ pub fn lower( } lowering.lower_block(function_block, 0)?; // the parameters are its variables too let end = Span::new(span.end as usize - 1, span.end as usize); // the `}` - lowering.finish(Terminator::FallOff(end)); + lowering.finish(mir::Terminator::FallOff(end)); Some(lowering.mir) } /// The slot of the THIR variable `variable`: their ids match (`lower`). -fn slot_of(variable: Id) -> Id { +fn slot_of(variable: Id) -> Id { Id::from_index(variable.index()) } struct Lowering<'t> { thir: &'t thir::Body, - types: &'t Types, - target: &'static Machine, - modules: &'t [Module], + types: &'t semantic_types::Types, + target: &'static machine::Machine, + modules: &'t [program::Module], debug_types: &'t mut ProgramDebugTypes, - mir: Body, - block: Id, // the block being filled - instructions: Vec, // that block's instructions so far - debug_scope: Id, // the one new instructions are written in - loops: Vec, // the loops being lowered, innermost last + mir: mir::Body, + block: Id, // the block being filled + instructions: Vec, // that block's instructions so far + debug_scope: Id, // the one new instructions are written in + loops: Vec, // the loops being lowered, innermost last /// The slots in scope, in the order declared: those of a block, from /// where it starts (`lower_block`), are the last. - declared: Vec>, + declared: Vec>, /// The temporaries each variable keeps (THIR's `kept_by`), found before /// any code: each joins `declared` just before its variable (`declare`), /// so it ends with it on every path. - kept: Vec>>, - usize: Class, // the class of a pointer-wide integer + kept: Vec>>, + usize: mir::Class, // the class of a pointer-wide integer } /// Where a loop's `continue` and `break` go, and where the slots they /// leave start in `declared`. struct Loop { - next: Id, // the start of the next pass - exit: Id, + next: Id, // the start of the next pass + exit: Id, declared: usize, } @@ -223,17 +198,17 @@ struct Loop { /// is in, or nothing. #[derive(Clone, Debug)] enum Value { - Register(Operand), - Memory(Place), + Register(mir::Operand), + Memory(mir::Place), /// Kept in memory at the place, read at the span out of a variable /// whose type moves: whoever takes the value marks it moved once its /// bytes are read (`put`, a method's receiver, an expression statement). - Moving(Place, Span), + Moving(mir::Place, Span), Nothing, } impl Value { - fn register(&self) -> Operand { + fn register(&self) -> mir::Operand { match self { Value::Register(operand) => *operand, Value::Memory(_) | Value::Moving(..) | Value::Nothing => { @@ -242,7 +217,7 @@ impl Value { } } - fn memory(self) -> Place { + fn memory(self) -> mir::Place { match self { Value::Memory(place) => place, Value::Moving(..) => unreachable!("a value that moves is taken where it moves"), @@ -259,10 +234,10 @@ const DEEPEST_DEBUG_TYPE: u32 = 5_000; impl Lowering<'_> { /// A new block starting at `span`; `finish` gives it its instructions and /// terminator. - fn new_block(&mut self, span: Span) -> Id { - let block = Block { + fn new_block(&mut self, span: Span) -> Id { + let block = mir::Block { instructions: arena::List::EMPTY, - terminator: Terminator::FallOff(span), // replaced by `finish` + terminator: mir::Terminator::FallOff(span), // replaced by `finish` debug_scope: self.debug_scope, }; self.mir.blocks.push(block, span) @@ -271,16 +246,16 @@ impl Lowering<'_> { /// Ends the block being filled with `terminator`, which leaves it for /// good (a `return`, a jump out, a panic): what follows, which nothing /// reaches, still gets a block. - fn finish_and_leave(&mut self, terminator: Terminator, span: Span) { + fn finish_and_leave(&mut self, terminator: mir::Terminator, span: Span) { self.finish(terminator); self.block = self.new_block(span); } /// Ends the block being filled with `terminator`. - fn finish(&mut self, terminator: Terminator) { + fn finish(&mut self, terminator: mir::Terminator) { let instructions = self.mir.lists.add(&self.instructions); self.instructions.clear(); - self.mir.blocks[self.block] = Block { + self.mir.blocks[self.block] = mir::Block { instructions, terminator, debug_scope: self.debug_scope, @@ -289,7 +264,7 @@ impl Lowering<'_> { /// Adds an instruction to the block being filled and gives its value. #[inline(always)] - fn emit(&mut self, kind: InstructionKind, span: Span) -> Operand { + fn emit(&mut self, kind: mir::InstructionKind, span: Span) -> mir::Operand { let instruction = self.mir.instructions.push( model::mir::Instruction { kind, @@ -298,29 +273,29 @@ impl Lowering<'_> { span, ); self.instructions.push(instruction.into()); - Operand::Value(instruction) + mir::Operand::Value(instruction) } /// Adds `left operation right` on values of the type `integer`, cut /// back to its width when the operation may carry past it (`narrow`). fn arithmetic( &mut self, - operation: IntegerOp, - integer: Integer, - left: Operand, - right: Operand, + operation: mir::IntegerOp, + integer: semantic_types::Integer, + left: mir::Operand, + right: mir::Operand, span: Span, - ) -> Operand { - let class = Class::integer(integer.bits); + ) -> mir::Operand { + let class = mir::Class::integer(integer.bits); let result = self.integer(operation, class, left, right, span); match operation { // A narrow type's lowest value over -1 is its highest plus one: // it fits the class, not the type. - IntegerOp::Add - | IntegerOp::Subtract - | IntegerOp::Multiply - | IntegerOp::ShiftLeft - | IntegerOp::SignedDivide => self.narrow(result, integer, span), + mir::IntegerOp::Add + | mir::IntegerOp::Subtract + | mir::IntegerOp::Multiply + | mir::IntegerOp::ShiftLeft + | mir::IntegerOp::SignedDivide => self.narrow(result, integer, span), _ => result, } } @@ -329,13 +304,13 @@ impl Lowering<'_> { /// (a counter's, or an operation that cannot carry past the width). fn integer( &mut self, - operation: IntegerOp, - class: Class, - left: Operand, - right: Operand, + operation: mir::IntegerOp, + class: mir::Class, + left: mir::Operand, + right: mir::Operand, span: Span, - ) -> Operand { - let kind = InstructionKind::Integer { + ) -> mir::Operand { + let kind = mir::InstructionKind::Integer { operation, class, left, @@ -347,13 +322,13 @@ impl Lowering<'_> { /// Adds `left comparison right` on operands of `class`; gives an `I8`. fn compare( &mut self, - comparison: Comparison, - class: Class, - left: Operand, - right: Operand, + comparison: mir::Comparison, + class: mir::Class, + left: mir::Operand, + right: mir::Operand, span: Span, - ) -> Operand { - let kind = InstructionKind::Compare { + ) -> mir::Operand { + let kind = mir::InstructionKind::Compare { comparison, class, left, @@ -364,20 +339,20 @@ impl Lowering<'_> { /// Stops the program with "panic: `message`" when `failed`, an `I8` /// written at `span`, is not 0. - fn emit_check(&mut self, failed: Operand, message: &str, span: Span) { - let kind = InstructionKind::Check { + fn emit_check(&mut self, failed: mir::Operand, message: &str, span: Span) { + let kind = mir::InstructionKind::Check { failed, message: message.into(), }; self.emit(kind, span); } - fn load(&mut self, class: Class, place: Place, span: Span) -> Operand { - self.emit(InstructionKind::Load { class, place }, span) + fn load(&mut self, class: mir::Class, place: mir::Place, span: Span) -> mir::Operand { + self.emit(mir::InstructionKind::Load { class, place }, span) } - fn store(&mut self, class: Class, place: Place, value: Operand, span: Span) { - let kind = InstructionKind::Store { + fn store(&mut self, class: mir::Class, place: mir::Place, value: mir::Operand, span: Span) { + let kind = mir::InstructionKind::Store { class, place, value, @@ -388,7 +363,7 @@ impl Lowering<'_> { /// Puts `value`, of the type `ty`, at `place`: a store, or a copy of /// the bytes of a value kept in memory. Nothing when the value is /// already there. - fn put(&mut self, place: Place, value: Value, ty: TypeId, span: Span) { + fn put(&mut self, place: mir::Place, value: Value, ty: semantic_types::TypeId, span: Span) { let (from, moved_at) = match value { Value::Register(value) => { let class = self.class(ty).expect("a register has a class"); @@ -402,8 +377,8 @@ impl Lowering<'_> { if from == place { return; // `a = a`: the bytes are already there } - let (size, _) = layout(self.types, ty, self.target); - let kind = InstructionKind::Copy { + let (size, _) = layout::layout(self.types, ty, self.target); + let kind = mir::InstructionKind::Copy { to: place, from: from.clone(), size, @@ -417,10 +392,16 @@ impl Lowering<'_> { /// `value`, of the type `ty`, as it is now: one in memory, or moving out /// of a variable, is copied into a temporary when `called_later`, as a /// call that runs before it is read could change it. - fn settled(&mut self, value: Value, ty: TypeId, called_later: bool, span: Span) -> Value { + fn settled( + &mut self, + value: Value, + ty: semantic_types::TypeId, + called_later: bool, + span: Span, + ) -> Value { match value { Value::Memory(_) | Value::Moving(..) if called_later => { - let copy = Place::whole(self.temporary(ty, span)); + let copy = mir::Place::whole(self.temporary(ty, span)); self.put(copy.clone(), value, ty, span); Value::Memory(copy) } @@ -433,10 +414,10 @@ impl Lowering<'_> { /// in memory, `Moving` when it moves out. A value read out of one of /// lowering's temporaries moves nothing: nothing reads the temporary /// again. - fn read(&mut self, place: Place, ty: TypeId, span: Span) -> Value { + fn read(&mut self, place: mir::Place, ty: semantic_types::TypeId, span: Span) -> Value { let temporary = matches!( place.root, - Root::Slot(slot) if slot.index() >= self.thir.variables.len() + mir::Root::Slot(slot) if slot.index() >= self.thir.variables.len() ); let moves = !self.types.is_copy(ty) && !temporary; let Some(class) = self.class(ty) else { @@ -455,16 +436,17 @@ impl Lowering<'_> { /// `Moved` for the value of the type `ty`, which moves, just read at /// `place` at `span`. - fn mark_moved(&mut self, place: Place, ty: TypeId, span: Span) { + fn mark_moved(&mut self, place: mir::Place, ty: semantic_types::TypeId, span: Span) { // As the checker lends one again (`ThirBuilder::reborrow`). - let lent_again = match self.types[ty] { - Type::Reference { mutable: true, .. } - | Type::InterfaceReference { mutable: true, .. } => Some(".*"), - Type::Slice { mutable: true, .. } => Some("[..]"), - _ => None, - }; - let (size, _) = layout(self.types, ty, self.target); - let kind = InstructionKind::Moved { + let lent_again = (self.types[ty].borrows() == Some(true)).then(|| { + if self.types[ty].is_slice_shaped() { + "[..]" + } else { + ".*" + } + }); + let (size, _) = layout::layout(self.types, ty, self.target); + let kind = mir::InstructionKind::Moved { place, size, lent_again, @@ -474,8 +456,8 @@ impl Lowering<'_> { /// A new slot for a value of the type `ty` made at `span`, in scope /// until the statement ends (`declared`). - fn temporary(&mut self, ty: TypeId, span: Span) -> Id { - let (size, align) = layout(self.types, ty, self.target); + fn temporary(&mut self, ty: semantic_types::TypeId, span: Span) -> Id { + let (size, align) = layout::layout(self.types, ty, self.target); let holders = self.holders(ty).into(); let slot = self.hidden_slot(size, align, holders, span); self.declared.push(slot); @@ -484,7 +466,7 @@ impl Lowering<'_> { /// A new slot holding one register of `class`, in scope until the /// statement ends. - fn register_slot(&mut self, class: Class, span: Span) -> Id { + fn register_slot(&mut self, class: mir::Class, span: Span) -> Id { let size = class.bytes(self.target.pointer_bytes()); let slot = self.hidden_slot(size, size.min(16), Box::default(), span); self.declared.push(slot); @@ -496,11 +478,11 @@ impl Lowering<'_> { &mut self, size: u64, align: u64, - holders: Box<[Holder]>, + holders: Box<[mir::Holder]>, span: Span, - ) -> Id { + ) -> Id { self.mir.slots.push( - Slot { + mir::Slot { size, align, holders, @@ -514,58 +496,47 @@ impl Lowering<'_> { } /// Adds read-only data and gives its operand. - fn global(&mut self, global: Global) -> Operand { + fn global(&mut self, global: mir::Global) -> mir::Operand { self.mir.globals.push(global); - Operand::Global((self.mir.globals.len() - 1) as u32) + mir::Operand::Global((self.mir.globals.len() - 1) as u32) } /// The class of a value of the type `ty`, or `None` for a value kept /// in memory. - fn class(&self, ty: TypeId) -> Option { - match self.types[ty] { - Type::Bool => Some(Class::I8), - Type::Integer(integer) => Some(Class::integer(integer.bits)), - Type::Float(float) => Some(float.class()), - Type::CString | Type::Reference { .. } | Type::RawPointer { .. } => { - Some(Class::Pointer) - } - Type::Slice { .. } - | Type::Str - | Type::InterfaceReference { .. } - | Type::Interface { .. } - | Type::Struct { .. } - | Type::Array { .. } - | Type::Range { .. } => None, - Type::Invalid | Type::Void | Type::Function { .. } | Type::Named { .. } => { - unreachable!("no value has this type") - } - Type::Alias { .. } => unreachable!("indexing looks through aliases"), + fn class(&self, ty: semantic_types::TypeId) -> Option { + match layout::held(self.types, ty) { + layout::Held::Register(class) => Some(class), + layout::Held::TwoWords | layout::Held::Memory => None, + layout::Held::Nothing => unreachable!("no value has this type"), } } /// How a value of the type `ty` is passed to or from a function. - fn passing(&self, ty: TypeId) -> Passing { + fn passing(&self, ty: semantic_types::TypeId) -> mir::Passing { let ty = self.types.real(ty); if let Some(class) = self.class(ty) { - return Passing::Register { + return mir::Passing::Register { class, - signed: matches!(self.types[ty], Type::Integer(Integer { signed: true, .. })), + signed: matches!( + self.types[ty], + semantic_types::Type::Integer(semantic_types::Integer { signed: true, .. }) + ), }; } - let (size, align) = layout(self.types, ty, self.target); - Passing::Memory { size, align } + let (size, align) = layout::layout(self.types, ty, self.target); + mir::Passing::Memory { size, align } } /// How a function's result of the type `result` is given; `None` for /// none. - fn result_passing(&self, result: TypeId) -> Option { - (self.types.real(result) != TypeId::VOID).then(|| self.passing(result)) + fn result_passing(&self, result: semantic_types::TypeId) -> Option { + (self.types.real(result) != semantic_types::TypeId::VOID).then(|| self.passing(result)) } /// How a Peeper function of the type `function` is passed its /// parameters and gives its result. - fn signature(&self, function: TypeId) -> Signature { - let Type::Function { + fn signature(&self, function: semantic_types::TypeId) -> mir::Signature { + let semantic_types::Type::Function { parameters, result, origins, @@ -574,7 +545,7 @@ impl Lowering<'_> { else { unreachable!("a signature is a function type's") }; - Signature { + mir::Signature { parameters: parameters.iter().map(|&ty| self.passing(ty)).collect(), result: self.result_passing(*result), c: None, @@ -587,13 +558,13 @@ impl Lowering<'_> { /// interface reference or an owned interface (on the struct it took) is /// one, at its start; a struct's fields' and an array's elements' are /// each at theirs. - fn holders(&self, ty: TypeId) -> Vec { + fn holders(&self, ty: semantic_types::TypeId) -> Vec { let mut holders = Vec::new(); self.add_holders(ty, 0, &mut holders); holders } - fn add_holders(&self, ty: TypeId, at: u64, holders: &mut Vec) { + fn add_holders(&self, ty: semantic_types::TypeId, at: u64, holders: &mut Vec) { let ty = self.types.real(ty); // A struct holding another twice has 2^depth fields, so a type with // no holders is not walked. @@ -601,14 +572,16 @@ impl Lowering<'_> { return; } match &self.types[ty] { - Type::Slice { .. } => holders.push(Holder { + semantic_types::Type::Slice { .. } => holders.push(mir::Holder { offset: at, - words: &SLICE_WORDS, + words: &mir::SLICE_WORDS, }), - Type::Reference { .. } | Type::InterfaceReference { .. } | Type::Interface { .. } => { - holders.push(Holder { + semantic_types::Type::Reference { .. } + | semantic_types::Type::InterfaceReference { .. } + | semantic_types::Type::Interface { .. } => { + holders.push(mir::Holder { offset: at, - words: &REFERENCE_WORDS, + words: &mir::REFERENCE_WORDS, }); } ty if let Some(members) = ty.members() => { @@ -616,9 +589,9 @@ impl Lowering<'_> { self.add_holders(field, at + offset, holders); } } - Type::Array { internals, .. } => { + semantic_types::Type::Array { internals, .. } => { let base = self.types.real(internals.base); - let (size, _) = layout(self.types, base, self.target); + let (size, _) = layout::layout(self.types, base, self.target); for index in 0..internals.count { self.add_holders(base, at + index * size, holders); } @@ -630,20 +603,20 @@ impl Lowering<'_> { /// The debug type of the language type `ty`, made once per program; /// `depth` pointers, slices and structs in from the type a variable or /// result has. - fn debug_type(&mut self, ty: TypeId, depth: u32) -> DebugTypeId { + fn debug_type(&mut self, ty: semantic_types::TypeId, depth: u32) -> mir::DebugTypeId { let ty = self.types.real(ty); if let Some(&id) = self.debug_types.of_type.get(&ty) { return id; } let pointer_bits = self.target.pointer_bits; - let basic = |name: &str, bits: u32, encoding: &'static str| DebugType::Basic { + let basic = |name: &str, bits: u32, encoding: &'static str| mir::DebugType::Basic { name: name.into(), bits, encoding, }; let debug_type = match &self.types[ty] { - Type::Bool => basic("bool", 8, "DW_ATE_boolean"), - Type::Integer(integer) => { + semantic_types::Type::Bool => basic("bool", 8, "DW_ATE_boolean"), + semantic_types::Type::Integer(integer) => { let encoding = if integer.signed { "DW_ATE_signed" } else { @@ -651,22 +624,30 @@ impl Lowering<'_> { }; basic(&integer.to_string(), integer.bits, encoding) } - Type::Float(Float::F32) => basic("f32", 32, "DW_ATE_float"), - Type::Float(Float::F64) => basic("f64", 64, "DW_ATE_float"), - Type::CString => { + semantic_types::Type::Float(semantic_types::Float::F32) => { + basic("f32", 32, "DW_ATE_float") + } + semantic_types::Type::Float(semantic_types::Float::F64) => { + basic("f64", 64, "DW_ATE_float") + } + semantic_types::Type::CString => { let char = self .debug_types .table .push(basic("char", 8, "DW_ATE_signed_char")); - DebugType::Pointer { + mir::DebugType::Pointer { name: "cstr".into(), to: Some(char), } } - Type::Reference { .. } | Type::RawPointer { .. } => { + semantic_types::Type::Reference { .. } | semantic_types::Type::RawPointer { .. } => { let to = match self.types[ty].pointee() { // A struct with an error: this output is never linked. - Some(pointee) if matches!(self.types[pointee], Type::Named { .. }) => None, + Some(pointee) + if matches!(self.types[pointee], semantic_types::Type::Named { .. }) => + { + None + } // shortcut: past `DEEPEST_DEBUG_TYPE` a debugger sees an // untyped pointer, or a struct with no fields. Some(_) if depth == DEEPEST_DEBUG_TYPE => None, @@ -677,22 +658,22 @@ impl Lowering<'_> { } None => None, // `rawptr` }; - DebugType::Pointer { + mir::DebugType::Pointer { name: "".into(), to, } } - Type::Slice { .. } | Type::Str => { + semantic_types::Type::Slice { .. } | semantic_types::Type::Str => { // A `&str` views bytes. let element = self.types[ty] .elements() - .map_or(TypeId::U8, |(element, _)| element); + .map_or(semantic_types::TypeId::U8, |(element, _)| element); // As a pointer's: a slice of slices nests as deep as the // source does. let base = (depth < DEEPEST_DEBUG_TYPE) .then(|| source::grow_stack(|| self.debug_type(element, depth + 1))); let name = model::program::type_text(self.modules, self.types, ty); - let pointer = DebugType::Pointer { + let pointer = mir::DebugType::Pointer { name: "".into(), to: base, }; @@ -701,87 +682,92 @@ impl Lowering<'_> { let usize = self.debug_types.table.push(usize); let pointer_bytes = self.target.pointer_bytes(); let members = [ - DebugMember { + mir::DebugMember { name: "ptr".into(), offset: 0, ty: pointer, }, - DebugMember { + mir::DebugMember { name: "len".into(), offset: pointer_bytes, ty: usize, }, ]; - DebugType::Composite { + mir::DebugType::Composite { name: name.into(), size: 2 * pointer_bytes, members: members.into(), } } // Its address and its methods' table, neither of a known type. - Type::InterfaceReference { .. } | Type::Interface { .. } => { + semantic_types::Type::InterfaceReference { .. } + | semantic_types::Type::Interface { .. } => { let name = model::program::type_text(self.modules, self.types, ty); - let pointer = DebugType::Pointer { + let pointer = mir::DebugType::Pointer { name: "".into(), to: None, }; let pointer = self.debug_types.table.push(pointer); let pointer_bytes = self.target.pointer_bytes(); let members = [ - DebugMember { + mir::DebugMember { name: "ptr".into(), offset: 0, ty: pointer, }, - DebugMember { + mir::DebugMember { name: "table".into(), offset: pointer_bytes, ty: pointer, }, ]; - DebugType::Composite { + mir::DebugType::Composite { name: name.into(), size: 2 * pointer_bytes, members: members.into(), } } // One node with a range per level, as C's debug info has. - Type::Array { internals, .. } => { + semantic_types::Type::Array { internals, .. } => { // Its base is no array: a pointer, slice or struct in it // counts the depth. let element = self.debug_type(internals.base, depth); let lengths = self.types.array_lengths(ty).collect(); - let (size, _) = layout(self.types, ty, self.target); - DebugType::Array { + let (size, _) = layout::layout(self.types, ty, self.target); + mir::DebugType::Array { element, size, lengths, } } - Type::Struct { + semantic_types::Type::Struct { definition, fields, .. } => { // A generic struct's copy as written: `Box`. let name = model::program::type_text(self.modules, self.types, ty); let names = model::program::field_names(self.modules, *definition); - let fields: Vec<(String, TypeId)> = + let fields: Vec<(String, semantic_types::TypeId)> = (names.map(str::to_string).zip(fields.iter().copied())).collect(); return self.debug_struct(ty, &name, &fields, depth); } - Type::Range { element, step } => { - let Type::Integer(integer) = self.types[*element] else { + semantic_types::Type::Range { element, step } => { + let semantic_types::Type::Integer(integer) = self.types[*element] else { unreachable!("a range is of integers") }; - let name = format!("{}[{integer}]", model::semantic_types::RANGE); - let fields: Vec<(String, TypeId)> = range_fields(*element, *step) - .map(|(field, ty)| (field.to_string(), ty)) - .into(); + let name = format!("{}[{integer}]", semantic_types::builtin::RANGE); + let fields: Vec<(String, semantic_types::TypeId)> = + semantic_types::ranges::range_fields(*element, *step) + .map(|(field, ty)| (field.to_string(), ty)) + .into(); return self.debug_struct(ty, &name, &fields, depth); } - Type::Invalid | Type::Void | Type::Function { .. } | Type::Named { .. } => { + semantic_types::Type::Invalid + | semantic_types::Type::Void + | semantic_types::Type::Function { .. } + | semantic_types::Type::Named { .. } => { unreachable!("no value has this type") } - Type::Alias { .. } => unreachable!("indexing looks through aliases"), + semantic_types::Type::Alias { .. } => unreachable!("indexing looks through aliases"), }; let id = self.debug_types.table.push(debug_type); self.debug_types.of_type.insert(ty, id); @@ -793,28 +779,28 @@ impl Lowering<'_> { /// again. fn debug_struct( &mut self, - ty: TypeId, + ty: semantic_types::TypeId, name: &str, - fields: &[(String, TypeId)], + fields: &[(String, semantic_types::TypeId)], depth: u32, - ) -> DebugTypeId { + ) -> mir::DebugTypeId { let composite = self.debug_types.table.reserve(); self.debug_types.of_type.insert(ty, composite); - let (size, _) = layout(self.types, ty, self.target); + let (size, _) = layout::layout(self.types, ty, self.target); let mut members = Vec::with_capacity(fields.len()); if depth < DEEPEST_DEBUG_TYPE { for (index, (field_name, field)) in fields.iter().enumerate() { - let (offset, _) = field_placed(self.types, ty, index, self.target); + let (offset, _) = layout::field_placed(self.types, ty, index, self.target); // Structs hold structs as deep as the declarations nest. let base = source::grow_stack(|| self.debug_type(*field, depth + 1)); - members.push(DebugMember { + members.push(mir::DebugMember { name: field_name.as_str().into(), offset, ty: base, }); } } - let debug_type = DebugType::Composite { + let debug_type = mir::DebugType::Composite { name: name.into(), size, members: members.into(), @@ -825,14 +811,22 @@ impl Lowering<'_> { /// Field `index` of the struct or range value of type `ty` at `place`: /// where it is, and its type. - fn field(&self, place: Place, ty: TypeId, index: usize) -> (Place, TypeId) { - let (offset, field) = field_placed(self.types, ty, index, self.target); - (place.then(Step::Offset(offset)), self.types.real(field)) + fn field( + &self, + place: mir::Place, + ty: semantic_types::TypeId, + index: usize, + ) -> (mir::Place, semantic_types::TypeId) { + let (offset, field) = layout::field_placed(self.types, ty, index, self.target); + ( + place.then(mir::Step::Offset(offset)), + self.types.real(field), + ) } /// The second word of a two-word value at `place`: a slice's length, /// an interface value's table (the first word is the address). - fn second_word(&self, place: Place) -> Place { - place.then(Step::Offset(self.target.pointer_bytes())) + fn second_word(&self, place: mir::Place) -> mir::Place { + place.then(mir::Step::Offset(self.target.pointer_bytes())) } } diff --git a/crates/kernel/lower/src/statement.rs b/crates/lower/src/statement.rs similarity index 97% rename from crates/kernel/lower/src/statement.rs rename to crates/lower/src/statement.rs index 88c9bf47..d9effb0c 100644 --- a/crates/kernel/lower/src/statement.rs +++ b/crates/lower/src/statement.rs @@ -74,6 +74,10 @@ impl Lowering<'_> { Some(()) } + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] fn lower_statement(&mut self, statement: Id) -> Option<()> { // Blocks in blocks and long `else if` chains are a deep recursion. source::grow_stack(|| { @@ -226,9 +230,10 @@ impl Lowering<'_> { else { unreachable!("the checker allows a jump only in a loop") }; - let target = match self.thir.stmts[statement] { - thir::Stmt::Break => exit, - _ => next, + let target = if let thir::Stmt::Break = self.thir.stmts[statement] { + exit + } else { + next }; self.emit_scope_ends(declared, span); self.finish_and_leave(Terminator::Jump(target), span); diff --git a/crates/kernel/lower/src/tests.rs b/crates/lower/src/tests.rs similarity index 99% rename from crates/kernel/lower/src/tests.rs rename to crates/lower/src/tests.rs index 5e65f981..a7392a90 100644 --- a/crates/kernel/lower/src/tests.rs +++ b/crates/lower/src/tests.rs @@ -14,7 +14,7 @@ use model::mir::DebugType; use model::mir::DebugTypes; use model::thir; use source::SourceFile; -use syntax::ast; +use tree::ast; /// The MIR text of the function `main` of the one-module program `text`, /// which must check without errors, for a 64-bit target. @@ -26,7 +26,7 @@ fn lowered(text: &str) -> String { /// MIR and the debug types lowering made. fn lower_main(text: &str, target: &str) -> (String, mir::Body, DebugTypes) { let file = Arc::new(SourceFile::new("main.peep", text)); - let (ast, parse) = parser::parse(&file, &features::RULES); + let (ast, parse) = parser::parse(&file); assert!(parse.is_empty(), "{parse:?}"); let modules = [model::program::Module { path: "app:main".to_string(), @@ -34,7 +34,7 @@ fn lower_main(text: &str, target: &str) -> (String, mir::Body, DebugTypes) { imports: Vec::new(), }]; let target = Machine::named(target).unwrap(); - let mut checker = Checker::new(&modules, target, false, &features::CHECK_HOOKS); + let mut checker = Checker::new(&modules, target, false); let tree = &modules[0].ast; let (index, name) = tree .declarations() diff --git a/crates/kernel/model/Cargo.toml b/crates/model/Cargo.toml similarity index 95% rename from crates/kernel/model/Cargo.toml rename to crates/model/Cargo.toml index e85af06e..ea81612b 100644 --- a/crates/kernel/model/Cargo.toml +++ b/crates/model/Cargo.toml @@ -14,7 +14,7 @@ literal.workspace = true runtime_abi.workspace = true rustc-hash.workspace = true source.workspace = true -syntax.workspace = true +tree.workspace = true [lints] workspace = true diff --git a/crates/kernel/model/src/constant.rs b/crates/model/src/constant.rs similarity index 100% rename from crates/kernel/model/src/constant.rs rename to crates/model/src/constant.rs diff --git a/crates/model/src/layout.rs b/crates/model/src/layout.rs new file mode 100644 index 00000000..5323e719 --- /dev/null +++ b/crates/model/src/layout.rs @@ -0,0 +1,203 @@ +//! How values are laid out in memory for the target: each type's size and +//! alignment, where a struct's fields go, and how a value is held (`held`: +//! in a register, as two words, in memory, or not at all). The checker +//! rejects a type too big for the target with it; the backend places and +//! copies values with it, and LLVM sees only the bytes. + +use crate::machine::Machine; +use crate::mir::Class; +use crate::semantic_types; +use crate::semantic_types::Float; +use crate::semantic_types::Type; +use crate::semantic_types::TypeId; +use crate::semantic_types::Types; + +/// The size and alignment in bytes of a value of type `ty` in memory for +/// `target`: an integer is aligned as the next of 8, 16, 32, 64 and 128 bits +/// that holds it, a 64-bit one as `target` says, and wider ones as 128; its +/// size is rounded up to that. LLVM loads and stores a scalar itself, so a +/// scalar's must match LLVM's; a value kept in memory is bytes to LLVM, so +/// this alone says where its parts are. A size past `u64` is `u64::MAX`, more +/// than any machine's `largest_object`: the checker rejects such a type, so +/// no later phase lays it out. +#[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants +)] +pub fn layout(types: &Types, ty: TypeId, target: &Machine) -> (u64, u64) { + match &types[ty] { + Type::Bool => (1, 1), + Type::Integer(integer) => { + let align: u64 = match integer.bits { + 1..=8 => 1, + 9..=16 => 2, + 17..=32 => 4, + 33..=64 => target.i64_align, + _ => 16, + }; + // The class's bytes: its own, rounded up to the alignment. + let bytes = Class::integer(integer.bits).bytes(target.pointer_bytes()); + (bytes, align) + } + Type::Float(Float::F32) => (4, 4), + Type::Float(Float::F64) => (8, target.i64_align), + Type::CString | Type::Reference { .. } | Type::RawPointer { .. } => { + let bytes = target.pointer_bytes(); + (bytes, bytes) + } + Type::Slice { .. } + | Type::Str + | Type::InterfaceReference { .. } + | Type::Interface { .. } => { + let bytes = target.pointer_bytes(); + (2 * bytes, bytes) + } + Type::Struct { internals, .. } => (internals.size, internals.align), + Type::Range { element, step } => { + let fields = semantic_types::ranges::range_fields(*element, *step).map(|(_, ty)| ty); + let (_, size, align) = struct_layout(types, &fields, target); + (size, align) + } + Type::Array { internals, .. } => { + let (size, align) = layout(types, internals.base, target); + (size.saturating_mul(internals.count), align) + } + Type::Invalid | Type::Void | Type::Function { .. } | Type::Named { .. } => { + unreachable!("no value is laid out with this type") + } + Type::Alias { .. } => unreachable!("indexing looks through aliases"), + } +} + +/// How a value of a type is held while the program runs (`held`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Held { + /// Whole, as one number of this class. + Register(Class), + /// As two words: an address, then a length or a method table. + TwoWords, + /// In memory, as bytes: a struct, an array or a range. LLVM splits a + /// value of such a type into one operation per part, so a big array as + /// one value made clang slow, then crash; the interpreter copies such a + /// value as its bytes. + Memory, + /// Not held: no value has the type, as it is an error's, nothing + /// (`void`), or a function's, not yet a value. + Nothing, +} + +/// How a value of type `ty` is held while the program runs. +#[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants +)] +pub fn held(types: &Types, ty: TypeId) -> Held { + match types[ty] { + Type::Bool => Held::Register(Class::I8), + Type::Integer(integer) => Held::Register(Class::integer(integer.bits)), + Type::Float(float) => Held::Register(float.class()), + Type::CString | Type::Reference { .. } | Type::RawPointer { .. } => { + Held::Register(Class::Pointer) + } + Type::Slice { .. } + | Type::Str + | Type::InterfaceReference { .. } + | Type::Interface { .. } => Held::TwoWords, + Type::Struct { .. } | Type::Array { .. } | Type::Range { .. } => Held::Memory, + Type::Invalid | Type::Void | Type::Function { .. } => Held::Nothing, + Type::Named { .. } => unreachable!("no value has a type not checked yet"), + Type::Alias { .. } => unreachable!("indexing looks through aliases"), + } +} + +/// Field `index` of the struct, range or `str` type `ty`: where it is from +/// the value's start, in bytes, and its type. A struct's offsets are kept +/// (`StructInternals`); a range's two or three fields are laid out here; a +/// `str` is its bytes' address, then its length. +pub fn field_placed(types: &Types, ty: TypeId, index: usize, target: &Machine) -> (u64, TypeId) { + match &types[ty] { + ty if let Some(members) = ty.members() => (members.offsets[index], members.fields[index]), + Type::Str => [(0, TypeId::RAWPTR), (target.pointer_bytes(), types.usize)][index], + Type::Range { element, step } => { + let fields = semantic_types::ranges::range_fields(*element, *step).map(|(_, ty)| ty); + let (offsets, ..) = struct_layout(types, &fields, target); + (offsets[index], fields[index]) + } + _ => unreachable!("only a struct, a range and a `str` have fields"), + } +} + +/// The offset of each of `fields` in a struct holding them in order, and the +/// struct's size and alignment, in bytes (`layout`): each field at the next +/// multiple of its alignment, the size rounded up to the largest. +pub fn struct_layout(types: &Types, fields: &[TypeId], target: &Machine) -> (Vec, u64, u64) { + let (mut offsets, mut end, mut align) = (Vec::with_capacity(fields.len()), 0u64, 1); + for &field in fields { + let (size, field_align) = layout(types, field, target); + let offset = end + .checked_next_multiple_of(field_align) + .unwrap_or(u64::MAX); + offsets.push(offset); + end = offset.saturating_add(size); + align = align.max(field_align); + } + let size = end.checked_next_multiple_of(align).unwrap_or(u64::MAX); + (offsets, size, align) +} + +#[cfg(test)] +mod tests { + use crate::machine::Machine; + use crate::semantic_types::TypeId; + use crate::semantic_types::Types; + + use super::struct_layout; + + /// Each struct's field offsets and size match what LLVM gives on x86-64 + /// and AArch64, and with 32-bit pointers on i686 (measured with + /// `getelementptr` folded by clang `-O1`, `-m32` for i686). + #[test] + fn struct_layout_matches_llvm() { + let mut types = Types::new(64); + let mut integer = |name: &str| types.builtin(name).unwrap(); + let (i8, i24, i40, i128, i200) = ( + integer("i8"), + integer("i24"), + integer("i40"), + integer("i128"), + integer("i200"), + ); + let layout = |fields: &[TypeId]| { + let (offsets, size, _) = + struct_layout(&types, fields, Machine::named("x86_64-linux").unwrap()); + (offsets, size) + }; + assert_eq!(layout(&[TypeId::I32, TypeId::I64]), (vec![0, 8], 16)); + assert_eq!( + layout(&[TypeId::BOOL, i128, TypeId::I32]), + (vec![0, 16, 32], 48) + ); + assert_eq!(layout(&[i8, i24, i8]), (vec![0, 4, 8], 12)); + assert_eq!(layout(&[i8, i200, i8]), (vec![0, 16, 48], 64)); + assert_eq!(layout(&[i8, i40]), (vec![0, 8], 16)); + assert_eq!( + layout(&[i8, TypeId::F64, TypeId::CSTR]), + (vec![0, 8, 16], 24) + ); + assert_eq!(layout(&[]), (vec![], 0)); + let i686 = |fields: &[TypeId]| { + let (offsets, size, _) = + struct_layout(&types, fields, Machine::named("i686-linux").unwrap()); + (offsets, size) + }; + assert_eq!(i686(&[TypeId::I32, TypeId::I64]), (vec![0, 4], 12)); + assert_eq!( + i686(&[TypeId::BOOL, i128, TypeId::I32]), + (vec![0, 16, 32], 48) + ); + assert_eq!(i686(&[i8, i24, i8]), (vec![0, 4, 8], 12)); + assert_eq!(i686(&[i8, i200, i8]), (vec![0, 16, 48], 64)); + assert_eq!(i686(&[i8, i40]), (vec![0, 4], 12)); + assert_eq!(i686(&[i8, TypeId::F64, TypeId::CSTR]), (vec![0, 4, 12], 16)); + } +} diff --git a/crates/kernel/model/src/lib.rs b/crates/model/src/lib.rs similarity index 97% rename from crates/kernel/model/src/lib.rs rename to crates/model/src/lib.rs index d2dfb5de..78b41c46 100644 --- a/crates/kernel/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -1,6 +1,6 @@ //! The program's data after parsing: THIR, MIR, the type model, constant //! values, and the ids every phase shares (`ModuleId`, `DefId`). The syntax -//! tree is the `syntax` crate's. Each phase keeps its own node types +//! tree is the `tree` crate's. Each phase keeps its own node types //! (`thir`, `mir`); the crates that build them hold only logic. See //! docs/ir-design.md. diff --git a/crates/kernel/model/src/machine.rs b/crates/model/src/machine.rs similarity index 100% rename from crates/kernel/model/src/machine.rs rename to crates/model/src/machine.rs diff --git a/crates/kernel/model/src/mir.rs b/crates/model/src/mir.rs similarity index 97% rename from crates/kernel/model/src/mir.rs rename to crates/model/src/mir.rs index 22f9f018..16c890ca 100644 --- a/crates/kernel/model/src/mir.rs +++ b/crates/model/src/mir.rs @@ -625,7 +625,7 @@ impl Comparison { /// How a `Convert` instruction reads a register as another class. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Conversion { +pub enum Cast { SignExtend, ZeroExtend, Truncate, @@ -671,7 +671,7 @@ pub enum InstructionKind { }, /// `value`, of the class `from`, as the class `to`. Convert { - conversion: Conversion, + cast: Cast, from: Class, to: Class, value: Operand, @@ -793,6 +793,10 @@ impl InstructionKind { /// not a list: the path checks ask for every line, so it compiles to a /// `match`. #[inline] + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] pub fn accesses<'p>(&'p self, mut each: impl FnMut(PlaceAccess<'p>)) { let mut on = |place: &'p Place, touched, kind| { let place = place.as_place_ref(); @@ -849,6 +853,10 @@ impl InstructionKind { /// Gives `each` the values it reads as its operands, a call's callee /// first; not those a place it touches reads (`PlaceRef::operands`). #[inline] + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] pub fn operands(&self, mut each: impl FnMut(Operand)) { match self { InstructionKind::Integer { left, right, .. } @@ -988,6 +996,10 @@ impl Body { /// The class of the register `operand` is; `None` for an instruction /// that gives no register: a store, copy, check, `Moved`, `Dead`, or a /// call that gives nothing or gives its result in memory. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] pub fn class_of(&self, operand: Operand) -> Option { match operand { Operand::Value(id) => match &self.instructions[id].kind { @@ -1071,6 +1083,10 @@ struct Printer<'b> { } impl Printer<'_> { + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] fn write_instruction(&mut self, kind: &InstructionKind) { match kind { InstructionKind::Integer { @@ -1130,29 +1146,27 @@ impl Printer<'_> { self.write_binary(name, *class, left, right); } InstructionKind::Convert { - conversion, + cast, from, to, value, } => { - let name = match conversion { - Conversion::SignExtend => "sext", - Conversion::ZeroExtend => "zext", - Conversion::Truncate => "trunc", - Conversion::SignedToFloat => "sitofp", - Conversion::UnsignedToFloat => "uitofp", - Conversion::FloatToSigned { .. } => "fptosi", - Conversion::FloatToUnsigned { .. } => "fptoui", - Conversion::FloatWiden => "fpext", - Conversion::FloatNarrow => "fptrunc", - Conversion::PointerCast => "bitcast", + let name = match cast { + Cast::SignExtend => "sext", + Cast::ZeroExtend => "zext", + Cast::Truncate => "trunc", + Cast::SignedToFloat => "sitofp", + Cast::UnsignedToFloat => "uitofp", + Cast::FloatToSigned { .. } => "fptosi", + Cast::FloatToUnsigned { .. } => "fptoui", + Cast::FloatWiden => "fpext", + Cast::FloatNarrow => "fptrunc", + Cast::PointerCast => "bitcast", }; _ = write!(self.out, "{name} {from} "); self.write_operand(value); _ = write!(self.out, " to {to}"); - if let Conversion::FloatToSigned { bits } | Conversion::FloatToUnsigned { bits } = - conversion - { + if let Cast::FloatToSigned { bits } | Cast::FloatToUnsigned { bits } = cast { _ = write!(self.out, " at {bits} bits"); } } diff --git a/crates/kernel/model/src/program.rs b/crates/model/src/program.rs similarity index 97% rename from crates/kernel/model/src/program.rs rename to crates/model/src/program.rs index 0091626d..3cf8af03 100644 --- a/crates/kernel/model/src/program.rs +++ b/crates/model/src/program.rs @@ -19,9 +19,9 @@ use crate::semantic_types::ConstArgument; use crate::semantic_types::Constant; use crate::semantic_types::TypeId; use crate::semantic_types::Types; -use syntax::ast; -use syntax::ast::Ident; -use syntax::ast::Tree; +use tree::ast; +use tree::ast::Ident; +use tree::ast::Tree; /// One source file, read and parsed. Its source file is `ast.file`. What /// `load` read never changes; what a compile finds, its scope included, is @@ -247,11 +247,9 @@ pub fn field_names(modules: &[Module], definition: DefId) -> impl Iterator ty.fields(), - _ => None, + let ast::Type::Struct { fields } = tree.types[written.ty] else { + unreachable!("`{definition:?}` declares a struct") }; - let fields = fields.unwrap_or_else(|| unreachable!("`{definition:?}` declares a struct")); let names = tree.children.lists.items(fields); names.map(move |field| tree.children.fields[field].name.text(&tree.file)) } @@ -266,10 +264,9 @@ pub fn interface_methods( let &ast::Decl::Type(written) = declaration(modules, definition) else { return None; }; - let ast::Type::Feature(ty) = tree.types[written.ty] else { + let ast::Type::Interface { methods } = tree.types[written.ty] else { return None; }; - let methods = ty.methods()?; Some( tree.children .lists diff --git a/crates/kernel/model/src/semantic_types.rs b/crates/model/src/semantic_types.rs similarity index 59% rename from crates/kernel/model/src/semantic_types.rs rename to crates/model/src/semantic_types.rs index c5484ae7..9e128176 100644 --- a/crates/kernel/model/src/semantic_types.rs +++ b/crates/model/src/semantic_types.rs @@ -8,15 +8,13 @@ use std::hash::Hash; use std::hash::Hasher; use std::ops::Index; -use bigint::Limbs; use rustc_hash::FxHashMap; use crate::ConstArguments; use crate::DefId; use crate::constant::Value; use crate::constant::integer_text; -use crate::machine::MAX_INTEGER_BITS; -use crate::mir::Class; +use crate::mir; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct TypeId(u32); @@ -34,21 +32,6 @@ pub enum ConstArgument { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct ImplementationId(u32); -impl ImplementationId { - /// Its place in `Types`'s list, which an interface reference's second - /// word holds. - pub fn index(self) -> usize { - self.0 as usize - } - - /// The one at place `index`, read back from an interface reference. - pub fn from_index(index: usize) -> ImplementationId { - ImplementationId( - u32::try_from(index).expect("a program has fewer than 2^32 implementations"), - ) - } -} - /// An integer type: `i5` is signed with 5 bits. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct Integer { @@ -56,79 +39,6 @@ pub struct Integer { pub bits: u32, } -impl fmt::Display for Integer { - fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(out, "{}{}", if self.signed { 'i' } else { 'u' }, self.bits) - } -} - -impl Integer { - /// Whether the number `magnitude` (64-bit limbs, lowest first), negated - /// when `negative`, is a value of this type: `-128` fits `i8`, `128` does - /// not. - pub fn fits(self, magnitude: &[u64], negative: bool) -> bool { - let length = magnitude - .iter() - .rposition(|&limb| limb != 0) - .map_or(0, |top| { - top as u64 * 64 + u64::from(64 - magnitude[top].leading_zeros()) - }); - let bits = u64::from(self.bits); - match (self.signed, negative) { - _ if length == 0 => true, // zero, also written `-0` - (false, false) => length <= bits, - (false, true) => false, - (true, false) => length < bits, - // Down to -2^(bits-1): shorter, or exactly that power of two. - (true, true) => { - let power_of_two = magnitude.iter().map(|limb| limb.count_ones()).sum::() == 1; - length < bits || length == bits && power_of_two - } - } - } - - /// Whether a range of this type from the constant `start` to `end` - /// counts up (`start <= end`), and how far apart the two are, read as - /// unsigned of the same width, so it never overflows. `range_count` - /// and lowering's walk of a constant range both start here, so they - /// agree on how many values it has. - pub fn range_distance(self, start: &Limbs, end: &Limbs) -> (bool, Limbs) { - let up = bigint::compare(self.bits, self.signed, start, end).is_le(); - let (near, far) = if up { (start, end) } else { (end, start) }; - (up, bigint::subtract(self.bits, far, near)) - } - - /// How many values a range of this type from the constant `start` to - /// `end` by `step` has, `end` counted when `inclusive`, as `for` counts - /// them: one bit wider than the type, so `0..=u64::MAX`, 2^64 values, - /// is exact. `None` for a zero step. - pub fn range_count( - self, - start: &Limbs, - end: &Limbs, - step: &Limbs, - inclusive: bool, - ) -> Option { - let (_, distance) = self.range_distance(start, end); - self.count_over(&distance, step, inclusive) - } - - /// How many values a range of this type or its step type has over - /// `distance` by `step`, as `range_count` gives them. - pub fn count_over(self, distance: &Limbs, step: &Limbs, inclusive: bool) -> Option { - let whole = bigint::divide(self.bits, false, distance, step)?; - let rest = bigint::remainder(self.bits, false, distance, step)?; - let extra = inclusive || rest.as_slice().iter().any(|&limb| limb != 0); - let wide = self.bits + 1; - let whole = bigint::extend(self.bits, false, &whole, wide); - Some(bigint::add( - wide, - &whole, - &Limbs::new(wide, &[u64::from(extra)]), - )) - } -} - /// What the compiler works out from a struct's fields, once, so that nothing /// walks them again: they nest as deep as the declarations do and can repeat. /// None of it is written in the source. `define_struct` makes it. @@ -163,16 +73,6 @@ pub enum Float { F64, } -impl Float { - /// The register class that holds a float of this type. - pub fn class(self) -> Class { - match self { - Float::F32 => Class::F32, - Float::F64 => Class::F64, - } - } -} - #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum Type { /// The type of something whose error was already reported; uses of it @@ -315,6 +215,10 @@ impl Type { /// `Some(mutable)` for a type whose values borrow what they view, a /// reference, a slice or an interface reference: the loan rules hold for /// each. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] pub fn borrows(&self) -> Option { // shortcut: `&str` and `&cstr` hold no loan, as each is a literal's // (which borrows nothing) or C's (which Peeper cannot see); make them @@ -325,7 +229,23 @@ impl Type { Type::Reference { mutable, .. } | Type::Slice { mutable, .. } | Type::InterfaceReference { mutable, .. } => Some(mutable), - _ => None, + // A struct, an array or an owned interface may hold loans without + // being one (`Types::holds_loans`). + Type::Invalid + | Type::Void + | Type::Bool + | Type::Integer(_) + | Type::Float(_) + | Type::CString + | Type::Str + | Type::Function { .. } + | Type::Alias { .. } + | Type::Named { .. } + | Type::Struct { .. } + | Type::Array { .. } + | Type::Range { .. } + | Type::Interface { .. } + | Type::RawPointer { .. } => None, } } @@ -356,25 +276,6 @@ impl Type { _ => None, } } - - /// What a name after `.` can mean on the type (docs/feature-front.md, - /// 5.1): its fields, for a struct. A type with members can also have - /// functions with it as owner. - pub fn members(&self) -> Option> { - match self { - Type::Struct { - definition, - fields, - internals, - .. - } => Some(Members { - definition: *definition, - fields, - offsets: &internals.offsets, - }), - _ => None, - } - } } /// A type's fields (`Type::members`): the declaration that names them, and @@ -393,9 +294,9 @@ pub enum Conversion { /// as a `rawptr`, the same address. Same, /// Every value of the one type is a value of the other, so it converts - /// without `as`: to a wider integer of the same signedness, from unsigned - /// to a wider signed integer, and from `f32` to `f64`. - Implicit, + /// without `as`, by the cast: to a wider integer of the same signedness, + /// from unsigned to a wider signed integer, and from `f32` to `f64`. + Implicit(mir::Cast), /// A `&mut T` used as a `&T`, a reference to an array used as a slice /// of it, a `&mut []T` used as a `&[]T`, or a `&mut Shape` used as a /// `&Shape`: lent again, so the reference or slice itself is not moved. @@ -406,200 +307,15 @@ pub enum Conversion { /// which the checker finds; or a struct moved into an owned interface, /// `Shape`, which views it the same way. ToInterface, - /// Converts only when written with `as`: between integers that lose - /// values, between floats and integers, from `f64` to `f32`, from - /// `bool` to an integer, and between raw pointers of other types (the - /// same address). - NeedsCast, + /// Converts only when written with `as`, by the cast: between integers + /// that lose values, between floats and integers, from `f64` to `f32`, + /// from `bool` to an integer, and between raw pointers of other types + /// (the same address). + NeedsCast(mir::Cast), /// No conversion. Never, } -const fn integer(signed: bool, bits: u32) -> Type { - Type::Integer(Integer { signed, bits }) -} - -/// Declares the types with fixed ids: `FIXED`, the types in id order (they -/// need no lookup); a `TypeId` constant for each, numbered in the order -/// written; `NAMED`, the name a program writes for each type given one; and -/// `fixed_doc`, the doc comment written on a type's row. Other integers are -/// named by rule (`Types::builtin`). -macro_rules! fixed_types { - ($( - $(#[doc = $doc:literal] $(#[doc = $doc_more:literal])*)? - $name:ident $($text:literal)? => $ty:expr, - )*) => { - const FIXED: &[Type] = &[$($ty,)*]; - - /// The position of each fixed type in `FIXED`, counted by the compiler. - #[allow(non_camel_case_types, clippy::upper_case_acronyms)] - enum Position { - $($name,)* - } - - impl TypeId { - $( - $(#[doc = $doc] $(#[doc = $doc_more])*)? - pub const $name: TypeId = TypeId(Position::$name as u32); - )* - } - - const NAMED: &[(&str, TypeId)] = &[$($(($text, TypeId::$name),)?)*]; - - /// The doc comment on the row of the fixed type `id`, as Markdown, - /// each line with the space after its `///`, which Markdown drops; - /// `None` when its row has none. - fn fixed_doc(id: TypeId) -> Option<&'static str> { - match id { - $($(TypeId::$name => Some(concat!($doc $(, "\n", $doc_more)*)),)?)* - _ => None, - } - } - }; -} - -// A named type that is not an integer has a doc; an integer's is worked out -// (`builtin_doc`). -fixed_types! { - INVALID => Type::Invalid, - VOID => Type::Void, - /// A truth value: `true` or `false`. - BOOL "bool" => Type::Bool, - I8 "i8" => integer(true, 8), - I16 "i16" => integer(true, 16), - I32 "i32" => integer(true, 32), - I64 "i64" => integer(true, 64), - I128 "i128" => integer(true, 128), - U8 "u8" => integer(false, 8), - U16 "u16" => integer(false, 16), - U32 "u32" => integer(false, 32), - U64 "u64" => integer(false, 64), - U128 "u128" => integer(false, 128), - /// A 32-bit floating-point number (IEEE 754 single precision). - F32 "f32" => Type::Float(Float::F32), - /// A 64-bit floating-point number (IEEE 754 double precision). - F64 "f64" => Type::Float(Float::F64), - /// C text: bytes ending in a zero byte, with none before it. It has any - /// length, so no fixed size, and is used only through a reference, - /// `&cstr`: the bytes' address, as C functions take it. - CSTR "cstr" => Type::CString, - /// Text: bytes of any length, such as a string literal's. It has no - /// fixed size, so it is used only through a reference, `&str`: the - /// bytes' address and how many there are. A `&str` copies; `.len` is - /// its length in bytes. - STR "str" => Type::Str, - // No name: `rawptr` is a keyword, not a type name. - RAWPTR => Type::RawPointer { target: None }, -} - -/// The name of the built-in range type, written with its values' type -/// after it in brackets: `range[i32]`. -pub const RANGE: &str = "range"; - -/// What `range[T]` is, as `builtin_doc` gives it: in the shape of a row's -/// doc, each line keeping the space after its `///`. -const RANGE_DOC: &str = " The integers from a start toward an end, a step apart: the type of `a..b`, `a..=b` and `a..b:step`. - - `range[T]` holds integers of the type `T`. It counts up or down, as its ends say, includes its end when written with `..=`, and copies. `for v in r` counts each of its values, and `[N]T{r...}` spreads them into an array. - - ```peeper - fn evens(n: i32) -> range[i32] { - return 0..n:2; - } - ```"; - -/// The fields of a value of `Type::Range { element, step }`, in order, each -/// with its name, as debug info shows it, and type: its walk, found once -/// when the range is made (`lower::Lowering::walk_range`). Its values are -/// `start`, then each `delta` more than the one before, wrapping, while -/// `left`, how far its end is, lasts by `step`, the end counted when -/// `inclusive`. `range_field` gives where each one is. -pub fn range_fields(element: TypeId, step: TypeId) -> [(&'static str, TypeId); 5] { - [ - ("start", element), - ("left", step), - ("step", step), - ("delta", element), - ("inclusive", TypeId::BOOL), - ] -} - -/// Where each field of a range value is in `range_fields`. -pub mod range_field { - pub const START: usize = 0; - pub const LEFT: usize = 1; - pub const STEP: usize = 2; - pub const DELTA: usize = 3; - pub const INCLUSIVE: usize = 4; -} - -/// The integer types as wide as a pointer, and whether each is signed. -const POINTER_SIZED: [(&str, bool); 2] = [("isize", true), ("usize", false)]; - -/// The built-in type names a program writes most, for "did you mean" -/// guesses: each in `NAMED`, `isize` and `usize`. -pub fn builtin_names() -> impl Iterator { - let named = NAMED.iter().map(|&(text, _)| text); - named.chain(POINTER_SIZED.iter().map(|&(text, _)| text)) -} - -/// The integer type `name` stands for when it is not in `NAMED`: `isize` and -/// `usize` (as wide as a pointer, `pointer_bits`), or `iN` and `uN` for N -/// from 1 to `machine::MAX_INTEGER_BITS`, written without leading zeros. -fn integer_named(name: &str, pointer_bits: u32) -> Option { - if let Some(&(_, signed)) = POINTER_SIZED.iter().find(|(text, _)| *text == name) { - return Some(Integer { - signed, - bits: pointer_bits, - }); - } - let (signed, width) = match name.split_at_checked(1)? { - ("i", width) => (true, width), - ("u", width) => (false, width), - _ => return None, - }; - let digits = !width.is_empty() && width.bytes().all(|b| b.is_ascii_digit()); - if !digits || width.starts_with('0') { - return None; // `u`, `i8x`, `u08` - } - let bits = (width.parse().ok()).filter(|&bits| bits <= MAX_INTEGER_BITS)?; - Some(Integer { signed, bits }) -} - -/// What the built-in type `name` is (`Types::builtin`), or `range`, as -/// Markdown, as an editor shows it: an integer's range, worked out, and -/// whether it is as wide as a pointer, `pointer_bits`; another type's doc, -/// from its row (`fixed_doc`). `None` when `name` is not a built-in type. -pub fn builtin_doc(name: &str, pointer_bits: u32) -> Option { - if name == RANGE { - return Some(RANGE_DOC.to_string()); - } - let Integer { signed, bits } = match NAMED.iter().find(|&&(text, _)| text == name) { - Some(&(_, id)) => match FIXED[id.0 as usize] { - Type::Integer(integer) => integer, - _ => return fixed_doc(id).map(str::to_string), - }, - None => integer_named(name, pointer_bits)?, - }; - let (min, max) = match (signed, bits) { - (true, ..=128) => ( - (i128::MIN >> (128 - bits)).to_string(), - (i128::MAX >> (128 - bits)).to_string(), - ), - (false, ..=128) => ("0".to_string(), (u128::MAX >> (128 - bits)).to_string()), - // Too many digits to read. - (true, _) => (format!("-2^{}", bits - 1), format!("2^{} - 1", bits - 1)), - (false, _) => ("0".to_string(), format!("2^{bits} - 1")), - }; - let kind = if signed { "A signed" } else { "An unsigned" }; - let size = if POINTER_SIZED.iter().any(|&(text, _)| text == name) { - format!("integer as wide as a pointer, {bits} bits on the target") - } else { - format!("{bits}-bit integer") - }; - Some(format!("{kind} {size}: from `{min}` to `{max}`.")) -} - /// The types of a program, for one compile (`check::Checker` holds them). pub struct Types { pub usize: TypeId, // as wide as a pointer of the target @@ -628,7 +344,7 @@ impl Types { argument_ids: FxHashMap::default(), }; types.const_arguments(&[]); - for ty in FIXED { + for ty in builtin::FIXED { types.intern(ty.clone()); } types.usize = types.intern(Type::Integer(Integer { @@ -716,206 +432,18 @@ impl Types { id } - /// The type `[length]element`. - pub fn array(&mut self, element: TypeId, length: u64) -> TypeId { - let (base, inner) = match self[element] { - Type::Array { internals, .. } => (internals.base, internals.count), - _ => (self.real(element), 1), - }; - let count = inner.saturating_mul(length); - self.intern(Type::Array { - element, - length, - internals: ArrayInternals { base, count }, - }) - } - - /// The lengths of the arrays in arrays that `id` is, outermost first; - /// none for any other type. - pub fn array_lengths(&self, mut id: TypeId) -> impl Iterator { - std::iter::from_fn(move || match self[id] { - Type::Array { - element, length, .. - } => { - id = element; - Some(length) - } - _ => None, - }) - } - - /// Makes the declared name `named` the struct of `fields`, laid out as - /// `struct_layout` gives (`offsets`, `size`, `align`), under its id, so a - /// `*T` written before `T` was complete is the `*T` of after. - pub fn define_struct( - &mut self, - named: TypeId, - fields: Box<[TypeId]>, - (offsets, size, align): (Vec, u64, u64), - ) { - let internals = StructInternals { - offsets: offsets.into(), - size, - align, - holders: self.holders_in_fields(&fields), - mutable_holder: (fields.iter()).any(|&field| self.holds_loans(field) == Some(true)), - }; - let slot = &mut self.types[named.0 as usize]; - let Type::Named { - definition, - arguments, - } = *slot - else { - unreachable!("only a declared name becomes a struct"); - }; - *slot = Type::Struct { - definition, - arguments, - fields, - internals, - }; - } - - /// Makes the declared name `named` the interface whose methods have the - /// function types `methods`, under its id, so an `&Shape` written before - /// the interface was checked, as its own methods' `&self` is, is the - /// `&Shape` of after. - pub fn define_interface(&mut self, named: TypeId, methods: Box<[TypeId]>) { - let slot = &mut self.types[named.0 as usize]; - let Type::Named { definition, .. } = *slot else { - unreachable!("only a declared name becomes an interface"); - }; - *slot = Type::Interface { - definition, - methods, - }; - } - - /// Adds the implementation whose functions are `methods`, in its - /// interface's order. - pub fn add_implementation(&mut self, methods: Box<[DefId]>) -> ImplementationId { - self.implementations.push(methods); - ImplementationId::from_index(self.implementations.len() - 1) - } - - /// The functions of the implementation `id`, in its interface's order. - pub fn implementation(&self, id: ImplementationId) -> &[DefId] { - &self.implementations[id.index()] - } - - /// The built-in type `name` stands for: one in `NAMED`, `isize` and `usize` - /// (as wide as a pointer: the `usize` this table was made with), or `iN` and `uN` for N from 1 to - /// `machine::MAX_INTEGER_BITS`, written without leading zeros. A number literal's - /// suffix (`5u24`) is one of these names too. - pub fn builtin(&mut self, name: &str) -> Option { - if let Some(&(_, id)) = NAMED.iter().find(|(text, _)| *text == name) { - return Some(id); - } - let Type::Integer(pointer) = self[self.usize] else { - unreachable!("`usize` is an integer") - }; - Some(self.intern(Type::Integer(integer_named(name, pointer.bits)?))) - } - - /// `range[element]`, of the integer type `element` (an alias looked - /// through), with its step type; `None` when `element` is not an - /// integer. - pub fn range(&mut self, element: TypeId) -> Option { - let Type::Integer(integer) = self[element] else { - return None; - }; - let element = self.real(element); - let step = self.intern(Type::Integer(Integer { - signed: false, - ..integer - })); - Some(self.intern(Type::Range { element, step })) - } - /// Whether `a` and `b` are one type, aliases looked through. pub fn same(&self, a: TypeId, b: TypeId) -> bool { self.real(a) == self.real(b) } - /// How a value of the type `from` becomes a value of the type `to`. - pub fn conversion(&self, from: TypeId, to: TypeId) -> Conversion { - if self.same(from, to) { - return Conversion::Same; - } - match (&self[from], &self[to]) { - (Type::Integer(from), Type::Integer(to)) => { - if to.bits > from.bits && (from.signed == to.signed || to.signed) { - Conversion::Implicit - } else { - Conversion::NeedsCast - } - } - (Type::Float(Float::F32), Type::Float(Float::F64)) => Conversion::Implicit, - (Type::Float(_) | Type::Integer(_), Type::Float(_) | Type::Integer(_)) - | (Type::Bool, Type::Integer(_)) => Conversion::NeedsCast, - ( - &Type::Reference { - mutable: true, - target: from, - }, - &Type::Reference { - mutable: false, - target: to, - }, - ) if self.same(from, to) => Conversion::Reborrow, - ( - &Type::Reference { - mutable: from_mutable, - target, - }, - &Type::Slice { mutable, element }, - ) if from_mutable || !mutable => match self[target] { - Type::Array { element: from, .. } if self.same(from, element) => { - Conversion::Reborrow - } - _ => Conversion::Never, - }, - ( - &Type::Slice { - mutable: true, - element: from, - }, - &Type::Slice { - mutable: false, - element: to, - }, - ) if self.same(from, to) => Conversion::Reborrow, - ( - &Type::InterfaceReference { - mutable: true, - interface: from, - }, - &Type::InterfaceReference { - mutable: false, - interface: to, - }, - ) if from == to => Conversion::Reborrow, - ( - &Type::Reference { - mutable: from_mutable, - target, - }, - &Type::InterfaceReference { mutable, .. }, - ) if (from_mutable || !mutable) && self[target].members().is_some() => { - Conversion::ToInterface - } - (from, Type::Interface { .. }) if from.members().is_some() => Conversion::ToInterface, - (Type::RawPointer { target: Some(_) }, Type::RawPointer { target: None }) => { - Conversion::Same - } - (Type::RawPointer { .. }, Type::RawPointer { .. }) => Conversion::NeedsCast, - _ => Conversion::Never, - } - } - /// `Some(whether one is mutable)` for a type whose values hold loans: a /// reference, a slice, an owned interface (on the struct it took), or a /// struct or array with one in a field or element, however deep. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] pub fn holds_loans(&self, id: TypeId) -> Option { match &self[id] { Type::Struct { internals, .. } => { @@ -923,7 +451,22 @@ impl Types { } Type::Array { internals, .. } => self.holds_loans(internals.base), Type::Interface { .. } => Some(true), - other => other.borrows(), + // Any other type holds a loan only by being one. + other @ (Type::Invalid + | Type::Void + | Type::Bool + | Type::Integer(_) + | Type::Float(_) + | Type::CString + | Type::Str + | Type::Function { .. } + | Type::Alias { .. } + | Type::Named { .. } + | Type::Range { .. } + | Type::Reference { .. } + | Type::Slice { .. } + | Type::InterfaceReference { .. } + | Type::RawPointer { .. }) => other.borrows(), } } @@ -931,6 +474,10 @@ impl Types { /// interfaces a value of the type `id` is: one for each, its fields' for /// a struct, its elements' for an array, as no other type holds one. Not /// past `usize`. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] pub fn holders_in(&self, id: TypeId) -> usize { match &self[id] { Type::Struct { internals, .. } => internals.holders, @@ -938,7 +485,21 @@ impl Types { .unwrap_or(usize::MAX) .saturating_mul(self.holders_in(internals.base)), Type::Interface { .. } => 1, - other => usize::from(other.borrows().is_some()), + other @ (Type::Invalid + | Type::Void + | Type::Bool + | Type::Integer(_) + | Type::Float(_) + | Type::CString + | Type::Str + | Type::Function { .. } + | Type::Alias { .. } + | Type::Named { .. } + | Type::Range { .. } + | Type::Reference { .. } + | Type::Slice { .. } + | Type::InterfaceReference { .. } + | Type::RawPointer { .. }) => usize::from(other.borrows().is_some()), } } @@ -963,6 +524,10 @@ impl Types { /// `bool`, `&cstr`, shared references and slices, raw pointers, ranges, and arrays of values /// that copy. Any other value moves, and the variable it moved from is /// unusable until set again. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] pub fn is_copy(&self, id: TypeId) -> bool { match self[id] { Type::Bool @@ -997,6 +562,10 @@ impl Types { /// differs between compiles: a declared type by what `declaration` /// feeds for it, then what a copy of it is given. A struct's fields and /// an interface's methods are not fed: its declaration holds them. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] pub fn hash( &self, id: TypeId, @@ -1097,6 +666,10 @@ impl Types { /// Writes the type `id` itself to `out`, aliases looked through: `u8`, /// `fn(i32) -> bool`, a named type by its name. Into one text, so a type /// nested as deep as the source does costs its length, not its square. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] fn write_real_text( &self, out: &mut String, @@ -1108,7 +681,7 @@ impl Types { Type::Invalid => out.push_str("{invalid}"), Type::Void => out.push_str("void"), Type::Bool | Type::Float(_) | Type::CString | Type::Str => { - let (text, _) = NAMED + let (text, _) = builtin::NAMED .iter() .find(|&&(_, named)| named == id) .expect("in `NAMED`"); @@ -1156,7 +729,7 @@ impl Types { self.write_real_text(out, internals.base, name_of); } Type::Range { element, .. } => { - _ = write!(out, "{RANGE}["); + _ = write!(out, "{}[", builtin::RANGE); self.write_real_text(out, *element, name_of); out.push(']'); } @@ -1194,6 +767,14 @@ impl Index for Types { } } +mod arrays; +pub mod builtin; +mod conversions; +mod integers; +mod interfaces; +mod primitive; +pub mod ranges; +mod structs; #[cfg(test)] mod tests; diff --git a/crates/model/src/semantic_types/arrays.rs b/crates/model/src/semantic_types/arrays.rs new file mode 100644 index 00000000..be5ddfa9 --- /dev/null +++ b/crates/model/src/semantic_types/arrays.rs @@ -0,0 +1,36 @@ +//! `[N]T`: arrays, and the arrays in arrays they can be. + +use super::ArrayInternals; +use super::Type; +use super::TypeId; +use super::Types; + +impl Types { + /// The type `[length]element`. + pub fn array(&mut self, element: TypeId, length: u64) -> TypeId { + let (base, inner) = match self[element] { + Type::Array { internals, .. } => (internals.base, internals.count), + _ => (self.real(element), 1), + }; + let count = inner.saturating_mul(length); + self.intern(Type::Array { + element, + length, + internals: ArrayInternals { base, count }, + }) + } + + /// The lengths of the arrays in arrays that `id` is, outermost first; + /// none for any other type. + pub fn array_lengths(&self, mut id: TypeId) -> impl Iterator { + std::iter::from_fn(move || match self[id] { + Type::Array { + element, length, .. + } => { + id = element; + Some(length) + } + _ => None, + }) + } +} diff --git a/crates/model/src/semantic_types/builtin.rs b/crates/model/src/semantic_types/builtin.rs new file mode 100644 index 00000000..a780e84a --- /dev/null +++ b/crates/model/src/semantic_types/builtin.rs @@ -0,0 +1,182 @@ +//! The built-in types, one table: each with its name and doc, and the +//! editor docs worked out from it. + +use super::Float; +use super::Integer; +use super::Type; +use super::TypeId; +use super::Types; +use super::integers; + +/// Declares the built-in types, one row each. First the types with fixed +/// ids: `FIXED`, the types in id order (they need no lookup); a `TypeId` +/// constant for each, numbered in the order written; `NAMED`, the name a +/// program writes for each type given one; and `fixed_doc`, the doc comment +/// written on a type's row. Then, after `;`, the names written with their +/// values' type in brackets (`range[i32]`), whose types `Types` makes per +/// element type, as it makes arrays: a constant for each name, and +/// `bracketed_doc`, the doc comment on its row. Other integers are named by +/// rule (`Types::builtin`). +macro_rules! builtin_types { + ( + $( + $(#[doc = $doc:literal] $(#[doc = $doc_more:literal])*)? + $name:ident $($text:literal)? => $ty:expr, + )* + ; + $( + #[doc = $bracketed_doc:literal] $(#[doc = $bracketed_doc_more:literal])* + $bracketed:ident $bracketed_text:literal, + )* + ) => { + pub(super) const FIXED: &[Type] = &[$($ty,)*]; + + /// The position of each fixed type in `FIXED`, counted by the compiler. + #[allow(non_camel_case_types, clippy::upper_case_acronyms)] + enum Position { + $($name,)* + } + + impl TypeId { + $( + $(#[doc = $doc] $(#[doc = $doc_more])*)? + pub const $name: TypeId = TypeId(Position::$name as u32); + )* + } + + pub(super) const NAMED: &[(&str, TypeId)] = &[$($(($text, TypeId::$name),)?)*]; + + /// The doc comment on the row of the fixed type `id`, as Markdown, + /// each line with the space after its `///`, which Markdown drops; + /// `None` when its row has none. + fn fixed_doc(id: TypeId) -> Option<&'static str> { + match id { + $($(TypeId::$name => Some(concat!($doc $(, "\n", $doc_more)*)),)?)* + _ => None, + } + } + + $( + #[doc = $bracketed_doc] $(#[doc = $bracketed_doc_more])* + pub const $bracketed: &str = $bracketed_text; + )* + + /// The doc comment on the row of the bracketed name `name`, as + /// `fixed_doc` gives a fixed type's; `None` for another name. + fn bracketed_doc(name: &str) -> Option<&'static str> { + match name { + $($bracketed_text => Some(concat!($bracketed_doc $(, "\n", $bracketed_doc_more)*)),)* + _ => None, + } + } + }; +} + +// A named type that is not an integer has a doc; an integer's is worked out +// (`builtin_doc`). +builtin_types! { + INVALID => Type::Invalid, + VOID => Type::Void, + /// A truth value: `true` or `false`. + BOOL "bool" => Type::Bool, + I8 "i8" => integers::integer(true, 8), + I16 "i16" => integers::integer(true, 16), + I32 "i32" => integers::integer(true, 32), + I64 "i64" => integers::integer(true, 64), + I128 "i128" => integers::integer(true, 128), + U8 "u8" => integers::integer(false, 8), + U16 "u16" => integers::integer(false, 16), + U32 "u32" => integers::integer(false, 32), + U64 "u64" => integers::integer(false, 64), + U128 "u128" => integers::integer(false, 128), + /// A 32-bit floating-point number (IEEE 754 single precision). + F32 "f32" => Type::Float(Float::F32), + /// A 64-bit floating-point number (IEEE 754 double precision). + F64 "f64" => Type::Float(Float::F64), + /// C text: bytes ending in a zero byte, with none before it. It has any + /// length, so no fixed size, and is used only through a reference, + /// `&cstr`: the bytes' address, as C functions take it. + CSTR "cstr" => Type::CString, + /// Text: bytes of any length, such as a string literal's. It has no + /// fixed size, so it is used only through a reference, `&str`: the + /// bytes' address and how many there are. A `&str` copies; `.len` is + /// its length in bytes. + STR "str" => Type::Str, + // No name: `rawptr` is a keyword, not a type name. + RAWPTR => Type::RawPointer { target: None }, + ; + /// The integers from a start toward an end, a step apart: the type of + /// `a..b`, `a..=b` and `a..b:step`. + /// + /// `range[T]` holds integers of the type `T`. It counts up or down, as its + /// ends say, includes its end when written with `..=`, and copies. + /// `for v in r` counts each of its values, and `[N]T{r...}` spreads them + /// into an array. + /// + /// ```peeper + /// fn evens(n: i32) -> range[i32] { + /// return 0..n:2; + /// } + /// ``` + RANGE "range", +} + +/// The built-in type names a program writes most, for "did you mean" +/// guesses: each in `NAMED`, `isize` and `usize`. +pub fn builtin_names() -> impl Iterator { + let named = NAMED.iter().map(|&(text, _)| text); + named.chain(integers::POINTER_SIZED.iter().map(|&(text, _)| text)) +} + +/// What the built-in type `name` is (`Types::builtin`), or `range`, as +/// Markdown, as an editor shows it: an integer's range, worked out, and +/// whether it is as wide as a pointer, `pointer_bits`; another type's doc, +/// from its row (`fixed_doc`). `None` when `name` is not a built-in type. +pub fn builtin_doc(name: &str, pointer_bits: u32) -> Option { + if let Some(doc) = bracketed_doc(name) { + return Some(doc.to_string()); + } + let Integer { signed, bits } = match NAMED.iter().find(|&&(text, _)| text == name) { + Some(&(_, id)) => match FIXED[id.0 as usize] { + Type::Integer(integer) => integer, + _ => return fixed_doc(id).map(str::to_string), + }, + None => integers::integer_named(name, pointer_bits)?, + }; + let (min, max) = match (signed, bits) { + (true, ..=128) => ( + (i128::MIN >> (128 - bits)).to_string(), + (i128::MAX >> (128 - bits)).to_string(), + ), + (false, ..=128) => ("0".to_string(), (u128::MAX >> (128 - bits)).to_string()), + // Too many digits to read. + (true, _) => (format!("-2^{}", bits - 1), format!("2^{} - 1", bits - 1)), + (false, _) => ("0".to_string(), format!("2^{bits} - 1")), + }; + let kind = if signed { "A signed" } else { "An unsigned" }; + let size = if integers::POINTER_SIZED + .iter() + .any(|&(text, _)| text == name) + { + format!("integer as wide as a pointer, {bits} bits on the target") + } else { + format!("{bits}-bit integer") + }; + Some(format!("{kind} {size}: from `{min}` to `{max}`.")) +} + +impl Types { + /// The built-in type `name` stands for: one in `NAMED`, `isize` and `usize` + /// (as wide as a pointer: the `usize` this table was made with), or `iN` and `uN` for N from 1 to + /// `machine::MAX_INTEGER_BITS`, written without leading zeros. A number literal's + /// suffix (`5u24`) is one of these names too. + pub fn builtin(&mut self, name: &str) -> Option { + if let Some(&(_, id)) = NAMED.iter().find(|(text, _)| *text == name) { + return Some(id); + } + let Type::Integer(pointer) = self[self.usize] else { + unreachable!("`usize` is an integer") + }; + Some(self.intern(Type::Integer(integers::integer_named(name, pointer.bits)?))) + } +} diff --git a/crates/model/src/semantic_types/conversions.rs b/crates/model/src/semantic_types/conversions.rs new file mode 100644 index 00000000..12220909 --- /dev/null +++ b/crates/model/src/semantic_types/conversions.rs @@ -0,0 +1,108 @@ +//! How a value of one type becomes a value of another, decided in one +//! place by the pair of types: whether it converts, with `as` or without, +//! and for a number, a `bool` or a raw pointer, the cast that does it. + +use crate::mir; + +use super::Conversion; +use super::Float; +use super::Integer; +use super::Type; +use super::TypeId; +use super::Types; + +impl Types { + /// How a value of the type `from` becomes a value of the type `to`. A + /// pair not named here never converts. + pub fn conversion(&self, from: TypeId, to: TypeId) -> Conversion { + if self.same(from, to) { + return Conversion::Same; + } + match (&self[from], &self[to]) { + (&Type::Integer(from), &Type::Integer(to)) => { + let cast = from.cast_to(to); + if to.bits > from.bits && (from.signed == to.signed || to.signed) { + Conversion::Implicit(cast) + } else { + Conversion::NeedsCast(cast) + } + } + (Type::Bool, &Type::Integer(to)) => Conversion::NeedsCast(Integer::BOOL.cast_to(to)), + (&Type::Integer(from), Type::Float(_)) => Conversion::NeedsCast(if from.signed { + mir::Cast::SignedToFloat + } else { + mir::Cast::UnsignedToFloat + }), + (Type::Float(_), &Type::Integer(to)) => Conversion::NeedsCast(if to.signed { + mir::Cast::FloatToSigned { bits: to.bits } + } else { + mir::Cast::FloatToUnsigned { bits: to.bits } + }), + (Type::Float(Float::F32), Type::Float(Float::F64)) => { + Conversion::Implicit(mir::Cast::FloatWiden) + } + (Type::Float(Float::F64), Type::Float(Float::F32)) => { + Conversion::NeedsCast(mir::Cast::FloatNarrow) + } + ( + &Type::Reference { + mutable: true, + target: from, + }, + &Type::Reference { + mutable: false, + target: to, + }, + ) if self.same(from, to) => Conversion::Reborrow, + ( + &Type::Reference { + mutable: from_mutable, + target, + }, + &Type::Slice { mutable, element }, + ) if from_mutable || !mutable => match self[target] { + Type::Array { element: from, .. } if self.same(from, element) => { + Conversion::Reborrow + } + _ => Conversion::Never, + }, + ( + &Type::Slice { + mutable: true, + element: from, + }, + &Type::Slice { + mutable: false, + element: to, + }, + ) if self.same(from, to) => Conversion::Reborrow, + ( + &Type::InterfaceReference { + mutable: true, + interface: from, + }, + &Type::InterfaceReference { + mutable: false, + interface: to, + }, + ) if from == to => Conversion::Reborrow, + ( + &Type::Reference { + mutable: from_mutable, + target, + }, + &Type::InterfaceReference { mutable, .. }, + ) if (from_mutable || !mutable) && self[target].members().is_some() => { + Conversion::ToInterface + } + (from, Type::Interface { .. }) if from.members().is_some() => Conversion::ToInterface, + (Type::RawPointer { target: Some(_) }, Type::RawPointer { target: None }) => { + Conversion::Same + } + (Type::RawPointer { .. }, Type::RawPointer { .. }) => { + Conversion::NeedsCast(mir::Cast::PointerCast) + } + _ => Conversion::Never, + } + } +} diff --git a/crates/model/src/semantic_types/integers.rs b/crates/model/src/semantic_types/integers.rs new file mode 100644 index 00000000..a6dcaa72 --- /dev/null +++ b/crates/model/src/semantic_types/integers.rs @@ -0,0 +1,133 @@ +//! Integer types: which values fit one, how ranges of one count, and +//! the names `isize`, `usize`, `iN` and `uN`. + +use std::fmt; + +use bigint::Limbs; + +use crate::machine; +use crate::mir; + +use super::Integer; +use super::Type; + +impl fmt::Display for Integer { + fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(out, "{}{}", if self.signed { 'i' } else { 'u' }, self.bits) + } +} + +impl Integer { + /// The integer a `bool` is converted as: 1 bit, unsigned, 1 for `true`. + pub const BOOL: Integer = Integer { + signed: false, + bits: 1, + }; + + /// The cast that makes a value of this type one of the integer type + /// `to`, each at its own width. + pub fn cast_to(self, to: Integer) -> mir::Cast { + if to.bits < self.bits { + mir::Cast::Truncate + } else if self.signed { + mir::Cast::SignExtend + } else { + mir::Cast::ZeroExtend + } + } + + /// Whether the number `magnitude` (64-bit limbs, lowest first), negated + /// when `negative`, is a value of this type: `-128` fits `i8`, `128` does + /// not. + pub fn fits(self, magnitude: &[u64], negative: bool) -> bool { + let length = magnitude + .iter() + .rposition(|&limb| limb != 0) + .map_or(0, |top| { + top as u64 * 64 + u64::from(64 - magnitude[top].leading_zeros()) + }); + let bits = u64::from(self.bits); + match (self.signed, negative) { + _ if length == 0 => true, // zero, also written `-0` + (false, false) => length <= bits, + (false, true) => false, + (true, false) => length < bits, + // Down to -2^(bits-1): shorter, or exactly that power of two. + (true, true) => { + let power_of_two = magnitude.iter().map(|limb| limb.count_ones()).sum::() == 1; + length < bits || length == bits && power_of_two + } + } + } + + /// Whether a range of this type from the constant `start` to `end` + /// counts up (`start <= end`), and how far apart the two are, read as + /// unsigned of the same width, so it never overflows. `range_count` + /// and lowering's walk of a constant range both start here, so they + /// agree on how many values it has. + pub fn range_distance(self, start: &Limbs, end: &Limbs) -> (bool, Limbs) { + let up = bigint::compare(self.bits, self.signed, start, end).is_le(); + let (near, far) = if up { (start, end) } else { (end, start) }; + (up, bigint::subtract(self.bits, far, near)) + } + + /// How many values a range of this type from the constant `start` to + /// `end` by `step` has, `end` counted when `inclusive`, as `for` counts + /// them: one bit wider than the type, so `0..=u64::MAX`, 2^64 values, + /// is exact. `None` for a zero step. + pub fn range_count( + self, + start: &Limbs, + end: &Limbs, + step: &Limbs, + inclusive: bool, + ) -> Option { + let (_, distance) = self.range_distance(start, end); + self.count_over(&distance, step, inclusive) + } + + /// How many values a range of this type or its step type has over + /// `distance` by `step`, as `range_count` gives them. + pub fn count_over(self, distance: &Limbs, step: &Limbs, inclusive: bool) -> Option { + let whole = bigint::divide(self.bits, false, distance, step)?; + let rest = bigint::remainder(self.bits, false, distance, step)?; + let extra = inclusive || rest.as_slice().iter().any(|&limb| limb != 0); + let wide = self.bits + 1; + let whole = bigint::extend(self.bits, false, &whole, wide); + Some(bigint::add( + wide, + &whole, + &Limbs::new(wide, &[u64::from(extra)]), + )) + } +} + +pub(super) const fn integer(signed: bool, bits: u32) -> Type { + Type::Integer(Integer { signed, bits }) +} + +/// The integer types as wide as a pointer, and whether each is signed. +pub(super) const POINTER_SIZED: [(&str, bool); 2] = [("isize", true), ("usize", false)]; + +/// The integer type `name` stands for when it is not in `NAMED`: `isize` and +/// `usize` (as wide as a pointer, `pointer_bits`), or `iN` and `uN` for N +/// from 1 to `machine::MAX_INTEGER_BITS`, written without leading zeros. +pub(super) fn integer_named(name: &str, pointer_bits: u32) -> Option { + if let Some(&(_, signed)) = POINTER_SIZED.iter().find(|(text, _)| *text == name) { + return Some(Integer { + signed, + bits: pointer_bits, + }); + } + let (signed, width) = match name.split_at_checked(1)? { + ("i", width) => (true, width), + ("u", width) => (false, width), + _ => return None, + }; + let digits = !width.is_empty() && width.bytes().all(|b| b.is_ascii_digit()); + if !digits || width.starts_with('0') { + return None; // `u`, `i8x`, `u08` + } + let bits = (width.parse().ok()).filter(|&bits| bits <= machine::MAX_INTEGER_BITS)?; + Some(Integer { signed, bits }) +} diff --git a/crates/model/src/semantic_types/interfaces.rs b/crates/model/src/semantic_types/interfaces.rs new file mode 100644 index 00000000..ec006e0a --- /dev/null +++ b/crates/model/src/semantic_types/interfaces.rs @@ -0,0 +1,53 @@ +//! Interfaces: the type an interface declaration makes, and the +//! implementations of it that interface references carry. + +use crate::DefId; + +use super::ImplementationId; +use super::Type; +use super::TypeId; +use super::Types; + +impl ImplementationId { + /// Its place in `Types`'s list, which an interface reference's second + /// word holds. + pub fn index(self) -> usize { + self.0 as usize + } + + /// The one at place `index`, read back from an interface reference. + pub fn from_index(index: usize) -> ImplementationId { + ImplementationId( + u32::try_from(index).expect("a program has fewer than 2^32 implementations"), + ) + } +} + +impl Types { + /// Makes the declared name `named` the interface whose methods have the + /// function types `methods`, under its id, so an `&Shape` written before + /// the interface was checked, as its own methods' `&self` is, is the + /// `&Shape` of after. + pub fn define_interface(&mut self, named: TypeId, methods: Box<[TypeId]>) { + let slot = &mut self.types[named.0 as usize]; + let Type::Named { definition, .. } = *slot else { + unreachable!("only a declared name becomes an interface"); + }; + *slot = Type::Interface { + definition, + methods, + }; + } + + /// Adds the implementation whose functions are `methods`, in its + /// interface's order. + pub fn add_implementation(&mut self, methods: Box<[DefId]>) -> ImplementationId { + self.implementations.push(methods); + ImplementationId::from_index(self.implementations.len() - 1) + } + + /// The functions of the implementation `id`, in its interface's order. + pub fn implementation(&self, id: ImplementationId) -> &[DefId] { + &self.implementations[id.index()] + } +} diff --git a/crates/model/src/semantic_types/primitive.rs b/crates/model/src/semantic_types/primitive.rs new file mode 100644 index 00000000..77401591 --- /dev/null +++ b/crates/model/src/semantic_types/primitive.rs @@ -0,0 +1,17 @@ +//! The small types: `bool`, floats, `str`, `cstr`, `void` and the type of +//! an error. Their row in `builtin.rs` says nearly all they need; what more +//! they need is here, which is a float's register class. + +use crate::mir; + +use super::Float; + +impl Float { + /// The register class that holds a float of this type. + pub fn class(self) -> mir::Class { + match self { + Float::F32 => mir::Class::F32, + Float::F64 => mir::Class::F64, + } + } +} diff --git a/crates/model/src/semantic_types/ranges.rs b/crates/model/src/semantic_types/ranges.rs new file mode 100644 index 00000000..b3e67fad --- /dev/null +++ b/crates/model/src/semantic_types/ranges.rs @@ -0,0 +1,48 @@ +//! `range[T]`: its type and the fields of its values. + +use super::Integer; +use super::Type; +use super::TypeId; +use super::Types; + +/// The fields of a value of `Type::Range { element, step }`, in order, each +/// with its name, as debug info shows it, and type: its walk, found once +/// when the range is made (`lower::Lowering::walk_range`). Its values are +/// `start`, then each `delta` more than the one before, wrapping, while +/// `left`, how far its end is, lasts by `step`, the end counted when +/// `inclusive`. `field` gives where each one is. +pub fn range_fields(element: TypeId, step: TypeId) -> [(&'static str, TypeId); 5] { + [ + ("start", element), + ("left", step), + ("step", step), + ("delta", element), + ("inclusive", TypeId::BOOL), + ] +} + +/// Where each field of a range value is in `range_fields`. +pub mod field { + pub const START: usize = 0; + pub const LEFT: usize = 1; + pub const STEP: usize = 2; + pub const DELTA: usize = 3; + pub const INCLUSIVE: usize = 4; +} + +impl Types { + /// The type `range[element]`, for the integer type `element` (an alias + /// is looked through). Its step's type is the unsigned integer as wide + /// as `element`. `None` when `element` is not an integer. + pub fn range(&mut self, element: TypeId) -> Option { + let Type::Integer(integer) = self[element] else { + return None; + }; + let element = self.real(element); + let step = self.intern(Type::Integer(Integer { + signed: false, + ..integer + })); + Some(self.intern(Type::Range { element, step })) + } +} diff --git a/crates/model/src/semantic_types/structs.rs b/crates/model/src/semantic_types/structs.rs new file mode 100644 index 00000000..33ae21dc --- /dev/null +++ b/crates/model/src/semantic_types/structs.rs @@ -0,0 +1,62 @@ +//! Structs: the type a struct declaration makes, and its fields. + +use super::Members; +use super::StructInternals; +use super::Type; +use super::TypeId; +use super::Types; + +impl Types { + /// Makes the declared name `named` the struct of `fields`, laid out as + /// `struct_layout` gives (`offsets`, `size`, `align`), under its id, so a + /// `*T` written before `T` was complete is the `*T` of after. + pub fn define_struct( + &mut self, + named: TypeId, + fields: Box<[TypeId]>, + (offsets, size, align): (Vec, u64, u64), + ) { + let internals = StructInternals { + offsets: offsets.into(), + size, + align, + holders: self.holders_in_fields(&fields), + mutable_holder: (fields.iter()).any(|&field| self.holds_loans(field) == Some(true)), + }; + let slot = &mut self.types[named.0 as usize]; + let Type::Named { + definition, + arguments, + } = *slot + else { + unreachable!("only a declared name becomes a struct"); + }; + *slot = Type::Struct { + definition, + arguments, + fields, + internals, + }; + } +} + +impl Type { + /// What a name after `.` can mean on the type (docs/feature-front.md, + /// 5.1): its fields, for a struct. A type with members can also have + /// functions with it as owner. + pub fn members(&self) -> Option> { + match self { + Type::Struct { + definition, + fields, + internals, + .. + } => Some(Members { + definition: *definition, + fields, + offsets: &internals.offsets, + }), + _ => None, + } + } +} diff --git a/crates/kernel/model/src/semantic_types/tests.rs b/crates/model/src/semantic_types/tests.rs similarity index 85% rename from crates/kernel/model/src/semantic_types/tests.rs rename to crates/model/src/semantic_types/tests.rs index 74e238a2..b3b0b84b 100644 --- a/crates/kernel/model/src/semantic_types/tests.rs +++ b/crates/model/src/semantic_types/tests.rs @@ -1,31 +1,31 @@ use super::ConstArgument; use super::Conversion; -use super::FIXED; use super::Float; use super::Integer; use super::StructInternals; use super::Type; use super::TypeId; use super::Types; -use super::builtin_doc; -use super::integer; +use super::builtin; +use super::integers; use crate::ConstArguments; use crate::DefId; use crate::ModuleId; use crate::layout::layout; use crate::machine::Machine; +use crate::mir; /// Every built-in type name has a doc; an integer's range is right at /// each edge of how it is worked out, and one as wide as a pointer says /// so. #[test] fn builtin_docs() { - for name in super::builtin_names() { - assert!(builtin_doc(name, 64).is_some(), "{name}"); + for name in builtin::builtin_names() { + assert!(builtin::builtin_doc(name, 64).is_some(), "{name}"); } - assert_eq!(builtin_doc("Meters", 64), None); - assert!(builtin_doc(super::RANGE, 64).is_some()); - let doc = |name: &str, pointer_bits: u32| builtin_doc(name, pointer_bits).unwrap(); + assert_eq!(builtin::builtin_doc("Meters", 64), None); + assert!(builtin::builtin_doc(builtin::RANGE, 64).is_some()); + let doc = |name: &str, pointer_bits: u32| builtin::builtin_doc(name, pointer_bits).unwrap(); assert_eq!(doc("i1", 64), "A signed 1-bit integer: from `-1` to `0`."); assert_eq!( doc("u8", 64), @@ -45,12 +45,12 @@ fn builtin_docs() { #[test] fn fixed_ids_are_the_interned_ids() { let mut types = Types::new(64); - for (index, ty) in FIXED.iter().enumerate() { + for (index, ty) in builtin::FIXED.iter().enumerate() { assert_eq!(types.intern(ty.clone()), TypeId(index as u32)); } - assert_eq!(types.intern(integer(true, 32)), TypeId::I32); - assert_eq!(types.intern(integer(false, 128)), TypeId::U128); - assert_eq!(types[TypeId::U8], integer(false, 8)); + assert_eq!(types.intern(integers::integer(true, 32)), TypeId::I32); + assert_eq!(types.intern(integers::integer(false, 128)), TypeId::U128); + assert_eq!(types[TypeId::U8], integers::integer(false, 8)); assert_eq!(types[TypeId::BOOL], Type::Bool); assert_eq!(types[TypeId::F64], Type::Float(Float::F64)); assert_eq!(types[TypeId::CSTR], Type::CString); @@ -126,18 +126,62 @@ fn conversions() { target: Some(TypeId::I64), }); let cases = [ - (TypeId::U8, TypeId::I16, Conversion::Implicit), - (TypeId::I8, TypeId::I16, Conversion::Implicit), - (TypeId::U8, TypeId::U16, Conversion::Implicit), - (TypeId::F32, TypeId::F64, Conversion::Implicit), + ( + TypeId::U8, + TypeId::I16, + Conversion::Implicit(mir::Cast::ZeroExtend), + ), + ( + TypeId::I8, + TypeId::I16, + Conversion::Implicit(mir::Cast::SignExtend), + ), + ( + TypeId::U8, + TypeId::U16, + Conversion::Implicit(mir::Cast::ZeroExtend), + ), + ( + TypeId::F32, + TypeId::F64, + Conversion::Implicit(mir::Cast::FloatWiden), + ), (TypeId::I32, TypeId::I32, Conversion::Same), - (TypeId::I8, TypeId::U16, Conversion::NeedsCast), // -1 is no u16 - (TypeId::U8, TypeId::I8, Conversion::NeedsCast), // 255 is no i8 - (TypeId::I16, TypeId::I8, Conversion::NeedsCast), - (TypeId::I32, TypeId::F64, Conversion::NeedsCast), - (TypeId::F64, TypeId::I32, Conversion::NeedsCast), - (TypeId::F64, TypeId::F32, Conversion::NeedsCast), - (TypeId::BOOL, TypeId::U8, Conversion::NeedsCast), + ( + TypeId::I8, + TypeId::U16, + Conversion::NeedsCast(mir::Cast::SignExtend), + ), // -1 is no u16 + ( + TypeId::U8, + TypeId::I8, + Conversion::NeedsCast(mir::Cast::ZeroExtend), + ), // 255 is no i8 + ( + TypeId::I16, + TypeId::I8, + Conversion::NeedsCast(mir::Cast::Truncate), + ), + ( + TypeId::I32, + TypeId::F64, + Conversion::NeedsCast(mir::Cast::SignedToFloat), + ), + ( + TypeId::F64, + TypeId::I32, + Conversion::NeedsCast(mir::Cast::FloatToSigned { bits: 32 }), + ), + ( + TypeId::F64, + TypeId::F32, + Conversion::NeedsCast(mir::Cast::FloatNarrow), + ), + ( + TypeId::BOOL, + TypeId::U8, + Conversion::NeedsCast(mir::Cast::ZeroExtend), + ), (TypeId::I32, TypeId::BOOL, Conversion::Never), (TypeId::BOOL, TypeId::F64, Conversion::Never), (mutable, shared, Conversion::Reborrow), @@ -156,8 +200,16 @@ fn conversions() { (array, view, Conversion::Never), // a slice is made only with `&` (TypeId::CSTR, TypeId::I64, Conversion::Never), (to_i32, untyped, Conversion::Same), - (untyped, to_i32, Conversion::NeedsCast), - (to_i32, to_i64, Conversion::NeedsCast), + ( + untyped, + to_i32, + Conversion::NeedsCast(mir::Cast::PointerCast), + ), + ( + to_i32, + to_i64, + Conversion::NeedsCast(mir::Cast::PointerCast), + ), (untyped, TypeId::U64, Conversion::Never), ]; for (from, to, conversion) in cases { @@ -280,7 +332,7 @@ fn builtin_names() { ] { assert_eq!(lookup(name), None, "{name}"); } - assert_eq!(types[u24], integer(false, 24)); + assert_eq!(types[u24], integers::integer(false, 24)); assert_eq!( Types::new(32).builtin("usize"), Some(TypeId::U32), @@ -293,7 +345,7 @@ fn builtin_names() { #[test] fn type_text() { let mut types = Types::new(64); - let u24 = types.intern(integer(false, 24)); + let u24 = types.intern(integers::integer(false, 24)); let function = types.intern(Type::Function { parameters: [TypeId::I32, u24].into(), result: TypeId::BOOL, @@ -360,9 +412,9 @@ fn type_text() { #[test] fn equal_types_have_equal_ids() { let mut types = Types::new(64); - let u24 = types.intern(integer(false, 24)); - assert_eq!(types.intern(integer(false, 24)), u24); - assert_ne!(types.intern(integer(true, 24)), u24); + let u24 = types.intern(integers::integer(false, 24)); + assert_eq!(types.intern(integers::integer(false, 24)), u24); + assert_ne!(types.intern(integers::integer(true, 24)), u24); let function = |parameters: &[TypeId]| Type::Function { parameters: parameters.into(), result: TypeId::VOID, diff --git a/crates/kernel/model/src/thir.rs b/crates/model/src/thir.rs similarity index 99% rename from crates/kernel/model/src/thir.rs rename to crates/model/src/thir.rs index 44890e0a..b4d8e303 100644 --- a/crates/kernel/model/src/thir.rs +++ b/crates/model/src/thir.rs @@ -25,8 +25,8 @@ use arena::Node; use arena::nodes; use source::SourceFile; use source::Span; -use syntax::operators::BinaryOp; -use syntax::operators::UnaryOp; +use tree::operators::BinaryOp; +use tree::operators::UnaryOp; nodes! { Body; diff --git a/crates/kernel/syntax/lexer/Cargo.toml b/crates/syntax/lexer/Cargo.toml similarity index 100% rename from crates/kernel/syntax/lexer/Cargo.toml rename to crates/syntax/lexer/Cargo.toml diff --git a/crates/kernel/syntax/lexer/src/lib.rs b/crates/syntax/lexer/src/lib.rs similarity index 100% rename from crates/kernel/syntax/lexer/src/lib.rs rename to crates/syntax/lexer/src/lib.rs diff --git a/crates/kernel/syntax/lexer/src/tests.rs b/crates/syntax/lexer/src/tests.rs similarity index 100% rename from crates/kernel/syntax/lexer/src/tests.rs rename to crates/syntax/lexer/src/tests.rs diff --git a/crates/kernel/syntax/parser/Cargo.toml b/crates/syntax/parser/Cargo.toml similarity index 94% rename from crates/kernel/syntax/parser/Cargo.toml rename to crates/syntax/parser/Cargo.toml index 5a44b24e..9ce301ad 100644 --- a/crates/kernel/syntax/parser/Cargo.toml +++ b/crates/syntax/parser/Cargo.toml @@ -13,7 +13,7 @@ token.workspace = true lexer.workspace = true literal.workspace = true arena.workspace = true -syntax.workspace = true +tree.workspace = true [lints] workspace = true diff --git a/crates/syntax/parser/src/arrays.rs b/crates/syntax/parser/src/arrays.rs new file mode 100644 index 00000000..3701cb5e --- /dev/null +++ b/crates/syntax/parser/src/arrays.rs @@ -0,0 +1,228 @@ +//! Arrays: `[N]T` and the array literals `[N]T{ ... }` and `[_]T{ ... }`. +//! A literal's entries may spread (`values...`), which a call to a `...` +//! parameter takes too. + +use crate::Parser; +use crate::Rules; +use crate::expression; +use arena::Id; +use diagnostics::Diagnostic; +use source::Span; +use token::Token; +use token::TokenKind; +use tree::ast; + +/// Adds the rules that read array types and array literals to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.type_start(TokenKind::LeftBracket, array_type); + rules.prefix(TokenKind::LeftBracket, array_literal); +} + +/// Reads the `N]T` of `[N]T`, a type that starts at `start`, with its `[`; +/// a `[]T` alone is reported, as it has no fixed size. +fn array_type(p: &mut Parser, start: u32) -> Id { + let open = Token { + kind: TokenKind::LeftBracket, + span: Span { + start, + end: start + 1, + }, + }; + let t = p.tok(); + // `[]T` alone, read whole so the message names it and parsing goes on. + if t.kind == TokenKind::RightBracket { + p.next(); + let element = p.type_expr(); + let ty = p.add(start, ast::Type::Invalid); + // An element reported already, as `[]i32` in `[][]i32`, is the + // one mistake: its fix fixes the whole. + if let ast::Type::Invalid = p.tree.types[element] { + return ty; + } + let element = p.tree.file.slice(p.tree.types.span(element)); + let message = + format!("`[]{element}` is any number of `{element}`s, so it has no fixed size"); + let label = format!("use `[N]{element}` for a fixed array or `&[]{element}` for a slice"); + let span = p.tree.types.span(ty); + p.repair(Diagnostic::new(diagnostics::INVALID_TYPE, message).label( + &p.tree.file, + span, + label, + )); + return ty; + } + if t.kind != TokenKind::Number { + p.fail( + Diagnostic::new(diagnostics::INVALID_TYPE, "expected array length").label( + &p.tree.file, + t.span, + "use `[N]T` for fixed arrays or `&[]T` for slices", + ), + ); + return p.add(start, ast::Type::Invalid); + } + p.next(); + p.check_number(t); + p.close(TokenKind::RightBracket, open); + let element = p.type_expr(); + let length = t.span; + p.add(start, ast::Type::Array { length, element }) +} + +/// Reads `[N]T{ entries }` or `[_]T{ entries }` (the length is the number of +/// values they give); an entry is a value, or `values...`, which spreads an +/// array or a range: `(0..3)...` or `0..3...`. Without `{` after it, `[N]T` +/// is the type alone. +fn array_literal(p: &mut Parser) -> Id { + let start = p.tok().span.start; + let ty = if p.ahead(1).kind == TokenKind::Underscore { + let open = p.next(); + p.next(); + p.close(TokenKind::RightBracket, open); + let element = p.type_expr(); + ast::ArrayLiteralType::Counted { element } + } else { + let ty = p.type_expr(); + // Without entries `[N]T` is the type alone, as an argument that + // takes one; `[_]T` needs its entries to have a length. + if !p.at(TokenKind::LeftBrace) { + return p.add(start, ast::Expr::Type(ty)); + } + ast::ArrayLiteralType::Written(ty) + }; + let entries = p.delimited( + TokenKind::LeftBrace, + TokenKind::RightBrace, + false, + expression::starts_expression, + expression::spreadable, + ); + p.add(start, ast::Expr::ArrayLiteral { ty, entries }) +} + +#[cfg(test)] +mod tests { + //! Parsing arrays: the types `[N]T`, the literals `[N]T{ ... }` and + //! `[_]T{ ... }`, and their errors. + + use crate::testing; + use arena::Id; + use tree::ast; + + /// The written type `ty` with `[N]` for each array, `&[]` for each slice + /// and the innermost type's text. + fn shape(tree: &ast::Tree, ty: Id) -> String { + match tree.types[ty] { + ast::Type::Array { length, element } => { + format!("[{}]{}", tree.file.slice(length), shape(tree, element)) + } + ast::Type::Slice { element, .. } => format!("&[]{}", shape(tree, element)), + _ => tree.file.slice(tree.types.span(ty)).to_string(), + } + } + + /// `[N]T` is a type wherever a type goes, an array's element too, and + /// where a value could go when no `{` follows; `[N]T{ }` and `[_]T{ }` are + /// literals, whose entries may spread. + #[test] + fn parses_types_and_literals() { + let text = "fn f(a: [4]u8, b: [2][3]i32, c: &[][2]u8) { + g([4]i32); + [2]i32{ 1, 2 }; + [_]u8{ 1, (b)..., a... }; + }"; + let (tree, errors) = testing::parse_text(text); + assert!(errors.is_empty(), "{errors:?}"); + let decl = tree.declarations().next().unwrap(); + let ast::Decl::Function(function) = tree.decls[decl] else { + panic!("not a function") + }; + let parameters: Vec = (tree.children.lists.items(function.signature.parameters)) + .map(|parameter| shape(&tree, tree.children.params[parameter].ty)) + .collect(); + assert_eq!(parameters, ["[4]u8", "[2][3]i32", "&[][2]u8"]); + let mut literals = Vec::new(); + for id in tree.exprs.ids() { + match tree.exprs[id] { + ast::Expr::Type(ty) => literals.push(format!("type {}", shape(&tree, ty))), + ast::Expr::ArrayLiteral { ty, entries } => { + let ty = match ty { + ast::ArrayLiteralType::Written(ty) => shape(&tree, ty), + ast::ArrayLiteralType::Counted { element } => { + format!("[_]{}", shape(&tree, element)) + } + }; + let entries: Vec<&str> = (tree.children.lists.items(entries)) + .map(|entry| match tree.exprs[entry] { + ast::Expr::Spread(_) => "spread", + _ => "value", + }) + .collect(); + literals.push(format!("{ty} {}", entries.join(" "))); + } + _ => {} + } + } + assert_eq!( + literals, + [ + "type [4]i32", + "[2]i32 value value", + "[_]u8 value spread spread" + ] + ); + } + + /// A `[]T` alone has no fixed size, and is read whole, so the parser stays + /// in step and reports the next one too; an element so reported is the + /// one mistake. + #[test] + fn type_errors() { + for (text, want) in [ + ("fn f(a: [n]i32) {}", &["expected array length"][..]), + ( + "fn f(a: []i32) {}", + &["`[]i32` is any number of `i32`s, so it has no fixed size"], + ), + ( + "fn f(a: [][]i32) {}", + &["`[]i32` is any number of `i32`s, so it has no fixed size"], + ), + ( + "fn f(a: []i32, b: []u8) {}", + &[ + "`[]i32` is any number of `i32`s, so it has no fixed size", + "`[]u8` is any number of `u8`s, so it has no fixed size", + ], + ), + ("fn f() { [x]i32{}; }", &["expected array length"]), + ( + "fn f() { []i32{}; }", + &["`[]i32` is any number of `i32`s, so it has no fixed size"], + ), + ("fn f() { [_]i32; }", &["expected `{`, found `;`"]), + ] { + assert_eq!(testing::messages(text), want, "{text}"); + } + } + + /// A `;` for a `,` in a literal's `{ }` is repaired with one error per + /// list; a `;` after an unclosed literal ends the statement, so its `}` is + /// missing. + #[test] + fn separators() { + let text = "fn f() { let v = [2]i32{1; 2}; }"; + let (_, errors) = testing::parse_text(text); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].message, "expected `,` between items, found `;`"); + let mut fixed = text.to_string(); + for fix in errors[0].notes[0].fixes().iter().rev() { + fixed.replace_range(fix.span.range(), &fix.new_text); + } + assert_eq!(fixed, "fn f() { let v = [2]i32{1, 2}; }"); + assert_eq!( + testing::messages("fn f() {\n let v = [3]i32{4, 5, 6;\n return;\n}"), + ["expected `}`, found `;`"] + ); + } +} diff --git a/crates/syntax/parser/src/chars.rs b/crates/syntax/parser/src/chars.rs new file mode 100644 index 00000000..6ee39332 --- /dev/null +++ b/crates/syntax/parser/src/chars.rs @@ -0,0 +1,43 @@ +//! Character literals: `'x'` and `b'x'`. + +use arena::Id; +use token::TokenKind; +use tree::ast; + +use crate::Parser; +use crate::Rules; + +/// Adds the rules that read character literals to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.prefix(TokenKind::Char, char_literal); + rules.prefix(TokenKind::ByteChar, char_literal); +} + +/// Reads `'x'` or `b'x'`. +fn char_literal(p: &mut Parser) -> Id { + let token = p.next(); + let byte = token.kind == TokenKind::ByteChar; + p.add(token.span.start, ast::Expr::Char { byte }) +} + +#[cfg(test)] +mod tests { + //! Reading character literals. + + use crate::testing; + use tree::ast; + + /// `'x'` is a character and `b'y'` a byte, each spanning its quotes. + #[test] + fn parses_literals() { + let (tree, errors) = testing::parse_text("fn f() { 'x'; b'y'; }"); + assert!(errors.is_empty(), "{errors:?}"); + let literals: Vec<(bool, &str)> = (tree.exprs.ids()) + .filter_map(|id| match tree.exprs[id] { + ast::Expr::Char { byte } => Some((byte, tree.file.slice(tree.exprs.span(id)))), + _ => None, + }) + .collect(); + assert_eq!(literals, [(false, "'x'"), (true, "b'y'")]); + } +} diff --git a/crates/kernel/syntax/parser/src/decl.rs b/crates/syntax/parser/src/declaration.rs similarity index 70% rename from crates/kernel/syntax/parser/src/decl.rs rename to crates/syntax/parser/src/declaration.rs index c26a9af2..51d84ab7 100644 --- a/crates/kernel/syntax/parser/src/decl.rs +++ b/crates/syntax/parser/src/declaration.rs @@ -5,32 +5,33 @@ use arena::Id; use arena::List; use diagnostics::Diagnostic; use source::Span; -use syntax::ast::Attribute; -use syntax::ast::Constraint; -use syntax::ast::Decl; -use syntax::ast::Expr; -use syntax::ast::Function; -use syntax::ast::Ident; -use syntax::ast::Import; -use syntax::ast::Metadata; -use syntax::ast::Name; -use syntax::ast::Param; -use syntax::ast::Signature; -use syntax::ast::Type; -use syntax::ast::TypeDecl; -use syntax::operators::Precedence; use token::TokenKind; +use tree::ast::Attribute; +use tree::ast::Constraint; +use tree::ast::Decl; +use tree::ast::Expr; +use tree::ast::Function; +use tree::ast::Ident; +use tree::ast::Import; +use tree::ast::Metadata; +use tree::ast::Name; +use tree::ast::Param; +use tree::ast::Signature; +use tree::ast::Type; +use tree::ast::TypeDecl; +use tree::operators::Precedence; use crate::Parser; +use crate::RULES; use crate::Rules; -use crate::expr::name_or_path; -use crate::expr::starts_expression; +use crate::expression::name_or_path; +use crate::expression::starts_expression; use crate::is_name; use crate::types::starts_type; /// Reads the declaration the current keyword begins, with its doc comment and /// attributes. -pub type DeclarationRule = fn(&mut Parser, Metadata) -> Id; +pub(crate) type DeclarationRule = fn(&mut Parser, Metadata) -> Id; /// The reader of each declaration a keyword begins, indexed by token kind; /// each takes the declaration's doc comment and attributes. @@ -41,15 +42,15 @@ pub(crate) const fn declaration_rows(rules: &mut Rules) { } /// Whether `kind` begins a declaration or an import. -pub(crate) fn starts_declaration(p: &Parser, kind: TokenKind) -> bool { - p.rules.declarations[kind as usize].is_some() || kind == TokenKind::Import +pub(crate) fn starts_declaration(kind: TokenKind) -> bool { + RULES.declarations[kind as usize].is_some() || kind == TokenKind::Import } -fn starts_parameter(p: &Parser, kind: TokenKind) -> bool { +fn starts_parameter(kind: TokenKind) -> bool { matches!( kind, TokenKind::Const | TokenKind::Mut | TokenKind::Underscore | TokenKind::SelfValue - ) || starts_type(p, kind) + ) || starts_type(kind) } impl Parser { @@ -59,11 +60,11 @@ impl Parser { loop { let metadata = self.metadata(); let kind = self.tok().kind; - if starts_declaration(self, kind) { + if starts_declaration(kind) { self.recovering = false; } let first = self.tree.children.lists.items(metadata.attributes).next(); - if self.rules.declarations[kind as usize].is_none() + if RULES.declarations[kind as usize].is_none() && let Some(attribute) = first { let span = self.tree.children.attributes.span(attribute); @@ -82,7 +83,7 @@ impl Parser { return; } TokenKind::Import => imports.extend(self.import_decl()), - kind if let Some(read) = self.rules.declarations[kind as usize] => { + kind if let Some(read) = RULES.declarations[kind as usize] => { let decl = read(self, metadata); self.list_items.push(decl.into()); } @@ -113,7 +114,7 @@ impl Parser { .label(&self.tree.file, t.span, "expected a declaration here") .help("move this statement into a function", Vec::new()), ); - while !self.at(TokenKind::Eof) && !starts_declaration(self, self.tok().kind) { + while !self.at(TokenKind::Eof) && !starts_declaration(self.tok().kind) { self.next(); } } @@ -195,7 +196,7 @@ impl Parser { ); while !self.at(TokenKind::RightBracket) && !self.at(TokenKind::Eof) - && !starts_declaration(self, self.tok().kind) + && !starts_declaration(self.tok().kind) { self.next(); } @@ -224,7 +225,7 @@ impl Parser { /// Reads `name(parameters) -> Result in origins where T: Bound` /// after a function's `fn` and owner: its name and signature. - pub fn named_signature(&mut self) -> (Ident, Signature) { + pub(crate) fn named_signature(&mut self) -> (Ident, Signature) { let name = self.name(); let type_parameters = self.type_parameters(); let mut signature = self.signature(type_parameters, starts_parameter, Self::parameter); @@ -299,12 +300,7 @@ impl Parser { return List::EMPTY; } let open = self.next(); - let names = self.items( - TokenKind::Greater, - false, - |_, kind| is_name(kind), - Self::name_node, - ); + let names = self.items(TokenKind::Greater, false, is_name, Self::name_node); self.close_angle(open); names } @@ -455,7 +451,7 @@ impl Parser { pub(crate) fn signature( &mut self, type_parameters: List, - starts_parameter: fn(&Parser, TokenKind) -> bool, + starts_parameter: fn(TokenKind) -> bool, parameter: impl FnMut(&mut Self) -> Id, ) -> Signature { let parameters = self.delimited( @@ -470,7 +466,7 @@ impl Parser { if kind == TokenKind::Arrow { self.next(); result = Some(self.type_expr()); - } else if starts_type(self, kind) && !starts_declaration(self, kind) { + } else if starts_type(kind) && !starts_declaration(kind) { // A type right after the parameters can only be the result; `fn`, // `struct`, `enum` or `iface` there starts the next declaration. let at = self.here(); @@ -493,7 +489,7 @@ impl Parser { TokenKind::LeftParen, TokenKind::RightParen, false, - |_, kind| is_name(kind) || kind == TokenKind::SelfValue, + |kind| is_name(kind) || kind == TokenKind::SelfValue, Self::origin, ); } else { @@ -570,12 +566,12 @@ pub(crate) fn const_decl(p: &mut Parser, metadata: Metadata) -> Id { /// Reads `type Name = Type;`, or a keyword, a name and the rest of the /// type the keyword begins: `enum Name { variants }`. A `;` after the /// `}` is allowed. -pub fn type_decl(p: &mut Parser, metadata: Metadata) -> Id { +pub(crate) fn type_decl(p: &mut Parser, metadata: Metadata) -> Id { let keyword = p.next(); let name = p.name(); let type_parameters = p.type_parameters(); let start = p.tok().span.start; - let ty = if let Some(read) = p.rules.type_starts[keyword.kind as usize] { + let ty = if let Some(read) = RULES.type_starts[keyword.kind as usize] { read(p, start) } else { p.expect(TokenKind::Assign); @@ -600,4 +596,270 @@ pub fn type_decl(p: &mut Parser, metadata: Metadata) -> Id { } #[cfg(test)] -mod tests; +mod tests { + use crate::testing; + use crate::tests::dump_of; + use crate::tests::one_error; + + #[test] + fn parses_variadic_parameters() { + let text = "fn f(first: i32, rest: ...mut i32);\nfn g(_: ...i32);\n"; + let want = "module + function declaration + declared name f + parameter + declared name first + type name i32 + variadic parameter + declared name rest + variadic type mut + type name i32 + function declaration + declared name g + variadic parameter + variadic type + type name i32 +"; + assert!(testing::messages(text).is_empty()); + assert_eq!(dump_of(text), want); + } + + /// `const T: type` takes a type; `type` is a type only there, which the + /// checker decides, so the parser reads it in any parameter. + #[test] + fn parses_type_parameters() { + let text = "fn f(x: i32, const T: type, t: type);\n"; + let want = "module + function declaration + declared name f + parameter + declared name x + type name i32 + const parameter + declared name T + type of a type type + parameter + declared name t + type of a type type +"; + assert!(testing::messages(text).is_empty()); + assert_eq!(dump_of(text), want); + } + + /// The lexer reads `&&` as one token; in a type it is two references. + #[test] + fn parses_two_references_written_as_one_token() { + let text = "fn f(a: &&i32, b: &&mut []u8);\n"; + let want = "module + function declaration + declared name f + parameter + declared name a + reference type + reference type + type name i32 + parameter + declared name b + reference type + slice type mut + type name u8 +"; + assert!(testing::messages(text).is_empty()); + assert_eq!(dump_of(text), want); + } + + #[test] + fn parses_signatures() { + let text = "fn Counter::Add(&mut self, mut delta: i32, scale: f64 = 1, &Counter) -> &T in (self, delta) where T: Shape, U: Sized(8) {} +fn Counter::Get(&self) {} +fn Counter::Into(self) {} +fn Counter::Doubled(mut self) {} +fn exit(code: i32); +fn Use(callback: fn(value: &Box, i32) -> &Box in value, view: &[]u8, edit: &mut []u8) -> a::Box>; +"; + let want = "module + function declaration + owner type Counter + declared name Add + declared name T + declared name U + parameter + declared name self + reference type mut + self type self + parameter mut + declared name delta + type name i32 + parameter + declared name scale + type name f64 + number literal 1 + parameter + reference type + type name Counter + reference type + type name T + name reference self + name reference delta + constraint + name reference T + name reference Shape + constraint + name reference U + name reference Sized + number literal 8 + block {} + function declaration + owner type Counter + declared name Get + parameter + declared name self + reference type + self type self + block {} + function declaration + owner type Counter + declared name Into + parameter + declared name self + self type self + block {} + function declaration + owner type Counter + declared name Doubled + parameter mut + declared name self + self type self + block {} + function declaration + declared name exit + parameter + declared name code + type name i32 + function declaration + declared name Use + parameter + declared name callback + function type + parameter + declared name value + reference type + type name Box + parameter + type name i32 + reference type + type name Box + name reference value + parameter + declared name view + slice type + type name u8 + parameter + declared name edit + slice type mut + type name u8 + path + type name a + generic type + type name Box + generic type + type name Box + type name T +"; + assert!(testing::messages(text).is_empty()); + assert_eq!(dump_of(text), want); + } + + #[test] + fn signature_errors() { + for (text, message, fixed) in [ + ( + "fn f() i32 {}", + "expected `->` before the return type", + Some("fn f() -> i32 {}"), + ), + ( + "fn f(mut mut a: i32) {}", + "`mut` is repeated", + Some("fn f(mut a: i32) {}"), + ), + ( + "fn f(mut i32) {}", + "mutable parameter requires a named binding", + None, + ), + ("fn f(a: ) {}", "expected type, found `)`", None), + ("fn f() -> i32", "missing function body", None), + ("fn f() {}", "expected `,`", Some("fn f() {}")), + ] { + one_error(text, message, fixed); + } + } + + #[test] + fn parses_declarations() { + let text = r#"/// The answer. +/// Twice checked. +const Answer: i32 = 42; +const Untyped = 1; +#[extern(rt_exit)] +fn exit(code: i32); +type Alias = T; +fn Pair::new() {} +"#; + let want = r#"module + const declaration + metadata + doc comment /// The answer. +/// Twice checked. + declared name Answer + type name i32 + number literal 42 + const declaration + declared name Untyped + number literal 1 + function declaration + metadata + attribute + name reference extern + name reference rt_exit + declared name exit + parameter + declared name code + type name i32 + type alias declaration + declared name Alias + declared name T + type name T + function declaration + owner type Pair + declared name new + block {} +"#; + assert!(testing::messages(text).is_empty()); + assert_eq!(dump_of(text), want); + } + + #[test] + fn declaration_errors() { + for (text, message) in [ + ("let a = 1;", "top-level `let` not allowed"), + ("a + 1;", "module scope expects declaration"), + ( + "#[a, b] fn f();", + "only one attribute is allowed per `#[...]` block", + ), + ("fn (p: Point) f() {}", "expected `identifier`, found `(`"), + ("type A i32;", "expected `=`, found `identifier`"), + ] { + one_error(text, message, None); + } + } + + /// A `///` on the line of earlier code is not the next declaration's + /// documentation. + #[test] + fn doc_comment_after_code() { + assert!(!dump_of("const a = 1; /// about a\nconst b = 2;").contains("metadata")); + } +} diff --git a/crates/kernel/syntax/parser/src/dump.rs b/crates/syntax/parser/src/dump.rs similarity index 70% rename from crates/kernel/syntax/parser/src/dump.rs rename to crates/syntax/parser/src/dump.rs index b2a1e538..6c1bf4b3 100644 --- a/crates/kernel/syntax/parser/src/dump.rs +++ b/crates/syntax/parser/src/dump.rs @@ -8,22 +8,22 @@ use std::fmt::Write; use arena::Id; use arena::List; use source::Span; -use syntax::ast; -use syntax::ast::Attribute; -use syntax::ast::Block; -use syntax::ast::Constraint; -use syntax::ast::Decl; -use syntax::ast::Expr; -use syntax::ast::Ident; -use syntax::ast::Import; -use syntax::ast::Metadata; -use syntax::ast::Param; -use syntax::ast::Pattern; -use syntax::ast::Signature; -use syntax::ast::Stmt; -use syntax::ast::StringKind; -use syntax::ast::Tree; -use syntax::ast::Type; +use tree::ast; +use tree::ast::Attribute; +use tree::ast::Block; +use tree::ast::Constraint; +use tree::ast::Decl; +use tree::ast::Expr; +use tree::ast::Ident; +use tree::ast::Import; +use tree::ast::Metadata; +use tree::ast::Param; +use tree::ast::Pattern; +use tree::ast::Signature; +use tree::ast::Stmt; +use tree::ast::StringKind; +use tree::ast::Tree; +use tree::ast::Type; use token::TokenKind; @@ -54,6 +54,10 @@ enum Item { Stmt(Id), Pattern(Id), Expr(Id), + Field(Id), + FieldValue(Id), + Variant(Id), + MatchArm(Id), Leaf(&'static str, Span), } @@ -113,6 +117,10 @@ impl<'t> Dumper<'t> { .then_some(Item::Metadata(metadata)) } + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] fn item(&mut self, item: Item, depth: usize) { let t = self.tree; let (kind, op, span, nested): (&str, Option<&'static str>, Span, Vec) = match item { @@ -185,10 +193,11 @@ impl<'t> Dumper<'t> { ("const declaration", None, span, nested) } Decl::Type(d) | Decl::Alias(d) => { - let Decl::Alias(_) = t.decls[id] else { - unreachable!("only a feature begins a type declaration") + let kind = if let Decl::Alias(_) = t.decls[id] { + "type alias declaration" + } else { + "type declaration" }; - let kind = "type alias declaration"; let mut nested: Vec = self.metadata(d.metadata).into_iter().collect(); nested.push(declared(d.name)); nested.extend(self.names("declared name", d.type_parameters)); @@ -222,6 +231,35 @@ impl<'t> Dumper<'t> { ) } Item::Type(id) => self.type_node(id), + Item::Field(id) => { + let field = t.children.fields[id]; + let nested = vec![declared(field.name), Item::Type(field.ty)]; + ("field", None, t.children.fields.span(id), nested) + } + Item::FieldValue(id) => { + let field = t.children.field_values[id]; + let nested = vec![ + Item::Leaf("field name", field.name.span), + Item::Expr(field.value), + ]; + ( + "field value", + None, + t.children.field_values.span(id), + nested, + ) + } + Item::Variant(id) => { + let variant = t.children.variants[id]; + let mut nested = vec![declared(variant.name)]; + nested.extend(variant.payload.map(Item::Type)); + ("variant", None, t.children.variants.span(id), nested) + } + Item::MatchArm(id) => { + let arm = t.children.match_arms[id]; + let nested = vec![Item::Pattern(arm.pattern), Item::Block(arm.body)]; + ("match arm", None, t.children.match_arms.span(id), nested) + } Item::Block(id) => ( "block", None, @@ -232,16 +270,26 @@ impl<'t> Dumper<'t> { .map(Item::Stmt) .collect(), ), - Item::Stmt(id) => match t.stmts[id] { - Stmt::Block(block) => return self.item(Item::Block(block), depth), - Stmt::Const(decl) => return self.item(Item::Decl(decl), depth), - _ => self.stmt(id), - }, + // A block or a `const` statement is written as the block or the + // declaration it holds; every other statement by `stmt`. + Item::Stmt(id) => { + if let Stmt::Block(block) = t.stmts[id] { + return self.item(Item::Block(block), depth); + } + if let Stmt::Const(decl) = t.stmts[id] { + return self.item(Item::Decl(decl), depth); + } + self.stmt(id) + } Item::Pattern(id) => self.pattern(id), - Item::Expr(id) => match t.exprs[id] { - Expr::Path(ty) => return self.item(Item::Type(ty), depth), - _ => self.expr(id), - }, + // A path is written as the type it names; every other expression + // by `expr`. + Item::Expr(id) => { + if let Expr::Path(ty) = t.exprs[id] { + return self.item(Item::Type(ty), depth); + } + self.expr(id) + } }; self.write(kind, op, span, &nested, depth); } @@ -260,12 +308,45 @@ impl<'t> Dumper<'t> { nested } + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] fn type_node(&self, id: Id) -> (&'static str, Option<&'static str>, Span, Vec) { let t = self.tree; let span = t.types.span(id); let one = |ty: Id| vec![Item::Type(ty)]; let (kind, op, nested) = match t.types[id] { - Type::Feature(_) => unreachable!("the core rules read no feature type"), + Type::Array { length, element } => ( + "array type", + None, + vec![Item::Leaf("array length", length), Item::Type(element)], + ), + Type::Enum { variants } => ( + "enum type", + None, + t.children + .lists + .items(variants) + .map(Item::Variant) + .collect(), + ), + Type::Interface { methods } => ( + "interface type", + None, + t.children.lists.items(methods).map(Item::Decl).collect(), + ), + Type::Optional(inner) => ("optional type", None, one(inner)), + Type::Pointer { target } => ( + "pointer type", + None, + target.map(Item::Type).into_iter().collect(), + ), + Type::Struct { fields } => ( + "struct type", + None, + t.children.lists.items(fields).map(Item::Field).collect(), + ), Type::Name => ("type name", None, vec![]), Type::Path(segments) => ( "path", @@ -299,6 +380,10 @@ impl<'t> Dumper<'t> { (kind, op, span, nested) } + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] fn stmt(&self, id: Id) -> (&'static str, Option<&'static str>, Span, Vec) { let t = self.tree; let (kind, op, nested) = match t.stmts[id] { @@ -319,7 +404,11 @@ impl<'t> Dumper<'t> { value.map(Item::Expr).into_iter().collect(), ), Stmt::Panic(message) => ("panic statement", None, vec![Item::Expr(message)]), - Stmt::Feature(_) => unreachable!("the core rules read no feature statement"), + Stmt::Match { subject, arms } => { + let mut nested = vec![Item::Expr(subject)]; + nested.extend(t.children.lists.items(arms).map(Item::MatchArm)); + ("match statement", None, nested) + } Stmt::Expression(e) => ("expression statement", None, vec![Item::Expr(e)]), Stmt::Assign { target, value } => ( "assign statement", @@ -367,6 +456,10 @@ impl<'t> Dumper<'t> { (kind, op, t.stmts.span(id), nested) } + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] fn pattern(&self, id: Id) -> (&'static str, Option<&'static str>, Span, Vec) { let t = self.tree; let (kind, nested) = match t.patterns[id] { @@ -393,12 +486,60 @@ impl<'t> Dumper<'t> { (kind, None, t.patterns.span(id), nested) } + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] fn expr(&self, id: Id) -> (&'static str, Option<&'static str>, Span, Vec) { let t = self.tree; let one = |e: Id| vec![Item::Expr(e)]; let two = |a: Id, b: Item| vec![Item::Expr(a), b]; let (kind, op, nested) = match t.exprs[id] { - Expr::Feature(_) => unreachable!("the core rules read no feature expression"), + Expr::ArrayLiteral { ty, entries } => { + let (counted, ty) = match ty { + ast::ArrayLiteralType::Written(ty) => (None, ty), + ast::ArrayLiteralType::Counted { element } => (Some("_"), element), + }; + let mut nested = vec![Item::Type(ty)]; + nested.extend(t.children.lists.items(entries).map(Item::Expr)); + ("array literal", counted, nested) + } + Expr::CaseTest { value, case } => ("case test", None, two(value, Item::Type(case))), + Expr::Char { .. } => ("char literal", None, vec![]), + Expr::OrElse { value, fallback } => { + let fallback = match fallback { + ast::OrElseFallback::Value(fallback) => Item::Expr(fallback), + ast::OrElseFallback::Block(fallback) => Item::Block(fallback), + }; + ("orelse expression", None, two(value, fallback)) + } + Expr::Pipe { value, target } => { + ("pipe expression", None, two(value, Item::Expr(target))) + } + Expr::Print { newline, values } => ( + "print expression", + newline.then_some("ln"), + t.children.lists.items(values).map(Item::Expr).collect(), + ), + Expr::Range(written) => { + let parts = [written.start, written.end, written.step]; + ( + "range expression", + written.inclusive.then_some("..="), + parts.into_iter().flatten().map(Item::Expr).collect(), + ) + } + Expr::RawAddress(place) => ("address expression", None, one(place)), + Expr::StructLiteral { ty, fields } => { + let mut nested: Vec = ty.map(Item::Type).into_iter().collect(); + nested.extend(t.children.lists.items(fields).map(Item::FieldValue)); + ("struct literal", None, nested) + } + Expr::VariantLiteral { case, payload } => ( + "variant literal", + None, + vec![Item::Type(case), Item::Expr(payload)], + ), Expr::Name => ("name reference", None, vec![]), Expr::Number => ("number literal", None, vec![]), Expr::None => ("none literal", None, vec![]), diff --git a/crates/syntax/parser/src/enums.rs b/crates/syntax/parser/src/enums.rs new file mode 100644 index 00000000..e5c71263 --- /dev/null +++ b/crates/syntax/parser/src/enums.rs @@ -0,0 +1,387 @@ +//! Enums: the type `enum { A, B: Payload }` and its declaration, a variant +//! literal (`Enum::Case with payload`), a case test (`x is Enum::Case`) and +//! `match`. + +use crate::declaration; +use crate::is_name; +use std::num; +use tree::ast; +use tree::operators; + +use arena::Id; +use arena::List; +use diagnostics::Diagnostic; +use token::TokenKind; + +use crate::Parser; +use crate::Rules; + +/// Adds the rules that read enum types and declarations, variant +/// literals, `is` tests and `match` to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.declaration(TokenKind::Enum, declaration::type_decl); + rules.type_start(TokenKind::Enum, enum_type); + rules.infix( + TokenKind::With, + operators::Precedence::Call, + variant_literal, + ); + rules.infix(TokenKind::Is, operators::Precedence::Equality, case_test); + rules.statement(TokenKind::Match, match_statement); +} + +/// Reads `{ Name, Name: Payload, ... }`, the variants of an enum type that +/// starts at `start`. +fn enum_type(p: &mut Parser, start: u32) -> Id { + let variants = p.delimited( + TokenKind::LeftBrace, + TokenKind::RightBrace, + true, + is_name, + |p| { + let start = p.tok().span.start; + let name = p.name(); + let payload = p.at(TokenKind::Colon).then(|| { + p.next(); + p.type_expr() + }); + p.add(start, ast::Variant { name, payload }) + }, + ); + p.add(start, ast::Type::Enum { variants }) +} + +/// Reports `case` unless it is a full path `Enum::Case` (or a type already +/// reported as invalid). +fn require_path(p: &mut Parser, case: Id) { + if !matches!(p.tree.types[case], ast::Type::Path(_) | ast::Type::Invalid) { + let span = p.tree.types.span(case); + p.repair( + Diagnostic::new( + diagnostics::INVALID_EXPRESSION, + "enum case must use a fully named path", + ) + .label(&p.tree.file, span, "write `Enum::Variant`"), + ); + } +} + +/// Reads `with payload` after `case`, which is a full path `Enum::Case`. +fn variant_literal(p: &mut Parser, case: Id) -> Id { + p.next(); + let payload = p.expr(operators::Precedence::Lowest); + let path = match p.tree.exprs[case] { + ast::Expr::Path(path) if matches!(p.tree.types[path], ast::Type::Path(_)) => path, + _ => { + let span = p.tree.exprs.span(case); + p.repair( + Diagnostic::new( + diagnostics::INVALID_EXPRESSION, + "enum case must use a fully named path", + ) + .label(&p.tree.file, span, "write `Enum::Variant`"), + ); + return case; + } + }; + p.add( + p.start_of(case), + ast::Expr::VariantLiteral { + case: path, + payload, + }, + ) +} + +/// Reads `is Enum::Case` after `value`; the case is a full path. +fn case_test(p: &mut Parser, value: Id) -> Id { + p.next(); + let case = p.type_expr(); + require_path(p, case); + p.add(p.start_of(value), ast::Expr::CaseTest { value, case }) +} + +/// Reads `match subject { arms }`. An arm is `_ => { }`, `Enum::Case => { }` +/// or `Enum::Case with pattern => { }`; arms are not separated by commas. +fn match_statement(p: &mut Parser) -> Id { + let start = p.next().span.start; + let subject = p.expr(operators::Precedence::Lowest); + let mut arms = List::EMPTY; + if let Some(open) = p.expect(TokenKind::LeftBrace) { + let mut read: Vec = Vec::new(); + // Every arm begins with `_` or a path and reads at least it, so the + // loop always moves on. + while p.at(TokenKind::Underscore) || p.at(TokenKind::Ident) { + let arm_start = p.tok().span.start; + let (pattern, body) = match_arm(p); + read.push(p.add(arm_start, ast::MatchArm { pattern, body }).into()); + let t = p.tok(); + if t.kind == TokenKind::Comma { + p.next(); + let fix = p.fix(t.span, ""); + p.repair( + Diagnostic::new(diagnostics::EXPECTED_TOKEN, "match arms do not use commas") + .label(&p.tree.file, t.span, "") + .help("remove this comma", vec![fix]), + ); + } + } + arms = p.tree.children.lists.add(&read); + p.close(TokenKind::RightBrace, open); + } + p.add(start, ast::Stmt::Match { subject, arms }) +} + +/// Reads one arm's pattern, its `=>` and its block. A missing `=>` before +/// the block is read as if it were there. +fn match_arm(p: &mut Parser) -> (Id, Id) { + let t = p.tok(); + let pattern = if t.kind == TokenKind::Underscore { + let start = p.next().span.start; + p.add(start, ast::Pattern::Wildcard) + } else { + case_pattern(p) + }; + if p.at(TokenKind::LeftBrace) { + let at = p.here(); + let fix = p.fix(at, " =>"); + p.repair( + Diagnostic::new( + diagnostics::EXPECTED_TOKEN, + "expected `=>` after match case", + ) + .label(&p.tree.file, at, "") + .help("add missing `=>`", vec![fix]), + ); + } else if p.expect(TokenKind::FatArrow).is_none() { + p.sync(); + } + (pattern, p.block()) +} + +/// Reads `Enum::Case`, perhaps followed by `with` and the pattern of its +/// payload. The case is a full path. +fn case_pattern(p: &mut Parser) -> Id { + // Cases in cases, `A::B with C::D with ...`, are a deep recursion. + source::grow_stack(|| { + let start = p.tok().span.start; + let case = p.type_expr(); + require_path(p, case); + let inner = p.at(TokenKind::With).then(|| { + p.next(); + payload_pattern(p) + }); + p.add(start, ast::Pattern::Case { case, inner }) + }) +} + +/// Reads the pattern after `with`: `none`, `_`, a name to bind, +/// `.{ fields }`, or another case. +fn payload_pattern(p: &mut Parser) -> Id { + let t = p.tok(); + match t.kind { + TokenKind::None => { + p.next(); + p.add(t.span.start, ast::Pattern::None) + } + TokenKind::Underscore => { + p.next(); + p.add(t.span.start, ast::Pattern::Wildcard) + } + TokenKind::Dot => p.struct_pattern(), + TokenKind::Ident if !matches!(p.ahead(1).kind, TokenKind::ColonColon | TokenKind::Less) => { + let name = p.name(); + p.tree.add(ast::Pattern::Binding, name.span) + } + TokenKind::Ident => case_pattern(p), + _ => { + p.fail( + Diagnostic::new( + diagnostics::EXPECTED_TOKEN, + "expected a pattern after `with`", + ) + .label(&p.tree.file, t.span, "") + .help( + "write `none`, `_`, a name, `.{ field }`, or a case of the payload's enum", + Vec::new(), + ), + ); + p.add(p.here().start, ast::Pattern::Invalid) + } + } +} + +#[cfg(test)] +mod tests { + //! Reading enums and `match`, and their errors. + + use crate::testing; + use arena::Id; + use tree::ast; + + /// The pattern `pattern` as written, a case's payload pattern in + /// parentheses. + fn shape(tree: &ast::Tree, pattern: Id) -> String { + match tree.patterns[pattern] { + ast::Pattern::Case { case, inner } => { + let case = tree.file.slice(tree.types.span(case)); + match inner { + Some(inner) => format!("{case}({})", shape(tree, inner)), + None => case.to_string(), + } + } + ast::Pattern::Wildcard => "_".to_string(), + ast::Pattern::None => "none".to_string(), + ast::Pattern::Binding => { + format!("bind {}", tree.file.slice(tree.patterns.span(pattern))) + } + ast::Pattern::Struct(fields) => format!("struct of {}", fields.len()), + other => panic!("not a match pattern: {other:?}"), + } + } + + /// An enum's variants are names, each perhaps with a payload type; a + /// trailing or doubled comma is style. + #[test] + fn parses_declarations() { + let (tree, errors) = + testing::parse_text("enum Status { Ready, Waiting: Pair,, Done, }"); + assert!(errors.is_empty(), "{errors:?}"); + let decl = tree.declarations().next().unwrap(); + let ast::Decl::Type(declared) = tree.decls[decl] else { + panic!("not a type declaration") + }; + let ast::Type::Enum { variants } = tree.types[declared.ty] else { + panic!("not an enum") + }; + let found: Vec<(&str, Option<&str>)> = (tree.children.lists.items(variants)) + .map(|variant| { + let variant = tree.children.variants[variant]; + let payload = variant + .payload + .map(|ty| tree.file.slice(tree.types.span(ty))); + (tree.file.slice(variant.name.span), payload) + }) + .collect(); + assert_eq!( + found, + [ + ("Ready", None), + ("Waiting", Some("Pair")), + ("Done", None) + ] + ); + assert_eq!(testing::messages("enum E { A B }").len(), 1); + assert_eq!(testing::messages("enum E { A: }").len(), 1); + } + + /// A variant literal takes the whole expression after `with`, and a case + /// test binds as `==` does. + #[test] + fn parses_expressions() { + let (tree, errors) = + testing::parse_text("fn f() { Shape::Line with 1 + 2; a is E::B && c; }"); + assert!(errors.is_empty(), "{errors:?}"); + let found = testing::statements(&tree); + let text = |span| tree.file.slice(span); + let ast::Expr::VariantLiteral { case, payload } = tree.exprs[found[0]] else { + panic!("not a variant literal: {:?}", tree.exprs[found[0]]) + }; + assert_eq!(text(tree.types.span(case)), "Shape::Line"); + assert_eq!(text(tree.exprs.span(payload)), "1 + 2"); + let ast::Expr::Binary { left, .. } = tree.exprs[found[1]] else { + panic!("not a binary operation: {:?}", tree.exprs[found[1]]) + }; + let ast::Expr::CaseTest { value, case } = tree.exprs[left] else { + panic!("not a case test: {:?}", tree.exprs[left]) + }; + assert_eq!(text(tree.exprs.span(value)), "a"); + assert_eq!(text(tree.types.span(case)), "E::B"); + } + + /// An arm is `_`, a case, or a case with the pattern of its payload: + /// `none`, `_`, a name, a struct pattern or another case. + #[test] + fn parses_matches() { + let (tree, errors) = testing::parse_text( + "fn f() { + match shape { + Shape::Dot => { } + Shape::Line with .{ end } => { } + Shape::Maybe with none => { } + Shape::Wrap with Inner::Leaf with value => { } + Shape::Any with _ => { } + _ => { } + } + }", + ); + assert!(errors.is_empty(), "{errors:?}"); + let arms = (tree.stmts.ids()) + .find_map(|id| match tree.stmts[id] { + ast::Stmt::Match { arms, .. } => Some(arms), + _ => None, + }) + .unwrap(); + let found: Vec = (tree.children.lists.items(arms)) + .map(|arm| shape(&tree, tree.children.match_arms[arm].pattern)) + .collect(); + assert_eq!( + found, + [ + "Shape::Dot", + "Shape::Line(struct of 1)", + "Shape::Maybe(none)", + "Shape::Wrap(Inner::Leaf(bind value))", + "Shape::Any(_)", + "_" + ] + ); + } + + /// Each mistake is one error. + #[test] + fn errors() { + let path = "enum case must use a fully named path"; + for (text, message) in [ + ("a is b;", path), + ("a with 1;", path), + ("match x { a => {} }", path), + ("match x { A::B {} }", "expected `=>` after match case"), + ( + "match x { A::B => {}, _ => {} }", + "match arms do not use commas", + ), + ( + "match x { A::B with => {} }", + "expected a pattern after `with`", + ), + ] { + assert_eq!( + testing::messages(&format!("fn f() {{ {text} }}")), + [message], + "{text}" + ); + } + } + + /// Broken input still gives a tree, and nesting far deeper than the + /// thread's stack would hold still parses. + #[test] + fn broken_and_deep_input() { + for text in [ + "fn f() { A::B with ; }", + "fn f() { match }", + "fn f() { match x { }", + "fn f() { match x { let } }", + ] { + let (tree, errors) = testing::parse_text(text); + assert_eq!(tree.top_level.len(), 1, "{text}"); + assert!(!errors.is_empty(), "{text}"); + } + let deep = format!( + "fn f() {{ match x {{ {}c => {{}} }} }}", + "A::B with ".repeat(100_000) + ); + assert_eq!(testing::parse_text(&deep).0.top_level.len(), 1); + } +} diff --git a/crates/syntax/parser/src/expression.rs b/crates/syntax/parser/src/expression.rs new file mode 100644 index 00000000..f85d35d7 --- /dev/null +++ b/crates/syntax/parser/src/expression.rs @@ -0,0 +1,718 @@ +//! Expressions, read by a Pratt parser. A prefix rule reads an expression that +//! a token begins (a name, a literal, `(`); an infix rule reads what a token +//! adds after an expression on its left (an operator and its right side, a +//! call). Each token with an infix rule has a precedence: it joins the expression being read only when it +//! binds tighter than the operator before it, so precedence and associativity +//! live in the table below and not in nested grammar rules. + +use arena::Id; +use arena::List; +use diagnostics::Diagnostic; +use source::Span; +use token::TokenKind; +use tree::ast::Expr; +use tree::ast::Type; +use tree::operators::BinaryOp; +use tree::operators::Precedence; +use tree::operators::UnaryOp; + +use crate::Parser; +use crate::RULES; +use crate::Rules; + +mod literals; + +/// Reads the expression the current token begins. +pub(crate) type PrefixRule = fn(&mut Parser) -> Id; + +/// Reads what continues the path `path` in an expression, from the token +/// after it. +pub(crate) type AfterPathRule = fn(&mut Parser, Id) -> Id; + +/// Reads what the current token adds to the expression `left`. +pub(crate) type InfixRule = fn(&mut Parser, Id) -> Id; + +impl Rules { + pub(crate) const fn prefix(&mut self, kind: TokenKind, read: PrefixRule) { + assert!( + self.prefix[kind as usize].is_none(), + "two rules begin an expression with one token" + ); + self.prefix[kind as usize] = Some(read); + } + + pub(crate) const fn infix(&mut self, kind: TokenKind, precedence: Precedence, read: InfixRule) { + assert!( + self.infix[kind as usize].is_none(), + "two rules continue an expression with one token" + ); + self.infix[kind as usize] = Some((precedence, read)); + } + + /// The rule that reads what continues a path when the two tokens after + /// it are `first` and `second`. + fn after_path_rule(&self, first: TokenKind, second: TokenKind) -> Option { + let (paired, read) = self.after_path[first as usize]?; + (paired == second).then_some(read) + } + + const fn binary_operator(&mut self, kind: TokenKind, op: BinaryOp) { + self.infix(kind, op.precedence(), binary); + self.binary[kind as usize] = Some(op); + } +} + +/// Adds the rules of names, literals and operators to `rules`. +pub(crate) const fn expression_rows(rules: &mut Rules) { + // values + rules.prefix(TokenKind::Ident, name_or_path); + rules.prefix(TokenKind::SelfValue, self_name); + rules.prefix(TokenKind::Number, literals::number_literal); + rules.prefix(TokenKind::None, literals::none_literal); + rules.prefix(TokenKind::True, literals::bool_literal); + rules.prefix(TokenKind::False, literals::bool_literal); + rules.prefix(TokenKind::String, literals::string_literal); + rules.prefix(TokenKind::CString, literals::string_literal); + rules.prefix(TokenKind::LeftParen, parentheses); + + // prefix operators + rules.prefix(TokenKind::Plus, leading_plus); + rules.prefix(TokenKind::Minus, unary); + rules.prefix(TokenKind::Bang, unary); + rules.prefix(TokenKind::Tilde, unary); + rules.prefix(TokenKind::Ampersand, reference); + + // logical + rules.binary_operator(TokenKind::OrOr, BinaryOp::LogicalOr); + rules.binary_operator(TokenKind::AndAnd, BinaryOp::LogicalAnd); + + // bitwise + rules.binary_operator(TokenKind::Pipe, BinaryOp::BitOr); + rules.binary_operator(TokenKind::Caret, BinaryOp::BitXor); + rules.binary_operator(TokenKind::Ampersand, BinaryOp::BitAnd); + + // equality and comparison + rules.binary_operator(TokenKind::EqualEqual, BinaryOp::EqualTo); + rules.binary_operator(TokenKind::BangEqual, BinaryOp::NotEqualTo); + rules.binary_operator(TokenKind::Less, BinaryOp::LessThan); + rules.binary_operator(TokenKind::LessEqual, BinaryOp::LessOrEqual); + rules.binary_operator(TokenKind::Greater, BinaryOp::GreaterThan); + rules.binary_operator(TokenKind::GreaterEqual, BinaryOp::GreaterOrEqual); + + // arithmetic + rules.binary_operator(TokenKind::ShiftLeft, BinaryOp::ShiftLeft); + rules.binary_operator(TokenKind::ShiftRight, BinaryOp::ShiftRight); + rules.binary_operator(TokenKind::Plus, BinaryOp::Add); + rules.binary_operator(TokenKind::Minus, BinaryOp::Subtract); + rules.binary_operator(TokenKind::Asterisk, BinaryOp::Multiply); + rules.binary_operator(TokenKind::Slash, BinaryOp::Divide); + rules.binary_operator(TokenKind::Percent, BinaryOp::Remainder); + + // call, index and selector + rules.infix(TokenKind::LeftParen, Precedence::Call, call); + rules.infix(TokenKind::LeftBracket, Precedence::Call, index); + rules.infix(TokenKind::Dot, Precedence::Call, selector); + + rules.infix(TokenKind::As, Precedence::Cast, cast); +} + +/// Whether an expression can begin with `kind`. +pub(crate) fn starts_expression(kind: TokenKind) -> bool { + RULES.prefix[kind as usize].is_some() +} + +impl Parser { + /// Reads an expression whose operators bind tighter than `min`. + pub(crate) fn expr(&mut self, min: Precedence) -> Id { + source::grow_stack(|| { + let t = self.tok(); + let Some(read) = RULES.prefix[t.kind as usize] else { + self.fail( + Diagnostic::new( + diagnostics::EXPECTED_TOKEN, + format!("expected expression, found `{}`", t.kind.text()), + ) + .label( + &self.tree.file, + t.span, + "expected an expression here", + ), + ); + return self.add(self.last_end, Expr::Invalid); + }; + let mut left = read(self); + while let Some((precedence, read)) = RULES.infix[self.tok().kind as usize] + && precedence > min + { + left = read(self, left); + } + left + }) + } + + /// Reads the current token as an expression without children. + pub(crate) fn leaf(&mut self, node: Expr) -> Id { + let start = self.next().span.start; + self.add(start, node) + } + + /// The start of expression `id`, where an infix expression on it starts. + pub(crate) fn start_of(&self, id: Id) -> u32 { + self.tree.exprs.span(id).start + } + + /// Whether the name at the current token begins a path or a type rather + /// than standing alone: `::` follows it, or `.{`, or type arguments that + /// `::` or `.{` follow. + fn starts_path(&self) -> bool { + match self.ahead(1).kind { + TokenKind::ColonColon => true, + first => RULES.after_path_rule(first, self.ahead(2).kind).is_some(), + } + } +} + +/// Reads `self`, the name of a type's function's first parameter. +fn self_name(p: &mut Parser) -> Id { + p.leaf(Expr::Name) +} + +/// Reads a name; or, when a path or type arguments follow it, a path +/// (`a::B`, `Box::::new`) or what a feature reads after one +/// (`Point.{...}`). +pub(crate) fn name_or_path(p: &mut Parser) -> Id { + if !p.starts_path() { + return p.leaf(Expr::Name); + } + let path = p.expression_path(); + let start = p.tree.types.span(path).start; + if let Some(read) = RULES.after_path_rule(p.tok().kind, p.ahead(1).kind) { + return read(p, path); + } + p.add(start, Expr::Path(path)) +} + +/// Reads `as Type` after `value`. +fn cast(p: &mut Parser, value: Id) -> Id { + p.next(); + let ty = p.type_expr(); + p.add(p.start_of(value), Expr::Cast { value, ty }) +} + +/// Reads `( expression )`. +fn parentheses(p: &mut Parser) -> Id { + let open = p.next(); + let inner = p.expr(Precedence::Lowest); + p.close(TokenKind::RightParen, open); + p.add(open.span.start, Expr::Parentheses(inner)) +} + +/// Reads a binary operator and its right side. The right side takes only +/// operators that bind tighter, so operators of one precedence group to the +/// left: a - b - c is (a - b) - c. +fn binary(p: &mut Parser, left: Id) -> Id { + let kind = p.next().kind; + let op = RULES.binary[kind as usize].expect("binary is the rule of operator tokens only"); + let right = p.expr(op.precedence()); + p.add(p.start_of(left), Expr::Binary { op, left, right }) +} + +/// Reads the arguments of a call to `callee`. The type arguments of a +/// callee written `f::` or `a::f::` are the call's, and the callee +/// is the name or path without them. +fn call(p: &mut Parser, callee: Id) -> Id { + let start = p.start_of(callee); + let mut callee = callee; + let mut type_arguments = List::EMPTY; + if let Expr::Path(path) = p.tree.exprs[callee] { + let segments: Vec> = match p.tree.types[path] { + Type::Path(segments) => p.tree.children.lists.items(segments).collect(), + _ => vec![path], + }; + let (&last, before) = segments.split_last().expect("a path has a name"); + if let Type::Generic { name, arguments } = p.tree.types[last] { + type_arguments = arguments; + callee = if before.is_empty() { + p.tree.add(Expr::Name, name.span) + } else { + let last = p.tree.add(Type::Name, name.span); + let items: Vec<_> = before.iter().chain([&last]).map(|&s| s.into()).collect(); + let segments = p.tree.children.lists.add(&items); + let span = Span::new(start as usize, name.span.end as usize); + let path = p.tree.add(Type::Path(segments), span); + p.tree.add(Expr::Path(path), span) + }; + } + } + let arguments = p.delimited( + TokenKind::LeftParen, + TokenKind::RightParen, + false, + starts_expression, + spreadable, + ); + p.add( + start, + Expr::Call { + callee, + type_arguments, + arguments, + }, + ) +} + +/// Reads an entry of an array literal or an argument of a call: `value` or +/// `value...`. +pub(crate) fn spreadable(p: &mut Parser) -> Id { + let start = p.tok().span.start; + let value = p.expr(Precedence::Lowest); + if !p.at(TokenKind::Ellipsis) { + return value; + } + p.next(); + p.add(start, Expr::Spread(value)) +} + +/// Reads `+x` as `x`, reporting the `+`: there is no unary `+`, as it would +/// change nothing. +fn leading_plus(p: &mut Parser) -> Id { + let plus = p.next().span; + let fix = p.fix(plus, ""); + p.repair( + Diagnostic::new( + diagnostics::INVALID_EXPRESSION, + "`+` is not a prefix operator", + ) + .label(&p.tree.file, plus, "") + .help("remove it; `+x` is just `x`", vec![fix]), + ); + p.expr(Precedence::Prefix) +} + +/// Reads `-x`, `!x` or `~x`. +fn unary(p: &mut Parser) -> Id { + let token = p.next(); + let op = match token.kind { + TokenKind::Minus => UnaryOp::Negate, + TokenKind::Bang => UnaryOp::LogicalNot, + TokenKind::Tilde => UnaryOp::BitNot, + _ => unreachable!("unary is the rule of operator tokens only"), + }; + let value = p.expr(Precedence::Prefix); + p.add(token.span.start, Expr::Unary { op, value }) +} + +/// Reads `&x` or `&mut x`. +fn reference(p: &mut Parser) -> Id { + let start = p.next().span.start; + // `&[]T` and `&mut []T` are slice types; nothing after `&` reads `[]`. + let after_mut = usize::from(p.at(TokenKind::Mut)); + let open = p.ahead(after_mut); + if open.kind == TokenKind::LeftBracket && p.ahead(after_mut + 1).kind == TokenKind::RightBracket + { + let ty = p.reference_type(start); + if p.at(TokenKind::LeftBrace) { + let written = p.tree.file.slice(p.tree.types.span(ty)); + let fix = p.fix(Span::at(open.span.end as usize), "_"); + p.fail( + Diagnostic::new( + diagnostics::INVALID_EXPRESSION, + format!("`{written}` is a slice type, so it takes no values"), + ) + .label(&p.tree.file, p.tree.types.span(ty), "") + .help( + "write `[_]` to lend an array's values as a slice", + vec![fix], + ), + ); + } + return p.add(start, Expr::Type(ty)); + } + let mutable = p.at(TokenKind::Mut); + if mutable { + p.next(); + } + let value = p.expr(Precedence::Prefix); + p.add(start, Expr::Reference { mutable, value }) +} + +/// Reads `[index]` after `value`. +fn index(p: &mut Parser, value: Id) -> Id { + let open = p.next(); + let index = p.expr(Precedence::Lowest); + p.close(TokenKind::RightBracket, open); + p.add(p.start_of(value), Expr::Index { value, index }) +} + +/// Reads `.name` or `.*` after `value`. +fn selector(p: &mut Parser, value: Id) -> Id { + p.next(); + if p.at(TokenKind::Asterisk) { + p.next(); + return p.add(p.start_of(value), Expr::Dereference(value)); + } + let field = p.name(); + p.add(p.start_of(value), Expr::Selector { value, field }) +} + +#[cfg(test)] +mod tests { + use tree::ast::Decl; + use tree::ast::Stmt; + use tree::ast::StringKind; + use tree::ast::Tree; + + use super::*; + use crate::testing; + use crate::tests::dump_of; + use crate::tests::one_error; + + /// There is no unary `+`: a leading one is reported, and its fix removes it. + #[test] + fn leading_plus() { + one_error( + "fn f() { let a = +5; }", + "`+` is not a prefix operator", + Some("fn f() { let a = 5; }"), + ); + } + + /// An operator is written as the token it is read from: each binary and + /// unary operator comes from exactly one operator token, whose text is + /// the operator's symbol. + #[test] + fn operators_are_written_as_their_tokens() { + let (mut binary, mut unary) = (0, 0); + for &kind in token::OPERATORS { + for text in [ + format!("fn f() {{ a {} b; }}", kind.text()), + format!("fn f() {{ {}a; }}", kind.text()), + ] { + let (tree, errors) = testing::parse_text(&text); + if !errors.is_empty() { + continue; + } + for id in tree.exprs.ids() { + match tree.exprs[id] { + Expr::Binary { op, .. } => { + assert_eq!(op.symbol(), kind.text(), "{text}"); + binary += 1; + } + Expr::Unary { op, .. } => { + assert_eq!(op.symbol(), kind.text(), "{text}"); + unary += 1; + } + _ => {} + } + } + } + } + assert_eq!((binary, unary), (18, 3)); + } + + /// The expression of the first statement of the first function. + fn first_expression(tree: &Tree) -> Id { + let decl = tree.declarations().next().unwrap(); + let Decl::Function(f) = tree.decls[decl] else { + panic!("not a function") + }; + let statement = tree + .children + .lists + .items(tree.blocks[f.body.unwrap()].statements) + .next() + .unwrap(); + let Stmt::Expression(e) = tree.stmts[statement] else { + panic!("not an expression statement") + }; + e + } + + /// An expression with each binary operation and cast in parentheses. + fn grouped(t: &Tree, id: Id) -> String { + let text = |span| t.file.slice(span).to_string(); + match t.exprs[id] { + Expr::Cast { value, ty } => { + format!("({} as {})", grouped(t, value), text(t.types.span(ty))) + } + Expr::Binary { op, left, right } => { + format!( + "({} {} {})", + grouped(t, left), + op.symbol(), + grouped(t, right) + ) + } + Expr::Unary { value, .. } | Expr::Reference { value, .. } => { + let (span, inner) = (t.exprs.span(id), t.exprs.span(value)); + let prefix = t.file.text[span.start as usize..inner.start as usize].trim(); + let space = if let Expr::Reference { mutable: true, .. } = t.exprs[id] { + " " + } else { + "" + }; + format!("{prefix}{space}{}", grouped(t, value)) + } + Expr::Selector { value, field } => { + format!("{}.{}", grouped(t, value), text(field.span)) + } + Expr::Dereference(value) => format!("{}.*", grouped(t, value)), + Expr::Index { value, index } => { + format!("{}[{}]", grouped(t, value), text(t.exprs.span(index))) + } + Expr::Call { + callee, arguments, .. + } => { + let arguments: Vec<_> = t + .children + .lists + .items(arguments) + .map(|a| grouped(t, a)) + .collect(); + format!("{}({})", grouped(t, callee), arguments.join(", ")) + } + _ => text(t.exprs.span(id)), + } + } + + /// How operators group, from loosest to tightest, and that operators of + /// one precedence group to the left. A cast binds tighter than every binary + /// operator. + #[test] + fn precedence() { + for (text, want) in [ + ("a || b && c", "(a || (b && c))"), + ("a | b ^ c & d", "(a | (b ^ (c & d)))"), + ("a & b == c", "(a & (b == c))"), + ("a == b < c", "(a == (b < c))"), + ("a < b << c", "(a < (b << c))"), + ("a << b + c", "(a << (b + c))"), + ("a + b * c", "(a + (b * c))"), + ("a - b - c", "((a - b) - c)"), + ("a * b % c / d", "(((a * b) % c) / d)"), + ("(a + b) * f(c, d + e)", "((a + b) * f(c, (d + e)))"), + ("a != b >= c > d <= e", "(a != (((b >= c) > d) <= e))"), + ("-a * b", "(-a * b)"), + ("-a.b(c)[d]", "-a.b(c)[d]"), + ("!a && b", "(!a && b)"), + ("&mut a + b", "(&mut a + b)"), + ("x.y.z[0][i]", "x.y.z[0][i]"), + ("-r.* * r.x.*", "(-r.* * r.x.*)"), + ("&mut r.*.x", "&mut r.*.x"), + ("a + b as i64", "(a + (b as i64))"), + ("a as i32 * b", "((a as i32) * b)"), + ] { + let (tree, errors) = testing::parse_text(&format!("fn f() {{ {text}; }}")); + assert!(errors.is_empty(), "{text}: {errors:?}"); + assert_eq!(grouped(&tree, first_expression(&tree)), want, "{text}"); + } + } + + #[test] + fn parses_expressions() { + let text = r#"fn f() { + none; + Box::::new(1); + Max::(1); + list::Sum::(); + sum(1, (a)..., &mut b...); + items[n]; +} +"#; + let want = r#"module + function declaration + declared name f + block + expression statement + none literal none + expression statement + call expression + path + generic type + type name Box + type name i32 + type name new + number literal 1 + expression statement + call expression + name reference Max + type name f64 + type name i32 + number literal 1 + expression statement + call expression + path + type name list + type name Sum + type name u8 + expression statement + call expression + name reference sum + number literal 1 + spread + parentheses + name reference a + spread + reference expression mut + name reference b + expression statement + index expression + name reference items + name reference n +"#; + assert!(testing::messages(text).is_empty()); + assert_eq!(dump_of(text), want); + } + + #[test] + fn expression_errors() { + one_error("fn f() { a.; }", "expected `identifier`, found `;`", None); + } + + /// Values after a slice type are an array's, lent: `&[_]i32{ 1, 2 }`. + #[test] + fn slice_type_with_values() { + one_error( + "fn f() { let s = &[]i32{ 1, 2 }; }", + "`&[]i32` is a slice type, so it takes no values", + Some("fn f() { let s = &[_]i32{ 1, 2 }; }"), + ); + } + + /// A spelling that can only be a type is read as one where a value could go, + /// for an argument that takes a type. + #[test] + fn type_expressions() { + let text = "fn f() { g(&[]i32, &mut []u8, &x); }\n"; + let want = r#"module + function declaration + declared name f + block + expression statement + call expression + name reference g + type expression + slice type + type name i32 + type expression + slice type mut + type name u8 + reference expression + name reference x +"#; + assert!(testing::messages(text).is_empty()); + assert_eq!(dump_of(text), want); + } + + /// In an expression `<` compares; type arguments follow `::`. + #[test] + fn comparison_is_not_type_arguments() { + for (text, want) in [ + ("a < b && c > d;", "binary"), + ("Box::::new();", "call"), + ("a < b;", "binary"), + ("f(a < b, c > d);", "call"), + ("Max::(1);", "call"), + ("a < b > (c);", "binary"), + ("a < b && c > (d);", "binary"), + ] { + let (tree, errors) = testing::parse_text(&format!("fn f() {{ {text} }}")); + assert!(errors.is_empty(), "{text}: {errors:?}"); + let got = match tree.exprs[first_expression(&tree)] { + Expr::Binary { .. } => "binary", + Expr::Call { .. } => "call", + other => panic!("{text}: {other:?}"), + }; + assert_eq!(got, want, "{text}"); + } + } + + /// Number literal suffixes, with the old compiler's messages. Digits outside + /// the base are the lexer's to report; a leading zero (007) is left to a + /// later lint pass. + #[test] + fn number_checks() { + for (literal, message) in [ + ("1i", "invalid numeric literal suffix i"), + ("1i_32", "invalid numeric literal suffix i_32"), + ("1i8_", "invalid numeric literal suffix i8_"), + ("1u", "invalid numeric literal suffix u"), + ("1f", "invalid numeric literal suffix f"), + ("0b1i", "invalid numeric literal suffix i"), + ("0o7u", "invalid numeric literal suffix u"), + ( + "2.4i32", + "integer suffix i32 cannot be used on a float literal", + ), + ( + "1e3u8", + "integer suffix u8 cannot be used on a float literal", + ), + ("0", ""), + ("0.5", ""), + ("007", ""), + ("01i32", ""), + ("01f32", ""), + ("1.5f32", ""), + ("0x1f_u8", ""), + ("0xffu24", ""), + ("1_000i64", ""), + ("1e3f64", ""), + ] { + let text = format!("fn f() {{ {literal}; }}"); + let (_, errors) = testing::parse_text(&text); + if message.is_empty() { + assert!(errors.is_empty(), "{literal}: {errors:?}"); + continue; + } + let start = text.find(literal).unwrap(); + assert!( + errors.len() == 1 + && errors[0].message == message + && errors[0].labels[0].span.range() == (start..start + literal.len()), + "{literal}: {errors:?}" + ); + } + } + + /// `true` and `false` are bool literals, each spanning its word, and an + /// operand like any value. + #[test] + fn bool_literals() { + let (tree, errors) = testing::parse_text("fn f() { true; false; !true == false; }"); + assert!(errors.is_empty(), "{errors:?}"); + let literals: Vec<(bool, &str)> = (tree.exprs.ids()) + .filter_map(|id| match tree.exprs[id] { + Expr::Bool(value) => Some((value, tree.file.slice(tree.exprs.span(id)))), + _ => None, + }) + .collect(); + assert_eq!( + literals, + [ + (true, "true"), + (false, "false"), + (true, "true"), + (false, "false") + ] + ); + } + + /// `"..."` is a plain string literal and `c"..."` a C one, each spanning + /// its quotes. + #[test] + fn string_literals() { + let (tree, errors) = testing::parse_text(r#"fn f() { g("a", c"b"); }"#); + assert!(errors.is_empty(), "{errors:?}"); + let literals: Vec<(StringKind, &str)> = (tree.exprs.ids()) + .filter_map(|id| match tree.exprs[id] { + Expr::String(kind) => Some((kind, tree.file.slice(tree.exprs.span(id)))), + _ => None, + }) + .collect(); + assert_eq!( + literals, + [(StringKind::Plain, "\"a\""), (StringKind::C, "c\"b\"")] + ); + } +} diff --git a/crates/kernel/syntax/parser/src/literals.rs b/crates/syntax/parser/src/expression/literals.rs similarity index 94% rename from crates/kernel/syntax/parser/src/literals.rs rename to crates/syntax/parser/src/expression/literals.rs index 986fd964..19045e72 100644 --- a/crates/kernel/syntax/parser/src/literals.rs +++ b/crates/syntax/parser/src/expression/literals.rs @@ -2,10 +2,10 @@ use arena::Id; use diagnostics::Diagnostic; -use syntax::ast::Expr; -use syntax::ast::StringKind; use token::Token; use token::TokenKind; +use tree::ast::Expr; +use tree::ast::StringKind; use crate::Parser; @@ -13,7 +13,7 @@ impl Parser { /// Checks the type suffix of number literal `t`, the part of a number the /// lexer leaves to the parser. Whether the value fits its type is the type /// checker's to decide. - pub fn check_number(&mut self, t: Token) { + pub(crate) fn check_number(&mut self, t: Token) { let literal = literal::numeric::split(self.text(t)); let message = if literal.suffix.is_empty() { return; // most numbers diff --git a/crates/syntax/parser/src/interfaces.rs b/crates/syntax/parser/src/interfaces.rs new file mode 100644 index 00000000..129aee43 --- /dev/null +++ b/crates/syntax/parser/src/interfaces.rs @@ -0,0 +1,152 @@ +//! Interfaces: `iface { fn name(&self) -> Result, ... }`. The tree holds an +//! interface type (`ast::Type::Interface`) whose methods are function +//! signatures without bodies. + +use crate::declaration; +use arena::Id; +use token::TokenKind; +use tree::ast; + +use crate::Parser; +use crate::Rules; + +/// Adds the rules that read interfaces to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.declaration(TokenKind::Iface, declaration::type_decl); + rules.type_start(TokenKind::Iface, interface_type); +} + +/// Reads `{ fn name(parameters) -> Result, ... }`, the methods of an +/// interface type that starts at `start`: function signatures without +/// bodies. A method takes no default values. +fn interface_type(p: &mut Parser, start: u32) -> Id { + let methods = p.delimited( + TokenKind::LeftBrace, + TokenKind::RightBrace, + true, + |kind| kind == TokenKind::Fn, + |p| { + let start = p.next().span.start; + let (name, signature) = p.named_signature(); + p.add( + start, + ast::Decl::Function(ast::Function { + metadata: ast::Metadata::NONE, + owner: None, + name, + signature, + body: None, + }), + ) + }, + ); + p.add(start, ast::Type::Interface { methods }) +} + +#[cfg(test)] +mod tests { + //! Reading interfaces. + + use crate::testing; + use arena::Id; + use tree::ast; + + /// The written type `ty` in short: `&self`, `&mut self`, or its text. + fn written_type(tree: &ast::Tree, ty: Id) -> String { + match tree.types[ty] { + ast::Type::Reference { mutable, target } + if matches!(tree.types[target], ast::Type::Owner) => + { + if mutable { "&mut self" } else { "&self" }.to_string() + } + _ => tree.file.slice(tree.types.span(ty)).to_string(), + } + } + + /// Each method of the interface type `ty` as `name(name: type, ...) -> result`. + fn methods(tree: &ast::Tree, ty: Id) -> Vec { + let ast::Type::Interface { methods } = tree.types[ty] else { + panic!("not an interface type: {:?}", tree.types[ty]) + }; + let method = |id| { + let ast::Decl::Function(function) = tree.decls[id] else { + panic!("an interface holds functions") + }; + assert!(function.body.is_none(), "a method has no body"); + let signature = function.signature; + let names = tree.children.lists.items(signature.type_parameters); + let names: Vec<_> = names + .map(|name| tree.file.slice(tree.children.names.span(name))) + .collect(); + let parameters: Vec<_> = (tree.children.lists.items(signature.parameters)) + .map(|parameter| { + let ast::Param { name, ty, .. } = tree.children.params[parameter]; + let name = name.map_or("_", |name| name.text(&tree.file)); + format!("{name}: {}", written_type(tree, ty)) + }) + .collect(); + let result = signature + .result + .map(|result| format!(" -> {}", written_type(tree, result))); + format!( + "{}<{}>({}){}", + function.name.text(&tree.file), + names.join(", "), + parameters.join(", "), + result.unwrap_or_default() + ) + }; + tree.children.lists.items(methods).map(method).collect() + } + + /// An interface declaration's type is an interface type, whose methods are + /// signatures without bodies. + #[test] + fn parses_declarations() { + let text = + "iface Summer {\n fn sum(&self) -> i32,\n fn add(&mut self, value: T)\n}\n"; + let (tree, errors) = testing::parse_text(text); + assert!(errors.is_empty(), "{errors:?}"); + let declarations: Vec<_> = tree.declarations().collect(); + assert_eq!(declarations.len(), 1); + let ast::Decl::Type(declared) = tree.decls[declarations[0]] else { + panic!("not a type declaration") + }; + assert_eq!(declared.name.text(&tree.file), "Summer"); + assert_eq!( + methods(&tree, declared.ty), + [ + "sum<>(self: &self) -> i32", + "add(self: &mut self, value: T)" + ] + ); + } + + /// A method's default value is read as any function's: checking a + /// signature refuses it, for every function alike. + #[test] + fn default_values_are_read() { + let (tree, errors) = testing::parse_text("iface I { fn f(&self, a: i32 = 1) }"); + assert!(errors.is_empty()); + let ast::Decl::Type(declared) = tree.decls[tree.declarations().next().unwrap()] else { + panic!("not a type declaration") + }; + assert_eq!(methods(&tree, declared.ty), ["f<>(self: &self, a: i32)"]); + } + + /// Every span of a tree read from broken interfaces lies in the text and + /// starts before it ends. + #[test] + fn spans_lie_in_the_text() { + for text in ["iface I { fn", "iface I { fn (", "iface", "iface I {"] { + let (tree, _) = testing::parse_text(text); + let spans = (tree.types.ids().map(|id| tree.types.span(id))) + .chain(tree.decls.ids().map(|id| tree.decls.span(id))) + .chain((tree.children.params.ids()).map(|id| tree.children.params.span(id))); + for span in spans { + let (start, end) = (span.start as usize, span.end as usize); + assert!(start <= end && end <= text.len(), "{text:?}: {span:?}"); + } + } + } +} diff --git a/crates/kernel/syntax/parser/src/lib.rs b/crates/syntax/parser/src/lib.rs similarity index 84% rename from crates/kernel/syntax/parser/src/lib.rs rename to crates/syntax/parser/src/lib.rs index a07333c4..28cab822 100644 --- a/crates/kernel/syntax/parser/src/lib.rs +++ b/crates/syntax/parser/src/lib.rs @@ -15,15 +15,29 @@ //! stack segment when little stack is left, so no nesting depth overflows the //! stack. -pub mod decl; -pub mod expr; -mod literals; +mod declaration; +mod expression; mod pattern; -mod stmt; +mod statement; mod types; +// One file per concept, each with its parse rows (`rows`); the checker has +// a file of the same name for each. +mod arrays; +mod chars; +mod enums; +mod interfaces; +mod optionals; +mod pipes; +mod printing; +mod ranges; +mod raw_pointers; +mod structs; + #[cfg(test)] mod dump; +#[cfg(test)] +mod testing; use std::num::NonZeroU32; use std::sync::Arc; @@ -35,18 +49,18 @@ use diagnostics::Diagnostic; use diagnostics::fix::Fix; use source::SourceFile; use source::Span; -use syntax::ast::Ident; -use syntax::ast::Tree; -use syntax::operators::BinaryOp; -use syntax::operators::Precedence; use token::Token; use token::TokenKind; - -use crate::decl::DeclarationRule; -use crate::expr::AfterPathRule; -use crate::expr::InfixRule; -use crate::expr::PrefixRule; -use crate::stmt::StatementRule; +use tree::ast::Ident; +use tree::ast::Tree; +use tree::operators::BinaryOp; +use tree::operators::Precedence; + +use crate::declaration::DeclarationRule; +use crate::expression::AfterPathRule; +use crate::expression::InfixRule; +use crate::expression::PrefixRule; +use crate::statement::StatementRule; use crate::types::TypeStartRule; /// The rules of each token, indexed by token kind. A token without a prefix @@ -55,7 +69,7 @@ use crate::types::TypeStartRule; /// writes. A statement or declaration rule reads what its keyword begins; /// any other token begins an expression statement. Two rules for one token /// are a build error, not one replacing the other. -pub struct Rules { +pub(crate) struct Rules { prefix: [Option; 256], /// After a path, the rule of the token there when the token after it is /// the one paired with it (`Point.{` begins a struct literal). @@ -71,9 +85,9 @@ pub struct Rules { } impl Rules { - /// The core's rules, which each feature's are added to. - pub const fn core() -> Rules { - let mut rules = Rules { + /// A table with no rules. + const fn empty() -> Rules { + Rules { prefix: [None; 256], after_path: [None; 256], infix: [None; 256], @@ -81,15 +95,11 @@ impl Rules { statements: [None; 256], declarations: [None; 256], type_starts: [None; 256], - }; - expr::expression_rows(&mut rules); - stmt::statement_rows(&mut rules.statements); - decl::declaration_rows(&mut rules); - rules + } } /// Reads the statement the keyword `kind` begins with `read`. - pub const fn statement(&mut self, kind: TokenKind, read: StatementRule) { + pub(crate) const fn statement(&mut self, kind: TokenKind, read: StatementRule) { assert!( self.statements[kind as usize].is_none(), "two rules begin a statement with one token" @@ -98,7 +108,7 @@ impl Rules { } /// Reads the declaration `kind` begins with `read`. - pub const fn declaration(&mut self, kind: TokenKind, read: DeclarationRule) { + pub(crate) const fn declaration(&mut self, kind: TokenKind, read: DeclarationRule) { assert!( self.declarations[kind as usize].is_none(), "two rules begin a declaration with one token" @@ -106,12 +116,12 @@ impl Rules { self.declarations[kind as usize] = Some(read); } - /// Reads the type the token `kind` begins with `read`. A token the - /// core's types begin with cannot be one: `Parser::type_expr` reads - /// those first. - pub const fn type_start(&mut self, kind: TokenKind, read: TypeStartRule) { + /// Reads the type the token `kind` begins with `read`. A token + /// `Parser::type_expr` has an arm for cannot be one: it reads those + /// first. + pub(crate) const fn type_start(&mut self, kind: TokenKind, read: TypeStartRule) { assert!( - !types::starts_core_type(kind) && self.type_starts[kind as usize].is_none(), + !types::starts_type_expr_arm(kind) && self.type_starts[kind as usize].is_none(), "two rules begin a type with one token" ); self.type_starts[kind as usize] = Some(read); @@ -119,7 +129,12 @@ impl Rules { /// Reads with `read` what a path continues with when the token after it /// is `first` and the next one `second`. - pub const fn after_path(&mut self, first: TokenKind, second: TokenKind, read: AfterPathRule) { + pub(crate) const fn after_path( + &mut self, + first: TokenKind, + second: TokenKind, + read: AfterPathRule, + ) { assert!( self.after_path[first as usize].is_none(), "two rules continue a path with one token" @@ -128,12 +143,30 @@ impl Rules { } } -/// Returns the syntax tree of `file`, read with `rules`, and the lexical and -/// syntax errors in it. -pub fn parse(file: &Arc, rules: &'static Rules) -> (Tree, Vec) { +/// Every token's rules, built once, when the compiler is: two rules for one +/// token fail the build. +static RULES: Rules = { + let mut rules = Rules::empty(); + expression::expression_rows(&mut rules); + statement::statement_rows(&mut rules); + declaration::declaration_rows(&mut rules); + arrays::rows(&mut rules); + chars::rows(&mut rules); + enums::rows(&mut rules); + interfaces::rows(&mut rules); + optionals::rows(&mut rules); + pipes::rows(&mut rules); + printing::rows(&mut rules); + ranges::rows(&mut rules); + raw_pointers::rows(&mut rules); + structs::rows(&mut rules); + rules +}; + +/// Returns the syntax tree of `file` and the lexical and syntax errors in it. +pub fn parse(file: &Arc) -> (Tree, Vec) { let (tokens, errors) = lexer::scan(file); let mut p = Parser { - rules, tree: Tree::new(file.clone()), tokens, pos: 0, @@ -148,9 +181,7 @@ pub fn parse(file: &Arc, rules: &'static Rules) -> (Tree, Vec, pos: usize, @@ -173,17 +204,17 @@ impl Parser { i } - pub fn tok(&self) -> Token { + pub(crate) fn tok(&self) -> Token { self.tokens[self.current()] } - pub fn at(&self, kind: TokenKind) -> bool { + pub(crate) fn at(&self, kind: TokenKind) -> bool { self.tok().kind == kind } /// The token `n` tokens after the current one, or the end of file past the /// end. - pub fn ahead(&self, mut n: usize) -> Token { + pub(crate) fn ahead(&self, mut n: usize) -> Token { let mut i = self.current(); while n > 0 && self.tokens[i].kind != TokenKind::Eof { i += 1; @@ -195,11 +226,7 @@ impl Parser { self.tokens[i] } - #[expect( - clippy::should_implement_trait, - reason = "a parser moves over its tokens, which it is not an iterator of" - )] - pub fn next(&mut self) -> Token { + pub(crate) fn next(&mut self) -> Token { self.pos = self.current(); let t = self.tokens[self.pos]; if t.kind != TokenKind::Eof { @@ -210,7 +237,7 @@ impl Parser { } /// An empty span at the end of what was read. - pub fn here(&self) -> Span { + pub(crate) fn here(&self) -> Span { Span::at(self.last_end as usize) } @@ -222,7 +249,7 @@ impl Parser { self.tree.file.slice(t.span) } - pub fn fix(&self, span: Span, new_text: &str) -> Fix { + pub(crate) fn fix(&self, span: Span, new_text: &str) -> Fix { Fix { file: self.tree.file.clone(), span, @@ -233,7 +260,7 @@ impl Parser { /// Adds `node`, spanning from `start`, where the token beginning it was, to /// the end of the last token read. A node that read nothing (its start lies /// past what was read) is an empty span at the read position. - pub fn add>(&mut self, start: u32, node: T) -> Id { + pub(crate) fn add>(&mut self, start: u32, node: T) -> Id { let span = Span::new(start.min(self.last_end) as usize, self.last_end as usize); self.tree.add(node, span) } @@ -242,7 +269,7 @@ impl Parser { /// Nothing is reported while recovering already, or when a lexical error lies /// between the last token read and the current one: an illegal character /// makes no token, so the parser's error would only repeat it. - pub fn fail(&mut self, d: Diagnostic) { + pub(crate) fn fail(&mut self, d: Diagnostic) { if !self.recovering && !self.after_lexical_error() { self.errors.push(d); } @@ -252,7 +279,7 @@ impl Parser { /// Reports a mistake the parser reads past as if the missing token were /// there, so it stays in step and goes on reporting. - pub fn repair(&mut self, d: Diagnostic) { + pub(crate) fn repair(&mut self, d: Diagnostic) { if !self.recovering { self.errors.push(d); } @@ -266,7 +293,7 @@ impl Parser { }) } - pub fn expect(&mut self, kind: TokenKind) -> Option { + pub(crate) fn expect(&mut self, kind: TokenKind) -> Option { if self.at(kind) { return Some(self.next()); } @@ -326,7 +353,7 @@ impl Parser { /// at this depth, what stands before it cannot be in the list: that is /// reported, and parsing skips to the closer. Otherwise the closer is /// missing, and the error also marks `open` if it is on an earlier line. - pub fn close(&mut self, kind: TokenKind, open: Token) { + pub(crate) fn close(&mut self, kind: TokenKind, open: Token) { if self.at(kind) { self.next(); return; @@ -356,7 +383,7 @@ impl Parser { /// to a `}` closing the current block, a keyword that starts a statement, or /// the end of file. Brackets opened on the way are skipped whole, and a stray /// closing `)` or `]` is skipped. Passing a `;` puts the parser in step again. - pub fn sync(&mut self) { + pub(crate) fn sync(&mut self) { let mut depth = 0usize; while !self.at(TokenKind::Eof) { match self.tok().kind { @@ -373,7 +400,7 @@ impl Parser { self.recovering = false; return; } - kind if depth == 0 && starts_statement(self, kind) => return, + kind if depth == 0 && starts_statement(kind) => return, _ => {} } self.next(); @@ -394,7 +421,7 @@ impl Parser { &mut self, close: TokenKind, in_declaration: bool, - starts_item: fn(&Parser, TokenKind) -> bool, + starts_item: fn(TokenKind) -> bool, mut item: impl FnMut(&mut Self) -> Id, ) -> List { let mark = self.list_items.len(); @@ -404,7 +431,7 @@ impl Parser { while self.at(TokenKind::Comma) { self.next(); } - if !starts_item(self, self.tok().kind) { + if !starts_item(self.tok().kind) { break; // neither the close nor the end of file starts an item } let id = item(self); @@ -428,7 +455,7 @@ impl Parser { } // `>` is no bracket the closer scan follows; in `` the next name // can only be another item. - if starts_item(self, t.kind) + if starts_item(t.kind) && (close == TokenKind::Greater || self.tokens[self.closer_ahead()].kind == close) { missing.push(self.fix(self.here(), ",")); @@ -462,12 +489,12 @@ impl Parser { /// Reads `open`, the items of a list up to `close` (see `items`), and /// `close`. A missing `open` is reported and gives an empty list. - pub fn delimited( + pub(crate) fn delimited( &mut self, open: TokenKind, close: TokenKind, in_declaration: bool, - starts_item: fn(&Parser, TokenKind) -> bool, + starts_item: fn(TokenKind) -> bool, item: impl FnMut(&mut Self) -> Id, ) -> List { let Some(open) = self.expect(open) else { @@ -520,7 +547,7 @@ impl Parser { } /// Reads a name; a missing one is empty, where it should be. - pub fn name(&mut self) -> Ident { + pub(crate) fn name(&mut self) -> Ident { let span = match self.expect(TokenKind::Ident) { Some(t) => t.span, None => self.here(), @@ -532,7 +559,7 @@ impl Parser { /// again. A `;` missing at the end of a line, before what starts the next /// statement or closes the block, is read as if it were there: nothing /// needs skipping. Otherwise the parser skips to where parsing can go on. - pub fn end(&mut self) { + pub(crate) fn end(&mut self) { if self.at(TokenKind::Semicolon) { self.next(); self.recovering = false; @@ -543,7 +570,7 @@ impl Parser { let next_starts = matches!( t.kind, TokenKind::RightBrace | TokenKind::Eof | TokenKind::Ident - ) || starts_statement(self, t.kind); + ) || starts_statement(t.kind); if next_line && next_starts { let d = self.missing(TokenKind::Semicolon); self.repair(d); @@ -557,11 +584,11 @@ impl Parser { /// Whether `kind` begins a statement or declaration wherever it appears, so /// parsing is in step again there. -fn starts_statement(p: &Parser, kind: TokenKind) -> bool { - stmt::is_statement_keyword(p, kind) || decl::starts_declaration(p, kind) +fn starts_statement(kind: TokenKind) -> bool { + statement::is_statement_keyword(kind) || declaration::starts_declaration(kind) } -pub fn is_name(kind: TokenKind) -> bool { +pub(crate) fn is_name(kind: TokenKind) -> bool { kind == TokenKind::Ident } diff --git a/crates/syntax/parser/src/optionals.rs b/crates/syntax/parser/src/optionals.rs new file mode 100644 index 00000000..3bba58ed --- /dev/null +++ b/crates/syntax/parser/src/optionals.rs @@ -0,0 +1,122 @@ +//! Optional types and `orelse`: the parser reads `?T` and `value orelse +//! fallback`. The checker refuses both until optional values exist. + +use arena::Id; +use token::TokenKind; +use tree::ast; +use tree::operators; + +use crate::Parser; +use crate::Rules; + +/// Adds the rules that read optional types and `orelse` to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.type_start(TokenKind::Question, optional_type); + rules.type_start(TokenKind::QuestionQuestion, doubled_optional_type); + rules.infix(TokenKind::Orelse, operators::Precedence::OrElse, or_else); +} + +/// Reads the type after a `?` that starts at `start`. +fn optional_type(p: &mut Parser, start: u32) -> Id { + let inner = p.type_expr(); + p.add(start, ast::Type::Optional(inner)) +} + +/// Reads the type after a `??`, one token holding two markers. The second +/// changes nothing (`??T` is `?T`); it is kept in the tree as written and +/// left to a lint to report. +fn doubled_optional_type(p: &mut Parser, start: u32) -> Id { + let inner = optional_type(p, start + 1); + p.add(start, ast::Type::Optional(inner)) +} + +/// Reads `orelse fallback` or `orelse { block }` after `value`. The fallback +/// may itself end in `orelse`: a orelse b orelse c is a orelse (b orelse c). +fn or_else(p: &mut Parser, value: Id) -> Id { + p.next(); + let fallback = if p.at(TokenKind::LeftBrace) { + ast::OrElseFallback::Block(p.block()) + } else { + // One below OrElse: groups to the right. + ast::OrElseFallback::Value(p.expr(operators::Precedence::Lowest)) + }; + p.add(p.start_of(value), ast::Expr::OrElse { value, fallback }) +} + +#[cfg(test)] +mod tests { + //! Reading optional types and `orelse`. + + use crate::testing; + use arena::Id; + use tree::ast; + + /// `expr` with each `orelse` in parentheses; a block fallback as `{}`. + fn grouped(tree: &ast::Tree, expr: Id) -> String { + match tree.exprs[expr] { + ast::Expr::OrElse { value, fallback } => { + let fallback = match fallback { + ast::OrElseFallback::Value(fallback) => grouped(tree, fallback), + ast::OrElseFallback::Block(_) => "{}".to_string(), + }; + format!("({} orelse {fallback})", grouped(tree, value)) + } + _ => tree.file.slice(tree.exprs.span(expr)).to_string(), + } + } + + /// `orelse` groups to the right and binds looser than `||` and `..`; its + /// fallback may be a block. + #[test] + fn parses_or_else() { + let text = "fn f() { a orelse b orelse c; a || b orelse { return; }; d orelse e..f; g..h orelse i; }"; + let (tree, errors) = testing::parse_text(text); + assert!(errors.is_empty(), "{errors:?}"); + let found: Vec = (testing::statements(&tree).into_iter()) + .map(|statement| grouped(&tree, statement)) + .collect(); + assert_eq!( + found, + [ + "(a orelse (b orelse c))", + "(a || b orelse {})", + "(d orelse e..f)", + "g..h orelse i" + ] + ); + // The last one is a range whose end is the `orelse`. + let last = (tree.exprs.ids()) + .filter(|&id| matches!(tree.exprs[id], ast::Expr::OrElse { .. })) + .last() + .unwrap(); + assert_eq!(tree.file.slice(tree.exprs.span(last)), "h orelse i"); + } + + /// Each `?` is one optional type, and `??` is two; a missing fallback is + /// one error. + #[test] + fn parses_types() { + let (tree, errors) = testing::parse_text("fn f(a: ?i32, b: ??i32, c: ? ??u8);"); + assert!(errors.is_empty(), "{errors:?}"); + let optionals = (tree.types.ids()) + .filter(|&id| matches!(tree.types[id], ast::Type::Optional(_))) + .map(|id| tree.file.slice(tree.types.span(id))) + .collect::>(); + assert_eq!(optionals.len(), 6, "{optionals:?}"); + assert!(optionals.contains(&"?i32") && optionals.contains(&"??i32")); + assert_eq!(testing::messages("fn f() { a orelse ; }").len(), 1); + } + + /// Nesting far deeper than the thread's stack would hold still parses. + #[test] + fn deep_nesting_does_not_overflow() { + let n = 100_000; + for text in [ + format!("fn f() {{ let a = b{}", " orelse { c".repeat(n)), + format!("fn f(a: {}i32) {{}}", "?".repeat(n)), + ] { + let (tree, _) = testing::parse_text(&text); + assert_eq!(tree.top_level.len(), 1); + } + } +} diff --git a/crates/kernel/syntax/parser/src/pattern.rs b/crates/syntax/parser/src/pattern.rs similarity index 94% rename from crates/kernel/syntax/parser/src/pattern.rs rename to crates/syntax/parser/src/pattern.rs index 2fc5a29e..7930e368 100644 --- a/crates/kernel/syntax/parser/src/pattern.rs +++ b/crates/syntax/parser/src/pattern.rs @@ -2,7 +2,7 @@ use arena::Id; use diagnostics::Diagnostic; -use syntax::ast::Pattern; +use tree::ast::Pattern; use token::TokenKind; @@ -13,13 +13,13 @@ impl Parser { /// Reads `.{ a, b as c, _ }`: fields to bind, each by its own name or by the /// name after `as`, and a `_` for the fields left out, which must come last. /// A `=` written for `as` is read as `as`. - pub fn struct_pattern(&mut self) -> Id { + pub(crate) fn struct_pattern(&mut self) -> Id { let start = self.next().span.start; // `.` let fields = self.delimited( TokenKind::LeftBrace, TokenKind::RightBrace, false, - |_, kind| is_name(kind) || kind == TokenKind::Underscore, + |kind| is_name(kind) || kind == TokenKind::Underscore, |p| { let field_token = p.tok(); if field_token.kind == TokenKind::Underscore { diff --git a/crates/syntax/parser/src/pipes.rs b/crates/syntax/parser/src/pipes.rs new file mode 100644 index 00000000..39267a01 --- /dev/null +++ b/crates/syntax/parser/src/pipes.rs @@ -0,0 +1,67 @@ +//! Pipes: reads `value |> target` into `ast::Expr::Pipe`; the checker reads +//! the target as the call that takes the value first. + +use arena::Id; +use token::TokenKind; +use tree::ast; +use tree::operators; + +use crate::Parser; +use crate::Rules; + +/// Adds the rule that reads pipes to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.infix(TokenKind::PipeArrow, operators::Precedence::Pipe, pipe); +} + +/// Reads `|> target` after `value`. The target takes only what binds +/// tighter than a prefix operator, so `a |> len() as i32` is +/// (a |> len()) as i32. +fn pipe(p: &mut Parser, value: Id) -> Id { + p.next(); + let target = p.expr(operators::Precedence::Prefix); + let pipe = ast::Expr::Pipe { value, target }; + p.add(p.start_of(value), pipe) +} + +#[cfg(test)] +mod tests { + //! Reading pipes. + + use crate::testing; + use arena::Id; + use tree::ast; + + /// `expr` with each pipe in parentheses. + fn grouped(tree: &ast::Tree, expr: Id) -> String { + match tree.exprs[expr] { + ast::Expr::Pipe { value, target } => { + format!("({} |> {})", grouped(tree, value), grouped(tree, target)) + } + _ => tree.file.slice(tree.exprs.span(expr)).to_string(), + } + } + + /// A pipe groups to the left and binds looser than `+`; what is written + /// after its target, as `as`, takes the whole pipe. Any target is read: + /// the checker says what one may be. + #[test] + fn parses_pipes() { + let (tree, errors) = testing::parse_text( + "fn f() { a |> f(b) |> g(); a + b |> f(); a |> b; c |> len() as i32; }", + ); + assert!(errors.is_empty(), "{errors:?}"); + let found: Vec = (testing::statements(&tree).into_iter()) + .map(|statement| grouped(&tree, statement)) + .collect(); + assert_eq!( + found[..3], + ["((a |> f(b)) |> g())", "(a + b |> f())", "(a |> b)"] + ); + let last = (tree.exprs.ids()) + .filter(|&id| matches!(tree.exprs[id], ast::Expr::Pipe { .. })) + .last() + .unwrap(); + assert_eq!(tree.file.slice(tree.exprs.span(last)), "c |> len()"); + } +} diff --git a/crates/syntax/parser/src/printing.rs b/crates/syntax/parser/src/printing.rs new file mode 100644 index 00000000..944e15d0 --- /dev/null +++ b/crates/syntax/parser/src/printing.rs @@ -0,0 +1,68 @@ +//! Printing: reads `print(values)` and `println(values)` into +//! `ast::Expr::Print`, which the checker turns into calls of the prelude's +//! print functions. + +use crate::expression; +use arena::Id; +use token::TokenKind; +use tree::ast; +use tree::operators; + +use crate::Parser; +use crate::Rules; + +/// Adds the rules that read `print` and `println` to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.prefix(TokenKind::Print, print); + rules.prefix(TokenKind::Println, print); +} + +/// Reads `print(values)` or `println(values)`, which take any number of +/// values. +fn print(p: &mut Parser) -> Id { + let keyword = p.next(); + let print = ast::Expr::Print { + newline: keyword.kind == TokenKind::Println, + values: p.delimited( + TokenKind::LeftParen, + TokenKind::RightParen, + false, + expression::starts_expression, + |p| p.expr(operators::Precedence::Lowest), + ), + }; + p.add(keyword.span.start, print) +} + +#[cfg(test)] +mod tests { + //! Reading `print` and `println`. What they accept is the test programs' + //! to show. + + use crate::testing; + use tree::ast; + + /// Each takes any number of values, none too; `println` is the one with a + /// newline. + #[test] + fn parses_prints() { + let (tree, errors) = testing::parse_text("fn f() { print(); println(items[n], 1); }"); + assert!(errors.is_empty(), "{errors:?}"); + let prints: Vec<(bool, usize)> = (tree.exprs.ids()) + .filter_map(|id| match tree.exprs[id] { + ast::Expr::Print { newline, values } => Some((newline, values.len())), + _ => None, + }) + .collect(); + assert_eq!(prints, [(false, 0), (true, 2)]); + } + + /// An unclosed list is one error, and the statement after it is read. + #[test] + fn unclosed_values() { + assert_eq!( + testing::messages("fn f() { print(; return; }"), + ["expected `)`, found `;`"] + ); + } +} diff --git a/crates/syntax/parser/src/ranges.rs b/crates/syntax/parser/src/ranges.rs new file mode 100644 index 00000000..c0e22624 --- /dev/null +++ b/crates/syntax/parser/src/ranges.rs @@ -0,0 +1,151 @@ +//! Ranges: `a..b`, `a..=b`, `a..b:step`, and `..b` or `a..` before a `]`. +//! The parser reads the written parts into a `WrittenRange`, as slicing reads +//! them (`Tree::written_range`); the checker's file checks a range into the +//! built-in type `range[T]`. + +use crate::Parser; +use crate::Rules; +use arena::Id; +use diagnostics::Diagnostic; +use token::TokenKind; +use tree::ast; +use tree::operators; + +/// Adds the rules that read ranges to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.prefix(TokenKind::DotDot, open_range); + rules.prefix(TokenKind::DotDotEqual, open_range); + rules.infix(TokenKind::DotDot, operators::Precedence::Range, range); + rules.infix(TokenKind::DotDotEqual, operators::Precedence::Range, range); +} + +/// Reads a range with no start: `..b`, `..=b`, or `..` before `]`. +fn open_range(p: &mut Parser) -> Id { + let start = p.tok().span.start; + range_from(p, start, None) +} + +/// Reads a range from `low`: `a..b`, `a..=b`, or `a..` before `]`. +fn range(p: &mut Parser, low: Id) -> Id { + range_from(p, p.start_of(low), Some(low)) +} + +/// Reads `..` or `..=` and what follows it: an end, then `:step` to step by +/// more than one. Only right before the `]` may a range leave out its end. +fn range_from(p: &mut Parser, start: u32, low: Option>) -> Id { + let op = p.next(); + let mut high = None; + if !p.at(TokenKind::RightBracket) { + high = Some(p.expr(operators::Precedence::Range)); + } else if op.kind == TokenKind::DotDotEqual { + p.repair( + Diagnostic::new( + diagnostics::INVALID_EXPRESSION, + "inclusive range requires an end bound", + ) + .label( + &p.tree.file, + op.span, + "add the inclusive end bound after `..=`", + ), + ); + } + let mut step = None; + if high.is_some() && p.at(TokenKind::Colon) { + p.next(); + step = Some(p.expr(operators::Precedence::Range)); + } + let inclusive = op.kind == TokenKind::DotDotEqual; + let written = ast::WrittenRange { + inclusive, + start: low, + end: high, + step, + }; + p.add(start, ast::Expr::Range(written)) +} + +#[cfg(test)] +mod tests { + //! Parsing ranges: how a range binds, and where an end may be left out. + + use crate::testing; + use arena::Id; + use tree::ast; + + /// The expression `id` with each range and binary operation in + /// parentheses, and the rest as written. + fn grouped(tree: &ast::Tree, id: Id) -> String { + let text = |span| tree.file.slice(span).to_string(); + match tree.exprs[id] { + ast::Expr::Range(written) => { + let ast::WrittenRange { + inclusive, + start, + end, + step, + } = written; + let part = |part: Option>| { + part.map_or(String::new(), |part| grouped(tree, part)) + }; + let op = if inclusive { "..=" } else { ".." }; + let step = step.map_or(String::new(), |step| format!(":{}", grouped(tree, step))); + format!("({}{op}{}{step})", part(start), part(end)) + } + ast::Expr::Binary { op, left, right } => { + let (left, right) = (grouped(tree, left), grouped(tree, right)); + format!("({left} {} {right})", op.symbol()) + } + ast::Expr::Index { value, index } => { + format!("{}[{}]", grouped(tree, value), grouped(tree, index)) + } + _ => text(tree.exprs.span(id)), + } + } + + /// A range binds looser than every binary operator, its step is read as an end is, and ranges group to the left. + #[test] + fn precedence() { + for (text, want) in [ + ("x.y.z[0][i..j]", "x.y.z[0][(i..j)]"), + ("a + b..c * d", "((a + b)..(c * d))"), + ("a..=b:c + d", "(a..=b:(c + d))"), + ("a..b..c", "((a..b)..c)"), + ("a[..b]", "a[(..b)]"), + ("a[b..]", "a[(b..)]"), + ] { + let (tree, errors) = testing::parse_text(&format!("fn f() {{ {text}; }}")); + assert!(errors.is_empty(), "{text}: {errors:?}"); + let decl = tree.declarations().next().unwrap(); + let ast::Decl::Function(function) = tree.decls[decl] else { + panic!("not a function") + }; + let statements = tree.blocks[function.body.unwrap()].statements; + let statement = tree.children.lists.items(statements).next().unwrap(); + let ast::Stmt::Expression(expr) = tree.stmts[statement] else { + panic!("not an expression statement") + }; + assert_eq!(grouped(&tree, expr), want, "{text}"); + } + } + + /// Only right before a `]` may a range leave out its end, and an inclusive + /// one never. + #[test] + fn open_ends() { + for (text, message) in [ + ( + "fn f() { a[1..=]; }", + "inclusive range requires an end bound", + ), + ( + "fn f() { for i in 0.. { } }", + "expected expression, found `{`", + ), + ] { + let (_, errors) = testing::parse_text(text); + let got: Vec<_> = errors.iter().map(|e| e.message.as_str()).collect(); + assert_eq!(got, [message], "{text}"); + } + } +} diff --git a/crates/syntax/parser/src/raw_pointers.rs b/crates/syntax/parser/src/raw_pointers.rs new file mode 100644 index 00000000..047064e3 --- /dev/null +++ b/crates/syntax/parser/src/raw_pointers.rs @@ -0,0 +1,136 @@ +//! Raw pointers: the parser reads `rawptr`, `*T` and `@x`. The checker gives +//! them their types and addresses. + +use arena::Id; +use token::TokenKind; +use tree::ast; +use tree::operators; + +use crate::Parser; +use crate::Rules; + +/// Adds the rules that read raw pointer types and `@place` to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.type_start(TokenKind::Asterisk, typed_pointer); + rules.type_start(TokenKind::Rawptr, raw_pointer); + // types that cannot be values + rules.prefix(TokenKind::Asterisk, type_value); + rules.prefix(TokenKind::Rawptr, type_value); + rules.prefix(TokenKind::At, raw_address); +} + +/// Reads the `T` of `*T`, a pointer type that starts at `start`. +fn typed_pointer(p: &mut Parser, start: u32) -> Id { + let target = Some(p.type_expr()); + p.add(start, ast::Type::Pointer { target }) +} + +/// `rawptr`, which starts at `start`. +fn raw_pointer(p: &mut Parser, start: u32) -> Id { + p.add(start, ast::Type::Pointer { target: None }) +} + +/// Reads a type that cannot be a value (`*T`, `rawptr`) where a value could +/// go. +fn type_value(p: &mut Parser) -> Id { + let start = p.tok().span.start; + let ty = p.type_expr(); + p.add(start, ast::Expr::Type(ty)) +} + +/// Reads `@x`. +fn raw_address(p: &mut Parser) -> Id { + let start = p.next().span.start; + let place = p.expr(operators::Precedence::Prefix); + p.add(start, ast::Expr::RawAddress(place)) +} + +#[cfg(test)] +mod tests { + //! Reading raw pointers. + + use crate::testing; + use arena::Id; + use tree::ast; + + /// The written type `ty` as `*` for each pointer to a pointer, then + /// `rawptr` or the innermost type's text. + fn shape(tree: &ast::Tree, ty: Id) -> String { + match tree.types[ty] { + ast::Type::Pointer { + target: Some(target), + } => format!("*{}", shape(tree, target)), + ast::Type::Pointer { target: None } => "rawptr".to_string(), + ast::Type::Reference { target, .. } => format!("&{}", shape(tree, target)), + _ => tree.file.slice(tree.types.span(ty)).to_string(), + } + } + + /// The types of the parameters of the first function of `tree`. + fn parameter_types(tree: &ast::Tree) -> Vec { + let decl = tree.declarations().next().unwrap(); + let ast::Decl::Function(function) = tree.decls[decl] else { + panic!("not a function") + }; + (tree.children.lists.items(function.signature.parameters)) + .map(|parameter| shape(tree, tree.children.params[parameter].ty)) + .collect() + } + + /// A pointer's target is any type, a pointer or `rawptr` too, and a + /// pointer is any type's part. + #[test] + fn parses_types() { + let (tree, errors) = + testing::parse_text("fn f(a: *u8, b: **u8, c: *rawptr, d: rawptr, e: &*rawptr);"); + assert!(errors.is_empty(), "{errors:?}"); + assert_eq!( + parameter_types(&tree), + ["*u8", "**u8", "*rawptr", "rawptr", "&*rawptr"] + ); + } + + /// A spelling that can only be a type is read as one where a value could + /// go, for an argument that takes a type; `@` takes the place after it. + #[test] + fn parses_expressions() { + let (tree, errors) = testing::parse_text("fn f() { g(*Node, rawptr); @a.b; }"); + assert!(errors.is_empty(), "{errors:?}"); + let found = testing::statements(&tree); + let ast::Expr::Call { arguments, .. } = tree.exprs[found[0]] else { + panic!("not a call: {:?}", tree.exprs[found[0]]) + }; + let types: Vec = (tree.children.lists.items(arguments)) + .map(|argument| match tree.exprs[argument] { + ast::Expr::Type(ty) => shape(&tree, ty), + other => panic!("not a type: {other:?}"), + }) + .collect(); + assert_eq!(types, ["*Node", "rawptr"]); + let ast::Expr::RawAddress(place) = tree.exprs[found[1]] else { + panic!("not a raw address: {:?}", tree.exprs[found[1]]) + }; + assert_eq!(tree.file.slice(tree.exprs.span(place)), "a.b"); + } + + /// Every span of a tree read from broken pointers lies in the text and + /// starts before it ends. + #[test] + fn spans_lie_in_the_text() { + for text in [ + "fn f(a: *", + "fn f(a: *) {}", + "fn f() { @ }", + "fn f() { g(*); }", + ] { + let (tree, _) = testing::parse_text(text); + let spans = (tree.types.ids().map(|id| tree.types.span(id))) + .chain(tree.exprs.ids().map(|id| tree.exprs.span(id))) + .chain(tree.decls.ids().map(|id| tree.decls.span(id))); + for span in spans { + let (start, end) = (span.start as usize, span.end as usize); + assert!(start <= end && end <= text.len(), "{text:?}: {span:?}"); + } + } + } +} diff --git a/crates/kernel/syntax/parser/src/stmt.rs b/crates/syntax/parser/src/statement.rs similarity index 57% rename from crates/kernel/syntax/parser/src/stmt.rs rename to crates/syntax/parser/src/statement.rs index a971d613..0c542c78 100644 --- a/crates/kernel/syntax/parser/src/stmt.rs +++ b/crates/syntax/parser/src/statement.rs @@ -3,54 +3,56 @@ use arena::Id; use arena::List; use diagnostics::Diagnostic; -use syntax::ast::Block; -use syntax::ast::Expr; -use syntax::ast::Metadata; -use syntax::ast::Stmt; -use syntax::operators::BinaryOp; -use syntax::operators::Precedence; use token::TokenKind; +use tree::ast::Block; +use tree::ast::Expr; +use tree::ast::Metadata; +use tree::ast::Stmt; +use tree::operators::BinaryOp; +use tree::operators::Precedence; use crate::Parser; -use crate::decl::const_decl; -use crate::decl::starts_declaration; -use crate::expr::starts_expression; +use crate::RULES; +use crate::Rules; +use crate::declaration::const_decl; +use crate::declaration::starts_declaration; +use crate::expression::starts_expression; use crate::starts_statement; /// Reads the statement the current keyword begins. -pub type StatementRule = fn(&mut Parser) -> Id; +pub(crate) type StatementRule = fn(&mut Parser) -> Id; -/// The reader of each statement a keyword begins, indexed by token kind; any -/// other token begins an expression statement. -pub(crate) const fn statement_rows(statements: &mut [Option; 256]) { - statements[TokenKind::Let as usize] = Some(let_statement); - statements[TokenKind::Const as usize] = Some(|p| { +/// Adds the reader of each statement a keyword begins; any other token +/// begins an expression statement. +pub(crate) const fn statement_rows(rules: &mut Rules) { + rules.statement(TokenKind::Let, let_statement); + rules.statement(TokenKind::Const, |p| { let decl = const_decl(p, Metadata::NONE); let span = p.tree.decls.span(decl); p.tree.add(Stmt::Const(decl), span) }); - statements[TokenKind::Return as usize] = Some(return_statement); - statements[TokenKind::Panic as usize] = Some(panic_statement); - statements[TokenKind::If as usize] = Some(if_statement); - statements[TokenKind::For as usize] = Some(for_statement); - statements[TokenKind::Break as usize] = Some(jump_statement); - statements[TokenKind::Continue as usize] = Some(jump_statement); - statements[TokenKind::LeftBrace as usize] = Some(|p| { + rules.statement(TokenKind::Return, return_statement); + rules.statement(TokenKind::Panic, panic_statement); + rules.statement(TokenKind::If, if_statement); + rules.statement(TokenKind::For, for_statement); + rules.statement(TokenKind::Break, jump_statement); + rules.statement(TokenKind::Continue, jump_statement); + rules.statement(TokenKind::LeftBrace, |p| { let block = p.block(); p.block_statement(block) }); } /// Whether `kind` begins a statement other than an expression statement. -pub(crate) fn is_statement_keyword(p: &Parser, kind: TokenKind) -> bool { - p.rules.statements[kind as usize].is_some() +pub(crate) fn is_statement_keyword(kind: TokenKind) -> bool { + RULES.statements[kind as usize].is_some() } impl Parser { /// Reads a block. A keyword that begins a declaration but not a statement /// means its `}` is missing: the block ends there and the declaration is /// read next. - pub fn block(&mut self) -> Id { + pub(crate) fn block(&mut self) -> Id { let Some(open) = self.expect(TokenKind::LeftBrace) else { return self.add( self.last_end, @@ -64,7 +66,7 @@ impl Parser { let kind = self.tok().kind; if kind == TokenKind::RightBrace || kind == TokenKind::Eof - || starts_declaration(self, kind) && !is_statement_keyword(self, kind) + || starts_declaration(kind) && !is_statement_keyword(kind) { break; } @@ -73,7 +75,7 @@ impl Parser { self.next(); continue; } - if starts_statement(self, kind) { + if starts_statement(kind) { self.recovering = false; } let statement = self.stmt(); @@ -91,7 +93,7 @@ impl Parser { /// an assignment `target = value;`. fn stmt(&mut self) -> Id { source::grow_stack(|| { - if let Some(read) = self.rules.statements[self.tok().kind as usize] { + if let Some(read) = RULES.statements[self.tok().kind as usize] { return read(self); } let start = self.tok().span.start; @@ -292,7 +294,7 @@ fn jump_statement(p: &mut Parser) -> Id { /// begin one, such as the `}` after a `return` missing its `;`, ends it. fn return_statement(p: &mut Parser) -> Id { let start = p.next().span.start; - let value = starts_expression(p, p.tok().kind).then(|| p.expr(Precedence::Lowest)); + let value = starts_expression(p.tok().kind).then(|| p.expr(Precedence::Lowest)); p.end(); p.add(start, Stmt::Return(value)) } @@ -306,4 +308,171 @@ fn panic_statement(p: &mut Parser) -> Id { } #[cfg(test)] -mod tests; +mod tests { + use tree::ast::Stmt; + + use crate::testing; + use crate::tests::dump_of; + use crate::tests::one_error; + + /// A `return` without a value needs only its `;`: one missing at a line + /// end is read past with a fix, one missing inside a line is reported. + #[test] + fn lone_return() { + one_error( + "fn f() {\n return\n}", + "expected `;`, found `}`", + Some("fn f() {\n return;\n}"), + ); + one_error("fn f() { return }", "expected `;`, found `}`", None); + } + + #[test] + fn parses_statements() { + let text = "fn f() { + let mut n: i32 = 0; + let .{ x, y as z, _ } = point; + const limit = 10; + n = n + 1; + if n == 1 { } else if n == 2 { } else { } + for { break; } + for n < limit { continue; } + for item in items { } + for i, item in items { } + for n { } + for v in values { } + { } +} +"; + let want = "module + function declaration + declared name f + block + let statement mut + declared name n + type name i32 + number literal 0 + destructure statement + struct pattern + field pattern + field name x + field pattern + field name y + declared name z + rest pattern _ + name reference point + const declaration + declared name limit + number literal 10 + assign statement + name reference n + binary expression + + name reference n + number literal 1 + if statement + binary expression == + name reference n + number literal 1 + block { } + if statement + binary expression == + name reference n + number literal 2 + block { } + block { } + loop statement + block + break statement break; + loop statement + binary expression < + name reference n + name reference limit + block + continue statement continue; + for in statement + declared name item + name reference items + block { } + for in statement + declared name i + declared name item + name reference items + block { } + loop statement + name reference n + block { } + for in statement + declared name v + name reference values + block { } + block { } +"; + assert!(testing::messages(text).is_empty()); + assert_eq!(dump_of(text), want); + } + + /// `if a = b` is read as the comparison it was meant to be. + #[test] + fn assignment_in_condition_is_read_as_equal_to() { + let (tree, _) = testing::parse_text("fn f() { if a = b {} }"); + let condition = tree + .stmts + .ids() + .find_map(|statement| match tree.stmts[statement] { + tree::ast::Stmt::If { condition, .. } => Some(condition), + _ => None, + }) + .expect("an if statement"); + assert!(matches!( + tree.exprs[condition], + tree::ast::Expr::Binary { + op: tree::operators::BinaryOp::EqualTo, + .. + } + )); + } + + #[test] + fn statement_errors() { + for (text, message, fixed) in [ + ( + "if a = b {}", + "expected `==` in condition, found `=`", + Some("if a == b {}"), + ), + ("if a", "missing if body", None), + ("if a {} else", "missing else body", None), + ("for x in items", "missing for body", None), + ("for a.b in x {}", "invalid loop variable", None), + ("break outer;", "labeled break is not supported yet", None), + ( + "let .{ a = b } = v;", + "a destructure field is renamed with `as`", + Some("let .{ a as b } = v;"), + ), + ( + "let .{ _, a } = v;", + "`_` must be the last destructure item", + None, + ), + ] { + let fixed = fixed.map(|f| format!("fn f() {{ {f} }}")); + one_error(&format!("fn f() {{ {text} }}"), message, fixed.as_deref()); + } + } + + /// `panic` takes one expression and ends with `;`. + #[test] + fn panics() { + let (tree, errors) = testing::parse_text("fn f() { panic \"stop\"; panic (message); }"); + assert!(errors.is_empty(), "{errors:?}"); + let found: Vec<&str> = (tree.stmts.ids()) + .filter_map(|id| match tree.stmts[id] { + Stmt::Panic(message) => Some(tree.file.slice(tree.exprs.span(message))), + _ => None, + }) + .collect(); + assert_eq!(found, ["\"stop\"", "(message)"]); + assert_eq!(testing::messages("fn f() { panic ; }").len(), 1); + } +} diff --git a/crates/syntax/parser/src/structs.rs b/crates/syntax/parser/src/structs.rs new file mode 100644 index 00000000..815a11e8 --- /dev/null +++ b/crates/syntax/parser/src/structs.rs @@ -0,0 +1,312 @@ +//! Structs: `struct { name: Type, ... }` and `Type.{ name = value, ... }`. +//! The tree holds a struct type (`ast::Type::Struct`) and a struct literal +//! (`ast::Expr::StructLiteral`), with `ast::Field` and `ast::FieldValue`. +//! Reading a field, as in `point.x`, is an infix rule of `expression.rs`. + +use crate::declaration; +use crate::is_name; +use arena::Id; +use diagnostics::Diagnostic; +use token::TokenKind; +use tree::ast; +use tree::operators; + +use crate::Parser; +use crate::Rules; + +/// Adds the rules that read struct types, declarations and literals +/// to `rules`. +pub(crate) const fn rows(rules: &mut Rules) { + rules.declaration(TokenKind::Struct, declaration::type_decl); + rules.type_start(TokenKind::Struct, struct_type); + rules.prefix(TokenKind::Dot, anonymous_literal); + rules.after_path(TokenKind::Dot, TokenKind::LeftBrace, typed_literal); +} + +/// Reads `{ name: Type, ... }`, the fields of a struct type that starts at +/// `start`. +fn struct_type(p: &mut Parser, start: u32) -> Id { + let fields = p.delimited( + TokenKind::LeftBrace, + TokenKind::RightBrace, + true, + is_name, + |p| { + let start = p.tok().span.start; + let name = p.name(); + p.expect(TokenKind::Colon); + let ty = p.type_expr(); + p.add(start, ast::Field { name, ty }) + }, + ); + p.add(start, ast::Type::Struct { fields }) +} + +/// Reads `.{ name = value, ... }`, a struct literal without a type. +fn anonymous_literal(p: &mut Parser) -> Id { + let start = p.tok().span.start; + literal(p, None, start) +} + +/// Reads `.{ name = value, ... }` after the type `path`. +fn typed_literal(p: &mut Parser, path: Id) -> Id { + let start = p.tree.types.span(path).start; + literal(p, Some(path), start) +} + +/// Reads `.{ name = value, ... }` after `ty` (none when there is no type), a +/// literal that starts at `start`. A `name: value` field, the colon of a +/// declaration where a field is set, is read as if it were `=`, and all such +/// colons are reported in one error. +fn literal(p: &mut Parser, ty: Option>, start: u32) -> Id { + p.next(); // `.` + let mut colons = Vec::new(); + let fields = p.delimited( + TokenKind::LeftBrace, + TokenKind::RightBrace, + false, + is_name, + |p| { + let field_start = p.tok().span.start; + let name = p.name(); + let t = p.tok(); + if t.kind == TokenKind::Colon { + p.next(); + colons.push(p.fix(t.span, " =")); + } else { + p.expect(TokenKind::Assign); + } + let value = p.expr(operators::Precedence::Lowest); + p.add(field_start, ast::FieldValue { name, value }) + }, + ); + if !colons.is_empty() { + let d = Diagnostic::new( + diagnostics::EXPECTED_TOKEN, + "expected `=` after struct literal field name", + ) + .label(&p.tree.file, colons[0].span, ""); + p.repair(d.help("set a field with `=`", colons)); + } + p.add(start, ast::Expr::StructLiteral { ty, fields }) +} + +#[cfg(test)] +mod tests { + //! Reading structs. + + use crate::testing; + use arena::Id; + use diagnostics::Diagnostic; + use source::Span; + use tree::ast; + + /// `text` with the fixes of the first help of `d` applied. + fn fixed(text: &str, d: &Diagnostic) -> String { + let mut text = text.to_string(); + for fix in d.notes[0].fixes().iter().rev() { + text.replace_range(fix.span.range(), &fix.new_text); + } + text + } + + /// Checks that `text` gives exactly one error, `message`, and that its fix + /// (when `want_fixed` is given) gives `want_fixed`. + fn one_error(text: &str, message: &str, want_fixed: Option<&str>) { + let (_, errors) = testing::parse_text(text); + let got: Vec<_> = errors.iter().map(|e| e.message.as_str()).collect(); + assert_eq!(got, [message], "{text:?}"); + if let Some(want) = want_fixed { + assert_eq!(fixed(text, &errors[0]), want, "{text:?}"); + } + } + + fn written(tree: &ast::Tree, span: Span) -> &str { + tree.file.slice(span) + } + + /// The fields of the struct type `ty`: each as `name: type`, the type as + /// written, and the type. + fn fields(tree: &ast::Tree, ty: Id) -> Vec<(String, Id)> { + let ast::Type::Struct { fields } = tree.types[ty] else { + panic!("not a struct type: {:?}", tree.types[ty]) + }; + let field = |id| { + let ast::Field { name, ty } = tree.children.fields[id]; + let field = format!( + "{}: {}", + name.text(&tree.file), + written(tree, tree.types.span(ty)) + ); + (field, ty) + }; + tree.children.lists.items(fields).map(field).collect() + } + + /// The struct literal `expr`: its type as written, if any, and each field + /// as `name = value`, the value as written. + fn literal(tree: &ast::Tree, expr: Id) -> (Option<&str>, Vec) { + let ast::Expr::StructLiteral { ty, fields } = tree.exprs[expr] else { + panic!("not a struct literal: {:?}", tree.exprs[expr]) + }; + let field = |id| { + let ast::FieldValue { name, value } = tree.children.field_values[id]; + format!( + "{} = {}", + name.text(&tree.file), + written(tree, tree.exprs.span(value)) + ) + }; + let ty = ty.map(|ty| written(tree, tree.types.span(ty))); + (ty, tree.children.lists.items(fields).map(field).collect()) + } + + /// A struct declaration's type is a struct type, which a field's type can + /// be too; a `;` after its `}` is allowed. + #[test] + fn parses_declarations() { + let text = "struct Pair {\n first: T,\n second: struct { flag: bool },\n};\n"; + let (tree, errors) = testing::parse_text(text); + assert!(errors.is_empty(), "{errors:?}"); + let declarations: Vec<_> = tree.declarations().collect(); + assert_eq!(declarations.len(), 1); + let ast::Decl::Type(declared) = tree.decls[declarations[0]] else { + panic!("not a type declaration") + }; + assert_eq!(declared.name.text(&tree.file), "Pair"); + assert_eq!(declared.type_parameters.len(), 1); + let found = fields(&tree, declared.ty); + let names: Vec<_> = found.iter().map(|(field, _)| field.as_str()).collect(); + assert_eq!(names, ["first: T", "second: struct { flag: bool }"]); + let nested = fields(&tree, found[1].1); + assert_eq!(nested[0].0, "flag: bool"); + assert_eq!(nested.len(), 1); + } + + #[test] + fn declaration_errors() { + one_error( + "struct S { a i32 }", + "expected `:`, found `identifier`", + None, + ); + } + + /// A literal with a type, without one, and as an argument. + #[test] + fn parses_expressions() { + let text = "fn f() {\n Point.{ x = 1, y = -2 };\n .{ a = &mut v, b = !flag };\n line(.{ end = Box::::new(1) });\n}\n"; + let (tree, errors) = testing::parse_text(text); + assert!(errors.is_empty(), "{errors:?}"); + let found = testing::statements(&tree); + assert_eq!( + literal(&tree, found[0]), + (Some("Point"), vec!["x = 1".into(), "y = -2".into()]) + ); + assert_eq!( + literal(&tree, found[1]), + (None, vec!["a = &mut v".into(), "b = !flag".into()]) + ); + let ast::Expr::Call { arguments, .. } = tree.exprs[found[2]] else { + panic!("not a call") + }; + let argument = tree.children.lists.items(arguments).next().unwrap(); + assert_eq!( + literal(&tree, argument), + (None, vec!["end = Box::::new(1)".into()]) + ); + } + + #[test] + fn expression_errors() { + one_error( + "fn f() { .{ a: 1, b: 2 }; }", + "expected `=` after struct literal field name", + None, + ); + } + + /// In an expression, type arguments follow `::`, before `.{` too. + #[test] + fn comparison_is_not_type_arguments() { + let (tree, errors) = testing::parse_text("fn f() { Pair::.{}; }"); + assert!(errors.is_empty(), "{errors:?}"); + assert_eq!( + literal(&tree, testing::statements(&tree)[0]), + (Some("Pair::"), Vec::new()) + ); + } + + /// Every span of a tree read from broken structs lies in the text and + /// starts before it ends. + #[test] + fn spans_lie_in_the_text() { + for text in [ + "fn f() { .{ a = }; }", + "fn f() { .{ a: 1, b: 2 }; }", + "fn f() { a::.{}; }", + "struct", + "struct S {", + "struct S { a: }", + "struct S {} struct", + "fn f() {\nstruct S {}", + ] { + let (tree, _) = testing::parse_text(text); + let spans = (tree.exprs.ids().map(|id| tree.exprs.span(id))) + .chain(tree.types.ids().map(|id| tree.types.span(id))) + .chain(tree.decls.ids().map(|id| tree.decls.span(id))) + .chain(tree.stmts.ids().map(|id| tree.stmts.span(id))) + .chain(tree.blocks.ids().map(|id| tree.blocks.span(id))) + .chain( + tree.children + .fields + .ids() + .map(|id| tree.children.fields.span(id)), + ) + .chain( + (tree.children.field_values.ids()) + .map(|id| tree.children.field_values.span(id)), + ); + for span in spans { + let (start, end) = (span.start as usize, span.end as usize); + assert!(start <= end && end <= text.len(), "{text:?}: {span:?}"); + } + } + } + + /// A closer that comes later means what stands before it does not belong: + /// that is reported once, and the list ends at its own closer. + #[test] + fn missing_token_place() { + let (tree, errors) = + testing::parse_text("fn f() { let p = Point.{ .x = 1, y = 2 }; }\nfn g() {}"); + let got: Vec<_> = errors.iter().map(|e| e.message.as_str()).collect(); + assert_eq!(got, ["expected `}`, found `.`"]); + assert_eq!(tree.top_level.len(), 2); + } + + /// Extra and trailing commas are left to a lint; a `;` for a `,` is + /// repaired with one error per list. + #[test] + fn separators() { + for text in [ + "struct S { a: i32, b: i32, }", + "fn f() { let p = .{ a = 1,, }; }", + ] { + assert!(testing::messages(text).is_empty(), "{text:?}"); + } + for (text, want) in [ + ("struct S { a: i32; b: i32 }", "struct S { a: i32, b: i32 }"), + ( + "struct S { a: i32; b: i32; }", + "struct S { a: i32, b: i32 }", + ), + ( + "fn f() { let p = .{ a = 1; b = 2 }; }", + "fn f() { let p = .{ a = 1, b = 2 }; }", + ), + ] { + one_error(text, "expected `,` between items, found `;`", Some(want)); + } + } +} diff --git a/crates/syntax/parser/src/testing.rs b/crates/syntax/parser/src/testing.rs new file mode 100644 index 00000000..9a8635c4 --- /dev/null +++ b/crates/syntax/parser/src/testing.rs @@ -0,0 +1,37 @@ +//! What the parser's tests share: a text read as Peeper. + +use std::sync::Arc; + +use arena::Id; +use diagnostics::Diagnostic; +use source::SourceFile; +use tree::ast; + +/// The tree of `text` and its syntax errors. +pub(crate) fn parse_text(text: &str) -> (ast::Tree, Vec) { + crate::parse(&Arc::new(SourceFile::new("t.peep", text))) +} + +/// The message of each syntax error of `text`. +pub(crate) fn messages(text: &str) -> Vec { + let (_, errors) = parse_text(text); + errors.into_iter().map(|error| error.message).collect() +} + +/// The expressions of the statements of the first function of `tree`. +pub(crate) fn statements(tree: &ast::Tree) -> Vec> { + let decl = tree.declarations().next().unwrap(); + let ast::Decl::Function(function) = tree.decls[decl] else { + panic!("not a function") + }; + let statements = tree.blocks[function.body.unwrap()].statements; + let expression = |statement| match tree.stmts[statement] { + ast::Stmt::Expression(expr) => expr, + other => panic!("not an expression statement: {other:?}"), + }; + tree.children + .lists + .items(statements) + .map(expression) + .collect() +} diff --git a/crates/kernel/syntax/parser/src/tests.rs b/crates/syntax/parser/src/tests.rs similarity index 70% rename from crates/kernel/syntax/parser/src/tests.rs rename to crates/syntax/parser/src/tests.rs index cb45d277..6cc6922d 100644 --- a/crates/kernel/syntax/parser/src/tests.rs +++ b/crates/syntax/parser/src/tests.rs @@ -1,21 +1,10 @@ use super::*; -/// The core's rules alone: the parser's tests read no feature, since the -/// `features` crate depends on this one. -static RULES: Rules = Rules::core(); - -pub(crate) fn parse_text(text: &str) -> (Tree, Vec) { - parse(&Arc::new(SourceFile::new("t.peep", text)), &RULES) -} +use crate::testing; /// The tree of `text` in the dump format. pub(crate) fn dump_of(text: &str) -> String { - dump::dump(&parse_text(text).0, false) -} - -/// The error messages for `text`. -pub(crate) fn messages(text: &str) -> Vec { - parse_text(text).1.into_iter().map(|e| e.message).collect() + dump::dump(&testing::parse_text(text).0, false) } /// `text` with the fixes of the first help of `d` applied. @@ -30,7 +19,7 @@ pub(crate) fn fixed(text: &str, d: &Diagnostic) -> String { /// Checks that `text` gives exactly one error, `message`, and that its fix /// (when `want_fixed` is given) gives `want_fixed`. pub(crate) fn one_error(text: &str, message: &str, want_fixed: Option<&str>) { - let (_, errors) = parse_text(text); + let (_, errors) = testing::parse_text(text); let got: Vec<_> = errors.iter().map(|e| e.message.as_str()).collect(); assert_eq!(got, [message], "{text:?}"); if let Some(want) = want_fixed { @@ -101,14 +90,14 @@ fn parses_a_program() { name reference x return statement return; "#; - assert!(messages(PROGRAM).is_empty()); + assert!(testing::messages(PROGRAM).is_empty()); assert_eq!(dump_of(PROGRAM), want); } #[test] fn recovers_after_a_missing_semicolon() { let text = "fn f() { let a = 1 let b = 2; return b; }"; - let errors = messages(text); + let errors = testing::messages(text); assert!( errors.len() == 1 && errors[0].contains("expected `;`"), "{errors:?}" @@ -122,7 +111,7 @@ fn underscore_binds_nothing() { for _, v in xs {} let .{ b, _ } = s; }"; - assert_eq!(messages(text), Vec::::new()); + assert_eq!(testing::messages(text), Vec::::new()); let dump = dump_of(text); assert!(dump.contains("rest pattern"), "{dump}"); assert!(!dump.contains("declared name _"), "{dump}"); @@ -143,7 +132,7 @@ fn underscore_binds_nothing() { fn one_error_for_unexpected_top_level_text() { let text = "let b = 1;\nx + 1; y();\nfn f() {}"; assert_eq!( - messages(text), + testing::messages(text), [ "top-level `let` not allowed", "module scope expects declaration" @@ -238,7 +227,7 @@ const BROKEN_INPUTS: &[&str] = &[ #[test] fn spans_lie_in_the_text() { for text in std::iter::once(&PROGRAM).chain(BROKEN_INPUTS) { - let (tree, _) = parse_text(text); + let (tree, _) = testing::parse_text(text); for line in dump::dump(&tree, true).lines() { // the span follows the kind; a doc comment's later lines have none let Some(at) = line.find(" @") else { continue }; @@ -298,7 +287,7 @@ fn one_error_per_mistake() { &["expected `;`, found `fn`", "expected `}`, found `fn`"], ), ] { - assert_eq!(messages(text), want, "{text:?}"); + assert_eq!(testing::messages(text), want, "{text:?}"); } } @@ -313,7 +302,7 @@ fn complete_trees() { ("fn f() { a $ 1; }", false), ("fn f() { let a = 1; }", true), ] { - let (tree, errors) = parse_text(text); + let (tree, errors) = testing::parse_text(text); assert_eq!(tree.complete, complete, "{text:?} {errors:?}"); } } @@ -341,7 +330,7 @@ fn missing_commas_are_repaired() { name reference c "; assert_eq!(dump_of(text), want); - let (_, errors) = parse_text(text); + let (_, errors) = testing::parse_text(text); assert_eq!(errors.len(), 2); assert_eq!(errors[0].notes[0].fixes().len(), 1); assert_eq!(errors[1].notes[0].fixes().len(), 2); @@ -352,12 +341,12 @@ fn missing_commas_are_repaired() { /// A missing closer on a later line points back at what is still open. #[test] fn unclosed_marks_the_opener() { - let (_, errors) = parse_text("fn f() {\n g(1;\n}"); + let (_, errors) = testing::parse_text("fn f() {\n g(1;\n}"); assert!( errors.len() == 1 && errors[0].labels.len() == 1, "same line: {errors:?}" ); - let (_, errors) = parse_text("fn f() {\n let a = 1;\n"); + let (_, errors) = testing::parse_text("fn f() {\n let a = 1;\n"); assert!( errors.len() == 1 && errors[0].labels.len() == 2 @@ -377,7 +366,7 @@ fn missing_token_place() { Some("fn f() {\n let a = 1;\n return a;\n}"), ); let text = "fn f() { let a = 1 let b = 2; }"; - let (_, errors) = parse_text(text); + let (_, errors) = testing::parse_text(text); assert!( errors.len() == 1 && errors[0].notes.is_empty(), "{errors:?}" @@ -385,7 +374,7 @@ fn missing_token_place() { assert_eq!(&text[errors[0].labels[0].span.range()], "let"); // A missing closer always belongs where the read text ends. let text = "fn f() { g(1 + 2; }"; - let (_, errors) = parse_text(text); + let (_, errors) = testing::parse_text(text); assert_eq!(errors.len(), 1); assert_eq!( errors[0].notes[0].fixes()[0].span.start as usize, @@ -397,7 +386,7 @@ fn missing_token_place() { /// trailing commas and empty statements are style, left to a lint. #[test] fn separators() { - assert!(messages("fn f(a: i32,, b: i32,) { g(1,, 2,); ;; }").is_empty()); + assert!(testing::messages("fn f(a: i32,, b: i32,) { g(1,, 2,); ;; }").is_empty()); } /// Nesting far deeper than the thread's stack would hold still parses: @@ -411,7 +400,148 @@ fn deep_nesting_does_not_overflow() { format!("fn f() {{ if a {{ }}{} }}", " else if a { }".repeat(n)), format!("fn f(a: {}i32) {{}}", "& ".repeat(n)), ] { - let (tree, _) = parse_text(&text); + let (tree, _) = testing::parse_text(&text); assert_eq!(tree.top_level.len(), 1); } } + +/// Each concept's node is dumped with its parts in source order: the parse +/// tests of a concept look at the tree, so this is the one check of the dump. +#[test] +fn dumps_each_concept_node() { + let text = "struct P { x: i32 }\nenum E { A, B: i32 }\niface I { fn f(&self) }\nfn g(p: *P, r: rawptr, o: ?i32, a: [2]u8) {\n let l = [2]u8{ 1, 2 };\n let m = [_]u8{ 1 };\n let s = P.{ x = 1 };\n let v = E::B with 1;\n let c = 'a';\n let d = b'a';\n let w = o orelse 0;\n let x = o orelse { return; };\n let y = 1 |> h();\n let z = 0..=10:2;\n let q = @s;\n let t = v is E::A;\n println(1, 2);\n print();\n match v {\n E::A => { }\n E::B with n => { }\n }\n}\n"; + let want = r#"module + type declaration + declared name P + struct type + field + declared name x + type name i32 + type declaration + declared name E + enum type + variant + declared name A + variant + declared name B + type name i32 + type declaration + declared name I + interface type + function declaration + declared name f + parameter + declared name self + reference type + self type self + function declaration + declared name g + parameter + declared name p + pointer type + type name P + parameter + declared name r + pointer type rawptr + parameter + declared name o + optional type + type name i32 + parameter + declared name a + array type + array length 2 + type name u8 + block + let statement + declared name l + array literal + array type + array length 2 + type name u8 + number literal 1 + number literal 2 + let statement + declared name m + array literal _ + type name u8 + number literal 1 + let statement + declared name s + struct literal + type name P + field value + field name x + number literal 1 + let statement + declared name v + variant literal + path + type name E + type name B + number literal 1 + let statement + declared name c + char literal 'a' + let statement + declared name d + char literal b'a' + let statement + declared name w + orelse expression + name reference o + number literal 0 + let statement + declared name x + orelse expression + name reference o + block + return statement return; + let statement + declared name y + pipe expression + number literal 1 + call expression + name reference h + let statement + declared name z + range expression ..= + number literal 0 + number literal 10 + number literal 2 + let statement + declared name q + address expression + name reference s + let statement + declared name t + case test + name reference v + path + type name E + type name A + expression statement + print expression ln + number literal 1 + number literal 2 + expression statement + print expression print() + match statement + name reference v + match arm + case pattern + path + type name E + type name A + block { } + match arm + case pattern + path + type name E + type name B + declared name n + block { } +"#; + assert!(testing::messages(text).is_empty()); + assert_eq!(dump_of(text), want); +} diff --git a/crates/kernel/syntax/parser/src/types.rs b/crates/syntax/parser/src/types.rs similarity index 93% rename from crates/kernel/syntax/parser/src/types.rs rename to crates/syntax/parser/src/types.rs index e3a625ce..53a80bd7 100644 --- a/crates/kernel/syntax/parser/src/types.rs +++ b/crates/syntax/parser/src/types.rs @@ -5,20 +5,21 @@ use arena::Id; use arena::List; use diagnostics::Diagnostic; use source::Span; -use syntax::ast::Param; -use syntax::ast::Type; use token::Token; use token::TokenKind; +use tree::ast::Param; +use tree::ast::Type; use crate::Parser; +use crate::RULES; /// Reads the type a token begins, after the token, as one starting at /// `start`. -pub type TypeStartRule = fn(&mut Parser, u32) -> Id; +pub(crate) type TypeStartRule = fn(&mut Parser, u32) -> Id; /// Whether `kind` begins one of the types `Parser::type_expr` has an arm /// for, so a new arm there is added here too. -pub(crate) const fn starts_core_type(kind: TokenKind) -> bool { +pub(crate) const fn starts_type_expr_arm(kind: TokenKind) -> bool { matches!( kind, TokenKind::Ident @@ -30,13 +31,13 @@ pub(crate) const fn starts_core_type(kind: TokenKind) -> bool { } /// Whether a type can begin with `kind`. -pub(crate) fn starts_type(p: &Parser, kind: TokenKind) -> bool { - starts_core_type(kind) || p.rules.type_starts[kind as usize].is_some() +pub(crate) fn starts_type(kind: TokenKind) -> bool { + starts_type_expr_arm(kind) || RULES.type_starts[kind as usize].is_some() } impl Parser { /// Reads a type. - pub fn type_expr(&mut self) -> Id { + pub(crate) fn type_expr(&mut self) -> Id { source::grow_stack(|| { let t = self.tok(); match t.kind { @@ -67,7 +68,7 @@ impl Parser { self.add(t.span.start, Type::Type) } _ => { - if let Some(read) = self.rules.type_starts[t.kind as usize] { + if let Some(read) = RULES.type_starts[t.kind as usize] { self.next(); return read(self, t.span.start); } @@ -197,7 +198,7 @@ impl Parser { let start = self.next().span.start; let signature = self.signature( List::EMPTY, - |p, kind| kind == TokenKind::Underscore || starts_type(p, kind), + |kind| kind == TokenKind::Underscore || starts_type(kind), |p| { let start = p.tok().span.start; let name = p.parameter_name(); diff --git a/crates/kernel/syntax/token/Cargo.toml b/crates/syntax/token/Cargo.toml similarity index 100% rename from crates/kernel/syntax/token/Cargo.toml rename to crates/syntax/token/Cargo.toml diff --git a/crates/kernel/syntax/token/src/lib.rs b/crates/syntax/token/src/lib.rs similarity index 100% rename from crates/kernel/syntax/token/src/lib.rs rename to crates/syntax/token/src/lib.rs diff --git a/crates/kernel/syntax/tree/Cargo.toml b/crates/syntax/tree/Cargo.toml similarity index 95% rename from crates/kernel/syntax/tree/Cargo.toml rename to crates/syntax/tree/Cargo.toml index df4529ea..602b14a9 100644 --- a/crates/kernel/syntax/tree/Cargo.toml +++ b/crates/syntax/tree/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "syntax" +name = "tree" description = "The syntax tree the parser builds, and the operator kinds it names" version.workspace = true edition.workspace = true diff --git a/crates/kernel/syntax/tree/src/ast.rs b/crates/syntax/tree/src/ast.rs similarity index 75% rename from crates/kernel/syntax/tree/src/ast.rs rename to crates/syntax/tree/src/ast.rs index e8841c08..b3066f41 100644 --- a/crates/kernel/syntax/tree/src/ast.rs +++ b/crates/syntax/tree/src/ast.rs @@ -21,8 +21,8 @@ use crate::operators::UnaryOp; /// A range as written: `start..end`, or `start..=end` when `inclusive`, /// stepping by `start..end:step`, inside `[ ]`, after `in` or as an array -/// literal's value; an end may be left out before a `]`. Slicing reads it, -/// so it is the core's. +/// literal's value; an end may be left out before a `]`. Ranges and slicing +/// both read it. #[derive(Clone, Copy, Debug)] pub struct WrittenRange { pub inclusive: bool, @@ -140,7 +140,7 @@ impl Tree { /// The parts of `expr`, if it is a written range. pub fn written_range(&self, expr: Id) -> Option { match &self.exprs[expr] { - Expr::Feature(FeatureExpr::Range(range)) => Some(range.written), + Expr::Range(written) => Some(*written), _ => None, } } @@ -209,8 +209,9 @@ pub enum Decl { ty: Option>, value: Option>, }, - /// a feature's, such as `struct Name { fields }` or - /// `iface Name { methods }`; its type, a `Type::Feature`, says which + /// a type declaration, such as `struct Name { fields }` or + /// `iface Name { methods }`; its type (`Type::Struct`, + /// `Type::Interface`, `Type::Enum`) says which Type(TypeDecl), /// `type Name = Type;` Alias(TypeDecl), @@ -336,8 +337,18 @@ pub enum Type { Owner, /// `type`, written as a parameter's type: the parameter takes a type Type, - /// a feature's written type - Feature(FeatureType), + /// `[length]element`; `length` is the written number + Array { length: Span, element: Id }, + /// `enum { variants }` + Enum { variants: List }, + /// `iface { methods }`: `Decl::Function`s without bodies + Interface { methods: List }, + /// `?T` + Optional(Id), + /// `*T`, or `rawptr` without a `target` + Pointer { target: Option> }, + /// `struct { fields }` + Struct { fields: List }, /// a type that could not be parsed Invalid, } @@ -363,8 +374,11 @@ pub enum Stmt { Return(Option>), /// `panic message;` Panic(Id), - /// a feature's statement - Feature(FeatureStmt), + /// `match subject { arms }` + Match { + subject: Id, + arms: List, + }, /// an expression followed by `;` Expression(Id), /// `target = value;` @@ -486,8 +500,37 @@ pub enum Expr { /// (`*T`, `rawptr`, `[N]T` with no `{` after it, `&[]T`): only an /// argument that takes a type accepts it Type(Id), - /// a feature's expression - Feature(FeatureExpr), + /// `[N]T{ entries }` or `[_]T{ entries }`; each entry is a value or a + /// `values...` spread + ArrayLiteral { + ty: ArrayLiteralType, + entries: List, + }, + /// `value is Enum::Variant` + CaseTest { value: Id, case: Id }, + /// `'x'`, or `b'x'` when `byte` + Char { byte: bool }, + /// `value orelse fallback` + OrElse { + value: Id, + fallback: OrElseFallback, + }, + /// `value |> target`, as written + Pipe { value: Id, target: Id }, + /// `print(values)`, or `println(values)` when `newline` + Print { newline: bool, values: List }, + /// a range, as written: slicing and loops read its parts + /// (`Tree::written_range`) + Range(WrittenRange), + /// `@place` + RawAddress(Id), + /// `Type.{ name = value }`, or `.{ ... }` without a type + StructLiteral { + ty: Option>, + fields: List, + }, + /// `Enum::Variant with payload`; the case is a `Type::Path` + VariantLiteral { case: Id, payload: Id }, /// an expression that could not be parsed Invalid, } @@ -496,6 +539,10 @@ impl Expr { /// The precedence the expression's last part was read at: an operator /// written after it that binds tighter joins that part, not the whole /// (`-a.*` reads `a`, `a + b as T` casts `b`). + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] pub fn precedence(&self) -> Precedence { match self { Expr::Binary { op, .. } => op.precedence(), @@ -514,17 +561,15 @@ impl Expr { | Expr::Spread(_) | Expr::Parentheses(_) | Expr::Type(_) + | Expr::ArrayLiteral { .. } + | Expr::Char { .. } + | Expr::Print { .. } + | Expr::StructLiteral { .. } | Expr::Invalid => Precedence::Call, - Expr::Feature(expr) => match expr { - FeatureExpr::ArrayLiteral(_) - | FeatureExpr::Char(_) - | FeatureExpr::Print(_) - | FeatureExpr::StructLiteral(_) => Precedence::Call, - FeatureExpr::CaseTest(_) => Precedence::Equality, - FeatureExpr::OrElse(_) | FeatureExpr::VariantLiteral(_) => Precedence::Lowest, - FeatureExpr::Pipe(_) | FeatureExpr::RawAddress(_) => Precedence::Prefix, - FeatureExpr::Range(_) => Precedence::Range, - }, + Expr::CaseTest { .. } => Precedence::Equality, + Expr::OrElse { .. } | Expr::VariantLiteral { .. } => Precedence::Lowest, + Expr::Pipe { .. } | Expr::RawAddress(_) => Precedence::Prefix, + Expr::Range(_) => Precedence::Range, } } } @@ -536,91 +581,6 @@ pub struct FieldValue { pub value: Id, } -// The nodes of the features: each feature's file in the `features` crate -// parses and checks its own (docs/structure-mapping.md, step 7). - -/// An expression of a feature's, by feature. -#[derive(Clone, Copy, Debug)] -pub enum FeatureExpr { - ArrayLiteral(ArrayLiteral), - CaseTest(CaseTest), - Char(CharLiteral), - OrElse(OrElse), - Pipe(Pipe), - Print(Print), - Range(Range), - RawAddress(RawAddress), - StructLiteral(StructLiteral), - VariantLiteral(VariantLiteral), -} - -/// A statement of a feature's, by feature. -#[derive(Clone, Copy, Debug)] -pub enum FeatureStmt { - Match(Match), -} - -/// A written type of a feature's, by feature. -#[derive(Clone, Copy, Debug)] -pub enum FeatureType { - Array(ArrayType), - Enum(EnumType), - Interface(InterfaceType), - Optional(OptionalType), - Pointer(PointerType), - Struct(StructType), -} - -impl FeatureType { - /// Its fields, if it has fields. - pub fn fields(&self) -> Option> { - match self { - FeatureType::Struct(ty) => Some(ty.fields), - _ => None, - } - } - - /// Its methods, if it is an interface: `Decl::Function`s without bodies. - pub fn methods(&self) -> Option> { - match self { - FeatureType::Interface(ty) => Some(ty.methods), - _ => None, - } - } - - /// The written type it points to, if it is a typed pointer (`*T`). - pub fn pointee(&self) -> Option> { - match self { - FeatureType::Pointer(ty) => ty.target, - _ => None, - } - } - - /// The written element type, if it is an array type (`[N]T`). - pub fn element(&self) -> Option> { - match self { - FeatureType::Array(ty) => Some(ty.element), - _ => None, - } - } -} - -/// `[length]element` -#[derive(Clone, Copy, Debug)] -pub struct ArrayType { - /// the written number - pub length: Span, - pub element: Id, -} - -/// `[N]T{ entries }` or `[_]T{ entries }`; each entry is a value or a -/// `values...` spread. -#[derive(Clone, Copy, Debug)] -pub struct ArrayLiteral { - pub ty: ArrayLiteralType, - pub entries: List, -} - /// The type an array literal is written with. #[derive(Clone, Copy, Debug)] pub enum ArrayLiteralType { @@ -630,107 +590,9 @@ pub enum ArrayLiteralType { Counted { element: Id }, } -/// `'x'`, or `b'x'` when `byte` -#[derive(Clone, Copy, Debug)] -pub struct CharLiteral { - pub byte: bool, -} - -/// `enum { variants }` -#[derive(Clone, Copy, Debug)] -pub struct EnumType { - pub variants: List, -} - -/// `Enum::Variant with payload`; the case is a `Type::Path` -#[derive(Clone, Copy, Debug)] -pub struct VariantLiteral { - pub case: Id, - pub payload: Id, -} - -/// `value is Enum::Variant` -#[derive(Clone, Copy, Debug)] -pub struct CaseTest { - pub value: Id, - pub case: Id, -} - -/// `match subject { arms }` -#[derive(Clone, Copy, Debug)] -pub struct Match { - pub subject: Id, - pub arms: List, -} - -/// `iface { methods }`: `Decl::Function`s without bodies. -#[derive(Clone, Copy, Debug)] -pub struct InterfaceType { - pub methods: List, -} - -/// `?T` -#[derive(Clone, Copy, Debug)] -pub struct OptionalType { - pub inner: Id, -} - -/// `value orelse fallback` -#[derive(Clone, Copy, Debug)] -pub struct OrElse { - pub value: Id, - pub fallback: OrElseFallback, -} - /// What `orelse` gives when its value is missing. #[derive(Clone, Copy, Debug)] pub enum OrElseFallback { Value(Id), Block(Id), } - -/// `value |> target`, as written -#[derive(Clone, Copy, Debug)] -pub struct Pipe { - pub value: Id, - pub target: Id, -} - -/// `print(values)`, or `println(values)` when `newline` -#[derive(Clone, Copy, Debug)] -pub struct Print { - pub newline: bool, - pub values: List, -} - -/// A range, as written: its parts are the core's, which slicing and loops -/// read (`Tree::written_range`). -#[derive(Clone, Copy, Debug)] -pub struct Range { - pub written: WrittenRange, -} - -/// `*T`, or `rawptr` without a `target` -#[derive(Clone, Copy, Debug)] -pub struct PointerType { - pub target: Option>, -} - -/// `@place` -#[derive(Clone, Copy, Debug)] -pub struct RawAddress { - pub place: Id, -} - -/// `Type.{ name = value }`, or `.{ ... }` without a type -#[derive(Clone, Copy, Debug)] -pub struct StructLiteral { - pub ty: Option>, - pub fields: List, -} - -/// `struct { fields }` -#[derive(Clone, Copy, Debug)] -pub struct StructType { - pub fields: List, -} diff --git a/crates/kernel/syntax/tree/src/lib.rs b/crates/syntax/tree/src/lib.rs similarity index 75% rename from crates/kernel/syntax/tree/src/lib.rs rename to crates/syntax/tree/src/lib.rs index 18671295..a96ff6aa 100644 --- a/crates/kernel/syntax/tree/src/lib.rs +++ b/crates/syntax/tree/src/lib.rs @@ -1,6 +1,6 @@ //! The syntax tree the parser builds (`ast`) and the operator kinds it //! names (`operators`). The checker reads the tree; `thir` reuses the -//! operator kinds. See docs/feature-front.md, section 9. +//! operator kinds. See docs/compiler-layout.md. pub mod ast; pub mod operators; diff --git a/crates/kernel/syntax/tree/src/operators.rs b/crates/syntax/tree/src/operators.rs similarity index 100% rename from crates/kernel/syntax/tree/src/operators.rs rename to crates/syntax/tree/src/operators.rs diff --git a/docs/architecture.md b/docs/architecture.md index 2f556fec..bb4e1a76 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -165,7 +165,7 @@ this rule (#165 came from breaking it). | `source` | source files and byte spans; line and column on demand | rewritten (old one tracked line and column per character and allocated every location) | | `token`, `lexer` | tokens, lexing | old frontend, reviewed | | `literal` | rules of literal text shared by the phases: values of string, character and byte literals, and number literals (base, digits, suffix) in `literal::numeric` | string rules split out of the lexer; number rules rewritten, old ones were regex based | -| `parser` (tree in `syntax::ast`) | syntax tree, parsing | old frontend, reviewed (parser only parses) | +| `parser` (tree in `tree::ast`) | syntax tree, parsing | old frontend, reviewed (parser only parses) | | `diagnostics` | one diagnostic value and how it is printed | rewritten small; the old Go emitter and `suggest.go` reviewed | | `project` | import resolution from a package map, workers, graph, cycles; `project::manifest` reads `peeper.toml` in one folder (the project name), and `project_in` makes the project from it for the command line and the browser alike | new; ideas from old loader/resolver | | `peeper` | the command line: `check`, `fix`, `build`, `run`, `init`, `lsp` | new | @@ -179,23 +179,24 @@ needed now, is it the simplest form, does something else already do it. The parser uses two methods, each in its own files, so every file stays small and has one job: -- **Pratt parsing for expressions** (`expr.rs`), driven by one table indexed - by token kind, as in the Go parser: `rules.prefix(kind, rule)` and +- **Pratt parsing for expressions** (`expression.rs`), driven by one table + indexed by token kind, as in the Go parser: `rules.prefix(kind, rule)` and `rules.infix(kind, precedence, rule)` register each token's rule in one line. Whether a token starts an expression is read from the table, never kept in a second list. - Literal rules live in `literals.rs`, the operators and the table in - `expr.rs`. -- **Recursive descent for everything else**: statements (`stmt.rs`), types - (`types.rs`), declarations (`decl.rs`), patterns. The keyword that begins - a statement or declaration picks its rule from a table too, the same way, + Literal rules live in `expression/literals.rs`, the operators and the + table in `expression.rs`. +- **Recursive descent for everything else**: statements (`statement.rs`), types + (`types.rs`), declarations (`declaration.rs`), patterns. The keyword that + begins a statement or declaration picks its rule from a table too, the same way, and so does a keyword that begins a type (`struct { ... }`). -- The tables are one `Rules` value per language, built by `const` code: - `Rules::core()` adds the core's rows, and the `features` crate's list - (`crates/features/src/lib.rs`) adds each feature's (`structs::rows`, - `interfaces::rows`, `raw_pointers::rows`). A feature's rule lives in its - file (`crates/features/src/structs.rs`), and calls the parser's public - reading methods. +- The tables are one `static RULES`, built by `const` code in `lib.rs` + from an empty table: `expression.rs`, `statement.rs` and + `declaration.rs` add their rows, then each concept file adds its own + (`structs::rows`, `interfaces::rows`, ...). Two rules for one token + fail the build. A concept's rules live in + its file (`structs.rs`), named as the checker's file that checks it + (docs/compiler-layout.md). - Rules in a table are plain functions taking `p: &mut Parser`; shared helpers stay methods. - `lib.rs` holds only what all rules share: the token cursor, errors and diff --git a/docs/compiler-layout.md b/docs/compiler-layout.md new file mode 100644 index 00000000..2e419467 --- /dev/null +++ b/docs/compiler-layout.md @@ -0,0 +1,150 @@ +# Design page: the compiler's layout + +Decided by Fuad on 2026-11-18, after the registry pilot (kept as a stash). +Each phase can be read alone, and a developer adding a feature is led to +every place that must change by the compiler itself, never by memory, +docs or a search. The shape follows Carbon's toolchain: split by phase, +and inside a phase one list, one dispatch and one file per concept. + +## The rules + +1. **One list per phase.** Each phase names every kind it knows once, as + a closed Rust `enum`: tokens (`token`), syntax nodes (`syntax/tree` + `ast.rs`), checked types (`model` `semantic_types.rs`), THIR and MIR + nodes (`model`). The list holds names and shapes, no logic. +2. **One dispatch per phase, exhaustive.** A phase reaches a kind's work + through one `match` with no `_ =>` arm, so a new kind is a compile + error at the exact place its handler goes. A dispatch function carries + `#[deny(clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants)]`, so a `_ =>` added to it + later fails clippy. A concept file must be named by a `mod` line; + `scripts/check.sh` fails on a source file no `mod` names, which Rust + would skip without a word. +3. **One file per concept, same name in every phase.** Pipes are + `parser/src/pipes.rs` and `check/src/pipes.rs`; to read how pipes + work, open those two files. The dispatch files share names too: + `expression.rs` (with `expression/literals.rs`), `statement.rs` and + `declaration.rs` in both. +4. **Each fact about a type has one exhaustive function.** A question + every checked type must answer (how it is laid out and held, whether + it copies or holds loans, its text and hash) is one `match` in + `semantic_types` or `layout.rs`, with the lints of rule 2, so a new + type is a compile error at each. An answer is worked out when asked, + not stored: each is one `match`. The other phases read the answers and + do not decide them again. A `match` that asks only "is it an array?" + keeps its `_ =>`: a new type is not an array. +5. **Conversions are decided in one file**, `semantic_types/conversions.rs`, + by the pair of types: whether a value converts, with `as` or without, + and the cast that does it. A pair it does not name is refused. Lowering + and the constant folder take the cast from it and decide nothing again. + An integer cast (`bool` is `Integer::BOOL`) is `Integer::cast_to`, which + this file calls and lowering calls for a range's walk too: one rule, + two callers. +6. **THIR and MIR hold core ideas only.** A concept checks into core THIR + nodes, so lowering needs no handler for it unless it brings a new core + idea. MIR already follows this; LLVM, borrow flow and the interpreter + read only MIR. +7. **No runtime registry.** No table found by address, no `Any`, no type + parameter for the language: plain enums and functions. + +## Layout + +``` +syntax/token the list of tokens +syntax/lexer engine +syntax/tree the `tree` crate. ast.rs: the list of nodes; + operators.rs: the precedence ladder +syntax/parser lib.rs engine; RULES (token โ†’ parse function, built once); + expression.rs, statement.rs, declaration.rs, types.rs: + the rules; one file per concept (arrays.rs, pipes.rs, ...) +check lib.rs engine (Checker, scopes, reports); expression.rs, + statement.rs, declaration.rs: the dispatch; one file + per concept, as in the parser +model the data between phases: semantic_types (list, table, + facts), thir, mir, layout (size, alignment, how a value + is held), machine, constant, program. + semantic_types.rs holds the list, the shapes and one + match per question; a type with logic of its own has a + file in semantic_types/ (integers.rs, structs.rs, ...), + the small ones share primitive.rs; conversions.rs + decides every conversion +lower engine and dispatch over core THIR nodes +flow, eval MIR only +backend/llvm MIR only +base, driver, tools shared pieces, the programs that run the phases, tools +``` + +The `features` crate is gone: a feature's parse half is a concept file of +the parser, its check half one of the checker. + +## Adding a feature + +| Step | Where | Found by | +| --- | --- | --- | +| a token, if new | `token` | the developer | +| a precedence rung, if new | `tree/operators.rs` | the developer | +| the node | `tree/ast.rs` | the developer: the start | +| how it is read | `parser/src/.rs`, one line in `RULES` | the developer | +| its precedence, dump, check | the exhaustive `match`es | compile errors | +| how it is checked | `check/src/.rs` | the dispatch arm calls it | +| a new type | `semantic_types.rs`, then each fact it must answer | compile errors | + +## Measures + +Each step reports these before and after: + +- places to touch to add a node, and how many of them a compile error finds; +- facts every type must answer that still have a `_ =>`, and decisions + about types written in two places; +- crates that name a concept's node or type. + +## Steps + +1. Dissolve `features`: concept files in `parser` and `semantic`, one + `parser::RULES`, no `CheckHooks`; the tree's `Feature*` wrappers are + folded into the lists, so the main `match` of each phase is the + dispatch. Done. Measured by adding a probe `Expr` variant: the + compiler then points at precedence, dump and the check dispatch (3 + compile errors, 2 before); a node is named in 3 crates (tree, parser, + semantic), 4 before. +2. Type facts. Done. `borrows`, `holds_loans` and `holders_in` lost + their `_ =>`; `layout::held` (register, two words, memory, nothing) + replaces lowering's `class` list and `layout::in_memory`; lowering's + list of types lent again on a move reads `borrows`. A probe `Type` + variant now stops the build at 8 facts (4 before); facts with a + `_ =>` 4 โ†’ 0; decisions written twice 2 โ†’ 0. +3. Conversions in one file. Done. `Conversion::Implicit` and + `Conversion::NeedsCast` carry the cast (`mir::Cast`, renamed from + `mir::Conversion`, so one file does not use two types named + `Conversion`); `lower::arithmetic::cast_conversion`, a second match over + the same pairs whose `_ =>` relied on the checker agreeing, is gone, and + the checker's two hand-made `Conversion::Implicit` ask + `Types::conversion`. Places that decide how a pair converts 2 โ†’ 1; + conversions made by hand 2 โ†’ 0. +4. THIR nodes named after a concept become core ideas, where one exists. + Done, with no change: none has one. `Range` and `ForRange` walk with + wrapping arithmetic, which THIR has no node for; `ToInterface` needs a + function's address, which THIR cannot name; `StructLiteral` and + `ArrayLiteral` differ in spreads; `Length`, `Slice`, `Address`, `Panic` + and `Temporary` are core already. +5. The phases at the top of `crates/`: `kernel/` is gone, a folder is named + as its package (`check/`, was `kernel/semantic`), and the tree crate is + `tree` (was `syntax`), so `syntax/` names the group. +6. The lint of rule 2 on the last dispatches: `check_statement`, + `resolve_type` and the dump's `item`. Their inner two-arm "is it X?" + matches became `if let`, and `self`'s owner lists its impossible cases. + A probe `Stmt` variant stops the build at the dump and the check. + The same lint is on lowering's `lower_expr` and `lower_statement`, and + on every match over all of MIR's instructions: the interpreter's + `run_instruction`, LLVM's `write_instruction`, and `mir.rs`'s + `accesses`, `operands`, `class_of` and its text writer. Their two "is + it X?" matches became `if let`. +7. Review fixes. The parser's `decl.rs`, `expr.rs` and `stmt.rs` are + `declaration.rs`, `expression.rs` and `statement.rs`, and its + `literals.rs` is `expression/literals.rs`, as in the checker. A `bool` + converts as `Integer::BOOL` in the conversions file and in lowering, so + its cast is written once. The files that name `mir::Cast` and + `layout::held` import their modules (`use model::mir;`), two levels + deep, as every other `use`. + + diff --git a/docs/feature-free-mir.md b/docs/feature-free-mir.md index e7f02eec..77b7d23e 100644 --- a/docs/feature-free-mir.md +++ b/docs/feature-free-mir.md @@ -1,7 +1,8 @@ # Design page: a MIR of core concepts only -> The crates have moved since this was written: `middle/*` and -> `core/syntax` are now under `crates/kernel/` (docs/structure-mapping.md). +> The crates have moved since this was written: the phases are now +> `crates/syntax/*` (the tree crate is `tree`), `crates/check`, +> `crates/model`, `crates/lower`, `crates/flow` and `crates/eval`. Status: **done 2026-11-11.** Agreed 2026-11-10 (section 9) and built in order B; the old MIR, its lowering and `flow::cleanup` are deleted, and the diff --git a/docs/feature-front.md b/docs/feature-front.md index 2951d9a5..7571fbab 100644 --- a/docs/feature-front.md +++ b/docs/feature-front.md @@ -1,5 +1,9 @@ # Design page: a front split by feature +> Replaced on 2026-11-18 by docs/compiler-layout.md: the `features` crate +> is gone, its files are concept files of `parser` and `semantic`. Kept as +> the record of how the front got here. + Since 2026-11-13 the features are files of one crate, not a crate each, and since 2026-11-18 the phases are not generic over `L` (docs/structure-mapping.md, step 7): the tree lists every feature's node diff --git a/docs/flow-crate.md b/docs/flow-crate.md index 51f26115..60f49530 100644 --- a/docs/flow-crate.md +++ b/docs/flow-crate.md @@ -1,7 +1,8 @@ # The `flow` crate -> The crates have moved since this was written: `middle/*` and -> `core/syntax` are now under `crates/kernel/` (docs/structure-mapping.md). +> The crates have moved since this was written: the phases are now +> `crates/syntax/*` (the tree crate is `tree`), `crates/check`, +> `crates/model`, `crates/lower`, `crates/flow` and `crates/eval`. The path checks: errors that depend on which routes execution can take through one function. Source: `crates/middle/flow/src/`: `lib.rs` (the diff --git a/docs/ir-design.md b/docs/ir-design.md index a03c2525..cb8f66f1 100644 --- a/docs/ir-design.md +++ b/docs/ir-design.md @@ -1,7 +1,8 @@ # Semantic design: check, THIR, MIR, LLVM -> The crates have moved since this was written: `middle/*` and -> `core/syntax` are now under `crates/kernel/` (docs/structure-mapping.md). +> The crates have moved since this was written: the phases are now +> `crates/syntax/*` (the tree crate is `tree`), `crates/check`, +> `crates/model`, `crates/lower`, `crates/flow` and `crates/eval`. Status: PROPOSAL. Decided by the owner (2026-10-17): the points marked **decided**. Open points are listed at the end. @@ -50,7 +51,7 @@ scheduled per declaration, on demand (Zig, Rust), not module by module. (`parser`, `check`, `lower` and later `llvm`) hold only logic. THIR and MIR keep their own node types: a tree and a graph have different shapes. Changed 2026-11-13: the syntax tree and the operator kinds left `model` - for the `syntax` crate (`crates/core/syntax`), so the parser does not + for the `tree` crate (`crates/syntax/tree`), so the parser does not depend on `model` (`docs/feature-front.md`, section 9). (Until 2026-10-17 this was an `ir` crate, with the tree in `ast` and THIR in `thir`.) @@ -90,14 +91,14 @@ peeper โ”€โ–บ build โ”€โ–บ project โ”€โ–บ parser โ”€โ–บ syntax โ”€โ–บ arena โ””โ”€โ–บ llvm โ”€โ”€โ–บ model, runtime_abi MIR -> LLVM text; clang ``` -The parser writes the tree in `syntax`; every later phase reads and writes +The parser writes the tree in `tree`; every later phase reads and writes its data in `model`; only `lower` reads THIR, and `llvm` and the interpreter read MIR and signatures. Signatures (struct fields, enum variants, function types) are `model` data, written by check. | crate | owns | |---|---| -| `syntax` | the syntax tree (`ast`) and operator kinds (`operators`: `BinaryOp`, `UnaryOp`, `Precedence`) | +| `tree` | the syntax tree (`ast`) and operator kinds (`operators`: `BinaryOp`, `UnaryOp`, `Precedence`) | | `model` | data only: `thir` (THIR nodes), `mir` (MIR graphs); `semantic_types` (`TypeId`, the type interner, the built-in types table); `constant` (constant values); `ModuleId`, `DefId`; signatures | | `check` | the checker: scopes, name lookup, building THIR, writing signatures; the declaration tables (`Checker`); folding operators and `as` on constants (`fold`: `binary`, `unary`, `convert`, `known_trap`) | | `eval` | what each MIR operation gives on register values (`operations`), which folding computes with; the MIR interpreter (`interpreter::run_function` for a constant's call, `interpreter::program::run` for a whole program) | diff --git a/docs/structure-mapping.md b/docs/structure-mapping.md index aa2009f9..ba05f682 100644 --- a/docs/structure-mapping.md +++ b/docs/structure-mapping.md @@ -1,5 +1,9 @@ # Structure mapping: from today's crates to `kernel/` and `features/` +> Replaced on 2026-11-18 by docs/compiler-layout.md: the `features` crate +> is gone, its files are concept files of `parser` and `semantic`. Kept as +> the record of how the front got here. + Status: agreed by Fuad, GPT and Claude. Steps 1 to 4, 6 and 7 are done; step 5 waits for enums. diff --git a/rust-style.md b/rust-style.md index b2851614..323732c0 100644 --- a/rust-style.md +++ b/rust-style.md @@ -83,7 +83,7 @@ match these rules, so `cargo clippy -- -D warnings` holds them. - **Declare a table once and generate the rest.** When an enum, its texts, constants and lookup lists must agree, write one `macro_rules!` table with - one row per item (`tokens!`, `fixed_types!`, `operators!`). Two hand lists + one row per item (`tokens!`, `builtin_types!`, `operators!`). Two hand lists drift apart; one row cannot be half added. - **A fact's doc sits on its row.** What a token, a built-in type or an operator does is a `///` comment on its row of the table, gathered into a @@ -103,7 +103,7 @@ match these rules, so `cargo clippy -- -D warnings` holds them. ## Where code goes - **Data lives in `model`; logic lives in the crate that builds it.** Name a - data module by its path: `use syntax::ast;`, then `ast::Expr`. + data module by its path: `use tree::ast;`, then `ast::Expr`. - **`main` only wires the parts together.** Parsing arguments, compiling and reporting each live in their own module. - **A struct lists what it is made of first.** Storage reached only through diff --git a/scripts/check.sh b/scripts/check.sh index 87116444..d9bb76c2 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -28,47 +28,38 @@ check "clippy" cargo clippy --workspace --all-targets -- -D warnings check "runtime format" rustfmt --edition 2024 --check runtime/peeper_rt.rs check "runtime clippy" clippy-driver --edition=2024 -Cpanic=abort --crate-type=staticlib \ --emit=metadata --out-dir target/runtime-clippy -D warnings runtime/peeper_rt.rs -# The phases after lowering read only the MIR of core concepts -# (docs/feature-front.md section 8): `model`'s core files name no front -# module, and eval, flow and llvm name only those. llvm's tests load and -# compile a whole program, so they may. -# shortcut: this is a grep; replace it with the crate split of section 9, -# which Cargo checks. -front='semantic_types|thir|program|layout' -check "middle boundary" bash -c " - ! grep -rnE 'crate::($front)' crates/kernel/model/src/{mir,machine,constant}.rs && - ! grep -nE '^use crate::' crates/kernel/model/src/lib.rs && - ! grep -rnE 'model::($front)' crates/kernel/eval crates/kernel/flow && - ! grep -rnE --exclude=tests.rs 'model::($front)' crates/backend/llvm && - ! grep -rnE '\bsyntax::' crates/kernel/model/src/{mir,machine,constant,lib}.rs \ - crates/kernel/{eval,flow} crates/backend/llvm" -# A phase names no feature: only its tests may use the `features` crate -# (docs/structure-mapping.md, step 7); Cargo refuses the cycle for the crates -# `features` depends on, this the others. The tree lists every feature's node, -# but only the tree's own shape answers (`ast.rs`) and the `features` crate -# name one (`FeatureExpr::Range`): elsewhere a node is only `Feature(_)`, -# handed to its feature. And a feature's files, nested ones too, name no -# other feature: of their own crate, no module's path (`crate::structs`, -# `crate::{structs}`) and no `super` path to another feature -# (`super::structs`, `super::super::structs`). -feature_boundary() { - local manifest file own others - for manifest in crates/{base,backend}/*/Cargo.toml crates/kernel/syntax/*/Cargo.toml \ - crates/kernel/{semantic,model,lower,flow,eval}/Cargo.toml crates/driver/project/Cargo.toml; do - sed '/^\[dev-dependencies\]/,$d' "$manifest" | grep -H --label="$manifest" '^features\b' && return 1 +# The phases after lowering read only MIR (docs/compiler-layout.md, rule +# 6): `model`'s MIR files name none of the modules before MIR, and eval, +# flow and llvm name only the MIR files. llvm's tests load and compile a +# whole program, so they may. +# shortcut: this is a grep; a crate of its own for MIR would let Cargo +# check it. +before_mir='semantic_types|thir|program|layout' +check "MIR readers read only MIR" bash -c " + ! grep -rnE 'crate::($before_mir)' crates/model/src/{mir,machine,constant}.rs && + ! grep -nE '^use crate::' crates/model/src/lib.rs && + ! grep -rnE 'model::($before_mir)' crates/eval crates/flow && + ! grep -rnE --exclude=tests.rs 'model::($before_mir)' crates/backend/llvm && + ! grep -rnE '\btree::' crates/model/src/{mir,machine,constant,lib}.rs \ + crates/{eval,flow} crates/backend/llvm" +# Rust skips a source file no `mod` line names, so a concept file left out +# of its crate's list builds clean and does nothing. +unlisted_files() { + local file dir stem parent found=0 + for file in $(find crates -path '*/src/*' -name '*.rs' ! -path '*/src/bin/*' \ + ! -name lib.rs ! -name main.rs); do + dir=${file%/*} stem=${file##*/} stem=${stem%.rs} + if [ "$stem" = mod ]; then stem=${dir##*/} dir=${dir%/*}; fi + if [ "${dir##*/}" = src ]; then parent="$dir/lib.rs $dir/main.rs" + else parent="$dir.rs $dir/mod.rs"; fi + # shellcheck disable=SC2086 + parent=$(ls $parent 2>/dev/null) + [ -n "$parent" ] && grep -qE "\bmod $stem;" $parent || + { echo "$file: no \`mod $stem;\` names it"; found=1; } done - grep -rnE --include='*.rs' '\bFeature(Expr|Stmt|Type)::[A-Z]' crates | - grep -vE '^crates/(features/|kernel/syntax/tree/src/ast\.rs:)' && return 1 - for file in $(find crates/features/src -name '*.rs' ! -name lib.rs ! -name testing.rs); do - own=${file#crates/features/src/} - own=${own%%[./]*} - others=$(sed -nE 's/^pub mod ([a-z_]+);$/\1/p' crates/features/src/lib.rs | grep -vx "$own" | paste -sd'|') - grep -HnE '\bcrate::([a-z_]|\{)' "$file" | grep -vE 'crate::testing\b' && return 1 - grep -HnE "\bsuper(::super)*::(\{[^}]*)?\b($others)\b" "$file" && return 1 - done - return 0 + return $found } -check "feature boundary" feature_boundary +check "every source file in a module" unlisted_files check "tests" cargo test --workspace --no-fail-fast check "bundle" bash scripts/build.sh check "test programs on the bundle" env PEEPER="$PWD/build/bin/peeper" \ From bfce4213badadbe6ef7d4cc60f9f944684189d69 Mon Sep 17 00:00:00 2001 From: itsfuad Date: Wed, 18 Nov 2026 23:58:03 +0600 Subject: [PATCH 11/24] Stop tracking the vault notes The .claude/vault notes are no longer kept in the repository: remove them, their .gitignore exception and their import in CLAUDE.md. --- .claude/vault/02-pipeline.md | 7 +++++-- .claude/vault/06-plan.md | 26 +++++++++++++++++++++----- .claude/vault/07-worklog.md | 22 ++++++++++++++++++++++ .gitignore | 3 --- CLAUDE.md | 1 - 5 files changed, 48 insertions(+), 11 deletions(-) diff --git a/.claude/vault/02-pipeline.md b/.claude/vault/02-pipeline.md index c28d5b5b..692b304a 100644 --- a/.claude/vault/02-pipeline.md +++ b/.claude/vault/02-pipeline.md @@ -29,8 +29,11 @@ stateDiagram-v2 - `compile_module` walks the module's declarations in order: a function goes through `Checker::build_function` and out as `Output::Function` (THIR, MIR, - facts); a constant through `Checker::constant` as `Output::Constant`; last - the module's remaining `Output::Facts`. + and only its own facts, `Checker::function_facts`); a constant through + `Checker::constant` as `Output::Constant`; last `Output::Facts`, the facts + no function took (`Checker::other_facts`), with no names of locals. The + checker keeps facts by the declaration they were found in, so a fact + naming a local always goes out with the body that declares it. - A `ModuleResults` keeps only the file, interface hash, diagnostics, `reused`, `changed` and `ran_modules` between compiles; ids, types, THIR and MIR are rebuilt every compile. diff --git a/.claude/vault/06-plan.md b/.claude/vault/06-plan.md index cc84c7e8..04648215 100644 --- a/.claude/vault/06-plan.md +++ b/.claude/vault/06-plan.md @@ -1,9 +1,9 @@ # Plan -`main` is at `2c498440` (2026-11-06): text views (`&str`, `&cstr`) and -slices (`&[]T`) merged. Open branch: `feature/size-of`, holding the -interface, allocator and type parameter work below, in PR #182. Order of work -(owner, 2026-11-06, `allocator.localplan.md` ORDER OF WORK): +`main` is at `35ebc893` (2026-11-17): generic functions and `where` +(PR #191) and the LSP facts fix merged. Open branch: `feature/generic-types` +(item 8). Items 1-7 below are from the order of work of 2026-11-06 +(`allocator.localplan.md` ORDER OF WORK) and were not rechecked since: 1. [x] Borrowed interfaces: `&Shape`, `&mut Shape`, method tables (60a3dbed, then b435b7ff for the `ref` style). @@ -70,12 +70,28 @@ interface, allocator and type parameter work below, in PR #182. Order of work (worklog, "References in arrays and slices"). - [ ] The Website, once the feature is complete. +8. [~] Generics (owner, 2026-11-17: "start the missing generics work"). + - [x] Generic functions, `where` constraints, `::` at a call + (PR #191, merged 91982660), with two review fixes: a literal after a + found type is checked as the copy's (48290c82), and a cycle through a + copy's own signature is reported (085a94fe). + - [x] LSP crash from PR #191: facts are handed on with the function + they were found in (4a133f60, merged 35ebc893); a new LSP test opens + every test program (worklog, "Facts go with their own function"). + - [~] Generic structs, `struct Box`, on `feature/generic-types` + (plan: `~/.claude/plans/snazzy-swimming-taco.md`). Rework agreed in + principle (owner, 2026-11-17): generics are one shared part used by + functions and types; structs and pointers keep only their own logic. + - [ ] Functions of generic structs, finding `T` from a struct literal, + generic aliases, `where` on a struct. + - [ ] The Website and editor grammars, once the feature is complete. + Later improvement (owner, 2026-11-08): diagnostics as one struct per kind of error, which owns its words and spans, as rustc's `#[derive(Diagnostic)]` does; today each is built in place with `Diagnostic::new(code, message)`. Later: lifetimes of references held in structs; enums and `match` with -`?T` (put off by the owner 2026-10-30); generics. +`?T` (put off by the owner 2026-10-30). Left for later from methods (`methods.localplan.md`): `Self` written as a type, functions of types other than structs. diff --git a/.claude/vault/07-worklog.md b/.claude/vault/07-worklog.md index 411b7ca5..85b0c681 100644 --- a/.claude/vault/07-worklog.md +++ b/.claude/vault/07-worklog.md @@ -1,3 +1,25 @@ +## Facts go with their own function (2026-11-17, 4a133f60, merged 35ebc893) + +- Found in Zed: the LSP died at start. `negative_where_conditions.peep` + (PR #191) panicked it at `lsp/src/checked.rs:175`, and so did valid code + where an earlier function calls one whose `where` names its parameters. +- Cause: the checker kept one fact list per module and the driver handed + "the facts found so far" to the next function built. A `where` is + checked when its signature is first asked for, often inside another + body, so its facts about locals were read against that other body: + a panic, or a wrong hover (`main`'s `const Ratio` shown for `Pick`'s `N`). +- Fix: the checker keeps facts by the declaration they were found in and + owns the rule; `Checker::function_facts` (a function's own, a copy none) + and `Checker::other_facts` (the rest, by declaration, no locals). The + driver only calls them. A first version put the rule in the driver + through a `pub` field; the owner rejected it as scattered responsibility. +- Tests: `checks_every_test_program` (LSP opens every test program, fails + on a panic; ~8 s) and `names_after_where_are_of_their_own_function`; + both fail on the old code. Two driver tests changed to the new pairing, + every fact still present. `check.sh` passes. +- Review lesson: the PR #191 review ran only `check`/`run`/`check.sh`, none + of which records facts; a review now drives `peeper lsp` too. + - Review fixes (Fuad: "fix all"), all from step 11's lowering, found by the review of the speed work: (1) a constant of the class `Wide` was diff --git a/.gitignore b/.gitignore index e79631e4..cc7ad7e1 100644 --- a/.gitignore +++ b/.gitignore @@ -40,9 +40,6 @@ test_local !.agents/skills/peeper-code-review/SKILL.md !.agents/skills/gstack-investigate/ !.agents/skills/gstack-plan-eng-review/ -!.claude/ -.claude/* -!.claude/vault/ !.gitignore !.github/ !.github/workflows/ diff --git a/CLAUDE.md b/CLAUDE.md index 45c532ae..63e8382a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,2 +1 @@ @RULES.md -@.claude/vault/README.md From e41486f4f65628a84f70ef661195fab58fc48ccc Mon Sep 17 00:00:00 2001 From: itsfuad Date: Thu, 19 Nov 2026 15:56:11 +0600 Subject: [PATCH 12/24] Ignore commented-out mod lines in the module check The check that every source file is named by a `mod` line matched `mod name;` anywhere, so a comment such as `// mod x;` counted as naming the file. It now matches only a `mod` line, with an optional `pub` or `pub(...)`. --- scripts/check.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/check.sh b/scripts/check.sh index d9bb76c2..91779ea6 100755 --- a/scripts/check.sh +++ b/scripts/check.sh @@ -54,7 +54,8 @@ unlisted_files() { else parent="$dir.rs $dir/mod.rs"; fi # shellcheck disable=SC2086 parent=$(ls $parent 2>/dev/null) - [ -n "$parent" ] && grep -qE "\bmod $stem;" $parent || + # A `mod` line, not one in a comment: `// mod x;` names nothing. + [ -n "$parent" ] && grep -qE "^\s*(pub(\([a-z ]+\))? )?mod $stem;" $parent || { echo "$file: no \`mod $stem;\` names it"; found=1; } done return $found From f0b3f3dfb79d729f833641cad3cc77a24537ac82 Mon Sep 17 00:00:00 2001 From: itsfuad Date: Thu, 19 Nov 2026 16:01:57 +0600 Subject: [PATCH 13/24] Check generic bodies with open types instead of syntax walks A generic declaration's own check gave its type parameters no type, so anything they reached was guessed from the written syntax, and an error in one place hid or invented errors in others. Each type parameter now stands for itself in its own check (`Type::Parameter`). A type holding one, or holding `Type::Undecided`, is open (stored at intern): what depends on it is left to each copy (`ExprKind::Undecided`, `Conversion::Undecided`) and `Type::Invalid` keeps one meaning, an error was reported. - A call finds its type arguments by matching types, not syntax (`Types::find_parameters`), for `Box`, `&[]T` and nested copies alike. The syntax walks it replaces are deleted. - A generic body calling another with open arguments makes no copy: the call's type is the callee's type with the arguments substituted. - An open struct such as `Box` stays `Type::Named`, with no copy or layout; its field types are read with what it is given, once per argument list (cached). - A range's step type is derived from its element type, not stored. - `where` on an open subject, and a compile-time call given one, is not known in the own check, so it reports nothing there. Fixtures cover struct copies through references, slices and nested copies, and the copy labels on errors found in a copy. docs/generics.md describes the design. --- crates/check/src/declaration.rs | 32 +- crates/check/src/expression.rs | 1 + crates/check/src/expression/operators.rs | 16 +- crates/check/src/expression/places.rs | 70 ++- crates/check/src/functions.rs | 15 +- crates/check/src/functions/bodies.rs | 6 +- crates/check/src/functions/calls.rs | 48 +- crates/check/src/generics.rs | 167 +++---- crates/check/src/generics/constraints.rs | 13 +- crates/check/src/generics/copies.rs | 136 ++++-- crates/check/src/lib.rs | 48 +- crates/check/src/locals.rs | 6 +- crates/check/src/printing.rs | 9 +- crates/check/src/ranges.rs | 2 +- crates/check/src/statement.rs | 12 +- crates/check/src/statement/assignments.rs | 5 +- crates/check/src/statement/loops.rs | 4 +- crates/check/src/statement/tests.rs | 6 +- crates/check/src/structs.rs | 41 +- crates/check/src/testing.rs | 6 +- crates/driver/compile/src/lib.rs | 8 +- crates/driver/lsp/src/checked.rs | 3 +- crates/driver/lsp/src/tests.rs | 6 +- crates/driver/peeper/src/dump.rs | 7 +- crates/lower/src/aggregates.rs | 7 +- crates/lower/src/expression.rs | 3 + crates/lower/src/lib.rs | 10 +- crates/model/src/layout.rs | 22 +- crates/model/src/program.rs | 26 +- crates/model/src/semantic_types.rs | 415 +++++++++++++++++- crates/model/src/semantic_types/builtin.rs | 1 + .../model/src/semantic_types/conversions.rs | 3 + crates/model/src/semantic_types/interfaces.rs | 2 +- crates/model/src/semantic_types/ranges.rs | 60 ++- crates/model/src/semantic_types/structs.rs | 2 +- crates/model/src/semantic_types/tests.rs | 11 +- crates/model/src/thir.rs | 34 +- docs/compiler-layout.md | 4 +- docs/feature-front.md | 4 +- docs/generics.md | 47 ++ docs/structure-mapping.md | 2 +- .../negative_generic_functions.peep | 7 + .../negative_where_conditions.peep | 4 +- .../run_generic_functions.out | 1 + .../run_generic_functions.peep | 15 + .../generic_types/negative_generic_types.peep | 38 +- .../generic_types/run_generic_types.out | 4 + .../generic_types/run_generic_types.peep | 100 +++++ 48 files changed, 1128 insertions(+), 361 deletions(-) create mode 100644 docs/generics.md diff --git a/crates/check/src/declaration.rs b/crates/check/src/declaration.rs index 08307eec..124e5084 100644 --- a/crates/check/src/declaration.rs +++ b/crates/check/src/declaration.rs @@ -42,10 +42,10 @@ impl Checker<'_> { /// a struct, interface or enum (`declare_written_type`), or the type an /// alias names. One with /// type parameters, `struct Box`, declares a type in each copy - /// (`copy_type`); its own check, with no type for its `T` - /// (`own_arguments`), reports what is wrong whatever its types are and - /// gives its name given nothing (`Type::Named`), which no value has; - /// invalid when that check reported an error. + /// (`copy_type`); its own check, its `T` a type parameter + /// (`own_arguments`), reports what is wrong whatever `T` is and gives + /// its name given nothing (`Type::Named`), which no value has; invalid + /// when that check reported an error. pub(crate) fn check_type_declaration(&mut self, definition: DefId) -> TypeId { let tree = &self.module().ast; let (written, is_alias) = match tree.decls[tree.declaration(definition.index)] { @@ -62,12 +62,7 @@ impl Checker<'_> { if written.type_parameters.is_empty() || self.in_copy() { return self.declare_written_type(definition, written); } - let module = definition.module.index(); - let reported = self.module_checks[module].diagnostics.len(); - // Invalid whenever a field is of a type `T` names, which reports nothing. - self.declare_written_type(definition, written); - let found = &self.module_checks[module].diagnostics[reported..]; - if found.iter().any(Diagnostic::is_error) { + if self.declare_written_type(definition, written) == TypeId::INVALID { return TypeId::INVALID; } self.types.intern(Type::Named { @@ -187,9 +182,16 @@ impl Checker<'_> { } /// `resolved`, written at `span`, as a value's type: a named type, or - /// copy of one, is checked (`copy_type`). + /// copy of one, is checked (`copy_type`); one given an open type + /// (`open_struct`) is not copied. pub(crate) fn value_type_at(&mut self, resolved: TypeId, span: Span) -> TypeId { match self.types[resolved] { + Type::Named { + definition, + arguments, + } if self.types.is_open(resolved) => { + self.open_struct(resolved, definition, arguments, span) + } Type::Named { definition, arguments, @@ -284,12 +286,16 @@ impl Checker<'_> { } /// `[length]element`, written at `span` (`element_type`), holding at - /// most `MOST_HOLDERS` references and slices. + /// most `MOST_HOLDERS` references and slices and fitting the target; + /// an open one's copies are checked for both. pub(crate) fn array_type(&mut self, element: TypeId, length: u64, span: Span) -> TypeId { let Some(element) = self.element_type(element) else { return TypeId::INVALID; }; let ty = self.types.array(element, length); + if self.types.is_open(ty) { + return ty; + } if self.reports_too_many_holders(ty, self.types.holders_in(ty), span) { return TypeId::INVALID; } @@ -608,7 +614,7 @@ impl Checker<'_> { given.push(ConstArgument::Type(self.types.real(resolved))); } if given.contains(&ConstArgument::Type(TypeId::INVALID)) { - return self.named_without_types(definition); + return TypeId::INVALID; // reported } let arguments = self.types.const_arguments(&given); return self.types.intern(Type::Named { diff --git a/crates/check/src/expression.rs b/crates/check/src/expression.rs index 63a00643..f44bc5d4 100644 --- a/crates/check/src/expression.rs +++ b/crates/check/src/expression.rs @@ -132,6 +132,7 @@ impl ThirBuilder<'_, '_> { } _ => ExprKind::Convert(self.body.add(expr, span)), }, + Conversion::Undecided => ExprKind::Convert(self.body.add(expr, span)), Conversion::Reborrow => return Some(self.reborrow(expr, span, to)), Conversion::ToInterface if let Type::Interface { .. } = self.checker.types[to] => { return Some(self.owned_interface(expr, span, to)); diff --git a/crates/check/src/expression/operators.rs b/crates/check/src/expression/operators.rs index 095175f6..8b2cf1db 100644 --- a/crates/check/src/expression/operators.rs +++ b/crates/check/src/expression/operators.rs @@ -115,10 +115,16 @@ impl ThirBuilder<'_, '_> { UnaryOp::LogicalNot => *ty == Type::Bool, UnaryOp::BitNot => matches!(ty, Type::Integer(_)), }; - if !fits(&ty) { + // On an open type, each copy decides whether it applies. + let open = self.checker.types.is_open(checked.ty); + if !open && !fits(&ty) { return self.report_invalid_operand(op.symbol(), checked.ty, operand, span, fits); } - let result = checked.ty; + let result = if op == UnaryOp::LogicalNot { + TypeId::BOOL + } else { + checked.ty + }; let kind = match checked.kind { ExprKind::Constant(constant) => { ExprKind::Constant(crate::fold::operators::unary(op, &ty, &constant)) @@ -194,7 +200,8 @@ impl ThirBuilder<'_, '_> { } BinaryOp::LogicalAnd | BinaryOp::LogicalOr => *ty == Type::Bool, }; - let left_fits = fits(&left_type); + // On an open type, each copy decides whether it applies. + let left_fits = self.checker.types.is_open(left.ty) || fits(&left_type); // In a constant's value, `false && x` and `true || x` are the left // operand: `x` is checked but, as when the program runs, not run. let skips_right = self.in_constant @@ -249,7 +256,8 @@ impl ThirBuilder<'_, '_> { return self.report_invalid_operand(op.symbol(), left.ty, left_operand, span, fits); } let right_type = self.checker.types[right.ty].clone(); - if shift && !matches!(right_type, Type::Integer(_)) { + if shift && !matches!(right_type, Type::Integer(_)) && !self.checker.types.is_open(right.ty) + { let count = self.checker.type_text(right.ty); let message = format!("a shift count must be an integer, found `{count}`"); let types = &self.checker.types; diff --git a/crates/check/src/expression/places.rs b/crates/check/src/expression/places.rs index 41245346..af3e6310 100644 --- a/crates/check/src/expression/places.rs +++ b/crates/check/src/expression/places.rs @@ -6,7 +6,6 @@ use diagnostics::Diagnostic; use diagnostics::suggest::nearest_name; use model::constant::Value; use model::semantic_types::Integer; -use model::semantic_types::Members; use model::semantic_types::Type; use model::semantic_types::TypeId; use model::thir::Expr; @@ -83,7 +82,16 @@ impl ThirBuilder<'_, '_> { } let value = self.through_pointer(value, self.body.exprs.span(value)); let ty = self.body.exprs[value].ty; - if self.checker.types[ty].members().is_none() { + // A struct given an open type has fields (`open_struct`); what else + // of an open type has, each copy decides. + let open_struct = matches!(self.checker.types[ty], Type::Named { .. }); + if !open_struct && self.checker.types.is_open(ty) { + return Expr { + ty: TypeId::UNDECIDED, + kind: ExprKind::Undecided, + }; + } + if !open_struct && self.checker.types[ty].members().is_none() { if ty != TypeId::INVALID { let message = format!("`{}` has no fields", self.checker.type_text(ty)); self.checker @@ -130,6 +138,13 @@ impl ThirBuilder<'_, '_> { let tree = &self.checker.module().ast; let index_span = self.body.exprs.span(index); let elements = self.checker.types[ty].elements(); + // What indexing it means, each copy decides. + if elements.is_none() && self.checker.types.is_open(ty) { + return Expr { + ty: TypeId::UNDECIDED, + kind: ExprKind::Undecided, + }; + } let (element, length) = elements.unwrap_or((TypeId::INVALID, None)); if element == TypeId::INVALID { if ty != TypeId::INVALID { @@ -239,6 +254,14 @@ impl ThirBuilder<'_, '_> { let array = self.through_pointer(array, tree.exprs.span(indexed)); let ty = self.body.exprs[array].ty; let Some((element, length)) = self.checker.types[ty].elements() else { + // What slicing it means, each copy decides; the ends are checked. + if self.checker.types.is_open(ty) { + self.check_slice_ends([start, end], inclusive, ty, None, range); + return Expr { + ty: TypeId::UNDECIDED, + kind: ExprKind::Undecided, + }; + } if ty != TypeId::INVALID { let message = format!("`{}` cannot be sliced", self.checker.type_text(ty)); self.checker @@ -339,6 +362,11 @@ impl ThirBuilder<'_, '_> { match &self.checker.types[ty] { pointer if let Some(target) = pointer.pointee() => self.dereference(reference, target), Type::Invalid => Expr::INVALID, + // What it reaches, each copy decides. + _ if self.checker.types.is_open(ty) => Expr { + ty: TypeId::UNDECIDED, + kind: ExprKind::Undecided, + }, found => { let message = format!( "`.*` needs a reference or a typed raw pointer, found `{}`", @@ -397,29 +425,41 @@ impl ThirBuilder<'_, '_> { } } - /// The index of the field `name` of the type `ty`, in declaration order, - /// and its type; `None` after reporting that the type has no such field, - /// with its nearest field name. + /// The index of the field `name` of the struct type `ty`, in + /// declaration order, and its type; `None` after reporting that the type + /// has no such field, with its nearest field name. A struct given an + /// open type has no copy holding its fields' types: they are read again + /// with what it is given (`field_types_given`). pub(crate) fn field_index(&mut self, ty: TypeId, name: Ident) -> Option<(usize, TypeId)> { - let Some(Members { - definition, fields, .. - }) = self.checker.types[ty].members() + let (Type::Struct { definition, .. } | Type::Named { definition, .. }) = + self.checker.types[ty] else { - unreachable!("only a type with members has fields") + unreachable!("only a struct has fields") }; let file = &self.checker.module().ast.file; let text = name.text(file); let modules = self.checker.modules; - let found = model::program::field_names(modules, definition) - .position(|field| field == text) - .map(|index| (index, fields[index])); - if found.is_none() { + let Some(index) = + model::program::field_names(modules, definition).position(|field| field == text) + else { let message = format!("`{}` has no field `{text}`", self.checker.type_text(ty)); let fields = model::program::field_names(modules, definition).map(|field| (field, 0)); let meant = nearest_name(text, fields).map(str::to_string); self.checker .report_unknown(diagnostics::UNKNOWN_FIELD, name.span, message, meant); - } - found + return None; + }; + let field_type = match self.checker.types[ty] { + Type::Named { arguments, .. } => self + .checker + .field_types_given(definition, arguments, name.span)[index], + _ => { + self.checker.types[ty] + .members() + .expect("a struct has members") + .fields[index] + } + }; + Some((index, field_type)) } } diff --git a/crates/check/src/functions.rs b/crates/check/src/functions.rs index e177bf27..d18fb188 100644 --- a/crates/check/src/functions.rs +++ b/crates/check/src/functions.rs @@ -257,22 +257,17 @@ impl Checker<'_> { if let ast::Type::Type = tree.types[parameter.ty] { continue; } - if self.resolve_value_type(parameter.ty) != semantic_types::TypeId::INVALID { - continue; + let ty = self.resolve_value_type(parameter.ty); + if ty == semantic_types::TypeId::INVALID { + return ty; // reported } // A value's type is read again at each call (`const_value_type`), // which cannot know a type parameter yet: only the copy does. - // Any other error in it was reported. - let tree = &self.module().ast; - let type_parameters: Vec<&str> = (model::program::copy_parameters(tree, signature)) - .flatten() - .map(|name| tree.file.slice(name)) - .collect(); - if generics::names_type_parameter(tree, parameter.ty, &type_parameters) { + if self.types.is_open(ty) { return self .not_supported(span, "`const` values whose type names a type parameter"); } - return semantic_types::TypeId::INVALID; + continue; } if is_variadic && !kind.takes_variadic { let message = format!("{} cannot have a `...` parameter", kind.name); diff --git a/crates/check/src/functions/bodies.rs b/crates/check/src/functions/bodies.rs index 5d66c293..ceb71262 100644 --- a/crates/check/src/functions/bodies.rs +++ b/crates/check/src/functions/bodies.rs @@ -86,11 +86,7 @@ impl Checker<'_> { flow::loans::report_loan_errors(&mir, pointer_bytes, file, diagnostics); flow::unreachable::warn_unreachable_code(&mir, file, diagnostics); // Last: it points at the closing brace. - let result_text = || { - types.text(*result, |definition| { - model::program::declared_text(modules, definition) - }) - }; + let result_text = || model::program::type_text(modules, types, *result); flow::missing_return::report_missing_return(&mir, file, result_text, diagnostics); Some(mir) } diff --git a/crates/check/src/functions/calls.rs b/crates/check/src/functions/calls.rs index 6e8ba9cf..b4b5bd23 100644 --- a/crates/check/src/functions/calls.rs +++ b/crates/check/src/functions/calls.rs @@ -60,13 +60,22 @@ impl builder::ThirBuilder<'_, '_> { let symbol = self.checker.resolve_path(path); self.function_called(symbol, callee_span) } - ast::Expr::Selector { value, field } => { - self.method(value, field, callee_span) - .map(|(place, callee, signature)| { - receiver = Some(place); - (callee, signature) - }) - } + ast::Expr::Selector { value, field } => match self.method(value, field, callee_span) { + Some(Some((place, callee, signature))) => { + receiver = Some(place); + Some((callee, signature)) + } + // Each copy finds the function: the arguments are checked + // for their own errors only. + Some(None) => { + self.call_found(None, None, callee_span, type_arguments, arguments, span); + return thir::Expr { + ty: semantic_types::TypeId::UNDECIDED, + kind: thir::ExprKind::Undecided, + }; + } + None => None, + }, _ => { self.checker .not_supported(callee_span, "calls of computed functions"); @@ -231,7 +240,12 @@ impl builder::ThirBuilder<'_, '_> { if !arity_matches { return thir::Expr::INVALID; } + // A call given an open type, as in a generic body's own check, runs + // in each copy only. + let runs_now = !matches!(callee, Callee::Function(function) + if self.checker.types.arguments_open(function.arguments)); if let Callee::Function(function) = callee + && runs_now && model::program::is_builtin(self.checker.modules, function.definition) { // Its answer is known now, wherever the call is. @@ -256,7 +270,14 @@ impl builder::ThirBuilder<'_, '_> { }); values.collect::>>() }; + if !runs_now && self.in_constant { + return thir::Expr { + ty: result, + kind: thir::ExprKind::Undecided, + }; + } if let Callee::Function(function) = callee + && runs_now && self.in_constant && result != semantic_types::TypeId::VOID && let Some(values) = constant_arguments() @@ -312,13 +333,15 @@ impl builder::ThirBuilder<'_, '_> { /// interface, or of what the interface reference views, which the call /// gives as `self`, the callee, and its type. An interface's own /// function (`fn Shape::name`) is found before its methods; a name - /// cannot be both (`scope::collect`). + /// cannot be both (`scope::collect`). `None` when reported; `Some(None)` + /// for a value of an open type (`Types::is_open`), whose function each + /// copy finds. fn method( &mut self, value: Id, name: ast::Ident, span: Span, - ) -> Option<(Id, Callee, semantic_types::TypeId)> { + ) -> Option, Callee, semantic_types::TypeId)>> { let value = self.add_expr(value, None); let ty = self.body.exprs[value].ty; let interface = match self.checker.types[ty] { @@ -333,10 +356,13 @@ impl builder::ThirBuilder<'_, '_> { .get(Some(definition), text) .is_none() { - return self.interface_method(value, interface, name); + return self.interface_method(value, interface, name).map(Some); } let place = self.through_pointer(value, self.body.exprs.span(value)); let ty = self.body.exprs[place].ty; + if self.checker.types.is_open(ty) && self.checker.types[ty].definition().is_none() { + return Some(None); + } let Some(definition) = self.checker.types[ty].definition() else { if ty != semantic_types::TypeId::INVALID { let message = format!("`{}` has no functions", self.checker.type_text(ty)); @@ -358,7 +384,7 @@ impl builder::ThirBuilder<'_, '_> { unreachable!("a type's member is a function") }; self.takes_self(function.definition, span) - .then_some((place, callee, signature)) + .then_some(Some((place, callee, signature))) } /// The method `name` of `interface` that `value`, an interface or a diff --git a/crates/check/src/generics.rs b/crates/check/src/generics.rs index d05c1b26..e9d47a0b 100644 --- a/crates/check/src/generics.rs +++ b/crates/check/src/generics.rs @@ -77,7 +77,8 @@ impl builder::ThirBuilder<'_, '_> { /// parameter's type known when compiling. A type parameter, ``, /// takes no argument: its type is written at the call, in /// `type_arguments`, or found from the arguments of the parameters - /// whose types name it (`find_type_argument`), each checked here, once, + /// whose types name it, each matched against its parameter's type in the + /// function's own type (`Types::find_parameters`), checked here, once, /// until every type parameter is found, and left in `checked_early` at /// its place for `check_call` to take. When a `const` one is missing, the /// function itself and its own type, for `check_call` to report the @@ -124,6 +125,20 @@ impl builder::ThirBuilder<'_, '_> { }; return Some((Callee::Function(function), pattern)); } + // Each written parameter's type in the function's own type, which + // leaves out the `const` ones; `None` for those. + let semantic_types::Type::Function { + parameters: pattern_parameters, + .. + } = &self.checker.types[pattern] + else { + unreachable!("a function's type is a function type") + }; + let mut pattern_parameters = pattern_parameters.iter().skip(first).copied(); + let parameter_types: Vec> = (written_parameters.iter()) + .map(|(_, parameter)| (!parameter.constant).then(|| pattern_parameters.next())) + .map(Option::flatten) + .collect(); // Its type parameters, ``, which take no argument of their own: // the types written at the call, or else found from the arguments. let names: Vec<&str> = (tree.children.lists) @@ -151,7 +166,9 @@ impl builder::ThirBuilder<'_, '_> { } } else if !names.is_empty() { checked_early.resize(arguments.len(), None); - for &(place, parameter) in &written_parameters { + for (&(place, parameter), ¶meter_type) in + written_parameters.iter().zip(¶meter_types) + { // The rest are checked as the copy's parameters, so a // literal takes the found type: `Max(small, 1)`. if types_found.iter().all(Option::is_some) { @@ -160,10 +177,14 @@ impl builder::ThirBuilder<'_, '_> { // shortcut: the arguments of a `...T` do not say what `T` is, // as `check_variadic` checks them; find it from them when a // function needs it. - if parameter.constant - || place >= arguments.len() + let Some(parameter_type) = parameter_type else { + continue; // `const` + }; + if place >= arguments.len() || matches!(tree.types[parameter.ty], ast::Type::Variadic { .. }) - || !names_type_parameter(tree, parameter.ty, &names) + || !(self.checker.types) + .parameters_named(parameter_type, definition, names.len()) + .contains(&true) { continue; } @@ -176,20 +197,25 @@ impl builder::ThirBuilder<'_, '_> { failed = true; } failed |= checked.ty == semantic_types::TypeId::INVALID; // reported - let types = &self.checker.types; - find_type_argument( - tree, - types, - parameter.ty, + (self.checker.types).find_parameters( + parameter_type, checked.ty, - &names, + definition, &mut types_found, ); checked_early[place] = Some(checked); } } + // A type parameter no parameter's type names, only the call can give. + let mut named = vec![false; names.len()]; + for &ty in parameter_types.iter().flatten() { + let found = (self.checker.types).parameters_named(ty, definition, names.len()); + for (named, found) in named.iter_mut().zip(found) { + *named |= found; + } + } let mut given = Vec::with_capacity(names.len() + const_parameters.len()); - for (name, found) in names.iter().zip(types_found) { + for ((name, found), named) in names.iter().zip(types_found).zip(named) { match found { Some(ty) => { let ty = self.checker.type_argument(ty, span); @@ -198,9 +224,6 @@ impl builder::ThirBuilder<'_, '_> { } None if failed => {} None => { - // No parameter names it, so only the call can. - let named = (written_parameters.iter()) - .any(|(_, parameter)| names_type_parameter(tree, parameter.ty, &[name])); let hint = if named { String::new() } else { @@ -240,7 +263,17 @@ impl builder::ThirBuilder<'_, '_> { definition, arguments: self.checker.types.const_arguments(&given), }; - let ty = self.checker.copy_type(copy, span); + // Given an open type, as in a generic body's own check, no copy is + // made: the call is of the function's own type, given what it gives. + // Nor is one in an own check, which is never lowered, for a call run + // only when the program runs; one run at compile time is made, to run. + let ty = if self.checker.types.arguments_open(copy.arguments) + || (!self.in_constant && self.checker.in_own_check()) + { + (self.checker.types).substitute(pattern, definition, copy.arguments) + } else { + self.checker.copy_type(copy, span) + }; Some((Callee::Function(copy), ty)) } } @@ -256,105 +289,3 @@ pub fn first_copy_parameter(tree: &ast::Tree, signature: ast::Signature) -> Opti let parameter = parameters.find(|¶meter| tree.children.params[parameter].constant)?; Some(tree.children.params.span(parameter)) } - -/// The type written inside the type written `ty` in `tree`, where a type -/// parameter can be named: a reference's or a pointer's target, or the -/// element of a slice, a `...`, an array or a range. `None` for a name and -/// for a type not looked into: a path names another module's type, and a -/// type the checker refuses (`resolve_type`), such as `?T`, is reported. -fn written_inside(tree: &ast::Tree, ty: Id) -> Option> { - match tree.types[ty] { - ast::Type::Bracketed { inner: written, .. } - | ast::Type::Reference { - target: written, .. - } - | ast::Type::Slice { - element: written, .. - } - | ast::Type::Variadic { - element: written, .. - } => Some(written), - ast::Type::Pointer { target } => target, - ast::Type::Array { element, .. } => Some(element), - // shortcut: a struct's fields, an interface's methods and an enum's - // variants are taken to name no type parameter, as a written one is - // not supported yet; an optional is refused when it is checked. - ast::Type::Struct { .. } - | ast::Type::Interface { .. } - | ast::Type::Enum { .. } - | ast::Type::Optional(_) => None, - ast::Type::Name - | ast::Type::Path(_) - | ast::Type::Generic { .. } - | ast::Type::Function(_) - | ast::Type::Owner - | ast::Type::Type - | ast::Type::Invalid => None, - } -} - -/// Finds the type one of the type parameters `names` of a function in -/// `tree` stands for, from one argument: its parameter is written `written` -/// and the argument has the type `ty`. The type is put in `found`, at the -/// name's place, unless an earlier argument gave it one. Each type written -/// around the name (`written_inside`) takes the argument's type one step -/// in; an argument of another shape finds another type, or none, and the -/// call reports the mismatch. -pub(crate) fn find_type_argument( - tree: &ast::Tree, - types: &semantic_types::Types, - written: Id, - ty: semantic_types::TypeId, - names: &[&str], - found: &mut [Option], -) { - let (mut written, mut ty) = (written, ty); - while let Some(inside) = written_inside(tree, written) { - ty = match (&tree.types[written], &types[ty]) { - // A `&[3]T` is given where a `&[]T` is taken. - (ast::Type::Slice { .. }, semantic_types::Type::Reference { target, .. }) => { - match &types[*target] { - semantic_types::Type::Array { element, .. } => *element, - _ => return, - } - } - (_, semantic_types::Type::Reference { target, .. }) => *target, - ( - _, - semantic_types::Type::Slice { element, .. } - | semantic_types::Type::Range { element, .. } - | semantic_types::Type::Array { element, .. }, - ) => *element, - ( - _, - semantic_types::Type::RawPointer { - target: Some(target), - }, - ) => *target, - _ => return, - }; - written = inside; - } - let name = tree.file.slice(tree.types.span(written)); - if let ast::Type::Name = tree.types[written] - && let Some(place) = names.iter().position(|¶meter| parameter == name) - { - found[place].get_or_insert(types.real(ty)); - } -} - -/// Whether the type written `ty` in `tree` names one of `parameters`, the -/// names of a function's type parameters, `` or `const T: type`, which -/// only its copies know. -pub(crate) fn names_type_parameter( - tree: &ast::Tree, - ty: Id, - parameters: &[&str], -) -> bool { - let mut ty = ty; - while let Some(inside) = written_inside(tree, ty) { - ty = inside; - } - matches!(tree.types[ty], ast::Type::Name) - && parameters.contains(&tree.file.slice(tree.types.span(ty))) -} diff --git a/crates/check/src/generics/constraints.rs b/crates/check/src/generics/constraints.rs index f62eb6c9..e198d39e 100644 --- a/crates/check/src/generics/constraints.rs +++ b/crates/check/src/generics/constraints.rs @@ -6,7 +6,6 @@ use arena::Id; use arena::List; use diagnostics::Diagnostic; -use model::ConstArguments; use model::constant; use model::semantic_types; use model::thir; @@ -30,7 +29,7 @@ impl Checker<'_> { let checking = (self.internals.declarations_being_checked.last()) .expect("a declaration is being checked"); let (arguments, copy) = (checking.arguments, checking.copy()); - let known = self.in_copy() || arguments == ConstArguments::NONE; + let known = !self.in_own_check(); let module = copy.definition.module.index(); let tree = &self.module().ast; let constraints: Vec> = @@ -87,7 +86,8 @@ impl builder::ThirBuilder<'_, '_> { /// a type, implements the interface its bound names, or the function its /// bound names gives `true` when called at compile time with the subject /// first, then the constraint's arguments. `None` when that is not - /// known: after an error, reported, or for a subject only a copy knows. + /// known: after an error, reported, or for an open subject + /// (`Types::is_open`), which each copy decides. fn constraint_value(&mut self, constraint: Id) -> Option { let tree = &self.checker.module().ast; let span = tree.children.constraints.span(constraint); @@ -112,7 +112,7 @@ impl builder::ThirBuilder<'_, '_> { let checked = self.call_found(found, None, bound_span, List::EMPTY, &given, span); self.in_constant = outer; if checked.ty == semantic_types::TypeId::INVALID { - return None; // reported, or only a copy knows it + return None; // reported } if checked.ty != semantic_types::TypeId::BOOL { let ty = self.checker.type_text(checked.ty); @@ -146,8 +146,9 @@ impl builder::ThirBuilder<'_, '_> { return None; } let ty = self.written_type_argument(subject); - if ty == semantic_types::TypeId::INVALID { - return None; // reported, or only a copy knows it + // Reported, or each copy knows it. + if ty == semantic_types::TypeId::INVALID || self.checker.types.is_open(ty) { + return None; } if self.checker.types[ty].members().is_none() { return Some(false); diff --git a/crates/check/src/generics/copies.rs b/crates/check/src/generics/copies.rs index a64777b8..1883e5c8 100644 --- a/crates/check/src/generics/copies.rs +++ b/crates/check/src/generics/copies.rs @@ -30,7 +30,9 @@ impl Checker<'_> { /// for, and for a function kept for the compile to build its body /// (`next_copy`). Invalid when the declaration's own check, or the /// copy's, has an error, or when copies are made inside each other too - /// deep (`COPY_DEPTH_LIMIT`), reported at `used_at`. + /// deep (`COPY_DEPTH_LIMIT`), reported at `used_at`. A copy is made only + /// for known types: one given an open type is not (`open_struct`, + /// `Types::substitute`). pub fn copy_type(&mut self, copy: DeclarationCopy, used_at: Span) -> semantic_types::TypeId { let has_body = matches!( model::program::declaration(self.modules, copy.definition), @@ -51,11 +53,6 @@ impl Checker<'_> { if copy.arguments == ConstArguments::NONE || own == semantic_types::TypeId::INVALID { return own; } - // Named in a type's own check by what names `T` - // (`named_without_types`): its own check's name, which no value has. - if copy.arguments == self.own_arguments(copy.definition) { - return semantic_types::TypeId::INVALID; - } if let Some(&Copied { ty, .. }) = self.internals.copies.get(©) { // No type yet: asked for again inside its own check, as a // `where` or a field can. @@ -73,19 +70,6 @@ impl Checker<'_> { .last() .expect("a use is being checked") .copy(); - // A function's own signature and body, with no type for its `T`, - // are checked for their names only, so they make no copy. A type's - // own check does: it finds what its fields hold. - let made_by_function = matches!( - model::program::declaration(self.modules, made_inside.definition), - ast::Decl::Function(_) - ); - if made_by_function - && made_inside.arguments != ConstArguments::NONE - && !self.internals.copies.contains_key(&made_inside) - { - return semantic_types::TypeId::INVALID; - } let (depth, reported_in) = match self.internals.copies.get(&made_inside) { Some(inside) => (inside.depth + 1, inside.reported_in), None => (1, self.current_module()), @@ -139,29 +123,77 @@ impl Checker<'_> { ty } - /// What `definition` named with an argument that has no type stands - /// for: one reported, or one that names a `T` no copy gives yet. - /// Invalid, but in a type's own check, which keeps the declaration - /// named, as in its own check: what holds it by value checks it - /// (`copy_type`), so a type that holds itself, as `Two<[2]T>` in `Two`, - /// is found once, whatever `T` is. - pub(crate) fn named_without_types(&mut self, definition: DefId) -> semantic_types::TypeId { - let checking = (self.internals.declarations_being_checked.last()) - .expect("a declaration is being checked"); - let in_own_type_check = checking.arguments != ConstArguments::NONE - && !self.in_copy() - && matches!( - model::program::declaration(self.modules, checking.definition), - ast::Decl::Type(_) - ); - if !in_own_type_check { + /// `named`, the struct `definition` given the open `arguments` + /// (`Types::is_open`), held by value at `span`. No copy is made: its + /// size and checks need what each copy gives. Its own check is, and + /// what its fields hold given `arguments` (`field_types_given`), so a + /// struct that holds itself through them, as `Two` holds `Box>`, + /// is found once, in its own check, whatever `T` is. Invalid when either + /// has an error, reported. + pub(crate) fn open_struct( + &mut self, + named: semantic_types::TypeId, + definition: DefId, + arguments: ConstArguments, + span: Span, + ) -> semantic_types::TypeId { + let own = DeclarationCopy { + definition, + arguments: ConstArguments::NONE, + }; + if self.copy_type(own, span) == semantic_types::TypeId::INVALID { + return semantic_types::TypeId::INVALID; + } + let fields = self.field_types_given(definition, arguments, span); + if fields.contains(&semantic_types::TypeId::INVALID) { return semantic_types::TypeId::INVALID; } - let arguments = self.own_arguments(definition); - self.types.intern(semantic_types::Type::Named { + named + } + + /// The types of the fields of the struct `definition`, in order, given + /// `arguments`, asked for at `span`: each as its declaration writes it, + /// read again with them (`resolve_value_type`), recording nothing, once + /// for each `arguments`. For a struct given an open type, which has no + /// copy to hold them. + pub(crate) fn field_types_given( + &mut self, + definition: DefId, + arguments: ConstArguments, + span: Span, + ) -> &[semantic_types::TypeId] { + let given = DeclarationCopy { definition, arguments, - }) + }; + if self.internals.open_struct_fields.contains_key(&given) { + return &self.internals.open_struct_fields[&given]; + } + let tree = &self.modules[definition.module.index()].ast; + let ast::Decl::Type(written) = tree.decls[tree.declaration(definition.index)] else { + unreachable!("only a struct declaration is given type arguments"); + }; + let ast::Type::Struct { fields } = tree.types[written.ty] else { + unreachable!("only a struct declaration is given type arguments"); + }; + let written: Vec> = (tree.children.lists.items(fields)) + .map(|field| tree.children.fields[field].ty) + .collect(); + let checking = Checking { + definition, + arguments, + used_at: span, + records_facts: false, + }; + let fields = self.checking_in(checking, |checker| { + (written.into_iter()) + .map(|ty| checker.resolve_value_type(ty)) + .collect() + }); + self.internals + .open_struct_fields + .entry(given) + .or_insert(fields) } /// A copy of a function whose body the compile has not built @@ -174,17 +206,29 @@ impl Checker<'_> { .filter(|_| !self.internals.copies_too_deep) } - /// What the declaration `definition` is checked with outside any copy: - /// an invalid type for each of its type and `const` parameters - /// (`declaration_copy_parameters`), so only a type one is read as one - /// (`resolve_global`) and reports nothing; nothing when it has none. + /// What the declaration `definition` is checked with outside any copy + /// (`declaration_copy_parameters`): each parameter that stands for a + /// type, `` or `const T: type`, is itself (`Type::Parameter`), so + /// what depends on it each copy decides; a `const` value's place holds + /// no value (`declare_parameters`). Nothing when it has none. pub(crate) fn own_arguments(&mut self, definition: DefId) -> ConstArguments { - let count = model::program::declaration_copy_parameters(self.modules, definition).count(); - if count == 0 { + let parameters: Vec> = + model::program::declaration_copy_parameters(self.modules, definition).collect(); + if parameters.is_empty() { return ConstArguments::NONE; } - let invalid = semantic_types::ConstArgument::Type(semantic_types::TypeId::INVALID); - self.types.const_arguments(&vec![invalid; count]) + let given: Vec = (parameters.iter().zip(0..)) + .map(|(parameter, place)| { + let ty = match parameter { + Some(_) => { + (self.types).intern(semantic_types::Type::Parameter { definition, place }) + } + None => semantic_types::TypeId::INVALID, + }; + semantic_types::ConstArgument::Type(ty) + }) + .collect(); + self.types.const_arguments(&given) } /// The types `written` at `span` after `name`, the type declaration diff --git a/crates/check/src/lib.rs b/crates/check/src/lib.rs index 755ab0ad..2ced7b27 100644 --- a/crates/check/src/lib.rs +++ b/crates/check/src/lib.rs @@ -61,6 +61,7 @@ use model::machine::Machine; use model::semantic_types::ConstArgument; use model::semantic_types::Constant; use model::semantic_types::ImplementationId; +use model::semantic_types::Naming; use model::semantic_types::Type; use model::semantic_types::TypeId; use model::semantic_types::Types; @@ -112,6 +113,9 @@ struct CheckerInternals { /// The copies made whose bodies the compile has not built yet, in the /// order made; it takes them (`next_copy`). copies_to_build: Vec, + /// The field types of each struct given an open type, which has no copy + /// to hold them, read once (`field_types_given`). + open_struct_fields: FxHashMap>, /// Whether copies nested too deep (`COPY_DEPTH_LIMIT`): then no copy's /// body is built any more, as a function that makes two copies inside /// each would make twice as many at each depth. @@ -140,15 +144,16 @@ struct Copied { /// function whose copy calls a copy for a new type each time would make /// copies without end. A type cannot: one that holds a new copy of itself, /// `struct S { next: S<[2]T> }`, holds itself, found in its own check -/// (`resolve_type`). +/// (`open_struct`). const COPY_DEPTH_LIMIT: u32 = 64; /// A declaration being checked (`CheckerInternals::declarations_being_checked`). struct Checking { definition: DefId, /// What its type and `const` parameters are given, when it is a - /// function or a struct that has them: a copy's, or invalid types in - /// its own check (`own_arguments`); else `ConstArguments::NONE`. + /// function or a struct that has them: a copy's, or each type + /// parameter itself in its own check (`own_arguments`); else + /// `ConstArguments::NONE`. arguments: ConstArguments, /// Where its asker wrote its name (its own name, when checked for its /// own sake). @@ -244,6 +249,7 @@ impl<'p> Checker<'p> { built_bodies: FxHashMap::default(), copies: FxHashMap::default(), copies_to_build: Vec::new(), + open_struct_fields: FxHashMap::default(), copies_too_deep: false, }, } @@ -369,8 +375,7 @@ impl<'p> Checker<'p> { } /// Whether the declaration being checked is a copy (`copy_type`). A - /// declaration's own check, with invalid types (`own_arguments`), is - /// none. + /// declaration's own check (`own_arguments`) is none. pub(crate) fn in_copy(&self) -> bool { let checking = self .internals @@ -380,6 +385,15 @@ impl<'p> Checker<'p> { self.internals.copies.contains_key(&checking.copy()) } + /// Whether the declaration being checked is a generic declaration's own + /// check (`own_arguments`): neither a copy nor a declaration without + /// type or `const` parameters. + pub(crate) fn in_own_check(&self) -> bool { + let checking = (self.internals.declarations_being_checked.last()) + .expect("a declaration is being checked"); + checking.arguments != ConstArguments::NONE && !self.in_copy() + } + /// The type `ty` as a message names it (`Types::text`). pub(crate) fn type_text(&self, ty: TypeId) -> String { model::program::type_text(self.modules, &self.types, ty) @@ -388,12 +402,14 @@ impl<'p> Checker<'p> { /// Both types as a message names them, with each one's module when two /// different declarations in them read the same: `a::Point`, `[1]b::Point`. pub(crate) fn type_texts(&self, first: TypeId, second: TypeId) -> (String, String) { - let name = |definition: DefId| model::program::declared_text(self.modules, definition); + let name = |naming: Naming| model::program::named_text(self.modules, naming); // `Types::text` needs a closure it can copy, so this one cannot own the list. let written = RefCell::new(Vec::new()); - let plain = |definition: DefId| { - written.borrow_mut().push(definition); - name(definition) + let plain = |naming: Naming| { + if let Naming::Declaration(definition) = naming { + written.borrow_mut().push(definition); + } + name(naming) }; let texts = ( self.types.text(first, plain), @@ -401,15 +417,21 @@ impl<'p> Checker<'p> { ); let written = written.into_inner(); let clash = |&one: &DefId| { - let same_name = |&other: &DefId| one != other && name(one) == name(other); + let same_name = |&other: &DefId| { + one != other && name(Naming::Declaration(one)) == name(Naming::Declaration(other)) + }; written.iter().any(same_name) }; if !written.iter().any(clash) { return texts; } - let with_module = |definition: DefId| { - let module = &self.modules[definition.module.index()]; - format!("{}::{}", module.path, name(definition)) + // A type parameter is the one of the declaration being checked. + let with_module = |naming: Naming| match naming { + Naming::Declaration(definition) => { + let module = &self.modules[definition.module.index()]; + format!("{}::{}", module.path, name(naming)) + } + Naming::Parameter { .. } => name(naming).to_owned(), }; ( self.types.text(first, with_module), diff --git a/crates/check/src/locals.rs b/crates/check/src/locals.rs index 1bd65a5a..34c51c36 100644 --- a/crates/check/src/locals.rs +++ b/crates/check/src/locals.rs @@ -146,10 +146,14 @@ impl builder::ThirBuilder<'_, '_> { ty: checked.ty, value, }), - thir::ExprKind::Invalid => None, + thir::ExprKind::Invalid => None, // reported _ => { let file = self.checker.module().ast.file.clone(); let unknown = self.body.first_named_variable(&checked.kind); + // Each copy knows it, unless it reads what only a run knows. + if unknown.is_none() && self.body.holds_undecided(&checked.kind) { + return None; + } let types = &self.checker.types; let message = if unknown.is_some() { "the value of a constant must be known at compile time" diff --git a/crates/check/src/printing.rs b/crates/check/src/printing.rs index cfdfe2e4..2b4cf119 100644 --- a/crates/check/src/printing.rs +++ b/crates/check/src/printing.rs @@ -302,17 +302,24 @@ pub(crate) fn check_print( ) -> thir::Expr { let tree = &builder.checker.module().ast; let mut checked = Vec::with_capacity(values.len()); + let mut failed = false; for value in tree.children.lists.items(values) { let span = tree.exprs.span(value); let expr = builder.check_expr(value, None); let ty = expr.ty; let types = &builder.checker.types; + // Each copy prints a value of an open type its own way; a generic + // body's own check, which never runs, leaves it out. + if types.is_open(ty) { + continue; + } // On an error the others are still checked, for their own. if !printable(types, ty) { if ty != semantic_types::TypeId::INVALID { let message = format!("`{}` cannot be printed", builder.checker.type_text(ty)); (builder.checker).error(diagnostics::INVALID_OPERATION, message, span); } + failed = true; continue; } let mut printed = builder.body.add(expr, span); @@ -333,7 +340,7 @@ pub(crate) fn check_print( } checked.push(printed); } - if checked.len() < values.len() { + if failed { return thir::Expr::INVALID; } let mut written = None; diff --git a/crates/check/src/ranges.rs b/crates/check/src/ranges.rs index 8f026529..2e24eba6 100644 --- a/crates/check/src/ranges.rs +++ b/crates/check/src/ranges.rs @@ -84,7 +84,7 @@ pub(crate) fn check_range( .checker .range_type(builder.body.exprs[start].ty, span); let step_type = match builder.checker.types[ty] { - semantic_types::Type::Range { step, .. } => step, + semantic_types::Type::Range { element } => builder.checker.types.range_step(element), _ => semantic_types::TypeId::INVALID, }; let step = check_range_step(builder, step, step_type, span); diff --git a/crates/check/src/statement.rs b/crates/check/src/statement.rs index eada483a..cbaaf227 100644 --- a/crates/check/src/statement.rs +++ b/crates/check/src/statement.rs @@ -40,9 +40,9 @@ impl Checker<'_> { /// what `body` held is dropped, its memory kept. False, with `body` /// untouched, for a function without a body or whose signature had /// an error. A function a copy is made for, given nothing, is checked - /// as its signature is, with no type for a type parameter and no value - /// for a `const` one (`own_arguments`): what its body names is found, - /// and it reports what is wrong whatever those are. + /// as its signature is, each type parameter standing for itself and no + /// value for a `const` one (`own_arguments`): what its body names is + /// found, and it reports what is wrong whatever those are. pub fn check_body( &mut self, copy: DeclarationCopy, @@ -486,7 +486,11 @@ impl<'a, 'p> ThirBuilder<'a, 'p> { } => { let iterable = self.add_expr(iterable, None); let ty = self.body.exprs[iterable].ty; - if let Type::Range { .. } = self.checker.types[ty] { + // What walking an open value means, each copy decides; the + // own check, never lowered, checks the body as a range's. + if matches!(self.checker.types[ty], Type::Range { .. }) + || self.checker.types.is_open(ty) + { self.check_for_range(index, Some(value), iterable, body?) } else { self.check_for_array(index, value, iterable, body?)? diff --git a/crates/check/src/statement/assignments.rs b/crates/check/src/statement/assignments.rs index 9897f98d..27e8cc3f 100644 --- a/crates/check/src/statement/assignments.rs +++ b/crates/check/src/statement/assignments.rs @@ -118,8 +118,9 @@ impl ThirBuilder<'_, '_> { place } }; - if let ExprKind::Invalid = self.body.exprs[place].kind { - return None; // its error was reported + // Its error was reported, or what it sets, each copy decides. + if let ExprKind::Invalid | ExprKind::Undecided = self.body.exprs[place].kind { + return None; } let (start, decider) = self.place_root(place); let variable = match self.body.exprs[start].kind { diff --git a/crates/check/src/statement/loops.rs b/crates/check/src/statement/loops.rs index c95602b2..4bc05a6c 100644 --- a/crates/check/src/statement/loops.rs +++ b/crates/check/src/statement/loops.rs @@ -64,8 +64,10 @@ impl ThirBuilder<'_, '_> { range: Id, body: Id, ) -> Stmt { - let element = match self.checker.types[self.body.exprs[range].ty] { + let ty = self.body.exprs[range].ty; + let element = match self.checker.types[ty] { Type::Range { element, .. } => element, + _ if self.checker.types.is_open(ty) => TypeId::UNDECIDED, _ => TypeId::INVALID, }; let enclosing = self.open_block(body); diff --git a/crates/check/src/statement/tests.rs b/crates/check/src/statement/tests.rs index ae7dfcf8..c02a8fae 100644 --- a/crates/check/src/statement/tests.rs +++ b/crates/check/src/statement/tests.rs @@ -1,6 +1,7 @@ use model::ConstArguments; use model::DeclarationCopy; use model::DefId; +use model::semantic_types::Naming; use model::thir::Body; use source::SourceFile; use tree::ast; @@ -44,7 +45,10 @@ fn bodies(text: &str) -> (Vec, Vec) { let file = SourceFile::new("main.peep", text); // A called function's name, by its place among the declarations. let names: Vec = (0..declared).map(|index| format!("f{index}")).collect(); - let name = |function: DefId| names[function.index as usize].as_str(); + let name = |naming: Naming| match naming { + Naming::Declaration(function) => names[function.index as usize].as_str(), + Naming::Parameter { .. } => unreachable!("no type parameter here"), + }; let shown = bodies .iter() .map(|body| body.text(&types, &file, name)) diff --git a/crates/check/src/structs.rs b/crates/check/src/structs.rs index a9cae137..3134497e 100644 --- a/crates/check/src/structs.rs +++ b/crates/check/src/structs.rs @@ -26,7 +26,8 @@ pub(crate) fn resolve_struct_type(checker: &mut Checker<'_>, span: Span) -> sema } /// The type the struct declaration `definition`, written `written` with -/// `fields`, declares, its fields laid out for the target. +/// `fields`, declares, its fields laid out for the target. Given an open +/// type, as in its own check, it stays a name: each copy is laid out. pub(crate) fn declare_struct_type( checker: &mut Checker<'_>, fields: List, @@ -57,9 +58,12 @@ pub(crate) fn declare_struct_type( if field_types.contains(&semantic_types::TypeId::INVALID) { return semantic_types::TypeId::INVALID; } + let named = checker.declared_name(definition); + if checker.types.is_open(named) { + return named; + } let (offsets, size, align) = layout::struct_layout(&checker.types, &field_types, checker.target); - let named = checker.declared_name(definition); let mut ty = checker.fits_target(named, size, written.name.span); let holders = checker.types.holders_in_fields(&field_types); if checker.reports_too_many_holders(named, holders, written.name.span) { @@ -86,17 +90,22 @@ pub(crate) fn check_struct_literal( let tree = &builder.checker.module().ast; let ty = match (written, expected) { (Some(written), _) => builder.checker.resolve_value_type(written), + // A struct, or one given an open type (`open_struct`). (None, Some(expected)) if matches!( builder.checker.types[expected], - semantic_types::Type::Struct { .. } + semantic_types::Type::Struct { .. } | semantic_types::Type::Named { .. } ) => { expected } - // Reported where it was written, or a `T` only a copy knows: - // `let b: Box = .{ ... }` in a generic function's own body. - (None, Some(semantic_types::TypeId::INVALID)) => semantic_types::TypeId::INVALID, + // Reported where it was written, or one each copy decides. + (None, Some(expected)) + if expected == semantic_types::TypeId::INVALID + || builder.checker.types.is_open(expected) => + { + expected + } (None, _) => { let message = "this struct literal needs its type: write it before `.{`"; builder @@ -104,13 +113,11 @@ pub(crate) fn check_struct_literal( .error(diagnostics::MISSING_TYPE, message, span) } }; - let semantic_types::Type::Struct { - definition, - fields: field_types, - .. - } = &builder.checker.types[ty] + let (semantic_types::Type::Struct { definition, .. } + | semantic_types::Type::Named { definition, .. }) = builder.checker.types[ty] else { - if ty != semantic_types::TypeId::INVALID { + let open = builder.checker.types.is_open(ty); + if ty != semantic_types::TypeId::INVALID && !open { let message = format!( "expected a struct type, found `{}`", builder.checker.type_text(ty) @@ -125,11 +132,17 @@ pub(crate) fn check_struct_literal( let value = tree.children.field_values[field].value; builder.add_expr(value, Some(semantic_types::TypeId::INVALID)); } + if open { + return thir::Expr { + ty: semantic_types::TypeId::UNDECIDED, + kind: thir::ExprKind::Undecided, + }; + } return thir::Expr::INVALID; }; - let definition = *definition; // Where each field is set, by its index. - let mut set: Vec> = vec![None; field_types.len()]; + let count = model::program::field_names(builder.checker.modules, definition).count(); + let mut set: Vec> = vec![None; count]; let mut checked: Vec = Vec::with_capacity(fields.len()); for field in tree.children.lists.items(fields) { let ast::FieldValue { name, value } = tree.children.field_values[field]; diff --git a/crates/check/src/testing.rs b/crates/check/src/testing.rs index 39ec8449..010ff619 100644 --- a/crates/check/src/testing.rs +++ b/crates/check/src/testing.rs @@ -9,6 +9,7 @@ use model::DefId; use model::ModuleId; use model::machine::Machine; use model::program::ImportKind; +use model::semantic_types::Naming; use model::semantic_types::Types; use model::thir; use source::SourceFile; @@ -120,7 +121,10 @@ pub(crate) fn bodies(text: &str) -> (Vec, Vec) { let names: Vec = (0..functions.len()) .map(|index| format!("f{index}")) .collect(); - let name = |function: DefId| names[function.index as usize].as_str(); + let name = |naming: Naming| match naming { + Naming::Declaration(function) => names[function.index as usize].as_str(), + Naming::Parameter { .. } => unreachable!("no type parameter here"), + }; (functions.iter()) .map(|&(definition, span)| { let copy = DeclarationCopy { diff --git a/crates/driver/compile/src/lib.rs b/crates/driver/compile/src/lib.rs index beada02f..6ffa97c0 100644 --- a/crates/driver/compile/src/lib.rs +++ b/crates/driver/compile/src/lib.rs @@ -431,10 +431,10 @@ fn compile_module( }; match tree.decls[declaration] { // A call makes a copy, built below. Its own body is checked with - // no type for a type parameter, where what is of such a type is - // unknown and reports nothing: what the body has wrong whatever - // its types are is reported here, once, though no call copies - // it, and an editor asks about its text. + // each type parameter standing for itself (`Type::Parameter`), + // where what each copy decides reports nothing: what the body has + // wrong whatever its types are is reported here, once, though no + // call copies it, and an editor asks about its text. ast::Decl::Function(function) if check::generics::first_copy_parameter(tree, function.signature).is_some() => { diff --git a/crates/driver/lsp/src/checked.rs b/crates/driver/lsp/src/checked.rs index 89e49133..64a25208 100644 --- a/crates/driver/lsp/src/checked.rs +++ b/crates/driver/lsp/src/checked.rs @@ -123,8 +123,7 @@ pub(crate) struct CachedFact { pub(crate) enum CachedKind { /// A variable of a body, this name being its declaration: whether it is /// `mut`, and its type's text; `None` for a type the check did not - /// find, as after an error, or in a function's own body for a type of - /// its `const T: type`, which only a copy knows. + /// find, as after an error. Variable { mutable: bool, ty: Option }, /// A `const` of a body or of the module, this name being its /// declaration, with its checked type and value; `None` when it had an diff --git a/crates/driver/lsp/src/tests.rs b/crates/driver/lsp/src/tests.rs index c2fc4aed..0c2f96a0 100644 --- a/crates/driver/lsp/src/tests.rs +++ b/crates/driver/lsp/src/tests.rs @@ -956,7 +956,7 @@ fn main() { // Its variables: one of a type every copy has, at a use. assert_eq!(hover(&server, utils, "kept", 1), shown("kept: i32", 5)); // No call copies `Unused`. What it calls is found, a call that - // would make a copy too; a `T` it is given is no one type. + // would make a copy too; a value of its `T` is of the type `T`. assert_eq!(hover(&server, utils, "Small", 2), small); assert_eq!( hover(&server, utils, "Pick", 1), @@ -988,8 +988,8 @@ fn main() { 12 ) ); - assert_eq!(hover(&server, utils, "given", 1), shown("given", 8)); - assert_eq!(hover(&server, utils, "held", 0), shown("mut held", 9)); + assert_eq!(hover(&server, utils, "given", 1), shown("given: T", 8)); + assert_eq!(hover(&server, utils, "held", 0), shown("mut held: T", 9)); // A type parameter shows where it is declared; only a copy knows its type. let item = shown("Item: type", 16); assert_eq!(hover(&server, utils, "Item", 3), item); // after `where` diff --git a/crates/driver/peeper/src/dump.rs b/crates/driver/peeper/src/dump.rs index afee4516..7295abf6 100644 --- a/crates/driver/peeper/src/dump.rs +++ b/crates/driver/peeper/src/dump.rs @@ -6,8 +6,8 @@ use std::io::Write; use std::path::Path; use model::DeclarationCopy; -use model::DefId; use model::mir; +use model::semantic_types::Naming; use model::semantic_types::Types; use model::thir; @@ -65,7 +65,10 @@ impl<'p> Dumps<'p> { types: &Types, ) { let modules = &self.program.modules; - let name = |definition: DefId| model::program::declared_path(modules, definition); + let name = |naming| match naming { + Naming::Declaration(definition) => model::program::declared_path(modules, definition), + Naming::Parameter { .. } => model::program::named_text(modules, naming).to_owned(), + }; let copy_name = |copy| model::program::copy_name(modules, types, copy); let module = function.definition.module.index(); let file = &modules[module].ast.file; diff --git a/crates/lower/src/aggregates.rs b/crates/lower/src/aggregates.rs index 60544905..609ce933 100644 --- a/crates/lower/src/aggregates.rs +++ b/crates/lower/src/aggregates.rs @@ -545,15 +545,16 @@ impl Lowering<'_> { &self, range_type: semantic_types::TypeId, ) -> (semantic_types::Integer, semantic_types::Integer) { - let semantic_types::Type::Range { element, step } = self.types[range_type] else { + let semantic_types::Type::Range { element } = self.types[range_type] else { unreachable!("only a range has a walk") }; - let (&semantic_types::Type::Integer(integer), &semantic_types::Type::Integer(step_integer)) = + let step = self.types.range_step(element); + let (&semantic_types::Type::Integer(integer), &semantic_types::Type::Integer(step)) = (&self.types[element], &self.types[step]) else { unreachable!("a range is of integers") }; - (integer, step_integer) + (integer, step) } /// Lowers the `thir::Stmt::ForRange` `statement`. On entry, once: diff --git a/crates/lower/src/expression.rs b/crates/lower/src/expression.rs index c2bf1a55..e15ff056 100644 --- a/crates/lower/src/expression.rs +++ b/crates/lower/src/expression.rs @@ -45,6 +45,9 @@ impl Lowering<'_> { thir::ExprKind::Invalid => { unreachable!("a body with an invalid value has errors and is not lowered") } + thir::ExprKind::Undecided => { + unreachable!("only a generic declaration's own check, never lowered, has it") + } thir::ExprKind::Constant(constant::Value::Bytes(_)) if ty == semantic_types::TypeId::STR => { diff --git a/crates/lower/src/lib.rs b/crates/lower/src/lib.rs index 6b5c07f0..0ba21b4f 100644 --- a/crates/lower/src/lib.rs +++ b/crates/lower/src/lib.rs @@ -750,13 +750,13 @@ impl Lowering<'_> { (names.map(str::to_string).zip(fields.iter().copied())).collect(); return self.debug_struct(ty, &name, &fields, depth); } - semantic_types::Type::Range { element, step } => { + semantic_types::Type::Range { element } => { let semantic_types::Type::Integer(integer) = self.types[*element] else { unreachable!("a range is of integers") }; let name = format!("{}[{integer}]", semantic_types::builtin::RANGE); let fields: Vec<(String, semantic_types::TypeId)> = - semantic_types::ranges::range_fields(*element, *step) + (self.types.range_fields(*element)) .map(|(field, ty)| (field.to_string(), ty)) .into(); return self.debug_struct(ty, &name, &fields, depth); @@ -764,8 +764,10 @@ impl Lowering<'_> { semantic_types::Type::Invalid | semantic_types::Type::Void | semantic_types::Type::Function { .. } - | semantic_types::Type::Named { .. } => { - unreachable!("no value has this type") + | semantic_types::Type::Named { .. } + | semantic_types::Type::Parameter { .. } + | semantic_types::Type::Undecided => { + unreachable!("no value has this type: a copy's types are known") } semantic_types::Type::Alias { .. } => unreachable!("indexing looks through aliases"), }; diff --git a/crates/model/src/layout.rs b/crates/model/src/layout.rs index 5323e719..92582add 100644 --- a/crates/model/src/layout.rs +++ b/crates/model/src/layout.rs @@ -6,7 +6,6 @@ use crate::machine::Machine; use crate::mir::Class; -use crate::semantic_types; use crate::semantic_types::Float; use crate::semantic_types::Type; use crate::semantic_types::TypeId; @@ -53,8 +52,8 @@ pub fn layout(types: &Types, ty: TypeId, target: &Machine) -> (u64, u64) { (2 * bytes, bytes) } Type::Struct { internals, .. } => (internals.size, internals.align), - Type::Range { element, step } => { - let fields = semantic_types::ranges::range_fields(*element, *step).map(|(_, ty)| ty); + Type::Range { element } => { + let fields = types.range_fields(*element).map(|(_, ty)| ty); let (_, size, align) = struct_layout(types, &fields, target); (size, align) } @@ -62,8 +61,13 @@ pub fn layout(types: &Types, ty: TypeId, target: &Machine) -> (u64, u64) { let (size, align) = layout(types, internals.base, target); (size.saturating_mul(internals.count), align) } - Type::Invalid | Type::Void | Type::Function { .. } | Type::Named { .. } => { - unreachable!("no value is laid out with this type") + Type::Invalid + | Type::Void + | Type::Function { .. } + | Type::Named { .. } + | Type::Parameter { .. } + | Type::Undecided => { + unreachable!("no value is laid out with this type: a copy's types are known") } Type::Alias { .. } => unreachable!("indexing looks through aliases"), } @@ -105,7 +109,9 @@ pub fn held(types: &Types, ty: TypeId) -> Held { | Type::Interface { .. } => Held::TwoWords, Type::Struct { .. } | Type::Array { .. } | Type::Range { .. } => Held::Memory, Type::Invalid | Type::Void | Type::Function { .. } => Held::Nothing, - Type::Named { .. } => unreachable!("no value has a type not checked yet"), + Type::Named { .. } | Type::Parameter { .. } | Type::Undecided => { + unreachable!("no value has a type not checked yet, or one each copy decides") + } Type::Alias { .. } => unreachable!("indexing looks through aliases"), } } @@ -118,8 +124,8 @@ pub fn field_placed(types: &Types, ty: TypeId, index: usize, target: &Machine) - match &types[ty] { ty if let Some(members) = ty.members() => (members.offsets[index], members.fields[index]), Type::Str => [(0, TypeId::RAWPTR), (target.pointer_bytes(), types.usize)][index], - Type::Range { element, step } => { - let fields = semantic_types::ranges::range_fields(*element, *step).map(|(_, ty)| ty); + Type::Range { element } => { + let fields = types.range_fields(*element).map(|(_, ty)| ty); let (offsets, ..) = struct_layout(types, &fields, target); (offsets[index], fields[index]) } diff --git a/crates/model/src/program.rs b/crates/model/src/program.rs index 3cf8af03..5744385c 100644 --- a/crates/model/src/program.rs +++ b/crates/model/src/program.rs @@ -17,6 +17,7 @@ use crate::ModuleId; use crate::constant::Value; use crate::semantic_types::ConstArgument; use crate::semantic_types::Constant; +use crate::semantic_types::Naming; use crate::semantic_types::TypeId; use crate::semantic_types::Types; use tree::ast; @@ -52,6 +53,20 @@ pub fn declared_text(modules: &[Module], definition: DefId) -> &str { name.text(file) } +/// The name `naming` asks for in `modules`: a declaration's +/// (`declared_text`), or one of its type parameters' as written. +pub fn named_text(modules: &[Module], naming: Naming) -> &str { + match naming { + Naming::Declaration(definition) => declared_text(modules, definition), + Naming::Parameter { definition, place } => { + let span = (declaration_copy_parameters(modules, definition).nth(place as usize)) + .flatten() + .expect("a type parameter's place"); + modules[definition.module.index()].ast.file.slice(span) + } + } +} + /// Whether other modules can use `name`: it starts with an upper case letter. pub fn is_exported(name: &str) -> bool { name.starts_with(char::is_uppercase) @@ -75,7 +90,7 @@ pub fn declared_path(modules: &[Module], definition: DefId) -> String { /// The type `ty` of `types` as a message names it, each declared type by the /// name its declaration in `modules` gives it (`Types::text`). pub fn type_text(modules: &[Module], types: &Types, ty: TypeId) -> String { - types.text(ty, |definition| declared_text(modules, definition)) + types.text(ty, |naming| named_text(modules, naming)) } /// The name the declaration `definition` of `modules` declares, and the file @@ -210,7 +225,10 @@ pub fn symbol(modules: &[Module], definition: DefId) -> String { /// make two names, and each float value by its bits, as two NaNs print /// alike. pub fn copy_symbol(modules: &[Module], types: &Types, copy: DeclarationCopy) -> String { - let qualified = |definition: DefId| { + let qualified = |naming: Naming| { + let Naming::Declaration(definition) = naming else { + unreachable!("a copy is made for known types") + }; let path = &modules[definition.module.index()].path; format!("{path}.{}", declared_text(modules, definition)) }; @@ -235,8 +253,8 @@ pub fn copy_symbol(modules: &[Module], types: &Types, copy: DeclarationCopy) -> /// dumps and a debugger show. pub fn copy_name(modules: &[Module], types: &Types, copy: DeclarationCopy) -> String { let declared = declared_path(modules, copy.definition); - types.copy_text(declared, copy.arguments, |definition| { - declared_text(modules, definition) + types.copy_text(declared, copy.arguments, |naming| { + named_text(modules, naming) }) } diff --git a/crates/model/src/semantic_types.rs b/crates/model/src/semantic_types.rs index 9e128176..17e45448 100644 --- a/crates/model/src/semantic_types.rs +++ b/crates/model/src/semantic_types.rs @@ -78,6 +78,19 @@ pub enum Type { /// The type of something whose error was already reported; uses of it /// report nothing more. Invalid, + /// The `place`-th parameter a copy of the declaration `definition` is + /// made for that stands for a type, `` or `const T: type` + /// (`program::declaration_copy_parameters`), in the declaration's own + /// check, where no copy has given it one. A type that holds it is open + /// (`Types::is_open`). + Parameter { + definition: DefId, + place: u32, + }, + /// The type of a result that depends on a type parameter in a way the + /// declaration's own check cannot tell, as `t[0]` of a `t: T`: each + /// copy decides it. Open, and, unlike `Invalid`, no error was reported. + Undecided, /// What a function without a result gives. Void, Bool, @@ -142,13 +155,10 @@ pub enum Type { internals: ArrayInternals, }, /// `range[element]`: the integers from a start toward an end, a step - /// apart, up or down; its fields are `range_fields`. `step` is the - /// unsigned integer type as wide as `element`, the step's type, kept - /// here so a reader of the types finds it without adding it - /// (`Types::range` makes both). + /// apart, up or down; its fields are `Types::range_fields`, its step's + /// type `Types::range_step`. Range { element: TypeId, - step: TypeId, }, /// `&T`, or `&mut T` when `mutable`: a view of a `target` value held /// elsewhere, never itself a reference. @@ -230,8 +240,10 @@ impl Type { | Type::Slice { mutable, .. } | Type::InterfaceReference { mutable, .. } => Some(mutable), // A struct, an array or an owned interface may hold loans without - // being one (`Types::holds_loans`). + // being one (`Types::holds_loans`). An open type's copies decide. Type::Invalid + | Type::Parameter { .. } + | Type::Undecided | Type::Void | Type::Bool | Type::Integer(_) @@ -312,14 +324,34 @@ pub enum Conversion { /// from `bool` to an integer, and between raw pointers of other types /// (the same address). NeedsCast(mir::Cast), + /// One type is open (`Types::is_open`): whether and how it converts, + /// each copy decides. + Undecided, /// No conversion. Never, } +/// What `Types::text` asks its `name_of` for: the name of a declaration, +/// or of the `place`-th type parameter of one (`Type::Parameter`). +#[derive(Clone, Copy, Debug)] +pub enum Naming { + Declaration(DefId), + Parameter { definition: DefId, place: u32 }, +} + +/// A type in the `Types` table, with whether it is open: it holds a +/// `Type::Parameter` or `Type::Undecided`, so what depends on that, as its +/// size or whether an operator applies to it, each copy decides. Found +/// from its parts when it is added. +struct Entry { + ty: Type, + open: bool, +} + /// The types of a program, for one compile (`check::Checker` holds them). pub struct Types { pub usize: TypeId, // as wide as a pointer of the target - types: Vec, + types: Vec, ids: FxHashMap, /// Each implementation's functions, in its interface's order, by /// `ImplementationId`; the checker adds one at the first conversion of @@ -374,13 +406,14 @@ impl Types { } /// `name`: the function `name` of the copy made for `arguments`, - /// each type as `name_of` names its declaration, each value as Peeper + /// each type as `name_of` names its declaration or type parameter + /// (`Naming`), each value as Peeper /// text; `name` alone without `const` arguments. pub fn copy_text( &self, name: String, arguments: ConstArguments, - name_of: impl Fn(DefId) -> N + Copy, + name_of: impl Fn(Naming) -> N + Copy, ) -> String { let given = self.arguments(arguments); if given.is_empty() { @@ -397,7 +430,7 @@ impl Types { pub fn argument_text( &self, argument: &ConstArgument, - name_of: impl Fn(DefId) -> N + Copy, + name_of: impl Fn(Naming) -> N + Copy, ) -> String { match argument { ConstArgument::Type(ty) => self.text(*ty, name_of), @@ -427,7 +460,11 @@ impl Types { return id; } let id = TypeId(u32::try_from(self.types.len()).expect("fewer than 2^32 types")); - self.types.push(ty.clone()); + let open = self.holds_open(&ty); + self.types.push(Entry { + ty: ty.clone(), + open, + }); self.ids.insert(ty, id); id } @@ -453,6 +490,8 @@ impl Types { Type::Interface { .. } => Some(true), // Any other type holds a loan only by being one. other @ (Type::Invalid + | Type::Parameter { .. } + | Type::Undecided | Type::Void | Type::Bool | Type::Integer(_) @@ -486,6 +525,8 @@ impl Types { .saturating_mul(self.holders_in(internals.base)), Type::Interface { .. } => 1, other @ (Type::Invalid + | Type::Parameter { .. } + | Type::Undecided | Type::Void | Type::Bool | Type::Integer(_) @@ -542,17 +583,319 @@ impl Types { | Type::InterfaceReference { mutable, .. } => !mutable, Type::Array { internals, .. } => self.is_copy(internals.base), Type::Struct { .. } | Type::Interface { .. } => false, - // No value of these is moved: an error, nothing, or not yet a value. - Type::Invalid | Type::Void | Type::Function { .. } => true, + // No value of these is moved: an error, nothing, not yet a value, + // or one each copy decides for. + Type::Invalid + | Type::Parameter { .. } + | Type::Undecided + | Type::Void + | Type::Function { .. } => true, Type::Alias { .. } | Type::Named { .. } => { unreachable!("indexing `Types` looks through aliases; no value is named") } } } + /// Whether the type `id` is open (`Entry`): what depends on its type + /// parameters, each copy decides. + pub fn is_open(&self, id: TypeId) -> bool { + self.types[id.0 as usize].open + } + + /// Whether one of `arguments` is an open type (`is_open`). + pub fn arguments_open(&self, arguments: ConstArguments) -> bool { + (self.arguments(arguments).iter()).any(|argument| match argument { + ConstArgument::Type(part) => self.is_open(*part), + ConstArgument::Value(constant) => self.is_open(constant.ty), + }) + } + + /// `ty` with each type parameter of `definition` (`Type::Parameter`) + /// replaced by the type `arguments` give in its place: the type of the + /// declaration's copy for open `arguments`, which no copy is made for. + /// A part the copy would reject, as a range of `bool`, is undecided: + /// the copy, once one is made, reports it. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] + pub fn substitute( + &mut self, + ty: TypeId, + definition: DefId, + arguments: ConstArguments, + ) -> TypeId { + if !self.is_open(ty) { + return ty; + } + let part = |types: &mut Types, part: TypeId| types.substitute(part, definition, arguments); + match self[ty].clone() { + Type::Parameter { + definition: of, + place, + } if of == definition => match self.arguments(arguments)[place as usize] { + ConstArgument::Type(given) => given, + ConstArgument::Value(_) => unreachable!("a type parameter is given a type"), + }, + Type::Parameter { .. } | Type::Undecided => ty, + Type::Function { + parameters, + result, + origins, + variadic, + } => { + let parameters = (parameters.iter()) + .map(|¶meter| part(self, parameter)) + .collect(); + let result = part(self, result); + self.intern(Type::Function { + parameters, + result, + origins, + variadic, + }) + } + Type::Named { + definition: named, + arguments: given, + } => { + let given: Vec = (self.arguments(given).to_vec().into_iter()) + .map(|argument| match argument { + ConstArgument::Type(given) => ConstArgument::Type(part(self, given)), + value @ ConstArgument::Value(_) => value, + }) + .collect(); + let arguments = self.const_arguments(&given); + self.intern(Type::Named { + definition: named, + arguments, + }) + } + Type::Array { + element, length, .. + } => { + let element = part(self, element); + self.array(element, length) + } + Type::Range { element } => { + let element = part(self, element); + self.range(element).unwrap_or(TypeId::UNDECIDED) + } + Type::Reference { mutable, target } => { + let target = part(self, target); + self.intern(Type::Reference { mutable, target }) + } + Type::Slice { mutable, element } => { + let element = part(self, element); + self.intern(Type::Slice { mutable, element }) + } + Type::RawPointer { + target: Some(target), + } => { + let target = Some(part(self, target)); + self.intern(Type::RawPointer { target }) + } + Type::Invalid + | Type::Void + | Type::Bool + | Type::Integer(_) + | Type::Float(_) + | Type::CString + | Type::Str + | Type::Alias { .. } + | Type::Struct { .. } + | Type::Interface { .. } + | Type::InterfaceReference { .. } + | Type::RawPointer { target: None } => { + unreachable!("an open type holds a type parameter: these do not, or are copies") + } + } + } + + /// Puts in `found`, at each place, the type `actual` gives for the type + /// parameter of `definition` there (`Type::Parameter`) where `pattern`, + /// the type of a parameter of `definition`'s own check, names it: the + /// part of `actual` in its place. A place already found keeps its type; + /// a part of another shape finds nothing, and the call reports the + /// mismatch. A reference to an array, `&[3]i32`, given for a slice, + /// `&[]T`, gives its element. An undecided part (`Type::Undecided`), as + /// `t[0]` of a `t: T` in a generic body, leaves each parameter its + /// pattern names undecided: each copy finds it. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] + pub fn find_parameters( + &self, + pattern: TypeId, + actual: TypeId, + definition: DefId, + found: &mut [Option], + ) { + if !self.is_open(pattern) { + return; + } + let actual = self.real(actual); + let mut part = |pattern: TypeId, actual: TypeId| { + source::grow_stack(|| self.find_parameters(pattern, actual, definition, found)); + }; + match (&self[pattern], &self[actual]) { + ( + &Type::Parameter { + definition: of, + place, + }, + _, + ) => { + if of == definition + && let Some(slot) = found.get_mut(place as usize) + { + slot.get_or_insert(actual); + } + } + (Type::Undecided, _) => {} + (_, Type::Undecided) => { + let named = self.parameters_named(pattern, definition, found.len()); + for (slot, named) in found.iter_mut().zip(named) { + if named { + slot.get_or_insert(TypeId::UNDECIDED); + } + } + } + ( + Type::Function { + parameters, result, .. + }, + Type::Function { + parameters: given, + result: given_result, + .. + }, + ) => { + for (&pattern, &actual) in parameters.iter().zip(given.iter()) { + part(pattern, actual); + } + part(*result, *given_result); + } + ( + &Type::Named { + definition: named, + arguments, + }, + &(Type::Named { + definition: given_definition, + arguments: given, + } + | Type::Struct { + definition: given_definition, + arguments: given, + .. + }), + ) if named == given_definition => { + let pairs = self.arguments(arguments).iter().zip(self.arguments(given)); + for pair in pairs { + if let (&ConstArgument::Type(pattern), &ConstArgument::Type(actual)) = pair { + part(pattern, actual); + } + } + } + (Type::Array { element, .. }, Type::Array { element: given, .. }) + | (Type::Range { element }, Type::Range { element: given }) + | (Type::Slice { element, .. }, Type::Slice { element: given, .. }) + | ( + Type::Reference { + target: element, .. + }, + Type::Reference { target: given, .. }, + ) + | ( + Type::RawPointer { + target: Some(element), + }, + Type::RawPointer { + target: Some(given), + }, + ) => part(*element, *given), + (Type::Slice { element, .. }, &Type::Reference { target, .. }) => { + if let Type::Array { element: given, .. } = self[target] { + part(*element, given); + } + } + ( + Type::Function { .. } + | Type::Named { .. } + | Type::Array { .. } + | Type::Range { .. } + | Type::Slice { .. } + | Type::Reference { .. } + | Type::RawPointer { target: Some(_) }, + _, + ) => {} + ( + Type::Invalid + | Type::Void + | Type::Bool + | Type::Integer(_) + | Type::Float(_) + | Type::CString + | Type::Str + | Type::Alias { .. } + | Type::Struct { .. } + | Type::Interface { .. } + | Type::InterfaceReference { .. } + | Type::RawPointer { target: None }, + _, + ) => unreachable!("an open type holds a type parameter: these do not, or are copies"), + } + } + + /// Which of the first `count` type parameters of `definition`, by place, + /// the type `ty` names: what it finds matched against itself. + pub fn parameters_named(&self, ty: TypeId, definition: DefId, count: usize) -> Vec { + let mut named = vec![None; count]; + self.find_parameters(ty, ty, definition, &mut named); + named.iter().map(Option::is_some).collect() + } + + /// Whether the type `ty`, about to be added, is open: it is a type + /// parameter or undecided, or a part of it is open. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] + fn holds_open(&self, ty: &Type) -> bool { + match ty { + Type::Parameter { .. } | Type::Undecided => true, + Type::Invalid + | Type::Void + | Type::Bool + | Type::Integer(_) + | Type::Float(_) + | Type::CString + | Type::Str + | Type::RawPointer { target: None } => false, + Type::Function { + parameters, result, .. + } => self.is_open(*result) || parameters.iter().any(|&part| self.is_open(part)), + Type::Named { arguments, .. } | Type::Struct { arguments, .. } => { + self.arguments_open(*arguments) + } + Type::Interface { methods, .. } => methods.iter().any(|&part| self.is_open(part)), + Type::Alias { real: part, .. } + | Type::Array { element: part, .. } + | Type::Range { element: part } + | Type::Reference { target: part, .. } + | Type::Slice { element: part, .. } + | Type::InterfaceReference { + interface: part, .. + } + | Type::RawPointer { target: Some(part) } => self.is_open(*part), + } + } + /// The type `id` stands for: itself, or the type an alias names. pub fn real(&self, id: TypeId) -> TypeId { - match self.types[id.0 as usize] { + match self.types[id.0 as usize].ty { Type::Alias { real, .. } => real, _ => id, } @@ -614,6 +957,10 @@ impl Types { } } Type::Interface { definition, .. } => declaration(*definition, hasher), + Type::Parameter { definition, place } => { + declaration(*definition, hasher); + place.hash(hasher); + } Type::Array { internals, .. } => { // Lengths are any number: the count keeps one from reading as // the type after it. @@ -623,7 +970,7 @@ impl Types { } self.hash(internals.base, hasher, declaration); } - Type::Range { element, .. } => self.hash(*element, hasher, declaration), // `step` follows + Type::Range { element } => self.hash(*element, hasher, declaration), Type::Reference { mutable, target } | Type::Slice { mutable, @@ -643,18 +990,28 @@ impl Types { source::grow_stack(|| self.hash(*target, hasher, declaration)); } } - Type::Invalid | Type::Void | Type::Bool | Type::CString | Type::Str => {} + Type::Invalid + | Type::Undecided + | Type::Void + | Type::Bool + | Type::CString + | Type::Str => {} Type::Alias { .. } => unreachable!("indexing looks through aliases"), } } /// The type `id` as a program writes it, a declared type or an alias by its name, - /// which `name_of` gives for its declaration: an alias is followed by the + /// which `name_of` gives for its declaration or type parameter + /// (`Naming`): an alias is followed by the /// type itself (`Meters (aka i64)`). - pub fn text(&self, id: TypeId, name_of: impl Fn(DefId) -> N + Copy) -> String { + pub fn text( + &self, + id: TypeId, + name_of: impl Fn(Naming) -> N + Copy, + ) -> String { let mut text = String::new(); - if let Type::Alias { definition, real } = self.types[id.0 as usize] { - _ = write!(text, "{} (aka ", name_of(definition)); + if let Type::Alias { definition, real } = self.types[id.0 as usize].ty { + _ = write!(text, "{} (aka ", name_of(Naming::Declaration(definition))); self.write_real_text(&mut text, real, name_of); text.push(')'); } else { @@ -674,7 +1031,7 @@ impl Types { &self, out: &mut String, id: TypeId, - name_of: impl Fn(DefId) -> N + Copy, + name_of: impl Fn(Naming) -> N + Copy, ) { let id = self.real(id); match &self[id] { @@ -718,10 +1075,20 @@ impl Types { arguments, .. } => { - let name = name_of(*definition).to_string(); + let name = name_of(Naming::Declaration(*definition)).to_string(); out.push_str(&self.copy_text(name, *arguments, name_of)); } - Type::Interface { definition, .. } => _ = write!(out, "{}", name_of(*definition)), + Type::Interface { definition, .. } => { + _ = write!(out, "{}", name_of(Naming::Declaration(*definition))); + } + Type::Parameter { definition, place } => { + let parameter = Naming::Parameter { + definition: *definition, + place: *place, + }; + _ = write!(out, "{}", name_of(parameter)); + } + Type::Undecided => out.push_str("{undecided}"), Type::Array { internals, .. } => { for length in self.array_lengths(id) { _ = write!(out, "[{length}]"); @@ -763,7 +1130,7 @@ impl Index for Types { /// The type itself, aliases looked through (`Types::real`). fn index(&self, id: TypeId) -> &Type { - &self.types[self.real(id).0 as usize] + &self.types[self.real(id).0 as usize].ty } } diff --git a/crates/model/src/semantic_types/builtin.rs b/crates/model/src/semantic_types/builtin.rs index a780e84a..4d5699a1 100644 --- a/crates/model/src/semantic_types/builtin.rs +++ b/crates/model/src/semantic_types/builtin.rs @@ -77,6 +77,7 @@ macro_rules! builtin_types { builtin_types! { INVALID => Type::Invalid, VOID => Type::Void, + UNDECIDED => Type::Undecided, /// A truth value: `true` or `false`. BOOL "bool" => Type::Bool, I8 "i8" => integers::integer(true, 8), diff --git a/crates/model/src/semantic_types/conversions.rs b/crates/model/src/semantic_types/conversions.rs index 12220909..9f8fdba5 100644 --- a/crates/model/src/semantic_types/conversions.rs +++ b/crates/model/src/semantic_types/conversions.rs @@ -18,6 +18,9 @@ impl Types { if self.same(from, to) { return Conversion::Same; } + if self.is_open(from) || self.is_open(to) { + return Conversion::Undecided; + } match (&self[from], &self[to]) { (&Type::Integer(from), &Type::Integer(to)) => { let cast = from.cast_to(to); diff --git a/crates/model/src/semantic_types/interfaces.rs b/crates/model/src/semantic_types/interfaces.rs index ec006e0a..471b4c88 100644 --- a/crates/model/src/semantic_types/interfaces.rs +++ b/crates/model/src/semantic_types/interfaces.rs @@ -29,7 +29,7 @@ impl Types { /// the interface was checked, as its own methods' `&self` is, is the /// `&Shape` of after. pub fn define_interface(&mut self, named: TypeId, methods: Box<[TypeId]>) { - let slot = &mut self.types[named.0 as usize]; + let slot = &mut self.types[named.0 as usize].ty; let Type::Named { definition, .. } = *slot else { unreachable!("only a declared name becomes an interface"); }; diff --git a/crates/model/src/semantic_types/ranges.rs b/crates/model/src/semantic_types/ranges.rs index b3e67fad..655e8f0a 100644 --- a/crates/model/src/semantic_types/ranges.rs +++ b/crates/model/src/semantic_types/ranges.rs @@ -5,22 +5,6 @@ use super::Type; use super::TypeId; use super::Types; -/// The fields of a value of `Type::Range { element, step }`, in order, each -/// with its name, as debug info shows it, and type: its walk, found once -/// when the range is made (`lower::Lowering::walk_range`). Its values are -/// `start`, then each `delta` more than the one before, wrapping, while -/// `left`, how far its end is, lasts by `step`, the end counted when -/// `inclusive`. `field` gives where each one is. -pub fn range_fields(element: TypeId, step: TypeId) -> [(&'static str, TypeId); 5] { - [ - ("start", element), - ("left", step), - ("step", step), - ("delta", element), - ("inclusive", TypeId::BOOL), - ] -} - /// Where each field of a range value is in `range_fields`. pub mod field { pub const START: usize = 0; @@ -32,17 +16,49 @@ pub mod field { impl Types { /// The type `range[element]`, for the integer type `element` (an alias - /// is looked through). Its step's type is the unsigned integer as wide - /// as `element`. `None` when `element` is not an integer. + /// is looked through), or an open one (`is_open`), which each copy + /// checks. Its step's type is the unsigned integer as wide as `element`. + /// `None` when `element` is neither. pub fn range(&mut self, element: TypeId) -> Option { + let element = self.real(element); let Type::Integer(integer) = self[element] else { - return None; + return (self.is_open(element)).then(|| self.intern(Type::Range { element })); }; - let element = self.real(element); - let step = self.intern(Type::Integer(Integer { + // Its step's type, which `range_step` finds. + self.intern(Type::Integer(Integer { signed: false, ..integer })); - Some(self.intern(Type::Range { element, step })) + Some(self.intern(Type::Range { element })) + } + + /// The type of a step of a `range[element]` of an integer `element`: + /// the unsigned integer as wide as it. Only `range` makes a range type, + /// and it makes this type first, so it is there to find. + pub fn range_step(&self, element: TypeId) -> TypeId { + let Type::Integer(integer) = self[element] else { + unreachable!("a range is of integers") + }; + self.ids[&Type::Integer(Integer { + signed: false, + ..integer + })] + } + + /// The fields of a value of `range[element]`, in order, each with its + /// name, as debug info shows it, and type: its walk, found once when the + /// range is made (`lower::Lowering::walk_range`). Its values are + /// `start`, then each `delta` more than the one before, wrapping, while + /// `left`, how far its end is, lasts by `step`, the end counted when + /// `inclusive`. `field` gives where each one is. + pub fn range_fields(&self, element: TypeId) -> [(&'static str, TypeId); 5] { + let step = self.range_step(element); + [ + ("start", element), + ("left", step), + ("step", step), + ("delta", element), + ("inclusive", TypeId::BOOL), + ] } } diff --git a/crates/model/src/semantic_types/structs.rs b/crates/model/src/semantic_types/structs.rs index 33ae21dc..1e8b1848 100644 --- a/crates/model/src/semantic_types/structs.rs +++ b/crates/model/src/semantic_types/structs.rs @@ -23,7 +23,7 @@ impl Types { holders: self.holders_in_fields(&fields), mutable_holder: (fields.iter()).any(|&field| self.holds_loans(field) == Some(true)), }; - let slot = &mut self.types[named.0 as usize]; + let slot = &mut self.types[named.0 as usize].ty; let Type::Named { definition, arguments, diff --git a/crates/model/src/semantic_types/tests.rs b/crates/model/src/semantic_types/tests.rs index b3b0b84b..d2d74718 100644 --- a/crates/model/src/semantic_types/tests.rs +++ b/crates/model/src/semantic_types/tests.rs @@ -2,6 +2,7 @@ use super::ConstArgument; use super::Conversion; use super::Float; use super::Integer; +use super::Naming; use super::StructInternals; use super::Type; use super::TypeId; @@ -296,8 +297,9 @@ fn interface_references() { ); } let text = |ty| { - types.text(ty, |definition| { - ["Shape", "Square"][definition.index as usize] + types.text(ty, |naming| match naming { + Naming::Declaration(definition) => ["Shape", "Square"][definition.index as usize], + Naming::Parameter { .. } => unreachable!("no type parameter here"), }) }; assert_eq!(text(view), "&Shape"); @@ -392,8 +394,9 @@ fn type_text() { arguments, }); let text = |ty| { - types.text(ty, |definition| { - ["Point", "Place"][definition.index as usize] + types.text(ty, |naming| match naming { + Naming::Declaration(definition) => ["Point", "Place"][definition.index as usize], + Naming::Parameter { .. } => unreachable!("no type parameter here"), }) }; assert_eq!(text(u24), "u24"); diff --git a/crates/model/src/thir.rs b/crates/model/src/thir.rs index b4d8e303..3b92c14a 100644 --- a/crates/model/src/thir.rs +++ b/crates/model/src/thir.rs @@ -13,6 +13,7 @@ use crate::ModuleId; use crate::constant::Value; use crate::semantic_types::Constant; use crate::semantic_types::ImplementationId; +use crate::semantic_types::Naming; use crate::semantic_types::Type; use crate::semantic_types::TypeId; use crate::semantic_types::Types; @@ -263,6 +264,13 @@ pub enum ExprKind { /// The statements of the block, run where the expression is computed; /// it gives no value (`ty` is `void`). Block(Id), + /// A value each copy computes its own way, in a generic declaration's + /// own check, which never runs: an operation whose meaning depends on an + /// open type (`Types::is_open`), as `t[0]` of a `t: T`, or a call that + /// runs at compile time given one. Its type is what is known of it, + /// else `Type::Undecided`. + Undecided, + /// After an error, reported. Invalid, } @@ -399,6 +407,14 @@ impl Body { found } + /// Whether `kind` or a part of it, going through its parts as + /// `first_named_variable` does, is one each copy computes + /// (`ExprKind::Undecided`), as `size_of(T) + 1` in a generic body. + pub fn holds_undecided(&self, kind: &ExprKind) -> bool { + matches!(kind, ExprKind::Undecided) + || self.any_part(kind, |part| self.holds_undecided(&self.exprs[part].kind)) + } + /// Keeps every temporary made in computing `value`, the value a `let` or /// an assignment gives the variable `kept_by`, as long as `kept_by`: so /// what `kept_by` may hold a loan on lasts as long as it does. @@ -424,6 +440,7 @@ impl Body { ExprKind::Constant(_) | ExprKind::Variable(_) | ExprKind::Block(_) + | ExprKind::Undecided | ExprKind::Invalid => false, ExprKind::Binary { left, right, .. } | ExprKind::Index { @@ -465,7 +482,8 @@ impl Body { } /// The body as text, one statement per line, for `peeper -dump`. `file` is - /// where the body is written; `name_of` gives a declaration's name. A + /// where the body is written; `name_of` gives a declaration's or type + /// parameter's name. A /// variable shows as its name and index (`x.2`), a constant other than a /// `bool` with its type (`1:i32`), an operation in parentheses, and a /// field by its index (`p.0[1]`, `Point.{ [1] = 2:i32 }`). @@ -473,7 +491,7 @@ impl Body { &self, types: &Types, file: &SourceFile, - name_of: impl Fn(DefId) -> N + Copy, + name_of: impl Fn(Naming) -> N + Copy, ) -> String { let mut printer = Printer { body: self, @@ -496,7 +514,7 @@ struct Printer<'b, F> { out: String, } -impl N + Copy> Printer<'_, F> { +impl N + Copy> Printer<'_, F> { /// Each of `statements` on its own line, `depth` levels in. fn write_statements(&mut self, statements: List, depth: usize) { for statement in self.body.children.lists.items(statements) { @@ -652,7 +670,8 @@ impl N + Copy> Printer<'_, F> { } => { match callee { Callee::Function(function) => { - let name = (self.name_of)(function.definition).to_string(); + let name = + (self.name_of)(Naming::Declaration(function.definition)).to_string(); let copy = self.types.copy_text(name, function.arguments, self.name_of); _ = write!(self.out, "call {copy}("); } @@ -722,7 +741,11 @@ impl N + Copy> Printer<'_, F> { self.out.push_str("interface("); self.write_expr(*reference); for &method in self.types.implementation(*implementation) { - _ = write!(self.out, ", {}", (self.name_of)(method)); + _ = write!( + self.out, + ", {}", + (self.name_of)(Naming::Declaration(method)) + ); } _ = write!(self.out, "):{}", self.types.text(*ty, self.name_of)); } @@ -772,6 +795,7 @@ impl N + Copy> Printer<'_, F> { ExprKind::Block(_) => { unreachable!("a block gives no value, so only a statement holds it") } + ExprKind::Undecided => self.out.push_str("undecided"), ExprKind::Invalid => self.out.push_str("invalid"), } } diff --git a/docs/compiler-layout.md b/docs/compiler-layout.md index 2e419467..5414ea5c 100644 --- a/docs/compiler-layout.md +++ b/docs/compiler-layout.md @@ -30,7 +30,9 @@ and inside a phase one list, one dispatch and one file per concept. it copies or holds loans, its text and hash) is one `match` in `semantic_types` or `layout.rs`, with the lints of rule 2, so a new type is a compile error at each. An answer is worked out when asked, - not stored: each is one `match`. The other phases read the answers and + not stored: each is one `match`. One is stored: whether a type is open + (`docs/generics.md`), asked of every type checked, is worked out once + when the type is interned, by the same kind of `match`. The other phases read the answers and do not decide them again. A `match` that asks only "is it an array?" keeps its `_ =>`: a new type is not an array. 5. **Conversions are decided in one file**, `semantic_types/conversions.rs`, diff --git a/docs/feature-front.md b/docs/feature-front.md index 7571fbab..e6b93e29 100644 --- a/docs/feature-front.md +++ b/docs/feature-front.md @@ -90,7 +90,7 @@ with a node of that kind edits them: | `parser::dump::expr` | `ast::Expr` | 29 | | `model::thir::write_expr`, `any_part` | `thir::ExprKind` | 20 each | | `lower::expression::lower_expr` | `thir::ExprKind` | 20 | -| `check::declaration::resolve_type`, `names_type_parameter` | `ast::Type` | 17 each | +| `check::declaration::resolve_type` | `ast::Type` | 17 | | `check::statement::check_statement`, `parser::dump::stmt` | `ast::Stmt` | 14 each | | `model::thir::write_statement`, `lower::statement::lower_statement` | statements | 11 each | | `lower::expression::lower_into` | `thir::ExprKind` | 8 | @@ -126,7 +126,7 @@ largest): | Its elements and their count | `elements`, `count_spread`, `lower_array_literal`, `part_count`, `lower_slice`, `lower_index`, `check_for_array`, `help_spread`, `check_variadic`, `check_field` (`.len`) | | What it views and how | `pointee`, `borrows`, `is_slice_shaped`, `reborrow`, `place_root`, `check_slice`, `lower_borrow` | | Its members and functions | `check_call`, `method`, `implementation`, `check_type_declaration` | -| Its written form | `resolve_type`, `names_type_parameter`, `resolve_signature_type`, `reference_type`, `method_type` | +| Its written form | `resolve_type`, `resolve_signature_type`, `reference_type`, `method_type` | **An operation across two features:** `Types::conversion` (9 features), and `check_binary`'s raw pointer `+` with an integer. Section 4 splits each. diff --git a/docs/generics.md b/docs/generics.md new file mode 100644 index 00000000..64b1b19f --- /dev/null +++ b/docs/generics.md @@ -0,0 +1,47 @@ +# Generics: open types and copies + +A generic declaration (`fn Max`, `struct Box`, a `const T: type` +parameter) is checked twice over: + +1. **Its own check**, once, with no call: each type parameter stands for + itself, `Type::Parameter { definition, place }`. It reports what is + wrong whatever the parameters are, and an editor reads its types + (`given: T`). Its body is never lowered. +2. **Each copy**, one per list of arguments (`Max`), re-reads the + written declaration with the parameters bound (`resolve_global` gives + `Symbol::TypeArgument`). A copy is checked, laid out and lowered like + any declaration. + +## Open types + +A type that holds a `Type::Parameter` or `Type::Undecided` is **open** +(`Types::is_open`, stored at intern: it is asked of every type checked, and +a type never changes once interned). An open type means "each copy +decides". `Type::Invalid` keeps one meaning: an error was reported. + +What depends on an open type is left to each copy, silently, in the own +check: + +| Case | Own check gives | +| --- | --- | +| `t[0]`, `t.*`, `t.x` on a bare `T` | `Type::Undecided`, `ExprKind::Undecided` | +| `t.Name()` on a bare `T` | the arguments are checked; the call is `Undecided` | +| a conversion to or from an open type | `Conversion::Undecided` | +| an operator on an open operand | the operator's own result type | +| printing an open value | the value is left out | +| a `where` constraint on an open subject, a call run at compile time given one | not known (`None`) | +| a field of `Box` | the written field type, re-read with `T` bound (`field_types_given`) | + +An open struct, such as `Box` inside a generic body, stays +`Type::Named`: it has no copy and no layout, since its size is each copy's. + +## Finding type arguments + +A call finds `` by matching types, not syntax: each parameter's type in +the function's own type is the pattern, the argument's type the actual +(`Types::find_parameters`). `Box` against `Box`, `&[]T` against +`&[3]i32` and nested copies all find `T` the same way. + +Given an open argument (a generic body calling another generic function), +no copy is made: the call's type is the callee's own type with the +arguments substituted (`Types::substitute`). diff --git a/docs/structure-mapping.md b/docs/structure-mapping.md index ba05f682..b2e21819 100644 --- a/docs/structure-mapping.md +++ b/docs/structure-mapping.md @@ -102,7 +102,7 @@ API: `Language::string_kind` is removed. Its places: | `declaration.rs`: `FunctionKind`, `check_function`, `is_builtin_declared`, `signature_type`, `result_origins`, `resolve_signature_type` | extract | `functions.rs` | a function's type | | `function.rs`: `function_declaration` | extract | `model::program`, beside `declaration` | a function as written, which `functions`, `generics`, `conformance` and `statement` look up | | `declaration.rs`: `implementation`, `method_type` | extract | `conformance.rs` | whether a type implements an interface; receiver substitution; the cached `ImplementationId` | -| `declaration.rs`: `resolve_type_argument`, `type_argument`, `first_copy_parameter`, `written_inside`, `find_type_argument`, `names_type_parameter` | extract | `generics.rs` | finding and writing type arguments | +| `declaration.rs`: `resolve_type_argument`, `type_argument`, `first_copy_parameter` | extract | `generics.rs` | finding and writing type arguments | | `declaration.rs`: the rest (`check_attributes` for every declaration, type declarations, constants, resolving written types, `is_interface`, `reference_type`, `array_type`, `range_type`, ...) | stays | `declaration.rs` | about 670 of its 1382 lines leave | | `copies.rs` | move | `generics/copies.rs` | the one copy table | | `constraints.rs` | move | `generics/constraints.rs` | `where`: both interface constraints (through `conformance.rs`) and predicate functions run at compile time; neither form changes | diff --git a/test_programs/generic_functions/negative_generic_functions.peep b/test_programs/generic_functions/negative_generic_functions.peep index 6e5bc7a7..a89ca772 100644 --- a/test_programs/generic_functions/negative_generic_functions.peep +++ b/test_programs/generic_functions/negative_generic_functions.peep @@ -39,6 +39,13 @@ fn Width(const T: type) -> usize { return size_of(T); } +// A constant reading what only a run knows is wrong whatever `T` is, so the +// own check reports it, with no call. +fn RunTime(value: T, n: usize) -> usize { //~ label: `n` gets its value only when the program runs + const Y: usize = size_of(T) + n; //~ error[T0004]: the value of a constant must be known at compile time + return Y; +} + fn main() { Make(); //~ error[T0004]: the arguments of `Make` do not say what its `T` is: write it at the call, `Make::<...>(...)` Id::(1); //~ error[T0006]: `Id` takes 1 type argument, but 2 were given diff --git a/test_programs/generic_functions/negative_where_conditions.peep b/test_programs/generic_functions/negative_where_conditions.peep index 2fd36b6b..118fd0f8 100644 --- a/test_programs/generic_functions/negative_where_conditions.peep +++ b/test_programs/generic_functions/negative_where_conditions.peep @@ -154,7 +154,7 @@ where } fn main() { - Loop(1); //~ label: in `Loop`, the copy made here + Loop(1); Max(true, false); //~ error[T0004]: `T: Number` is false for `Max` Whole(Point.{ x = 1 }); //~ error[T0004]: `T: is_int` is false for `Whole` Eight(1); //~ error[T0004]: `T: Sized(8)` is false for `Eight` @@ -166,7 +166,7 @@ fn main() { Max(false, true); //~ error[T0004]: `T: Number` is false for `Max` // Types written at the call are asked about too. Max::(true, false); //~ error[T0004]: `T: Number` is false for `Max` - NotBool(1); //~ label: in `NotBool`, the copy made here + NotBool(1); Twice(true); //~ label: in `Twice`, the copy made here Negate(2.5); //~ label: in `Negate`, the copy made here } diff --git a/test_programs/generic_functions/run_generic_functions.out b/test_programs/generic_functions/run_generic_functions.out index bf561e8f..d4015b72 100644 --- a/test_programs/generic_functions/run_generic_functions.out +++ b/test_programs/generic_functions/run_generic_functions.out @@ -11,3 +11,4 @@ int 32 4 other 1 int 7 1 other 4 +10 11 diff --git a/test_programs/generic_functions/run_generic_functions.peep b/test_programs/generic_functions/run_generic_functions.peep index 54520485..8445765d 100644 --- a/test_programs/generic_functions/run_generic_functions.peep +++ b/test_programs/generic_functions/run_generic_functions.peep @@ -84,6 +84,20 @@ fn Twice(value: T) -> T { // A call on constants runs when compiling. const SEVEN: i32 = Id(7); +// A generic body's constants: one of a known type is worked out once, in +// its own check, which makes the copy it runs; one of `T`, and arithmetic on +// it, each copy works out. +fn SizeTwice(const T: type) -> usize { + return size_of(T) * 2; +} + +fn Sizes(value: T) -> i64 { + const KNOWN: usize = SizeTwice(i32); + const OWN: usize = SizeTwice(T) + 1; + const CAST: i64 = -(size_of(T) as i64); + return (KNOWN + OWN) as i64 + CAST; +} + fn main() { println(Id(1), Id(2.5), Id(true), Id("text")); let big: i64 = 9; @@ -111,4 +125,5 @@ fn main() { let narrow: u7 = 1; Kind(narrow); Kind(Point.{ x = 1 }); + println(Sizes(true), Sizes(1u16)); } diff --git a/test_programs/generic_types/negative_generic_types.peep b/test_programs/generic_types/negative_generic_types.peep index b8a220ac..aa574782 100644 --- a/test_programs/generic_types/negative_generic_types.peep +++ b/test_programs/generic_types/negative_generic_types.peep @@ -12,8 +12,10 @@ struct Grow { //~ error[T0013]: `Grow` holds itself inner: Grow>, } -// Through another struct's field too, and with two fields growing. +// Through another struct's field too: each field that closes the cycle is +// one report, as for any struct. struct Two { //~ error[T0013]: `Two` holds itself +//~ error[T0013]: `Two` holds itself first: Box>, second: Box>, } @@ -42,9 +44,43 @@ fn Uses(g: *Grow, h: Holds, w: Wrong) { let grown = g.*; } +// `T` is found in the argument's own type arguments: a struct without them +// gives none. +fn Take(b: Box) -> T { + return b.value; +} + +// What a `T` can do, each copy decides, and reports at the copy; what is +// wrong whatever `T` is, is reported once, with no call. +fn Sum(items: T) -> i32 { + let mut sum = 0; + for item in items { //~ error[T0043]: `for` over values other than ranges, arrays and slices are not supported yet + sum = sum + item; + } + return sum; +} + +fn Make() -> T { + let made: T = .{ x = 7 }; //~ error[P0007]: this struct literal needs its type: write it before `.{` + return made; +} + +fn First(items: T) -> i32 { + return items[0]; //~ error[T0004]: `bool` cannot be indexed +} + +fn Backward(items: &T) { + let part = &items[5..2]; //~ error[T0004]: slice `5..2` starts after it ends +} + fn main() { + Sum(Plain.{ x = 1 }); //~ label: in `Sum`, the copy made here + Make::(); //~ label: in `Make`, the copy made here + First(true); //~ label: in `First`, the copy made here let b: Box = .{ value = true }; //~ error[T0001]: mismatched types: expected `i32`, found `bool` let e: Box = .{}; //~ error[T0029]: missing field `value` in `Box` // The literal inside reports nothing more. let u: Box = .{ value = .{ x = 1 } }; //~ error[T0002]: unknown type `Unknown` + let p: Plain = .{ x = 1 }; + let t = Take(p); //~ error[T0004]: the arguments of `Take` do not say what its `T` is } diff --git a/test_programs/generic_types/run_generic_types.out b/test_programs/generic_types/run_generic_types.out index ceb9085c..a4eba5d2 100644 --- a/test_programs/generic_types/run_generic_types.out +++ b/test_programs/generic_types/run_generic_types.out @@ -2,3 +2,7 @@ 1 8 16 3 1 6 4 5 16 +3 7 0.5 9 +10 11 12 +13 14 16 +42 14 2 7 2 4 diff --git a/test_programs/generic_types/run_generic_types.peep b/test_programs/generic_types/run_generic_types.peep index 63a8b4ff..a6e9da00 100644 --- a/test_programs/generic_types/run_generic_types.peep +++ b/test_programs/generic_types/run_generic_types.peep @@ -39,6 +39,93 @@ fn Unwrap(b: Box) -> i32 { } // A generic function names a copy with its own `T`. +// A type parameter is found in a generic struct's arguments: `Get(a)` with +// `a: Box` is `Get::`, through a reference and nested copies too. +fn Get(b: Box) -> T { + return b.value; +} + +fn Second(pair: Pair) -> B { + return pair.second; +} + +fn Deepest(boxed: &Box>) -> T { + return boxed.value.value; +} + +fn Echo(boxed: &Box, value: T) -> T { + return value; +} + +// Inside a slice or an array too, and given an array where a slice is taken. +fn FirstOf(boxes: &[]Box) -> T { + return boxes[0].value; +} + +fn LastOf(boxes: [2]Box) -> T { + return boxes[1].value; +} + +type IntBox = Box; + +// What a `T` can do, each copy decides: indexing, `.*` and a field. +fn Head(items: T) -> i32 { + return items[0]; +} + +fn Read(at: T) -> i32 { + return at.*; +} + +fn Inner(boxed: T) -> i32 { + return boxed.value; +} + +fn Sum(items: T) -> i32 { + let mut sum = 0; + for item in items { + sum = sum + item; + } + return sum; +} + +fn Middle(items: &T) -> i32 { + let part = &items[1..3]; + return part[0]; +} + +fn SetX(point: &mut T) { + point.*.x = 2; +} + +fn Make() -> T { + let made: T = .{ x = 7 }; + return made; +} + +fn BorrowX(point: &T) -> i32 { + let x = &point.*.x; + return x.*; +} + +// An undecided value is given to another generic function: each copy finds +// its `T`. +fn Peek(boxed: &Box) -> T { + return boxed.value; +} + +fn PeekFirst(holder: T) -> i32 { + return Peek(&holder.first); +} + +struct Point { + x: i32, +} + +struct Holder { + first: Box, +} + fn Nest(value: T) -> Box> { let made: Box> = .{ value = .{ value = value } }; return made; @@ -59,4 +146,17 @@ fn main() { let chain: Chain = .{ value = 4, next = .{ to = none } }; let deep: Deep = .{ inner = .{ value = .{ value = 5 } } }; println(chain.value, deep.inner.value.value, size_of(Chain::)); + let c: Box = .{ value = 3 }; + println(Get(c), Deepest(&nested), Echo(&b, 0.5), Second(pair)); + let boxes = [2]Box{ .{ value = 10 }, .{ value = 11 } }; + let aliased: IntBox = .{ value = 12 }; + println(FirstOf(&boxes), LastOf(boxes), Get(aliased)); + let items = [3]i32{13, 14, 15}; + let d: Box = .{ value = 16 }; + println(Head(items), Read(&items[1]), Inner(d)); + let mut point = Point.{ x = 0 }; + SetX(&mut point); + let made = Make::(); + let holder = Holder.{ first = .{ value = 4 } }; + println(Sum(items), Middle(&items), point.x, made.x, BorrowX(&point), PeekFirst(holder)); } From 2cedc572c91758809e44be261b76b170d8013578 Mon Sep 17 00:00:00 2001 From: itsfuad Date: Thu, 19 Nov 2026 16:02:23 +0600 Subject: [PATCH 14/24] Make places.rs a type dispatch over the owning concepts `expression/places.rs` decided `value.field`, `array[index]`, `&array[i..j]` and `reference.*` for every concept itself: array length and elements, slice ends, struct fields, raw pointer targets and open types. Each operation is now one exhaustive match on the value's type that hands the work to the concept owning it: - `.len` and element reads move to `arrays.rs`; - slicing, its ends and the slice help for `.*` move to the new `slices.rs`; - finding and reading a struct field moves to `structs.rs`, with the field types of an open struct, which `generics/copies.rs` read from struct syntax; - an open type gives `Expr::UNDECIDED` in one arm per match. The dispatch keeps the errors for a type no concept takes and the shared reach through a pointer. Diagnostics and their order are unchanged. scripts/cross-concepts.py counts the decisions each checker concept file makes about another concept, to measure this layout: 155 before, 127 after, places.rs from 27 to 0. --- crates/check/src/arrays.rs | 114 +++++- crates/check/src/expression/borrows.rs | 2 +- crates/check/src/expression/places.rs | 474 +++++++++---------------- crates/check/src/generics/copies.rs | 48 +-- crates/check/src/lib.rs | 1 + crates/check/src/slices.rs | 121 +++++++ crates/check/src/structs.rs | 124 ++++++- crates/model/src/thir.rs | 7 + scripts/cross-concepts.py | 148 ++++++++ 9 files changed, 676 insertions(+), 363 deletions(-) create mode 100644 crates/check/src/slices.rs create mode 100755 scripts/cross-concepts.py diff --git a/crates/check/src/arrays.rs b/crates/check/src/arrays.rs index b7ef57eb..40d31310 100644 --- a/crates/check/src/arrays.rs +++ b/crates/check/src/arrays.rs @@ -3,16 +3,22 @@ //! `Type::Array` and an `ExprKind::ArrayLiteral`, so the phases after it know //! nothing of this file. A literal's entries and their `...` spreads are //! checked in `expression/literals.rs`, as a call to a `...` parameter checks -//! them too; slices (read after `&`) and indexing in `expression/places.rs`. +//! them too; slices in `slices.rs`. Indexing an array or a slice and their +//! `.len` are here; which values take them, the dispatch decides +//! (`expression/places.rs`). use crate::Checker; use crate::builder; use arena::Id; use arena::List; +use bigint::Limbs; +use diagnostics::suggest::nearest_name; +use model::constant::Value; use model::semantic_types; use model::thir; use source::Span; use tree::ast; +use tree::ast::Ident; /// The type `[length]element`, written at `span`: the length is a whole /// number without a suffix that an array can hold. @@ -87,6 +93,112 @@ pub(crate) fn check_array_literal( } } +/// `value.len`, written `value.field`, where `viewed` is the type of `value` +/// or of what it points to: an array's, a slice's or a `&str`'s length, its +/// only field. An array's type gives it, so the array is not read where +/// computing it runs nothing. +pub(crate) fn check_length( + builder: &mut builder::ThirBuilder<'_, '_>, + value: Id, + viewed: semantic_types::TypeId, + field: Ident, +) -> thir::Expr { + // shortcut: `len` as a field until the language can write it as a free + // function over any array; then move it there. + let text = field.text(&builder.checker.module().ast.file); + if text != "len" { + let viewed = builder.checker.type_text(viewed); + let message = format!("`{viewed}` has no field `{text}`"); + let meant = nearest_name(text, [("len", 0)]).map(str::to_string); + builder + .checker + .report_unknown(diagnostics::UNKNOWN_FIELD, field.span, message, meant); + return thir::Expr::INVALID; + } + let usize = builder.checker.types.usize; + // An array's length is folded only where computing the array runs + // nothing: a variable or constant, its fields and dereferences, and + // elements at constant indexes, which are checked here. A call, a + // run-time index or a literal's parts still run, and may fail. + let mut part = value; + let runs_nothing = loop { + match builder.body.exprs[part].kind { + thir::ExprKind::Variable(_) | thir::ExprKind::Constant(_) => break true, + thir::ExprKind::Field { value, .. } | thir::ExprKind::Dereference(value) => { + part = value; + } + thir::ExprKind::Index { array, index } + if matches!(builder.body.exprs[index].kind, thir::ExprKind::Constant(_)) + && !builder.checker.types[builder.body.exprs[array].ty].is_slice_shaped() => + { + part = array; + } + _ => break false, + } + }; + // A slice's or a `&str`'s length is known only when the program runs: + // read from the value, so through the reference to it, as an array's + // that must still be computed. + let length = builder.checker.types[viewed] + .elements() + .and_then(|(_, length)| length); + let Some(length) = length.filter(|_| runs_nothing) else { + let value = builder.through_pointer(value, builder.body.exprs.span(value)); + return thir::Expr { + ty: usize, + kind: thir::ExprKind::Length(value), + }; + }; + let length = Limbs::new(builder.checker.target.pointer_bits, &[length]); + thir::Expr { + ty: usize, + kind: thir::ExprKind::Constant(Value::Integer(length)), + } +} + +/// `array[index]`, written at `span`: the element at the checked integer +/// `index` of `array`, a checked array or slice in a place. A constant index +/// must be inside an array; a slice's must be at least 0 and fit a `u64`, +/// and is checked when the program runs. +pub(crate) fn check_element( + builder: &mut builder::ThirBuilder<'_, '_>, + array: Id, + index: Id, +) -> thir::Expr { + let ty = builder.body.exprs[array].ty; + let (element, length) = builder.checker.types[ty] + .elements() + .expect("only an array or a slice is indexed"); + let Some(integer) = builder.integer_index(index) else { + return thir::Expr::INVALID; + }; + // A negative constant, or one past `u64`, is outside every slice. + if let thir::ExprKind::Constant(Value::Integer(value)) = &builder.body.exprs[index].kind + && bigint::to_u64(integer.bits, integer.signed, value) + .is_none_or(|at| length.is_some_and(|length| at >= length)) + { + let index_span = builder.body.exprs.span(index); + let written = builder.checker.module().ast.file.slice(index_span); + let viewed = builder.checker.type_text(ty); + let message = match length { + Some(length) => { + format!("index `{written}` is outside `{viewed}`, whose length is {length}") + } + None => format!("index `{written}` is outside every `{viewed}`"), + }; + builder + .checker + .error(diagnostics::INVALID_OPERATION, message, index_span); + return thir::Expr::INVALID; + } + // An element is read through the array's address, so from a place. + builder.make_place(array); + thir::Expr { + ty: element, + kind: thir::ExprKind::Index { array, index }, + } +} + #[cfg(test)] mod tests { //! Checking arrays: the literals' lengths and entries, temporaries, and diff --git a/crates/check/src/expression/borrows.rs b/crates/check/src/expression/borrows.rs index a9e1b402..c9db0c0b 100644 --- a/crates/check/src/expression/borrows.rs +++ b/crates/check/src/expression/borrows.rs @@ -41,7 +41,7 @@ impl ThirBuilder<'_, '_> { /// (`lends_slice_elements`) is decided by its own type, never the /// variable holding it, unless it is behind a shared reference, through /// which nothing is written. - pub(super) fn check_lending(&mut self, ty: TypeId, place: Id) { + pub(crate) fn check_lending(&mut self, ty: TypeId, place: Id) { let (variable, decider) = self.make_place(place); let types = &self.checker.types; let decider = if types.lends_slice_elements(self.body.exprs[place].ty, ty) { diff --git a/crates/check/src/expression/places.rs b/crates/check/src/expression/places.rs index af3e6310..360d5e92 100644 --- a/crates/check/src/expression/places.rs +++ b/crates/check/src/expression/places.rs @@ -1,10 +1,12 @@ -//! Checking places: fields, indexes, slices and dereferences. +//! The dispatch for what reaches into a value: `value.field`, +//! `array[index]`, `&array[start..end]` and `reference.*`. Each looks at the +//! type of the value and hands the work to the concept that owns that type +//! (`arrays.rs`, `slices.rs`, `structs.rs`), reporting a +//! type that none takes. A value whose type each copy decides gives a value +//! each copy computes (`Expr::UNDECIDED`). use arena::Id; -use bigint::Limbs; use diagnostics::Diagnostic; -use diagnostics::suggest::nearest_name; -use model::constant::Value; use model::semantic_types::Integer; use model::semantic_types::Type; use model::semantic_types::TypeId; @@ -15,107 +17,66 @@ use tree::ast; use tree::ast::Ident; use tree::ast::WrittenRange; +use crate::arrays; use crate::builder::ThirBuilder; +use crate::slices; +use crate::structs; impl ThirBuilder<'_, '_> { - /// `value.field`: the field of a struct value, or of the struct a - /// reference or typed raw pointer points to; or `len`, an array's, a - /// slice's or a `&str`'s only field. An array's type gives it, so the - /// array is not read. + /// `value.field`: a field of a struct, or of the struct a reference or + /// typed raw pointer points to; or `len`, an array's, a slice's or a + /// `&str`'s, read without going through a reference to it. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] pub(super) fn check_field(&mut self, value: Id, field: Ident) -> Expr { let value = self.add_expr(value, None); let ty = self.body.exprs[value].ty; - let pointee = self.checker.types[ty].pointee(); - let viewed = pointee.unwrap_or(ty); - // `Some(length)` for an array, `Some(None)` for a slice or a `&str`, - // whose length is known only when the program runs. - let length = match &self.checker.types[viewed] { - Type::Str => Some(None), - other => other.elements().map(|(_, length)| length), - }; - // shortcut: `len` as a field until the language can write it as a - // free function over any array; then move it there. - if let Some(length) = length { - let text = field.text(&self.checker.module().ast.file); - if text != "len" { - let viewed = self.checker.type_text(viewed); - let message = format!("`{viewed}` has no field `{text}`"); - let meant = nearest_name(text, [("len", 0)]).map(str::to_string); - self.checker - .report_unknown(diagnostics::UNKNOWN_FIELD, field.span, message, meant); - return Expr::INVALID; + let viewed = self.checker.types[ty].pointee().unwrap_or(ty); + let span = self.body.exprs.span(value); + match self.checker.types[viewed] { + Type::Array { .. } | Type::Slice { .. } | Type::Str => { + arrays::check_length(self, value, viewed, field) + } + Type::Struct { .. } | Type::Named { .. } => { + let place = self.through_pointer(value, span); + structs::check_field(self, place, field) } - let usize = self.checker.types.usize; - // An array's length is folded only where computing the array runs - // nothing: a variable or constant, its fields and dereferences, - // and elements at constant indexes, which are checked here. A - // call, a run-time index or a literal's parts still run, and may - // fail. - let mut part = value; - let runs_nothing = loop { - match self.body.exprs[part].kind { - ExprKind::Variable(_) | ExprKind::Constant(_) => break true, - ExprKind::Field { value, .. } | ExprKind::Dereference(value) => part = value, - ExprKind::Index { array, index } - if matches!(self.body.exprs[index].kind, ExprKind::Constant(_)) - && !self.checker.types[self.body.exprs[array].ty].is_slice_shaped() => - { - part = array; - } - _ => break false, + Type::Parameter { .. } | Type::Undecided => Expr::UNDECIDED, + Type::Invalid => Expr::INVALID, + Type::Void + | Type::Bool + | Type::Integer(_) + | Type::Float(_) + | Type::CString + | Type::Function { .. } + | Type::Alias { .. } + | Type::Range { .. } + | Type::Reference { .. } + | Type::Interface { .. } + | Type::InterfaceReference { .. } + | Type::RawPointer { .. } => { + // Through a raw pointer, what it reaches is checked first. + let place = self.through_pointer(value, span); + let ty = self.body.exprs[place].ty; + if ty != TypeId::INVALID { + let message = format!("`{}` has no fields", self.checker.type_text(ty)); + self.checker + .error(diagnostics::INVALID_OPERATION, message, field.span); } - }; - // Read from the value, so through the reference to it: a slice's - // or a `&str`'s, or an array's that must still be computed. - let Some(length) = length.filter(|_| runs_nothing) else { - let value = self.through_pointer(value, self.body.exprs.span(value)); - return Expr { - ty: usize, - kind: ExprKind::Length(value), - }; - }; - let length = Limbs::new(self.checker.target.pointer_bits, &[length]); - return Expr { - ty: usize, - kind: ExprKind::Constant(Value::Integer(length)), - }; - } - let value = self.through_pointer(value, self.body.exprs.span(value)); - let ty = self.body.exprs[value].ty; - // A struct given an open type has fields (`open_struct`); what else - // of an open type has, each copy decides. - let open_struct = matches!(self.checker.types[ty], Type::Named { .. }); - if !open_struct && self.checker.types.is_open(ty) { - return Expr { - ty: TypeId::UNDECIDED, - kind: ExprKind::Undecided, - }; - } - if !open_struct && self.checker.types[ty].members().is_none() { - if ty != TypeId::INVALID { - let message = format!("`{}` has no fields", self.checker.type_text(ty)); - self.checker - .error(diagnostics::INVALID_OPERATION, message, field.span); + Expr::INVALID } - return Expr::INVALID; - } - let Some((index, field_type)) = self.field_index(ty, field) else { - return Expr::INVALID; - }; - Expr { - ty: field_type, - kind: ExprKind::Field { - value, - index: index as u32, - }, } } - /// `array[index]`: the element at an integer index of an array in a - /// place, of the array a reference or typed raw pointer points to, or of - /// a slice, written at `span`. A constant index must be inside an array; - /// a slice's must be at least 0 and fit a `u64`, and is checked when the - /// program runs. A written range slices, which only `&` does. + /// `array[index]`, written at `span`: an element of an array or slice + /// in a place, or of one a reference or typed raw pointer points to. A + /// written range slices, which only `&` does. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] pub(super) fn check_index( &mut self, array: Id, @@ -132,64 +93,46 @@ impl ThirBuilder<'_, '_> { let array = self.add_expr(array, None); let array = self.through_pointer(array, self.body.exprs.span(array)); let ty = self.body.exprs[array].ty; - let usize = self.checker.types.usize; - let index = self.add_expr(index, Some(usize)); - let index_type = self.body.exprs[index].ty; - let tree = &self.checker.module().ast; - let index_span = self.body.exprs.span(index); - let elements = self.checker.types[ty].elements(); - // What indexing it means, each copy decides. - if elements.is_none() && self.checker.types.is_open(ty) { - return Expr { - ty: TypeId::UNDECIDED, - kind: ExprKind::Undecided, - }; - } - let (element, length) = elements.unwrap_or((TypeId::INVALID, None)); - if element == TypeId::INVALID { - if ty != TypeId::INVALID { + let index = self.add_expr(index, Some(self.checker.types.usize)); + match self.checker.types[ty] { + Type::Array { .. } | Type::Slice { .. } => { + if let Type::Range { .. } = self.checker.types[self.body.exprs[index].ty] { + let index_span = self.body.exprs.span(index); + self.checker + .not_supported(index_span, "range values as indexes"); + return Expr::INVALID; + } + arrays::check_element(self, array, index) + } + Type::Parameter { .. } | Type::Undecided => Expr::UNDECIDED, + Type::Invalid => Expr::INVALID, + Type::Void + | Type::Bool + | Type::Integer(_) + | Type::Float(_) + | Type::CString + | Type::Str + | Type::Function { .. } + | Type::Alias { .. } + | Type::Named { .. } + | Type::Struct { .. } + | Type::Range { .. } + | Type::Reference { .. } + | Type::Interface { .. } + | Type::InterfaceReference { .. } + | Type::RawPointer { .. } => { let message = format!("`{}` cannot be indexed", self.checker.type_text(ty)); let span = self.body.exprs.span(array); self.checker .error(diagnostics::INVALID_OPERATION, message, span); + Expr::INVALID } - return Expr::INVALID; - } - if let Type::Range { .. } = self.checker.types[index_type] { - self.checker - .not_supported(index_span, "range values as indexes"); - return Expr::INVALID; - } - let Some(integer) = self.integer_index(index) else { - return Expr::INVALID; - }; - // A negative constant, or one past `u64`, is outside every slice. - if let ExprKind::Constant(Value::Integer(value)) = &self.body.exprs[index].kind - && bigint::to_u64(integer.bits, integer.signed, value) - .is_none_or(|at| length.is_some_and(|length| at >= length)) - { - let (written, viewed) = (tree.file.slice(index_span), self.checker.type_text(ty)); - let message = match length { - Some(length) => { - format!("index `{written}` is outside `{viewed}`, whose length is {length}") - } - None => format!("index `{written}` is outside every `{viewed}`"), - }; - self.checker - .error(diagnostics::INVALID_OPERATION, message, index_span); - return Expr::INVALID; - } - // An element is read through the array's address, so from a place. - self.make_place(array); - Expr { - ty: element, - kind: ExprKind::Index { array, index }, } } /// The integer type of the checked index `index`; `None` after an error, /// reported here for a type that is not an integer. - pub(super) fn integer_index(&mut self, index: Id) -> Option { + pub(crate) fn integer_index(&mut self, index: Id) -> Option { let ty = self.body.exprs[index].ty; match self.checker.types[ty] { Type::Integer(integer) => Some(integer), @@ -208,12 +151,13 @@ impl ThirBuilder<'_, '_> { } /// `&array[start..end]`, `&mut` when `mutable`, where `indexed` is - /// `array[start..end]`, its index a written range: a slice of the - /// elements of an array in a place, of one a reference points to, or of - /// a slice's, from `start` up to `end`, each left out or an integer as an - /// index is (`ExprKind::Slice`). Ends known at compile time must be - /// inside the array and in order; others, and every end of a slice's, - /// are checked when the program runs. A step is an error. + /// `array[start..end]`, its index a written range: a slice of an array + /// or slice in a place, or of one a reference points to + /// (`slices::check_slice`). A step is an error. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] pub(super) fn check_slice(&mut self, mutable: bool, indexed: Id) -> Expr { let tree = &self.checker.module().ast; let ast::Expr::Index { @@ -253,142 +197,91 @@ impl ThirBuilder<'_, '_> { // Written `r[i..j]`, so a message names that, as `r[i]`. let array = self.through_pointer(array, tree.exprs.span(indexed)); let ty = self.body.exprs[array].ty; - let Some((element, length)) = self.checker.types[ty].elements() else { - // What slicing it means, each copy decides; the ends are checked. - if self.checker.types.is_open(ty) { - self.check_slice_ends([start, end], inclusive, ty, None, range); - return Expr { - ty: TypeId::UNDECIDED, - kind: ExprKind::Undecided, - }; + match self.checker.types[ty] { + Type::Array { .. } | Type::Slice { .. } => { + slices::check_slice(self, mutable, array, ty, [start, end], inclusive, range) } - if ty != TypeId::INVALID { + // The ends are checked as any slice's. + Type::Parameter { .. } | Type::Undecided => { + slices::check_slice_ends(self, [start, end], inclusive, ty, None, range); + Expr::UNDECIDED + } + Type::Invalid => Expr::INVALID, + Type::Void + | Type::Bool + | Type::Integer(_) + | Type::Float(_) + | Type::CString + | Type::Str + | Type::Function { .. } + | Type::Alias { .. } + | Type::Named { .. } + | Type::Struct { .. } + | Type::Range { .. } + | Type::Reference { .. } + | Type::Interface { .. } + | Type::InterfaceReference { .. } + | Type::RawPointer { .. } => { let message = format!("`{}` cannot be sliced", self.checker.type_text(ty)); self.checker .error(diagnostics::INVALID_OPERATION, message, array_span); + Expr::INVALID } - return Expr::INVALID; - }; - let ends = self.check_slice_ends([start, end], inclusive, ty, length, range); - let Some([start, end]) = ends else { - return Expr::INVALID; - }; - let slice = self.checker.types.intern(Type::Slice { mutable, element }); - self.check_lending(slice, array); - Expr { - ty: slice, - kind: ExprKind::Slice { - array, - start, - end, - inclusive, - }, - } - } - - /// The ends, each left out or written, of the slice of `viewed`, an - /// array type of `length` elements or a slice type (no `length`), by - /// the written range `range`, `..=` when `inclusive`: integers of one - /// type, `usize` for literals without a suffix. Ends known at compile - /// time must be inside the array, or fit a `usize` for a slice, and in - /// order when both are; `None` after an error. - pub(super) fn check_slice_ends( - &mut self, - ends: [Option>; 2], - inclusive: bool, - viewed: TypeId, - length: Option, - range: Id, - ) -> Option<[Option>; 2]> { - // No slice is longer than the largest `usize`. - let limit = length.unwrap_or(u64::MAX >> (64 - self.checker.target.pointer_bits)); - let usize = Some(self.checker.types.usize); - let ends = match ends { - [Some(start), Some(end)] => { - let (start, end) = self.check_range_ends(start, end, usize); - [Some(start), Some(end)] - } - ends => ends.map(|end| end.map(|end| self.add_expr(end, usize))), - }; - // How many elements come before each end when known at compile - // time: a missing start is 0, a missing end the length; a written - // `..=` end has one more, past it. - let mut before_ends = [Some(0), length]; - let mut outside = false; - let past = [0, u64::from(inclusive)]; - for ((before, end), past) in before_ends.iter_mut().zip(ends).zip(past) { - let Some(end) = end else { - continue; - }; - let integer = self.integer_index(end)?; - let ExprKind::Constant(Value::Integer(value)) = &self.body.exprs[end].kind else { - *before = None; - continue; - }; - // A negative end, or one past `u64`, is outside every array. - let known = bigint::to_u64(integer.bits, integer.signed, value) - .and_then(|at| at.checked_add(past)); - outside |= known.is_none_or(|known| known > limit); - *before = known; } - let tree = &self.checker.module().ast; - let range_span = tree.exprs.span(range); - let written = tree.file.slice(range_span); - let error = if outside { - let viewed = self.checker.type_text(viewed); - match length { - Some(length) => { - format!("slice `{written}` is outside `{viewed}`, whose length is {length}") - } - None => format!("slice `{written}` is outside every `{viewed}`"), - } - } else if let [Some(first), Some(last)] = before_ends - && first > last - { - format!("slice `{written}` starts after it ends") - } else { - return Some(ends); - }; - self.checker - .error(diagnostics::INVALID_OPERATION, error, range_span); - None } - /// `reference.*`, written at `span`: the value a reference or a typed - /// raw pointer points to. + /// `reference.*`, written at `span`: the value a reference, an interface + /// reference or a typed raw pointer points to. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] pub(super) fn check_dereference(&mut self, reference: Id, span: Span) -> Expr { let reference = self.add_expr(reference, None); let ty = self.body.exprs[reference].ty; - match &self.checker.types[ty] { - pointer if let Some(target) = pointer.pointee() => self.dereference(reference, target), - Type::Invalid => Expr::INVALID, - // What it reaches, each copy decides. - _ if self.checker.types.is_open(ty) => Expr { - ty: TypeId::UNDECIDED, - kind: ExprKind::Undecided, - }, - found => { - let message = format!( - "`.*` needs a reference or a typed raw pointer, found `{}`", - self.checker.type_text(ty) - ); + let help = match self.checker.types[ty] { + Type::Reference { target, .. } + | Type::InterfaceReference { + interface: target, .. + } + | Type::RawPointer { + target: Some(target), + } => return self.dereference(reference, target), + Type::Parameter { .. } | Type::Undecided => return Expr::UNDECIDED, + Type::Invalid => return Expr::INVALID, + Type::Slice { .. } => { let file = &self.checker.module().ast.file; - let mut error = - Diagnostic::new(diagnostics::INVALID_OPERATION, message).label(file, span, ""); - // Rust writes `&*s` to lend a slice again; Peeper has no bare - // element type for `.*` to give, so the help names what does. - if let Type::Slice { .. } = found { - let text = file.slice(self.body.exprs.span(reference)); - let help = format!( - "a slice is lent again as it is (`f({text})`), or as `&{text}[..]` / \ - `&mut {text}[..]`" - ); - error = error.help(help, Vec::new()); - } - self.checker.report(error); - Expr::INVALID + Some(slices::lend_again_help( + file.slice(self.body.exprs.span(reference)), + )) } + Type::Void + | Type::Bool + | Type::Integer(_) + | Type::Float(_) + | Type::CString + | Type::Str + | Type::Function { .. } + | Type::Alias { .. } + | Type::Named { .. } + | Type::Struct { .. } + | Type::Array { .. } + | Type::Range { .. } + | Type::Interface { .. } + | Type::RawPointer { target: None } => None, + }; + let message = format!( + "`.*` needs a reference or a typed raw pointer, found `{}`", + self.checker.type_text(ty) + ); + let file = &self.checker.module().ast.file; + let mut error = + Diagnostic::new(diagnostics::INVALID_OPERATION, message).label(file, span, ""); + if let Some(help) = help { + error = error.help(help, Vec::new()); } + self.checker.report(error); + Expr::INVALID } /// `value`, or what it refers to when it is a reference or a typed raw @@ -403,14 +296,13 @@ impl ThirBuilder<'_, '_> { } /// What `reference`, whose type refers to `target`, refers to: a place. - pub(super) fn dereference(&mut self, reference: Id, target: TypeId) -> Expr { - let pointer = self.body.exprs[reference].ty; + fn dereference(&mut self, reference: Id, target: TypeId) -> Expr { let span = self.body.exprs.span(reference); // A pointer only names its target, which may hold it (`*Node` in // `Node`): reaching through it uses the target as a value, invalid // for a struct with an error, where lowering stops. let target = self.checker.value_type_at(target, span); - let ty = match self.checker.types[pointer] { + let ty = match self.checker.types[self.body.exprs[reference].ty] { Type::RawPointer { .. } if target != TypeId::INVALID => { let held = self.checker.reached_through_pointer(target, span); held.unwrap_or(TypeId::INVALID) @@ -424,42 +316,4 @@ impl ThirBuilder<'_, '_> { kind: ExprKind::Dereference(reference), } } - - /// The index of the field `name` of the struct type `ty`, in - /// declaration order, and its type; `None` after reporting that the type - /// has no such field, with its nearest field name. A struct given an - /// open type has no copy holding its fields' types: they are read again - /// with what it is given (`field_types_given`). - pub(crate) fn field_index(&mut self, ty: TypeId, name: Ident) -> Option<(usize, TypeId)> { - let (Type::Struct { definition, .. } | Type::Named { definition, .. }) = - self.checker.types[ty] - else { - unreachable!("only a struct has fields") - }; - let file = &self.checker.module().ast.file; - let text = name.text(file); - let modules = self.checker.modules; - let Some(index) = - model::program::field_names(modules, definition).position(|field| field == text) - else { - let message = format!("`{}` has no field `{text}`", self.checker.type_text(ty)); - let fields = model::program::field_names(modules, definition).map(|field| (field, 0)); - let meant = nearest_name(text, fields).map(str::to_string); - self.checker - .report_unknown(diagnostics::UNKNOWN_FIELD, name.span, message, meant); - return None; - }; - let field_type = match self.checker.types[ty] { - Type::Named { arguments, .. } => self - .checker - .field_types_given(definition, arguments, name.span)[index], - _ => { - self.checker.types[ty] - .members() - .expect("a struct has members") - .fields[index] - } - }; - Some((index, field_type)) - } } diff --git a/crates/check/src/generics/copies.rs b/crates/check/src/generics/copies.rs index 1883e5c8..e0b64839 100644 --- a/crates/check/src/generics/copies.rs +++ b/crates/check/src/generics/copies.rs @@ -22,6 +22,7 @@ use crate::COPY_DEPTH_LIMIT; use crate::Checker; use crate::Checking; use crate::Copied; +use crate::structs; impl Checker<'_> { /// The type of `copy`, asked for at `used_at`: given nothing, its @@ -144,58 +145,13 @@ impl Checker<'_> { if self.copy_type(own, span) == semantic_types::TypeId::INVALID { return semantic_types::TypeId::INVALID; } - let fields = self.field_types_given(definition, arguments, span); + let fields = structs::field_types_given(self, definition, arguments, span); if fields.contains(&semantic_types::TypeId::INVALID) { return semantic_types::TypeId::INVALID; } named } - /// The types of the fields of the struct `definition`, in order, given - /// `arguments`, asked for at `span`: each as its declaration writes it, - /// read again with them (`resolve_value_type`), recording nothing, once - /// for each `arguments`. For a struct given an open type, which has no - /// copy to hold them. - pub(crate) fn field_types_given( - &mut self, - definition: DefId, - arguments: ConstArguments, - span: Span, - ) -> &[semantic_types::TypeId] { - let given = DeclarationCopy { - definition, - arguments, - }; - if self.internals.open_struct_fields.contains_key(&given) { - return &self.internals.open_struct_fields[&given]; - } - let tree = &self.modules[definition.module.index()].ast; - let ast::Decl::Type(written) = tree.decls[tree.declaration(definition.index)] else { - unreachable!("only a struct declaration is given type arguments"); - }; - let ast::Type::Struct { fields } = tree.types[written.ty] else { - unreachable!("only a struct declaration is given type arguments"); - }; - let written: Vec> = (tree.children.lists.items(fields)) - .map(|field| tree.children.fields[field].ty) - .collect(); - let checking = Checking { - definition, - arguments, - used_at: span, - records_facts: false, - }; - let fields = self.checking_in(checking, |checker| { - (written.into_iter()) - .map(|ty| checker.resolve_value_type(ty)) - .collect() - }); - self.internals - .open_struct_fields - .entry(given) - .or_insert(fields) - } - /// A copy of a function whose body the compile has not built /// (`build_function`), the newest first; building one may make more. /// None once copies nested too deep. diff --git a/crates/check/src/lib.rs b/crates/check/src/lib.rs index 2ced7b27..b7f5fc83 100644 --- a/crates/check/src/lib.rs +++ b/crates/check/src/lib.rs @@ -23,6 +23,7 @@ mod pipes; mod printing; mod ranges; mod raw_pointers; +mod slices; mod structs; /// Why a call of `callee` with `given` arguments is wrong, when it takes /// `fixed` of them, or at least that many when `variadic`. diff --git a/crates/check/src/slices.rs b/crates/check/src/slices.rs new file mode 100644 index 00000000..488d4d5d --- /dev/null +++ b/crates/check/src/slices.rs @@ -0,0 +1,121 @@ +//! Slices in the checker: `&array[start..end]` and `&mut array[start..end]`, +//! a view of an array's or another slice's elements. The checker gives a +//! `Type::Slice` and an `ExprKind::Slice`, so the phases after it know +//! nothing of this file. Which values can be sliced, the dispatch decides +//! (`expression/places.rs`). + +use crate::builder; +use arena::Id; +use model::constant::Value; +use model::semantic_types; +use model::thir; +use tree::ast; + +/// The slice, `&mut` when `mutable`, of the elements of `array`, a checked +/// array or slice in a place, of the type `viewed`, from `start` up to `end`, +/// `..=` when `inclusive`, written as the range `range`: each end left out +/// or an integer, as an index is (`check_slice_ends`). +pub(crate) fn check_slice( + builder: &mut builder::ThirBuilder<'_, '_>, + mutable: bool, + array: Id, + viewed: semantic_types::TypeId, + [start, end]: [Option>; 2], + inclusive: bool, + range: Id, +) -> thir::Expr { + let (element, length) = builder.checker.types[viewed] + .elements() + .expect("only an array or a slice is sliced"); + let ends = check_slice_ends(builder, [start, end], inclusive, viewed, length, range); + let Some([start, end]) = ends else { + return thir::Expr::INVALID; + }; + let slice = (builder.checker.types).intern(semantic_types::Type::Slice { mutable, element }); + builder.check_lending(slice, array); + thir::Expr { + ty: slice, + kind: thir::ExprKind::Slice { + array, + start, + end, + inclusive, + }, + } +} + +/// The ends, each left out or written, of the slice of `viewed`, an +/// array type of `length` elements or a slice type (no `length`), by +/// the written range `range`, `..=` when `inclusive`: integers of one +/// type, `usize` for literals without a suffix. Ends known at compile +/// time must be inside the array, or fit a `usize` for a slice, and in +/// order when both are; `None` after an error. +pub(crate) fn check_slice_ends( + builder: &mut builder::ThirBuilder<'_, '_>, + ends: [Option>; 2], + inclusive: bool, + viewed: semantic_types::TypeId, + length: Option, + range: Id, +) -> Option<[Option>; 2]> { + // No slice is longer than the largest `usize`. + let limit = length.unwrap_or(u64::MAX >> (64 - builder.checker.target.pointer_bits)); + let usize = Some(builder.checker.types.usize); + let ends = match ends { + [Some(start), Some(end)] => { + let (start, end) = builder.check_range_ends(start, end, usize); + [Some(start), Some(end)] + } + ends => ends.map(|end| end.map(|end| builder.add_expr(end, usize))), + }; + // How many elements come before each end when known at compile + // time: a missing start is 0, a missing end the length; a written + // `..=` end has one more, past it. + let mut before_ends = [Some(0), length]; + let mut outside = false; + let past = [0, u64::from(inclusive)]; + for ((before, end), past) in before_ends.iter_mut().zip(ends).zip(past) { + let Some(end) = end else { + continue; + }; + let integer = builder.integer_index(end)?; + let thir::ExprKind::Constant(Value::Integer(value)) = &builder.body.exprs[end].kind else { + *before = None; + continue; + }; + // A negative end, or one past `u64`, is outside every array. + let known = + bigint::to_u64(integer.bits, integer.signed, value).and_then(|at| at.checked_add(past)); + outside |= known.is_none_or(|known| known > limit); + *before = known; + } + let tree = &builder.checker.module().ast; + let range_span = tree.exprs.span(range); + let written = tree.file.slice(range_span); + let error = if outside { + let viewed = builder.checker.type_text(viewed); + match length { + Some(length) => { + format!("slice `{written}` is outside `{viewed}`, whose length is {length}") + } + None => format!("slice `{written}` is outside every `{viewed}`"), + } + } else if let [Some(first), Some(last)] = before_ends + && first > last + { + format!("slice `{written}` starts after it ends") + } else { + return Some(ends); + }; + builder + .checker + .error(diagnostics::INVALID_OPERATION, error, range_span); + None +} + +/// What to write instead of `.*` on the slice written `text`: a slice has +/// no bare element type for `.*` to give, so the help names what lends it +/// again. +pub(crate) fn lend_again_help(text: &str) -> String { + format!("a slice is lent again as it is (`f({text})`), or as `&{text}[..]` / `&mut {text}[..]`") +} diff --git a/crates/check/src/structs.rs b/crates/check/src/structs.rs index 3134497e..374c6bbc 100644 --- a/crates/check/src/structs.rs +++ b/crates/check/src/structs.rs @@ -1,14 +1,18 @@ //! Structs: checking `struct { name: Type, ... }` declarations and -//! `Type.{ name = value, ... }` literals. The checker gives a `Type::Struct` -//! and a `ExprKind::StructLiteral`, so the phases after it know nothing of -//! this file. Reading a field, as in `point.x`, is checked in -//! `expression/places.rs`. +//! `Type.{ name = value, ... }` literals, and reading a field, as in +//! `point.x`. The checker gives a `Type::Struct`, an `ExprKind::StructLiteral` +//! and an `ExprKind::Field`, so the phases after it know nothing of this +//! file. Which values have fields, the dispatch decides +//! (`expression/places.rs`). use crate::builder; use crate::scope; use arena::Id; use arena::List; use diagnostics::Diagnostic; +use diagnostics::suggest::nearest_name; +use model::ConstArguments; +use model::DeclarationCopy; use model::DefId; use model::layout; use model::semantic_types; @@ -16,8 +20,10 @@ use model::thir; use source::Span; use std::num; use tree::ast; +use tree::ast::Ident; use crate::Checker; +use crate::Checking; /// The type a struct type written at `span` names: none yet, as only a /// declared struct is checked. @@ -146,7 +152,7 @@ pub(crate) fn check_struct_literal( let mut checked: Vec = Vec::with_capacity(fields.len()); for field in tree.children.lists.items(fields) { let ast::FieldValue { name, value } = tree.children.field_values[field]; - let Some((index, field_type)) = builder.field_index(ty, name) else { + let Some((index, field_type)) = field_index(builder, ty, name) else { builder.add_expr(value, Some(semantic_types::TypeId::INVALID)); // for its own errors continue; }; @@ -198,3 +204,111 @@ pub(crate) fn check_struct_literal( kind: thir::ExprKind::StructLiteral(builder.body.children.lists.add(&checked)), } } + +/// `place.name`: the field `name` of `place`, a checked struct in a place. +pub(crate) fn check_field( + builder: &mut builder::ThirBuilder<'_, '_>, + place: Id, + name: Ident, +) -> thir::Expr { + let ty = builder.body.exprs[place].ty; + let Some((index, field_type)) = field_index(builder, ty, name) else { + return thir::Expr::INVALID; + }; + thir::Expr { + ty: field_type, + kind: thir::ExprKind::Field { + value: place, + index: index as u32, + }, + } +} + +/// The index of the field `name` of the struct type `ty`, in declaration +/// order, and its type; `None` after reporting that the type has no such +/// field, with its nearest field name. A struct given an open type has no +/// copy holding its fields' types: they are read with what it is given +/// (`field_types_given`). +fn field_index( + builder: &mut builder::ThirBuilder<'_, '_>, + ty: semantic_types::TypeId, + name: Ident, +) -> Option<(usize, semantic_types::TypeId)> { + let (semantic_types::Type::Struct { definition, .. } + | semantic_types::Type::Named { definition, .. }) = builder.checker.types[ty] + else { + unreachable!("only a struct has fields") + }; + let file = &builder.checker.module().ast.file; + let text = name.text(file); + let modules = builder.checker.modules; + let Some(index) = + model::program::field_names(modules, definition).position(|field| field == text) + else { + let message = format!("`{}` has no field `{text}`", builder.checker.type_text(ty)); + let fields = model::program::field_names(modules, definition).map(|field| (field, 0)); + let meant = nearest_name(text, fields).map(str::to_string); + builder + .checker + .report_unknown(diagnostics::UNKNOWN_FIELD, name.span, message, meant); + return None; + }; + let field_type = match builder.checker.types[ty] { + semantic_types::Type::Named { arguments, .. } => { + field_types_given(builder.checker, definition, arguments, name.span)[index] + } + _ => { + builder.checker.types[ty] + .members() + .expect("a struct has members") + .fields[index] + } + }; + Some((index, field_type)) +} + +/// The types of the fields of the struct `definition`, in order, given +/// `arguments`, asked for at `span`: each as its declaration writes it, +/// read again with them (`resolve_value_type`), recording nothing, once +/// for each `arguments`. For a struct given an open type, which has no +/// copy to hold them. +pub(crate) fn field_types_given<'c>( + checker: &'c mut Checker<'_>, + definition: DefId, + arguments: ConstArguments, + span: Span, +) -> &'c [semantic_types::TypeId] { + let given = DeclarationCopy { + definition, + arguments, + }; + if checker.internals.open_struct_fields.contains_key(&given) { + return &checker.internals.open_struct_fields[&given]; + } + let tree = &checker.modules[definition.module.index()].ast; + let ast::Decl::Type(written) = tree.decls[tree.declaration(definition.index)] else { + unreachable!("only a struct declaration is given type arguments"); + }; + let ast::Type::Struct { fields } = tree.types[written.ty] else { + unreachable!("only a struct declaration is given type arguments"); + }; + let written: Vec> = (tree.children.lists.items(fields)) + .map(|field| tree.children.fields[field].ty) + .collect(); + let checking = Checking { + definition, + arguments, + used_at: span, + records_facts: false, + }; + let fields = checker.checking_in(checking, |checker| { + (written.into_iter()) + .map(|ty| checker.resolve_value_type(ty)) + .collect() + }); + checker + .internals + .open_struct_fields + .entry(given) + .or_insert(fields) +} diff --git a/crates/model/src/thir.rs b/crates/model/src/thir.rs index 3b92c14a..4ca89072 100644 --- a/crates/model/src/thir.rs +++ b/crates/model/src/thir.rs @@ -153,6 +153,13 @@ impl Expr { ty: TypeId::INVALID, kind: ExprKind::Invalid, }; + + /// A value each copy computes its own way (`ExprKind::Undecided`), of a + /// type each copy decides. + pub const UNDECIDED: Expr = Expr { + ty: TypeId::UNDECIDED, + kind: ExprKind::Undecided, + }; } #[derive(Clone, Debug)] diff --git a/scripts/cross-concepts.py b/scripts/cross-concepts.py new file mode 100755 index 00000000..0726c5b0 --- /dev/null +++ b/scripts/cross-concepts.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +"""Counts, in each concept file of the checker, the decisions it makes about +another concept: matching its checked types (`Type::Struct`) or syntax nodes +(`ast::Type::Struct`), calling its own functions, or deciding for open types +outside generics (docs/compiler-layout.md: one file per concept, one +dispatch). THIR nodes are core ideas (rule 6) and the type table's +questions, such as `elements()`, are the base API (rule 4): neither counts, +nor do core kinds (integers, bool, void, invalid, functions, calls, +variables), which no feature owns. Each use in a code line counts once. +Files not in `FILES` are skipped: the engine (`lib.rs`, `builder.rs`, +`scope.rs`, `testing.rs`) and the dispatch files, which name every kind to +pick its owner (`expression.rs`, `statement.rs`, `declaration.rs`, `fold.rs`, +`expression/places.rs`). + + python3 scripts/cross-concepts.py [list.md] + +prints the count per file; with a path, also writes every decision, by file +and function, there. It matches text, so a local named like a concept's +function counts too. +""" +import re +import sys +from collections import Counter, defaultdict +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent / "crates/check/src" + +# What each concept owns: a pattern per kind or question. +OWNERS = { + "generics": [r"Type::Parameter\b", r"Type::Undecided\b", r"TypeId::UNDECIDED\b", + r"ExprKind::Undecided\b", r"Conversion::Undecided\b", r"\bis_open\(", + r"\barguments_open\(", r"\bin_own_check\(", r"\bholds_undecided\(", + r"\bopen_struct\(", r"\bcopy_type\(", + r"\bown_arguments\("], + "text": [r"Type::CString\b", r"Type::Str\b", r"TypeId::STR\b", r"TypeId::CSTR\b"], + "aliases": [r"Type::Alias\b"], + "structs": [r"Type::Struct\b", r"Type::Named\b", r"\bfield_index\(", + r"\bfield_types_given\("], + "arrays": [r"Type::Array\b", r"\btypes\.array\("], + "slices": [r"Type::Slice\b"], + "ranges": [r"Type::Range\b", r"\brange_step\(", r"\brange_fields\(", r"\btypes\.range\("], + "references": [r"Type::Reference\b", r"\breborrow"], + "interfaces": [r"Type::Interface\b", r"Type::InterfaceReference\b", r"\bis_interface\(", + r"\bimplementation\(", r"\binterface_method\("], + "raw_pointers": [r"Type::RawPointer\b", r"\breached_through_pointer\("], + "printing": [r"\bprintable\(", r"\bcheck_print\("], + "constants": [r"\bknown_constant\(", r"\bcheck_constant_value\(", r"\bin_constant\b"], +} +# The syntax kinds each concept owns. +SYNTAX = { + "generics": ["Type::Generic", "Type::Type"], + "ranges": ["Type::Bracketed", "Expr::Range"], + "references": ["Type::Reference", "Expr::Reference", "Expr::Dereference"], + "slices": ["Type::Slice"], + "arrays": ["Type::Array", "Expr::Index", "Expr::Spread", "Expr::ArrayLiteral"], + "enums": ["Type::Enum", "Expr::CaseTest", "Expr::VariantLiteral", "Stmt::Match"], + "interfaces": ["Type::Interface"], + "optionals": ["Type::Optional", "Expr::OrElse", "Expr::None"], + "raw_pointers": ["Type::Pointer", "Expr::RawAddress"], + "structs": ["Type::Struct", "Expr::StructLiteral", "Expr::Selector"], + "operators": ["Expr::Binary", "Expr::Unary"], + "text": ["Expr::String", "Expr::Char"], + "pipes": ["Expr::Pipe"], + "printing": ["Expr::Print"], + "loops": ["Stmt::Loop", "Stmt::ForIn"], +} +for owner, kinds in SYNTAX.items(): + OWNERS.setdefault(owner, []).extend(r"ast::" + kind + r"\b" for kind in kinds) + +# Each concept file and the concepts it owns. +FILES = { + "arrays.rs": {"arrays"}, + "chars.rs": {"text"}, + "conformance.rs": {"interfaces"}, + "enums.rs": {"enums"}, + "expression/borrows.rs": {"references"}, + "expression/literals.rs": {"literals"}, + "expression/names.rs": set(), + "expression/operators.rs": {"operators"}, + "fold/conversions.rs": set(), + "fold/operators.rs": {"operators"}, + "functions.rs": set(), + "functions/bodies.rs": set(), + "functions/builtin.rs": set(), + "functions/calls.rs": set(), + "generics.rs": {"generics"}, + "generics/constraints.rs": {"generics"}, + "generics/copies.rs": {"generics"}, + "interfaces.rs": {"interfaces"}, + "locals.rs": {"constants"}, + "optionals.rs": {"optionals"}, + "pipes.rs": {"pipes"}, + "printing.rs": {"printing"}, + "ranges.rs": {"ranges"}, + "raw_pointers.rs": {"raw_pointers"}, + "slices.rs": {"slices"}, + "statement/assignments.rs": set(), + "statement/loops.rs": {"loops"}, + "structs.rs": {"structs"}, +} + +FN = re.compile(r"^\s*(?:pub(?:\([a-z]+\))?\s+)?fn\s+([a-z_0-9]+)") +compiled = [(owner, re.compile(p)) for owner, ps in OWNERS.items() for p in ps] + +per_file = {} +for name, own in FILES.items(): + path = ROOT / name + function = "(top)" + found = [] + in_tests = False + for number, line in enumerate(path.read_text().splitlines(), 1): + if re.match(r"^\s*#\[cfg\(test\)\]", line): + in_tests = True + if in_tests: + continue + code = line.split("//")[0] + match = FN.match(code) + if match: + function = match.group(1) + for owner, pattern in compiled: + if owner in own: + continue + for hit in pattern.finditer(code): + found.append((number, function, hit.group(0).strip("(."), owner)) + per_file[name] = found + +total = sum(len(found) for found in per_file.values()) +print(f"total cross decisions: {total}\n") +print(f"{'file':28} {'count':>5} by owner") +for name, found in sorted(per_file.items(), key=lambda item: -len(item[1])): + if not found: + continue + owners = Counter(owner for *_, owner in found) + text = ", ".join(f"{owner} {count}" for owner, count in owners.most_common()) + print(f"{name:28} {len(found):>5} {text}") +print("\nclean:", ", ".join(name for name, found in per_file.items() if not found) or "none") + +if len(sys.argv) > 1: + with open(sys.argv[1], "w") as out: + for name, found in sorted(per_file.items(), key=lambda item: -len(item[1])): + if not found: + continue + out.write(f"\n## {name} ({len(found)})\n") + by_function = defaultdict(list) + for number, function, what, owner in found: + by_function[function].append(f"{owner}: {what} (line {number})") + for function, items in by_function.items(): + out.write(f"- `{function}`: " + "; ".join(items) + "\n") From bf9e75c710621eae53334aa4fbe36294adb396e6 Mon Sep 17 00:00:00 2001 From: itsfuad Date: Thu, 19 Nov 2026 17:13:43 +0600 Subject: [PATCH 15/24] Ask the type table in the places dispatch Each of the four dispatches in expression/places.rs listed every checked type to pick an owner, so the same lists were written four times. They now ask the type table what the value's type has: `elements`, `is_slice_shaped`, `pointee`, and two new questions, `has_fields` (a struct, a copy or one given an open type) and `is_decided_per_copy` (a bare type parameter or undecided). `is_open` would be wrong there: `[2]T` and `Box` are open but still have elements and fields. The questions keep their `_ =>`, as docs/compiler-layout.md rule 4 asks of a match that only asks "is it one of these?". --- crates/check/src/expression/places.rs | 217 +++++++-------------- crates/model/src/semantic_types.rs | 7 + crates/model/src/semantic_types/structs.rs | 6 + 3 files changed, 86 insertions(+), 144 deletions(-) diff --git a/crates/check/src/expression/places.rs b/crates/check/src/expression/places.rs index 360d5e92..324f4e18 100644 --- a/crates/check/src/expression/places.rs +++ b/crates/check/src/expression/places.rs @@ -1,9 +1,10 @@ //! The dispatch for what reaches into a value: `value.field`, -//! `array[index]`, `&array[start..end]` and `reference.*`. Each looks at the -//! type of the value and hands the work to the concept that owns that type -//! (`arrays.rs`, `slices.rs`, `structs.rs`), reporting a -//! type that none takes. A value whose type each copy decides gives a value -//! each copy computes (`Expr::UNDECIDED`). +//! `array[index]`, `&array[start..end]` and `reference.*`. Each asks the +//! type table what the value's type has (`elements`, `has_fields`, +//! `pointee`) and hands the work to the concept that owns it (`arrays.rs`, +//! `slices.rs`, `structs.rs`), reporting a type that has none. A value whose +//! type each copy decides gives a value each copy computes +//! (`Expr::UNDECIDED`). use arena::Id; use diagnostics::Diagnostic; @@ -26,57 +27,40 @@ impl ThirBuilder<'_, '_> { /// `value.field`: a field of a struct, or of the struct a reference or /// typed raw pointer points to; or `len`, an array's, a slice's or a /// `&str`'s, read without going through a reference to it. - #[deny( - clippy::wildcard_enum_match_arm, - clippy::match_wildcard_for_single_variants - )] pub(super) fn check_field(&mut self, value: Id, field: Ident) -> Expr { let value = self.add_expr(value, None); let ty = self.body.exprs[value].ty; let viewed = self.checker.types[ty].pointee().unwrap_or(ty); let span = self.body.exprs.span(value); - match self.checker.types[viewed] { - Type::Array { .. } | Type::Slice { .. } | Type::Str => { - arrays::check_length(self, value, viewed, field) - } - Type::Struct { .. } | Type::Named { .. } => { - let place = self.through_pointer(value, span); - structs::check_field(self, place, field) - } - Type::Parameter { .. } | Type::Undecided => Expr::UNDECIDED, - Type::Invalid => Expr::INVALID, - Type::Void - | Type::Bool - | Type::Integer(_) - | Type::Float(_) - | Type::CString - | Type::Function { .. } - | Type::Alias { .. } - | Type::Range { .. } - | Type::Reference { .. } - | Type::Interface { .. } - | Type::InterfaceReference { .. } - | Type::RawPointer { .. } => { - // Through a raw pointer, what it reaches is checked first. - let place = self.through_pointer(value, span); - let ty = self.body.exprs[place].ty; - if ty != TypeId::INVALID { - let message = format!("`{}` has no fields", self.checker.type_text(ty)); - self.checker - .error(diagnostics::INVALID_OPERATION, message, field.span); - } - Expr::INVALID - } + let types = &self.checker.types; + // `&str` has a length as a slice does: an address, then a length. + if types[viewed].elements().is_some() || types[viewed].is_slice_shaped() { + return arrays::check_length(self, value, viewed, field); + } + if types[viewed].has_fields() { + let place = self.through_pointer(value, span); + return structs::check_field(self, place, field); + } + if types[viewed].is_decided_per_copy() { + return Expr::UNDECIDED; + } + if viewed == TypeId::INVALID { + return Expr::INVALID; + } + // Through a raw pointer, what it reaches is checked first. + let place = self.through_pointer(value, span); + let ty = self.body.exprs[place].ty; + if ty != TypeId::INVALID { + let message = format!("`{}` has no fields", self.checker.type_text(ty)); + self.checker + .error(diagnostics::INVALID_OPERATION, message, field.span); } + Expr::INVALID } /// `array[index]`, written at `span`: an element of an array or slice /// in a place, or of one a reference or typed raw pointer points to. A /// written range slices, which only `&` does. - #[deny( - clippy::wildcard_enum_match_arm, - clippy::match_wildcard_for_single_variants - )] pub(super) fn check_index( &mut self, array: Id, @@ -94,40 +78,26 @@ impl ThirBuilder<'_, '_> { let array = self.through_pointer(array, self.body.exprs.span(array)); let ty = self.body.exprs[array].ty; let index = self.add_expr(index, Some(self.checker.types.usize)); - match self.checker.types[ty] { - Type::Array { .. } | Type::Slice { .. } => { - if let Type::Range { .. } = self.checker.types[self.body.exprs[index].ty] { - let index_span = self.body.exprs.span(index); - self.checker - .not_supported(index_span, "range values as indexes"); - return Expr::INVALID; - } - arrays::check_element(self, array, index) - } - Type::Parameter { .. } | Type::Undecided => Expr::UNDECIDED, - Type::Invalid => Expr::INVALID, - Type::Void - | Type::Bool - | Type::Integer(_) - | Type::Float(_) - | Type::CString - | Type::Str - | Type::Function { .. } - | Type::Alias { .. } - | Type::Named { .. } - | Type::Struct { .. } - | Type::Range { .. } - | Type::Reference { .. } - | Type::Interface { .. } - | Type::InterfaceReference { .. } - | Type::RawPointer { .. } => { - let message = format!("`{}` cannot be indexed", self.checker.type_text(ty)); - let span = self.body.exprs.span(array); + let types = &self.checker.types; + if types[ty].elements().is_some() { + if let Type::Range { .. } = types[self.body.exprs[index].ty] { + let index_span = self.body.exprs.span(index); self.checker - .error(diagnostics::INVALID_OPERATION, message, span); - Expr::INVALID + .not_supported(index_span, "range values as indexes"); + return Expr::INVALID; } + return arrays::check_element(self, array, index); + } + if types[ty].is_decided_per_copy() { + return Expr::UNDECIDED; } + if ty != TypeId::INVALID { + let message = format!("`{}` cannot be indexed", self.checker.type_text(ty)); + let span = self.body.exprs.span(array); + self.checker + .error(diagnostics::INVALID_OPERATION, message, span); + } + Expr::INVALID } /// The integer type of the checked index `index`; `None` after an error, @@ -154,10 +124,6 @@ impl ThirBuilder<'_, '_> { /// `array[start..end]`, its index a written range: a slice of an array /// or slice in a place, or of one a reference points to /// (`slices::check_slice`). A step is an error. - #[deny( - clippy::wildcard_enum_match_arm, - clippy::match_wildcard_for_single_variants - )] pub(super) fn check_slice(&mut self, mutable: bool, indexed: Id) -> Expr { let tree = &self.checker.module().ast; let ast::Expr::Index { @@ -197,79 +163,42 @@ impl ThirBuilder<'_, '_> { // Written `r[i..j]`, so a message names that, as `r[i]`. let array = self.through_pointer(array, tree.exprs.span(indexed)); let ty = self.body.exprs[array].ty; - match self.checker.types[ty] { - Type::Array { .. } | Type::Slice { .. } => { - slices::check_slice(self, mutable, array, ty, [start, end], inclusive, range) - } + let types = &self.checker.types; + if types[ty].elements().is_some() { + return slices::check_slice(self, mutable, array, ty, [start, end], inclusive, range); + } + if types[ty].is_decided_per_copy() { // The ends are checked as any slice's. - Type::Parameter { .. } | Type::Undecided => { - slices::check_slice_ends(self, [start, end], inclusive, ty, None, range); - Expr::UNDECIDED - } - Type::Invalid => Expr::INVALID, - Type::Void - | Type::Bool - | Type::Integer(_) - | Type::Float(_) - | Type::CString - | Type::Str - | Type::Function { .. } - | Type::Alias { .. } - | Type::Named { .. } - | Type::Struct { .. } - | Type::Range { .. } - | Type::Reference { .. } - | Type::Interface { .. } - | Type::InterfaceReference { .. } - | Type::RawPointer { .. } => { - let message = format!("`{}` cannot be sliced", self.checker.type_text(ty)); - self.checker - .error(diagnostics::INVALID_OPERATION, message, array_span); - Expr::INVALID - } + slices::check_slice_ends(self, [start, end], inclusive, ty, None, range); + return Expr::UNDECIDED; + } + if ty != TypeId::INVALID { + let message = format!("`{}` cannot be sliced", self.checker.type_text(ty)); + self.checker + .error(diagnostics::INVALID_OPERATION, message, array_span); } + Expr::INVALID } /// `reference.*`, written at `span`: the value a reference, an interface /// reference or a typed raw pointer points to. - #[deny( - clippy::wildcard_enum_match_arm, - clippy::match_wildcard_for_single_variants - )] pub(super) fn check_dereference(&mut self, reference: Id, span: Span) -> Expr { let reference = self.add_expr(reference, None); let ty = self.body.exprs[reference].ty; - let help = match self.checker.types[ty] { - Type::Reference { target, .. } - | Type::InterfaceReference { - interface: target, .. - } - | Type::RawPointer { - target: Some(target), - } => return self.dereference(reference, target), - Type::Parameter { .. } | Type::Undecided => return Expr::UNDECIDED, - Type::Invalid => return Expr::INVALID, - Type::Slice { .. } => { - let file = &self.checker.module().ast.file; - Some(slices::lend_again_help( - file.slice(self.body.exprs.span(reference)), - )) - } - Type::Void - | Type::Bool - | Type::Integer(_) - | Type::Float(_) - | Type::CString - | Type::Str - | Type::Function { .. } - | Type::Alias { .. } - | Type::Named { .. } - | Type::Struct { .. } - | Type::Array { .. } - | Type::Range { .. } - | Type::Interface { .. } - | Type::RawPointer { target: None } => None, - }; + let types = &self.checker.types; + if let Some(target) = types[ty].pointee() { + return self.dereference(reference, target); + } + if types[ty].is_decided_per_copy() { + return Expr::UNDECIDED; + } + if ty == TypeId::INVALID { + return Expr::INVALID; + } + let help = matches!(types[ty], Type::Slice { .. }).then(|| { + let file = &self.checker.module().ast.file; + slices::lend_again_help(file.slice(self.body.exprs.span(reference))) + }); let message = format!( "`.*` needs a reference or a typed raw pointer, found `{}`", self.checker.type_text(ty) diff --git a/crates/model/src/semantic_types.rs b/crates/model/src/semantic_types.rs index 17e45448..f716c933 100644 --- a/crates/model/src/semantic_types.rs +++ b/crates/model/src/semantic_types.rs @@ -222,6 +222,13 @@ impl Type { matches!(self, Type::Slice { .. } | Type::Str) } + /// Whether each copy decides what this type is: a type parameter in its + /// own check, or a type that depends on one. An open type that only + /// holds one, such as `[2]T` or `Box`, is still an array or a struct. + pub fn is_decided_per_copy(&self) -> bool { + matches!(self, Type::Parameter { .. } | Type::Undecided) + } + /// `Some(mutable)` for a type whose values borrow what they view, a /// reference, a slice or an interface reference: the loan rules hold for /// each. diff --git a/crates/model/src/semantic_types/structs.rs b/crates/model/src/semantic_types/structs.rs index 1e8b1848..c8033849 100644 --- a/crates/model/src/semantic_types/structs.rs +++ b/crates/model/src/semantic_types/structs.rs @@ -41,6 +41,12 @@ impl Types { } impl Type { + /// Whether a value of the type has fields: a struct, a copy or one given + /// an open type, whose fields are read with what it is given. + pub fn has_fields(&self) -> bool { + matches!(self, Type::Struct { .. } | Type::Named { .. }) + } + /// What a name after `.` can mean on the type (docs/feature-front.md, /// 5.1): its fields, for a struct. A type with members can also have /// functions with it as owner. From 9d2fe1d4a8f676919a1d306a2ab3e2628a28bc54 Mon Sep 17 00:00:00 2001 From: itsfuad Date: Thu, 19 Nov 2026 17:13:43 +0600 Subject: [PATCH 16/24] Point the docs at the moved crate paths Three pages still named `crates/middle/...`, which the layout commit moved to `crates/...`. The flow page's link to where the checker runs the flow checks now names `functions/bodies.rs`, as `function.rs` was split. --- docs/feature-free-mir.md | 2 +- docs/flow-crate.md | 6 +++--- docs/ir-design.md | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/feature-free-mir.md b/docs/feature-free-mir.md index 77b7d23e..d0717de7 100644 --- a/docs/feature-free-mir.md +++ b/docs/feature-free-mir.md @@ -27,7 +27,7 @@ removing a feature touches the parser, check and lower, and no other crate. ## 2. What today's MIR carries, and who pays for it Today every instruction carries a language type (`Instruction::ty`, -`crates/middle/model/src/mir.rs:71`), every variable does +`crates/model/src/mir.rs:71`), every variable does (`Variable::ty`, `:46`), and eight of the twenty instruction kinds are language features: `Length`, `Borrow` of a slice, `ToInterface`, `Aggregate`, `ArrayParts`, `Print`, `Field`, the typed `Binary` and diff --git a/docs/flow-crate.md b/docs/flow-crate.md index 60f49530..f41ca7d5 100644 --- a/docs/flow-crate.md +++ b/docs/flow-crate.md @@ -5,7 +5,7 @@ > `crates/model`, `crates/lower`, `crates/flow` and `crates/eval`. The path checks: errors that depend on which routes execution can take -through one function. Source: `crates/middle/flow/src/`: `lib.rs` (the +through one function. Source: `crates/flow/src/`: `lib.rs` (the shared engine), `missing_return.rs`, `unreachable.rs`, `variable_state.rs`, and `loans/` (`mod.rs`, `places.rs`, `holders.rs`, `two_phase.rs`, `passes.rs`, `errors.rs`). Each check only reads one function's @@ -14,11 +14,11 @@ and `loans/` (`mod.rs`, `places.rs`, `holders.rs`, `two_phase.rs`, ## 1. Who calls it, what it gives The checker runs the four checks on each function's MIR -(`crates/middle/check/src/function.rs:213-218`). +(`crates/check/src/functions/bodies.rs:84-90`). ```mermaid flowchart LR - subgraph check["check crate: function.rs"] + subgraph check["check crate: functions/bodies.rs"] lower["lower::lower โ†’ mir::Body"] end lower --> VS["variable_state::report_variable_state_errors
(body, file, diagnostics)
T0039 T0034 T0035 T0007"] diff --git a/docs/ir-design.md b/docs/ir-design.md index cb8f66f1..cc3a399b 100644 --- a/docs/ir-design.md +++ b/docs/ir-design.md @@ -230,7 +230,7 @@ computed differed (issues #154, #155, PR #158). The rules that prevent them: width; the Go guard wrote the width as a constant of the count's type, so a `u2` count compared against 8 cut to 0. 5. **Constants are written from the same bits** (`iN u0x...`), and - `crates/middle/check/tests/llvm_parity.rs` runs every operator on widths 1 + `crates/check/tests/llvm_parity.rs` runs every operator on widths 1 to 1000 in `lli` and in `model` and requires equal bits. Floats (`f32`, `f64`) follow the same idea: @@ -883,7 +883,7 @@ entry and no `main`, and `build`, `run` and `-interpret` refuse it; even; a float becomes an integer cut toward zero, saturated at the ends of its range, NaN as 0 (Rust's rule, as LLVM's plain `fptosi` gives poison there). Folding and LLVM agree for every width - (`crates/middle/check/tests/llvm_parity.rs`): `llvm` writes LLVM's own + (`crates/check/tests/llvm_parity.rs`): `llvm` writes LLVM's own `sitofp`/`uitofp` and `llvm.fpto{s,u}i.sat`, which need LLVM 23 or newer above 128 bits (LLVM 22 crashes on the one and gives a wrong finite float for the other, llvm/llvm-project#189054), so the bundled toolchain is LLVM From acfc56c250b506ef360a00d43058fd2bcc23495e Mon Sep 17 00:00:00 2001 From: itsfuad Date: Thu, 19 Nov 2026 17:13:44 +0600 Subject: [PATCH 17/24] Use Expr::UNDECIDED for the undecided value --- crates/check/src/functions/calls.rs | 5 +---- crates/check/src/structs.rs | 5 +---- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/crates/check/src/functions/calls.rs b/crates/check/src/functions/calls.rs index b4b5bd23..a988ecbe 100644 --- a/crates/check/src/functions/calls.rs +++ b/crates/check/src/functions/calls.rs @@ -69,10 +69,7 @@ impl builder::ThirBuilder<'_, '_> { // for their own errors only. Some(None) => { self.call_found(None, None, callee_span, type_arguments, arguments, span); - return thir::Expr { - ty: semantic_types::TypeId::UNDECIDED, - kind: thir::ExprKind::Undecided, - }; + return thir::Expr::UNDECIDED; } None => None, }, diff --git a/crates/check/src/structs.rs b/crates/check/src/structs.rs index 374c6bbc..c1716218 100644 --- a/crates/check/src/structs.rs +++ b/crates/check/src/structs.rs @@ -139,10 +139,7 @@ pub(crate) fn check_struct_literal( builder.add_expr(value, Some(semantic_types::TypeId::INVALID)); } if open { - return thir::Expr { - ty: semantic_types::TypeId::UNDECIDED, - kind: thir::ExprKind::Undecided, - }; + return thir::Expr::UNDECIDED; } return thir::Expr::INVALID; }; From 581cbcf16bd3d226835edf0e872fd3279177c70e Mon Sep 17 00:00:00 2001 From: itsfuad Date: Thu, 19 Nov 2026 21:12:57 +0600 Subject: [PATCH 18/24] Report what is wrong for every copy in generic bodies A generic body's own check stayed silent for every type that held a `T`. Now only a bare `T` (or an undecided type) is left to each copy; `[2]T`, `*T` or `Box` are still arrays, pointers and structs, so `-pair` or `let flag: bool = pair` is reported for `pair: [2]T`. Conversions are three-valued: the same, the same in some copy (`Types::could_be_same`, `Conversion::Undecided`), or never. A spread's count is one type, `EntryCount`, in place of the `(known, later)` pair: counted now, counted when the program runs, or counted by each copy. `[_]i32{ 1, x... }` with `x: T` is an array of an undecided type; `[3]i32{ x... }` keeps its type, and more values than its length counted now is reported. Behavior change: in a `...` argument list, an error in one entry now stops the count, as it already did for array literals, so a later slice spread is no longer also reported. --- crates/check/src/arrays.rs | 7 +- crates/check/src/expression/literals.rs | 174 ++++++++++++------ crates/check/src/expression/operators.rs | 12 +- crates/check/src/functions/calls.rs | 2 +- crates/check/src/printing.rs | 22 ++- crates/check/src/statement.rs | 15 +- crates/check/src/structs.rs | 4 +- crates/model/src/semantic_types.rs | 138 ++++++++++++++ .../model/src/semantic_types/conversions.rs | 50 +++-- crates/model/src/semantic_types/tests.rs | 64 +++++++ docs/generics.md | 25 ++- scripts/cross-concepts.py | 3 +- .../negative_generic_functions.peep | 30 +++ 13 files changed, 440 insertions(+), 106 deletions(-) diff --git a/crates/check/src/arrays.rs b/crates/check/src/arrays.rs index 40d31310..93a658c5 100644 --- a/crates/check/src/arrays.rs +++ b/crates/check/src/arrays.rs @@ -79,12 +79,11 @@ pub(crate) fn check_array_literal( } }; let entries = tree.children.lists.items(entries); - let (parts, known, later) = builder.check_entries(entries, element, None); - let Some(known) = known.filter(|_| element != semantic_types::TypeId::INVALID) else { + let (parts, count) = builder.check_entries(entries, element, None); + let Some(count) = count.filter(|_| element != semantic_types::TypeId::INVALID) else { return thir::Expr::INVALID; }; - let Some(ty) = builder.array_literal_type(written, element, length, (known, later), span) - else { + let Some(ty) = builder.array_literal_type(written, element, length, count, span) else { return thir::Expr::INVALID; }; thir::Expr { diff --git a/crates/check/src/expression/literals.rs b/crates/check/src/expression/literals.rs index 7517f20a..b438de43 100644 --- a/crates/check/src/expression/literals.rs +++ b/crates/check/src/expression/literals.rs @@ -20,6 +20,40 @@ use tree::operators::Precedence; use crate::builder::ThirBuilder; use crate::expression::unsuffixed_literal; +/// How many values the entries of an array literal give, or one spread +/// (`count_spread`). +#[derive(Clone, Copy)] +pub(crate) struct EntryCount { + /// Counted now. + known: u128, + /// The first entry counted only when the program runs, and why: `[_]` + /// cannot count it. + later: Option<(Span, &'static str)>, + /// Whether a spread of a type each copy decides gives more, as many as + /// each copy finds. + per_copy: bool, +} + +impl EntryCount { + /// `known` values, all counted now. + fn known(known: u64) -> EntryCount { + EntryCount { + known: u128::from(known), + later: None, + per_copy: false, + } + } + + /// Values counted when the program runs, from the entry written at + /// `entry`, which `[_]` cannot count, for `reason`. + fn later(entry: Span, reason: &'static str) -> EntryCount { + EntryCount { + later: Some((entry, reason)), + ..EntryCount::known(0) + } + } +} + impl ThirBuilder<'_, '_> { /// The string literal at `span`, a `&str` or with its `c` a `&cstr` (`ty`): /// its bytes. @@ -60,27 +94,27 @@ impl ThirBuilder<'_, '_> { } /// The `entries` of an array of `element`s, each a value or a spread - /// (`count_spread`), checked: with how many values are known now, `None` - /// after an error in a spread, and the first spread not counted until the - /// program runs, with why. A value that mismatches is reported, with how - /// to spread it when it holds `element`s (`help_spread`, given `alone_in`). - /// Without an element type, each entry is checked for its own errors. + /// (`count_spread`), checked, with how many values they give; `None` + /// after an error in a spread. A value that mismatches is reported, with + /// how to spread it when it holds `element`s (`help_spread`, given + /// `alone_in`). Without an element type, each entry is checked for its + /// own errors. pub(crate) fn check_entries( &mut self, entries: impl Iterator>, element: TypeId, alone_in: Option, - ) -> (Vec, Option, Option<(Span, &'static str)>) { + ) -> (Vec, Option) { let tree = &self.checker.module().ast; let hint = (element != TypeId::INVALID).then_some(element); let mut parts: Vec = Vec::with_capacity(entries.size_hint().0); - // Each count fits a `usize`, so their sum fits a `u128`. - let (mut known, mut later) = (Some(0u128), None); + let mut total = Some(EntryCount::known(0)); for entry in entries { let (part, count) = if let ast::Expr::Spread(values) = tree.exprs[entry] { let spread = self.add_spread(tree.unparenthesized(values), element); - let Some(checked) = self.count_spread(spread, element) else { - known = None; + let Some(checked) = self.count_spread(spread, element, tree.exprs.span(entry)) + else { + total = None; continue; }; checked @@ -111,15 +145,17 @@ impl ThirBuilder<'_, '_> { }); self.body.exprs[value] = coerced; } - (value, Ok(1)) + (value, EntryCount::known(1)) }; - match count { - Ok(count) => known = known.map(|known| known + u128::from(count)), - Err(reason) => later = later.or(Some((tree.exprs.span(entry), reason))), - } + // Each count fits a `usize`, so their sum fits a `u128`. + total = total.map(|total| EntryCount { + known: total.known + count.known, + later: total.later.or(count.later), + per_copy: total.per_copy || count.per_copy, + }); parts.push(part.into()); } - (parts, known, later) + (parts, total) } /// `mismatch`, for `written`, the array, slice or reference to one `value` @@ -198,7 +234,7 @@ impl ThirBuilder<'_, '_> { let element = self.checker.types[parameter] .elements() .map_or(TypeId::INVALID, |(element, _)| element); - let (parts, known, later) = if let [only] = *values + let (parts, count) = if let [only] = *values && let ast::Expr::Spread(spread) = tree.exprs[only] { let written = tree.unparenthesized(spread); @@ -211,20 +247,29 @@ impl ThirBuilder<'_, '_> { self.body.exprs[spread] = self.require(slice, written, parameter); return spread; } - match self.count_spread(spread, element) { - Some((part, Ok(count))) => (vec![part.into()], Some(u128::from(count)), None), - Some((_, Err(reason))) => { - let span = tree.exprs.span(written); - self.checker.error(diagnostics::TYPE_MISMATCH, reason, span); - (Vec::new(), None, None) + match self.count_spread(spread, element, tree.exprs.span(written)) { + Some(( + _, + EntryCount { + later: Some((first, reason)), + .. + }, + )) => { + self.checker + .error(diagnostics::TYPE_MISMATCH, reason, first); + (Vec::new(), None) } - None => (Vec::new(), None, None), + Some((part, count)) => (vec![part.into()], Some(count)), + None => (Vec::new(), None), } } else { let alone_in = (values.len() == 1).then_some(parameter); self.check_entries(values.iter().copied(), element, alone_in) }; - if let Some((spread, reason)) = later { + let Some(count) = count.filter(|_| element != TypeId::INVALID) else { + return self.body.add(Expr::INVALID, span); + }; + if let Some((spread, reason)) = count.later { let message = format!( "{reason}, so a call cannot build an array around it; pass a slice as the \ only argument for `...`" @@ -233,10 +278,7 @@ impl ThirBuilder<'_, '_> { .error(diagnostics::TYPE_MISMATCH, message, spread); return self.body.add(Expr::INVALID, span); } - let Some(known) = known.filter(|_| element != TypeId::INVALID) else { - return self.body.add(Expr::INVALID, span); - }; - let Some(ty) = self.array_literal_type(span, element, None, (known, None), span) else { + let Some(ty) = self.array_literal_type(span, element, None, count, span) else { return self.body.add(Expr::INVALID, span); }; let kind = ExprKind::ArrayLiteral(self.body.children.lists.add(&parts)); @@ -247,18 +289,23 @@ impl ThirBuilder<'_, '_> { /// The type of the array literal written at `span`, its type at `written`, /// of `element`s, with `length` when written (`[N]`, as its type), whose - /// entries give `known` values now and more when the program runs if a - /// spread, first at `later` with why `[_]` cannot count it, is counted - /// then; `None` after reporting that they do not fit it - /// (`arrays::check_array_literal`). + /// entries give `count` values; `None` after reporting that they do not + /// fit it (`arrays::check_array_literal`). `[_]` cannot count a spread + /// counted when the program runs, and one each copy counts makes its + /// length, so its type, each copy's (`TypeId::UNDECIDED`). pub(crate) fn array_literal_type( &mut self, written: Span, element: TypeId, length: Option<(TypeId, u64)>, - (known, later): (u128, Option<(Span, &'static str)>), + count: EntryCount, span: Span, ) -> Option { + let EntryCount { + known, + later, + per_copy, + } = count; match (length, later) { (None, Some((spread, reason))) => { let message = format!("{reason}; write the length"); @@ -266,6 +313,7 @@ impl ThirBuilder<'_, '_> { .error(diagnostics::TYPE_MISMATCH, message, spread); None } + (None, None) if per_copy => Some(TypeId::UNDECIDED), (None, None) => { if !self .checker @@ -277,10 +325,12 @@ impl ThirBuilder<'_, '_> { } (Some((ty, length)), later) => { let length = u128::from(length); - if known == length || later.is_some() && known < length { + // More values come from a spread counted later. + let more = later.is_some() || per_copy; + if known == length || more && known < length { return Some(ty); } - let found = if later.is_some() { "at least " } else { "" }; + let found = if more { "at least " } else { "" }; let message = format!( "`{}` needs {length} values, found {found}{known}", self.checker.type_text(ty) @@ -299,37 +349,43 @@ impl ThirBuilder<'_, '_> { self.add_expr(values, hint) } - /// `spread`, the values of a `values...` going into an array of - /// `element`s, with how many it gives when that is known now, else why - /// it cannot be counted; `None` after an error. An array gives its - /// elements, which must be `element`s; a slice copies its elements, which - /// must copy; a range its values, counted now when it is written with - /// constant ends and step; a count no array can hold is reported. + /// `spread`, the values of a `values...` written at `entry` going into + /// an array of `element`s, with how many it gives; `None` after an + /// error. An array gives its elements, which must be `element`s; a slice + /// copies its elements, which must copy; a range its values, counted now + /// when it is written with constant ends and step; a count no array can + /// hold is reported. A value of a type each copy decides gives as many + /// as each copy finds. fn count_spread( &mut self, spread: Id, element: TypeId, - ) -> Option<(Id, Result)> { + entry: Span, + ) -> Option<(Id, EntryCount)> { let span = self.body.exprs.span(spread); let ty = self.body.exprs[spread].ty; let types = &self.checker.types; + // An element of a type each copy decides may be one in some copy. + let gives = |from: TypeId| { + element == TypeId::INVALID + || matches!( + types.conversion(from, element), + Conversion::Same | Conversion::Undecided + ) + }; match types[ty] { Type::Invalid => return None, Type::Array { element: from, length, .. - } if element == TypeId::INVALID - || types.conversion(from, element) == Conversion::Same => - { - return Some((spread, Ok(length))); + } if gives(from) => { + return Some((spread, EntryCount::known(length))); } Type::Slice { mutable, element: from, - } if element == TypeId::INVALID - || types.conversion(from, element) == Conversion::Same => - { + } if gives(from) => { if !types.is_copy(from) { let file = &self.checker.module().ast.file; let slice_text = self.checker.type_text(ty); @@ -360,10 +416,16 @@ impl ThirBuilder<'_, '_> { self.body.exprs[spread] = self.reborrow(reference, span, shared); } let reason = "a slice has a length known only when the program runs"; - return Some((spread, Err(reason))); + return Some((spread, EntryCount::later(entry, reason))); + } + Type::Range { element: from, .. } if gives(from) => {} + _ if types[ty].is_decided_per_copy() => { + let count = EntryCount { + per_copy: true, + ..EntryCount::known(0) + }; + return Some((spread, count)); } - Type::Range { element: from, .. } - if element == TypeId::INVALID || types.same(from, element) => {} _ => { let (expected, found) = self.checker.type_texts(element, ty); let message = format!( @@ -388,11 +450,11 @@ impl ThirBuilder<'_, '_> { inclusive, } = exprs[spread].kind else { - return Some((spread, Err(uncounted))); // a range value + return Some((spread, EntryCount::later(entry, uncounted))); // a range value }; let (Some(first), Some(last), Some(by)) = (constant(start), constant(end), constant(step)) else { - return Some((spread, Err(uncounted))); + return Some((spread, EntryCount::later(entry, uncounted))); }; let Type::Integer(integer) = types[exprs[start].ty] else { unreachable!("a range is of integers") @@ -401,7 +463,7 @@ impl ThirBuilder<'_, '_> { if !self.checker.length_fits(count.as_slice(), span) { return None; } - Some((spread, Ok(count.as_slice()[0]))) // it fits a `usize` + Some((spread, EntryCount::known(count.as_slice()[0]))) // it fits a `usize` } /// A range's or slice's ends `start` and `end`, of one type: a literal diff --git a/crates/check/src/expression/operators.rs b/crates/check/src/expression/operators.rs index 8b2cf1db..4dc5989c 100644 --- a/crates/check/src/expression/operators.rs +++ b/crates/check/src/expression/operators.rs @@ -115,9 +115,8 @@ impl ThirBuilder<'_, '_> { UnaryOp::LogicalNot => *ty == Type::Bool, UnaryOp::BitNot => matches!(ty, Type::Integer(_)), }; - // On an open type, each copy decides whether it applies. - let open = self.checker.types.is_open(checked.ty); - if !open && !fits(&ty) { + // On a type each copy decides, each copy decides whether it applies. + if !ty.is_decided_per_copy() && !fits(&ty) { return self.report_invalid_operand(op.symbol(), checked.ty, operand, span, fits); } let result = if op == UnaryOp::LogicalNot { @@ -200,8 +199,8 @@ impl ThirBuilder<'_, '_> { } BinaryOp::LogicalAnd | BinaryOp::LogicalOr => *ty == Type::Bool, }; - // On an open type, each copy decides whether it applies. - let left_fits = self.checker.types.is_open(left.ty) || fits(&left_type); + // On a type each copy decides, each copy decides whether it applies. + let left_fits = left_type.is_decided_per_copy() || fits(&left_type); // In a constant's value, `false && x` and `true || x` are the left // operand: `x` is checked but, as when the program runs, not run. let skips_right = self.in_constant @@ -256,8 +255,7 @@ impl ThirBuilder<'_, '_> { return self.report_invalid_operand(op.symbol(), left.ty, left_operand, span, fits); } let right_type = self.checker.types[right.ty].clone(); - if shift && !matches!(right_type, Type::Integer(_)) && !self.checker.types.is_open(right.ty) - { + if shift && !matches!(right_type, Type::Integer(_)) && !right_type.is_decided_per_copy() { let count = self.checker.type_text(right.ty); let message = format!("a shift count must be an integer, found `{count}`"); let types = &self.checker.types; diff --git a/crates/check/src/functions/calls.rs b/crates/check/src/functions/calls.rs index a988ecbe..05e1fa66 100644 --- a/crates/check/src/functions/calls.rs +++ b/crates/check/src/functions/calls.rs @@ -357,7 +357,7 @@ impl builder::ThirBuilder<'_, '_> { } let place = self.through_pointer(value, self.body.exprs.span(value)); let ty = self.body.exprs[place].ty; - if self.checker.types.is_open(ty) && self.checker.types[ty].definition().is_none() { + if self.checker.types[ty].is_decided_per_copy() { return Some(None); } let Some(definition) = self.checker.types[ty].definition() else { diff --git a/crates/check/src/printing.rs b/crates/check/src/printing.rs index 2b4cf119..adca9c4d 100644 --- a/crates/check/src/printing.rs +++ b/crates/check/src/printing.rs @@ -274,9 +274,10 @@ fn library_call( } /// Whether `print` writes a value of the type `ty`: a number, `bool`, -/// `&cstr`, `&str` or raw pointer, or a reference to one. A struct or array -/// prints only once a trait or interface lets its type say how. -fn printable(types: &semantic_types::Types, mut ty: semantic_types::TypeId) -> bool { +/// `&cstr`, `&str` or raw pointer, or a reference to one; `None` when each +/// copy decides, for a type parameter or a reference to one. A struct or +/// array prints only once a trait or interface lets its type say how. +fn printable(types: &semantic_types::Types, mut ty: semantic_types::TypeId) -> Option { // A loop, not recursion: references nest as deep as the source writes. loop { match &types[ty] { @@ -285,9 +286,10 @@ fn printable(types: &semantic_types::Types, mut ty: semantic_types::TypeId) -> b | semantic_types::Type::Bool | semantic_types::Type::CString | semantic_types::Type::Str - | semantic_types::Type::RawPointer { .. } => return true, + | semantic_types::Type::RawPointer { .. } => return Some(true), semantic_types::Type::Reference { target, .. } => ty = *target, - _ => return false, + _ if types[ty].is_decided_per_copy() => return None, + _ => return Some(false), } } } @@ -308,13 +310,13 @@ pub(crate) fn check_print( let expr = builder.check_expr(value, None); let ty = expr.ty; let types = &builder.checker.types; - // Each copy prints a value of an open type its own way; a generic - // body's own check, which never runs, leaves it out. - if types.is_open(ty) { + // Each copy prints a value of a type it decides its own way; a + // generic body's own check, which never runs, leaves it out. + let Some(printable) = printable(types, ty) else { continue; - } + }; // On an error the others are still checked, for their own. - if !printable(types, ty) { + if !printable { if ty != semantic_types::TypeId::INVALID { let message = format!("`{}` cannot be printed", builder.checker.type_text(ty)); (builder.checker).error(diagnostics::INVALID_OPERATION, message, span); diff --git a/crates/check/src/statement.rs b/crates/check/src/statement.rs index cbaaf227..b766ac23 100644 --- a/crates/check/src/statement.rs +++ b/crates/check/src/statement.rs @@ -485,11 +485,18 @@ impl<'a, 'p> ThirBuilder<'a, 'p> { body, } => { let iterable = self.add_expr(iterable, None); + let types = &self.checker.types; let ty = self.body.exprs[iterable].ty; - // What walking an open value means, each copy decides; the - // own check, never lowered, checks the body as a range's. - if matches!(self.checker.types[ty], Type::Range { .. }) - || self.checker.types.is_open(ty) + let walked = if let Type::Reference { target, .. } = types[ty] { + target + } else { + ty + }; + // What walking a type each copy decides means, each copy + // decides; the own check, never lowered, checks the body + // as a range's. + if matches!(types[ty], Type::Range { .. }) + || types[walked].is_decided_per_copy() { self.check_for_range(index, Some(value), iterable, body?) } else { diff --git a/crates/check/src/structs.rs b/crates/check/src/structs.rs index c1716218..d956c8cc 100644 --- a/crates/check/src/structs.rs +++ b/crates/check/src/structs.rs @@ -108,7 +108,7 @@ pub(crate) fn check_struct_literal( // Reported where it was written, or one each copy decides. (None, Some(expected)) if expected == semantic_types::TypeId::INVALID - || builder.checker.types.is_open(expected) => + || builder.checker.types[expected].is_decided_per_copy() => { expected } @@ -122,7 +122,7 @@ pub(crate) fn check_struct_literal( let (semantic_types::Type::Struct { definition, .. } | semantic_types::Type::Named { definition, .. }) = builder.checker.types[ty] else { - let open = builder.checker.types.is_open(ty); + let open = builder.checker.types[ty].is_decided_per_copy(); if ty != semantic_types::TypeId::INVALID && !open { let message = format!( "expected a struct type, found `{}`", diff --git a/crates/model/src/semantic_types.rs b/crates/model/src/semantic_types.rs index f716c933..fe10659c 100644 --- a/crates/model/src/semantic_types.rs +++ b/crates/model/src/semantic_types.rs @@ -864,6 +864,144 @@ impl Types { named.iter().map(Option::is_some).collect() } + /// Whether some copy could make the types `a` and `b` the same: they + /// are, or they differ only where one has a type each copy decides + /// (`is_decided_per_copy`). Each such part is matched alone, so `T` + /// against `i32` in one place and `bool` in another still could. + #[deny( + clippy::wildcard_enum_match_arm, + clippy::match_wildcard_for_single_variants + )] + // TODO: simplify later + pub fn could_be_same(&self, a: TypeId, b: TypeId) -> bool { + let (a, b) = (self.real(a), self.real(b)); + if a == b || self[a].is_decided_per_copy() || self[b].is_decided_per_copy() { + return true; + } + if !self.is_open(a) && !self.is_open(b) { + return false; + } + let part = |a: TypeId, b: TypeId| source::grow_stack(|| self.could_be_same(a, b)); + match (&self[a], &self[b]) { + ( + Type::Function { + parameters, + result, + variadic, + .. + }, + Type::Function { + parameters: given, + result: given_result, + variadic: given_variadic, + .. + }, + ) => { + variadic == given_variadic + && parameters.len() == given.len() + && (parameters.iter().zip(given.iter())).all(|(&a, &b)| part(a, b)) + && part(*result, *given_result) + } + ( + &(Type::Named { + definition, + arguments, + } + | Type::Struct { + definition, + arguments, + .. + }), + &(Type::Named { + definition: given_definition, + arguments: given, + } + | Type::Struct { + definition: given_definition, + arguments: given, + .. + }), + ) => { + definition == given_definition + && (self.arguments(arguments).iter().zip(self.arguments(given))).all(|pair| { + match pair { + (&ConstArgument::Type(a), &ConstArgument::Type(b)) => part(a, b), + (a, b) => a == b, + } + }) + } + ( + &Type::Array { + element, length, .. + }, + &Type::Array { + element: given, + length: given_length, + .. + }, + ) => length == given_length && part(element, given), + (&Type::Range { element }, &Type::Range { element: given }) + | ( + &Type::RawPointer { + target: Some(element), + }, + &Type::RawPointer { + target: Some(given), + }, + ) => part(element, given), + ( + &Type::Slice { mutable, element }, + &Type::Slice { + mutable: given_mutable, + element: given, + }, + ) + | ( + &Type::Reference { + mutable, + target: element, + }, + &Type::Reference { + mutable: given_mutable, + target: given, + }, + ) + | ( + &Type::InterfaceReference { + mutable, + interface: element, + }, + &Type::InterfaceReference { + mutable: given_mutable, + interface: given, + }, + ) => mutable == given_mutable && part(element, given), + ( + Type::Invalid + | Type::Parameter { .. } + | Type::Undecided + | Type::Void + | Type::Bool + | Type::Integer(_) + | Type::Float(_) + | Type::CString + | Type::Str + | Type::Function { .. } + | Type::Alias { .. } + | Type::Named { .. } + | Type::Struct { .. } + | Type::Array { .. } + | Type::Range { .. } + | Type::Reference { .. } + | Type::Slice { .. } + | Type::Interface { .. } + | Type::InterfaceReference { .. } + | Type::RawPointer { .. }, + _, + ) => false, + } + } + /// Whether the type `ty`, about to be added, is open: it is a type /// parameter or undecided, or a part of it is open. #[deny( diff --git a/crates/model/src/semantic_types/conversions.rs b/crates/model/src/semantic_types/conversions.rs index 9f8fdba5..17ec6dee 100644 --- a/crates/model/src/semantic_types/conversions.rs +++ b/crates/model/src/semantic_types/conversions.rs @@ -13,14 +13,44 @@ use super::Types; impl Types { /// How a value of the type `from` becomes a value of the type `to`. A - /// pair not named here never converts. + /// pair not named here never converts. A pair that holds a type each + /// copy decides is `Undecided` when copies differ: one makes the two + /// the same (`*T` to `*i32`, which another casts), or as written it + /// never converts but in some copy does (`&mut T` to `&i32`, `Box` + /// to an interface). `[2]T` to `bool` converts in none. pub fn conversion(&self, from: TypeId, to: TypeId) -> Conversion { if self.same(from, to) { return Conversion::Same; } - if self.is_open(from) || self.is_open(to) { + // The same type in some copy converts as `Same` there, whatever + // the pair needs as written. + if self.could_be_same(from, to) { return Conversion::Undecided; } + // `conversion` when the parts `a` and `b` are the same; `Undecided` + // when they are only in some copy. + let when_same = |a: TypeId, b: TypeId, conversion: Conversion| { + if self.same(a, b) { + conversion + } else if self.could_be_same(a, b) { + Conversion::Undecided + } else { + Conversion::Never + } + }; + // A struct given an open type has no copy to hold its members, and a + // type each copy decides may be a struct: in some copy, each has them. + let to_interface = |ty: TypeId| { + if self[ty].members().is_some() { + Conversion::ToInterface + } else if self[ty].is_decided_per_copy() + || (self.is_open(ty) && matches!(self[ty], Type::Named { .. })) + { + Conversion::Undecided + } else { + Conversion::Never + } + }; match (&self[from], &self[to]) { (&Type::Integer(from), &Type::Integer(to)) => { let cast = from.cast_to(to); @@ -56,7 +86,7 @@ impl Types { mutable: false, target: to, }, - ) if self.same(from, to) => Conversion::Reborrow, + ) => when_same(from, to, Conversion::Reborrow), ( &Type::Reference { mutable: from_mutable, @@ -64,9 +94,9 @@ impl Types { }, &Type::Slice { mutable, element }, ) if from_mutable || !mutable => match self[target] { - Type::Array { element: from, .. } if self.same(from, element) => { - Conversion::Reborrow - } + Type::Array { element: from, .. } => when_same(from, element, Conversion::Reborrow), + // In some copy, `T` is an array. + _ if self[target].is_decided_per_copy() => Conversion::Undecided, _ => Conversion::Never, }, ( @@ -78,7 +108,7 @@ impl Types { mutable: false, element: to, }, - ) if self.same(from, to) => Conversion::Reborrow, + ) => when_same(from, to, Conversion::Reborrow), ( &Type::InterfaceReference { mutable: true, @@ -95,10 +125,8 @@ impl Types { target, }, &Type::InterfaceReference { mutable, .. }, - ) if (from_mutable || !mutable) && self[target].members().is_some() => { - Conversion::ToInterface - } - (from, Type::Interface { .. }) if from.members().is_some() => Conversion::ToInterface, + ) if from_mutable || !mutable => to_interface(target), + (_, Type::Interface { .. }) => to_interface(from), (Type::RawPointer { target: Some(_) }, Type::RawPointer { target: None }) => { Conversion::Same } diff --git a/crates/model/src/semantic_types/tests.rs b/crates/model/src/semantic_types/tests.rs index d2d74718..c52f1d2f 100644 --- a/crates/model/src/semantic_types/tests.rs +++ b/crates/model/src/semantic_types/tests.rs @@ -218,6 +218,70 @@ fn conversions() { } } +/// A pair holding a type parameter converts as written where it does for +/// every copy, is undecided where some copy converts it, and never converts +/// where no copy does. +#[test] +fn conversions_of_open_types() { + let mut types = Types::new(64); + let parameter = types.intern(Type::Parameter { + definition: DefId { + module: ModuleId::from_index(0), + index: 0, + }, + place: 0, + }); + let reference = + |types: &mut Types, mutable, target| types.intern(Type::Reference { mutable, target }); + let pair = types.array(parameter, 2); + let to_pair = reference(&mut types, false, pair); + let mutable_parameter = reference(&mut types, true, parameter); + let shared_parameter = reference(&mut types, false, parameter); + let shared_i32 = reference(&mut types, false, TypeId::I32); + let view = |types: &mut Types, element| { + types.intern(Type::Slice { + mutable: false, + element, + }) + }; + let parameters = view(&mut types, parameter); + let numbers = view(&mut types, TypeId::I32); + let triple = types.array(TypeId::I32, 3); + let to_triple = reference(&mut types, false, triple); + // For every copy. + assert_eq!( + types.conversion(mutable_parameter, shared_parameter), + Conversion::Reborrow + ); + assert_eq!(types.conversion(to_pair, parameters), Conversion::Reborrow); + // In some copy. + assert_eq!( + types.conversion(parameter, TypeId::I64), + Conversion::Undecided + ); + assert_eq!( + types.conversion(mutable_parameter, shared_i32), + Conversion::Undecided + ); + assert_eq!(types.conversion(to_pair, numbers), Conversion::Undecided); + let raw_parameter = types.intern(Type::RawPointer { + target: Some(parameter), + }); + let raw_i32 = types.intern(Type::RawPointer { + target: Some(TypeId::I32), + }); + assert_eq!( + types.conversion(raw_parameter, raw_i32), + Conversion::Undecided + ); + let bools = types.array(TypeId::BOOL, 2); + assert!(types.could_be_same(pair, bools)); + // In none: an array is never a `bool`, and lengths do not change. + assert_eq!(types.conversion(pair, TypeId::BOOL), Conversion::Never); + assert_eq!(types.conversion(to_pair, to_triple), Conversion::Never); + assert!(!types.could_be_same(pair, triple)); +} + /// An interface keeps the id it was named by, so a `&Shape` written before /// it was checked is the one of after; a reference to a struct converts to /// a reference to it as a `&` converts to a `&`, the checker looking at the diff --git a/docs/generics.md b/docs/generics.md index 64b1b19f..761660ff 100644 --- a/docs/generics.md +++ b/docs/generics.md @@ -16,20 +16,25 @@ parameter) is checked twice over: A type that holds a `Type::Parameter` or `Type::Undecided` is **open** (`Types::is_open`, stored at intern: it is asked of every type checked, and -a type never changes once interned). An open type means "each copy -decides". `Type::Invalid` keeps one meaning: an error was reported. +a type never changes once interned). An open type has no copy of its +own: no layout, and a call given one makes none. `Type::Invalid` keeps +one meaning: an error was reported. -What depends on an open type is left to each copy, silently, in the own -check: +What depends on a type each copy decides (a bare `T`, or `Undecided`, +`Type::is_decided_per_copy`) is left to each copy, silently, in the own +check. A type that only holds one, as `[2]T` or `Box`, is still an +array or a struct, and what is wrong for it whatever `T` is, is reported: +`-pair` or `let flag: bool = pair` for `pair: [2]T`. | Case | Own check gives | | --- | --- | -| `t[0]`, `t.*`, `t.x` on a bare `T` | `Type::Undecided`, `ExprKind::Undecided` | -| `t.Name()` on a bare `T` | the arguments are checked; the call is `Undecided` | -| a conversion to or from an open type | `Conversion::Undecided` | -| an operator on an open operand | the operator's own result type | -| printing an open value | the value is left out | -| a `where` constraint on an open subject, a call run at compile time given one | not known (`None`) | +| `t[0]`, `t.*`, `t.x`, `t.Name()` on a bare `T` | `Expr::UNDECIDED` (a call's arguments are checked) | +| a conversion that some copy makes and another refuses: `T` to `i64`, `&mut T` to `&i32`, `&Box` to an interface reference | `Conversion::Undecided` (`Types::could_be_same`) | +| an operator on a bare `T` | the operator's own result type | +| printing a bare `T`, or a reference to one | the value is left out | +| `for` over a bare `T`, or a reference to one | the body is checked as a range's, its value undecided | +| a `where` constraint on a bare `T`, a call run at compile time given an open type | not known (`None`) | +| `x...` of a bare `T` in `[_]E{ ... }` or a `...` argument | the array literal is of `Type::Undecided`: its length is each copy's count; a `...` argument still lends it as the parameter's slice; `[N]E{ ... }` keeps its type, and more than `N` values counted now is reported | | a field of `Box` | the written field type, re-read with `T` bound (`field_types_given`) | An open struct, such as `Box` inside a generic body, stays diff --git a/scripts/cross-concepts.py b/scripts/cross-concepts.py index 0726c5b0..28f2bb2b 100755 --- a/scripts/cross-concepts.py +++ b/scripts/cross-concepts.py @@ -28,7 +28,8 @@ # What each concept owns: a pattern per kind or question. OWNERS = { "generics": [r"Type::Parameter\b", r"Type::Undecided\b", r"TypeId::UNDECIDED\b", - r"ExprKind::Undecided\b", r"Conversion::Undecided\b", r"\bis_open\(", + r"ExprKind::Undecided\b", r"Expr::UNDECIDED\b", r"Conversion::Undecided\b", + r"\bis_open\(", r"\bis_decided_per_copy\(", r"\bcould_be_same\(", r"\barguments_open\(", r"\bin_own_check\(", r"\bholds_undecided\(", r"\bopen_struct\(", r"\bcopy_type\(", r"\bown_arguments\("], diff --git a/test_programs/generic_functions/negative_generic_functions.peep b/test_programs/generic_functions/negative_generic_functions.peep index a89ca772..772b2624 100644 --- a/test_programs/generic_functions/negative_generic_functions.peep +++ b/test_programs/generic_functions/negative_generic_functions.peep @@ -32,6 +32,36 @@ fn Add(a: T, b: T) -> T { return a + b; //~ error[T0004]: operator `+` cannot be applied to `bool` } +fn Total(values: ...i32) -> i32 { + return 0; +} + +// Never called: what is wrong whatever `T` is, is still reported. What +// some copy accepts, each copy decides. +fn WrongForEvery(pair: [2]T, value: T, pointer: *T, list: &[]T, values: range[T]) { + let negated = -pair; //~ error[T0004]: operator `-` cannot be applied to `[2]T` + let flag: bool = pair; //~ error[T0001]: mismatched types: expected `bool`, found `[2]T` + pair.Area(); //~ error[T0004]: `[2]T` has no functions + let shape: &Shape = &pair; //~ error[T0001]: mismatched types: expected `&Shape`, found `&[2]T` + print(pair); //~ error[T0004]: `[2]T` cannot be printed + let elements: &[]i32 = &pair; + let held: &Shape = &value; + for each in &value {} + for each in pair {} + let raw: *i32 = pointer; + let spread = [_]i32{ pair... }; + // How many values `value...` gives, each copy counts. + let counted = [_]i32{ 1, value... }; + let written = [3]i32{ value... }; + let total = Total(value...); + let more = Total(1, value...); + let sliced = [4]i32{ list... }; + let ranged = [4]i32{ values... }; + let full = [2]i32{ 1, 2, 3, value... }; //~ error[T0001]: `[2]i32` needs 2 values, found at least 3 + let mixed = [_]i32{ elements..., value... }; //~ error[T0001]: a slice has a length known only when the program runs; write the length + print(value, -value, value + value); +} + #[extern("outside")] fn Outside(value: T); //~ error[P0005]: an `extern` function takes no type or `const` parameter: C gives one function for every call From e3a6829b284381cf850e42a2553937372e5d9aed Mon Sep 17 00:00:00 2001 From: itsfuad Date: Thu, 19 Nov 2026 22:26:50 +0600 Subject: [PATCH 19/24] Keep the type of a const value each copy gives In a generic declaration's own check, a `const` parameter had no value, so it was stored as `None`, the same as a constant with an error, and lost its type too. `let flag: bool = N;` for `const N: i32` was not reported, and `const RUN: i32 = Double(N);` gave a false "cannot be worked out at compile time" error. A body's constants are now `thir::CheckedConstant`: `Known(constant)`, or `PerCopy(type)` when each copy gives the value. `None` is only an error. Read, a per-copy constant is `ExprKind::Undecided` of its type, so `N`, `N * 2` and `Double(N)` are an `i32` whose value each copy gives. A `where` constraint takes a per-copy answer as unknown. shortcut: a per-copy value given to another function's `const` parameter, `H(N)`, still makes the call silent, until `ConstArguments` can hold such a value. --- crates/check/src/declaration.rs | 10 ++++++- crates/check/src/expression/names.rs | 14 +++++++--- crates/check/src/generics.rs | 10 +++++-- crates/check/src/generics/constraints.rs | 13 +++++++--- crates/check/src/locals.rs | 26 +++++++++++-------- crates/check/src/statement.rs | 24 ++++++++++++----- crates/driver/lsp/src/checked.rs | 10 +++++-- crates/model/src/thir.rs | 18 ++++++++++--- docs/generics.md | 1 + .../negative_generic_functions.peep | 16 ++++++++++++ 10 files changed, 110 insertions(+), 32 deletions(-) diff --git a/crates/check/src/declaration.rs b/crates/check/src/declaration.rs index 124e5084..09c6986a 100644 --- a/crates/check/src/declaration.rs +++ b/crates/check/src/declaration.rs @@ -19,6 +19,7 @@ use model::semantic_types::Type; use model::semantic_types::TypeId; use model::semantic_types::Types; use model::thir::Body; +use model::thir::CheckedConstant; use model::thir::FactKind; use model::thir::Symbol; use source::Span; @@ -156,7 +157,14 @@ impl Checker<'_> { pub(crate) fn check_constant(&mut self, definition: DefId) -> Option { let declaration = self.module().ast.declaration(definition.index); let mut body = Body::default(); - ThirBuilder::new(self, &mut body, TypeId::VOID).check_const_statement(declaration) + let checked = + ThirBuilder::new(self, &mut body, TypeId::VOID).check_const_statement(declaration); + match checked? { + CheckedConstant::Known(constant) => Some(constant), + CheckedConstant::PerCopy(_) => { + unreachable!("a module's constant is in no generic declaration's own check") + } + } } /// The type of a value whose type is written `ty`: a named type is the diff --git a/crates/check/src/expression/names.rs b/crates/check/src/expression/names.rs index 511a9a10..9745c949 100644 --- a/crates/check/src/expression/names.rs +++ b/crates/check/src/expression/names.rs @@ -26,7 +26,8 @@ impl builder::ThirBuilder<'_, '_> { return constant_expr(self.body.constants[constant].clone()); } Some(thir::Symbol::Constant(constant)) => { - return constant_expr(self.checker.constant(constant, span)); + let constant = self.checker.constant(constant, span); + return constant_expr(constant.map(thir::CheckedConstant::Known)); } Some(thir::Symbol::Function(_)) => { self.checker.not_supported(span, "functions as values"); @@ -47,13 +48,18 @@ impl builder::ThirBuilder<'_, '_> { } } -/// The value of a constant (`Checker::constant`) as an expression. -fn constant_expr(constant: Option) -> thir::Expr { +/// The value of a constant as an expression: each copy's, when only its +/// type is known. +fn constant_expr(constant: Option) -> thir::Expr { match constant { - Some(semantic_types::Constant { ty, value }) => thir::Expr { + Some(thir::CheckedConstant::Known(semantic_types::Constant { ty, value })) => thir::Expr { ty, kind: thir::ExprKind::Constant(value), }, + Some(thir::CheckedConstant::PerCopy(ty)) => thir::Expr { + ty, + kind: thir::ExprKind::Undecided, + }, None => thir::Expr::INVALID, } } diff --git a/crates/check/src/generics.rs b/crates/check/src/generics.rs index e9d47a0b..21616a0f 100644 --- a/crates/check/src/generics.rs +++ b/crates/check/src/generics.rs @@ -252,8 +252,14 @@ impl builder::ThirBuilder<'_, '_> { .checker .const_value_type(definition, parameter.ty, span); match self.check_constant_value(argument, Some(ty)) { - Some(constant) => given.push(semantic_types::ConstArgument::Value(constant)), - None => failed = true, // reported + Some(thir::CheckedConstant::Known(constant)) => { + given.push(semantic_types::ConstArgument::Value(constant)); + } + // Reported, or each copy gives it. shortcut: given a value + // each copy gives, no copy is made and the call stays + // silent; give it its type once `ConstArguments` can hold a + // per-copy value. + Some(thir::CheckedConstant::PerCopy(_)) | None => failed = true, } } if failed { diff --git a/crates/check/src/generics/constraints.rs b/crates/check/src/generics/constraints.rs index e198d39e..f1d0a533 100644 --- a/crates/check/src/generics/constraints.rs +++ b/crates/check/src/generics/constraints.rs @@ -122,9 +122,16 @@ impl builder::ThirBuilder<'_, '_> { .error(diagnostics::TYPE_MISMATCH, message, bound_span); return None; } - match self.known_constant(checked, span)?.value { - constant::Value::Bool(holds) => Some(holds), - _ => unreachable!("a `bool` constant is a `Value::Bool`"), + match self.known_constant(checked, span)? { + thir::CheckedConstant::Known(semantic_types::Constant { + value: constant::Value::Bool(holds), + .. + }) => Some(holds), + thir::CheckedConstant::Known(_) => { + unreachable!("a `bool` constant is a `Value::Bool`") + } + // Each copy works it out. + thir::CheckedConstant::PerCopy(_) => None, } } thir::Symbol::Type(definition) => { diff --git a/crates/check/src/locals.rs b/crates/check/src/locals.rs index 34c51c36..4c42fae4 100644 --- a/crates/check/src/locals.rs +++ b/crates/check/src/locals.rs @@ -92,12 +92,12 @@ impl builder::ThirBuilder<'_, '_> { } /// `const name: ty = value;`: a name for a value known at compile time. - /// Without a type, the constant takes its value's type. Gives its type and - /// value, or `None` after an error. + /// Without a type, the constant takes its value's type. Gives it as the + /// check knows it (`known_constant`), or `None` after an error. pub(crate) fn check_const_statement( &mut self, declaration: Id, - ) -> Option { + ) -> Option { let ast::Decl::Const { name, ty, value, .. } = self.checker.module().ast.decls[declaration] @@ -123,7 +123,7 @@ impl builder::ThirBuilder<'_, '_> { &mut self, value: Id, declared: Option, - ) -> Option { + ) -> Option { let span = self.checker.module().ast.exprs.span(value); let outer = std::mem::replace(&mut self.in_constant, true); let checked = match declared { @@ -135,24 +135,28 @@ impl builder::ThirBuilder<'_, '_> { } /// `checked`, worked out with `in_constant`, as a constant; reported at - /// `span` when it is not one. + /// `span` when it is not one. In a generic declaration's own check, one + /// each copy works out is known by its type only. pub(crate) fn known_constant( &mut self, checked: thir::Expr, span: Span, - ) -> Option { + ) -> Option { match checked.kind { - thir::ExprKind::Constant(value) => Some(semantic_types::Constant { - ty: checked.ty, - value, - }), + thir::ExprKind::Constant(value) => { + let ty = checked.ty; + Some(thir::CheckedConstant::Known(semantic_types::Constant { + ty, + value, + })) + } thir::ExprKind::Invalid => None, // reported _ => { let file = self.checker.module().ast.file.clone(); let unknown = self.body.first_named_variable(&checked.kind); // Each copy knows it, unless it reads what only a run knows. if unknown.is_none() && self.body.holds_undecided(&checked.kind) { - return None; + return Some(thir::CheckedConstant::PerCopy(checked.ty)); } let types = &self.checker.types; let message = if unknown.is_some() { diff --git a/crates/check/src/statement.rs b/crates/check/src/statement.rs index b766ac23..e2853b00 100644 --- a/crates/check/src/statement.rs +++ b/crates/check/src/statement.rs @@ -17,6 +17,7 @@ use model::semantic_types::Type; use model::semantic_types::TypeId; use model::thir::Block; use model::thir::Body; +use model::thir::CheckedConstant; use model::thir::ExprKind; use model::thir::FactKind; use model::thir::Local; @@ -111,7 +112,8 @@ impl<'a, 'p> ThirBuilder<'a, 'p> { /// checked, in `scope`: each one that is not `const` as a variable of /// its type in `types`, and each `const` value as a constant, the value /// `arguments` give it or, in the function's own body or signature - /// (`own_arguments`), one no call gave. A type parameter, `` or + /// (`own_arguments`), one known by its type only, each copy giving the + /// value (`CheckedConstant::PerCopy`). A type parameter, `` or /// `const T: type`, is a type (`resolve_global`). pub(crate) fn declare_parameters( &mut self, @@ -146,12 +148,22 @@ impl<'a, 'p> ThirBuilder<'a, 'p> { self.declare(name, Local::Variable(variable)); continue; } - let constant = match given.next() { - Some(ConstArgument::Value(constant)) => Some(constant), - _ => None, - }; + let given = given.next(); if !matches!(tree.types[parameter.ty], ast::Type::Type) { - let constant = self.body.constants.push(constant, name.span); + // A copy is given the value; the own check knows only its + // type, which the signature already resolved, with its facts. + let constant = if let Some(ConstArgument::Value(constant)) = given { + CheckedConstant::Known(constant) + } else { + let checking = (self.checker.internals.declarations_being_checked.last()) + .expect("a declaration is being checked"); + let (definition, used_at) = (checking.definition, checking.used_at); + let ty = self + .checker + .const_value_type(definition, parameter.ty, used_at); + CheckedConstant::PerCopy(ty) + }; + let constant = self.body.constants.push(Some(constant), name.span); self.declare(name, Local::Constant(constant)); } } diff --git a/crates/driver/lsp/src/checked.rs b/crates/driver/lsp/src/checked.rs index 64a25208..1fc16026 100644 --- a/crates/driver/lsp/src/checked.rs +++ b/crates/driver/lsp/src/checked.rs @@ -16,6 +16,7 @@ use model::semantic_types::TypeId; use model::semantic_types::Types; use model::semantic_types::value_text; use model::thir; +use model::thir::CheckedConstant; use model::thir::FactKind; use model::thir::Local; use model::thir::Symbol; @@ -183,8 +184,13 @@ impl CachedFact { } } Local::Constant(constant) => CachedKind::Constant { - text: (body.constants[constant].as_ref()) - .map(|constant| ConstantText::new(program, constant, types)), + text: match &body.constants[constant] { + Some(CheckedConstant::Known(constant)) => { + Some(ConstantText::new(program, constant, types)) + } + // Each copy gives the value. + Some(CheckedConstant::PerCopy(_)) | None => None, + }, }, } } diff --git a/crates/model/src/thir.rs b/crates/model/src/thir.rs index 4ca89072..da6b52e0 100644 --- a/crates/model/src/thir.rs +++ b/crates/model/src/thir.rs @@ -49,9 +49,9 @@ pub struct Body { /// a block comes before the blocks inside it. pub blocks: Arena, pub variables: Arena, // with the span of each name - /// Each `const` of the body, by its type and value, with the span of its + /// Each `const` of the body, as its check knows it, with the span of its /// name; `None` when its value had an error. Uses of it are folded. - pub constants: Arena>, + pub constants: Arena>, pub children: Children, /// Checking it reported an error, or it holds an invalid expression /// whose error another body's check reported: later phases would only @@ -93,12 +93,24 @@ pub enum Symbol { /// A name declared in a body, by its kind: checked in place with the /// body, never asked for on its own. +/// A constant as a check knows it: a `const` of a body, a `const` +/// parameter, or the value a `const` argument is given. +#[derive(Clone, Debug)] +pub enum CheckedConstant { + /// Its type and value. + Known(Constant), + /// Only its type, in a generic declaration's own check: each copy gives + /// the value, as it does a `const N: usize` parameter's, or `N * 2`. + /// Read, it is `ExprKind::Undecided` of that type. + PerCopy(TypeId), +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Local { /// A parameter or `let`: it holds a value at run time. Variable(Id), /// A `const`, folded where it is used. - Constant(Id>), + Constant(Id>), } /// What the checker found about the text at `span` of a module. Recorded diff --git a/docs/generics.md b/docs/generics.md index 761660ff..6c68eae1 100644 --- a/docs/generics.md +++ b/docs/generics.md @@ -35,6 +35,7 @@ array or a struct, and what is wrong for it whatever `T` is, is reported: | `for` over a bare `T`, or a reference to one | the body is checked as a range's, its value undecided | | a `where` constraint on a bare `T`, a call run at compile time given an open type | not known (`None`) | | `x...` of a bare `T` in `[_]E{ ... }` or a `...` argument | the array literal is of `Type::Undecided`: its length is each copy's count; a `...` argument still lends it as the parameter's slice; `[N]E{ ... }` keeps its type, and more than `N` values counted now is reported | +| a `const` parameter's value, or a `const` worked out from one (`N * 2`) | `thir::CheckedConstant::PerCopy`: its type is known; read, it is `ExprKind::Undecided` of that type | | a field of `Box` | the written field type, re-read with `T` bound (`field_types_given`) | An open struct, such as `Box` inside a generic body, stays diff --git a/test_programs/generic_functions/negative_generic_functions.peep b/test_programs/generic_functions/negative_generic_functions.peep index 772b2624..df882cd5 100644 --- a/test_programs/generic_functions/negative_generic_functions.peep +++ b/test_programs/generic_functions/negative_generic_functions.peep @@ -122,3 +122,19 @@ fn Uncalled(const COUNT: usize, value: T, pair: Pair) -> T { println(pair.right); //~ error[T0010]: `Pair` has no field `right` return doubled; } + +fn Double(value: i32) -> i32 { + return value * 2; +} + +// Never called: a `const` parameter's value is each copy's, but its type is +// known, so what is wrong for that type is reported. +fn WrongForEveryCount(const N: i32) { + let flag: bool = N; //~ error[T0001]: mismatched types: expected `bool`, found `i32` + const TWICE: i32 = N * 2; + let twice: bool = TWICE; //~ error[T0001]: mismatched types: expected `bool`, found `i32` + const RUN: i32 = Double(N); + let ran: bool = RUN; //~ error[T0001]: mismatched types: expected `bool`, found `i32` + const ABOVE: bool = N > 2; + let above: i32 = ABOVE; //~ error[T0001]: mismatched types: expected `i32`, found `bool` +} From 6be81e6e5274fd5b04ce5aa8a959905c0d43abb4 Mon Sep 17 00:00:00 2001 From: itsfuad Date: Fri, 20 Nov 2026 18:31:11 +0600 Subject: [PATCH 20/24] Keep per-copy const arguments and walk type parts once A const argument each copy gives (CheckedConstant::PerCopy) is now held in ConstArguments and makes them open, so the call keeps its type in a generic body's own check instead of staying silent. substitute, find_parameters, could_be_same and holds_open now share one walk over a type's parts (Types::parts); only data that is not a part, such as mutability or variadic, is compared by kind. --- crates/check/src/declaration.rs | 2 +- crates/check/src/expression/names.rs | 16 +- crates/check/src/generics.rs | 11 +- crates/check/src/generics/constraints.rs | 6 +- crates/check/src/generics/copies.rs | 5 +- crates/check/src/locals.rs | 15 +- crates/check/src/statement.rs | 6 +- crates/driver/lsp/src/checked.rs | 9 +- crates/model/src/program.rs | 5 +- crates/model/src/semantic_types.rs | 413 +++++++----------- crates/model/src/semantic_types/tests.rs | 23 + crates/model/src/thir.rs | 14 +- docs/generics.md | 2 +- .../negative_generic_functions.peep | 8 + 14 files changed, 239 insertions(+), 296 deletions(-) diff --git a/crates/check/src/declaration.rs b/crates/check/src/declaration.rs index 09c6986a..41628c63 100644 --- a/crates/check/src/declaration.rs +++ b/crates/check/src/declaration.rs @@ -12,6 +12,7 @@ use model::layout::layout; use model::program::BUILTIN_ATTRIBUTE; use model::program::EXTERN_ATTRIBUTE; use model::semantic_types; +use model::semantic_types::CheckedConstant; use model::semantic_types::ConstArgument; use model::semantic_types::Constant; use model::semantic_types::Integer; @@ -19,7 +20,6 @@ use model::semantic_types::Type; use model::semantic_types::TypeId; use model::semantic_types::Types; use model::thir::Body; -use model::thir::CheckedConstant; use model::thir::FactKind; use model::thir::Symbol; use source::Span; diff --git a/crates/check/src/expression/names.rs b/crates/check/src/expression/names.rs index 9745c949..7ce7dcdd 100644 --- a/crates/check/src/expression/names.rs +++ b/crates/check/src/expression/names.rs @@ -27,7 +27,7 @@ impl builder::ThirBuilder<'_, '_> { } Some(thir::Symbol::Constant(constant)) => { let constant = self.checker.constant(constant, span); - return constant_expr(constant.map(thir::CheckedConstant::Known)); + return constant_expr(constant.map(semantic_types::CheckedConstant::Known)); } Some(thir::Symbol::Function(_)) => { self.checker.not_supported(span, "functions as values"); @@ -50,13 +50,15 @@ impl builder::ThirBuilder<'_, '_> { /// The value of a constant as an expression: each copy's, when only its /// type is known. -fn constant_expr(constant: Option) -> thir::Expr { +fn constant_expr(constant: Option) -> thir::Expr { match constant { - Some(thir::CheckedConstant::Known(semantic_types::Constant { ty, value })) => thir::Expr { - ty, - kind: thir::ExprKind::Constant(value), - }, - Some(thir::CheckedConstant::PerCopy(ty)) => thir::Expr { + Some(semantic_types::CheckedConstant::Known(semantic_types::Constant { ty, value })) => { + thir::Expr { + ty, + kind: thir::ExprKind::Constant(value), + } + } + Some(semantic_types::CheckedConstant::PerCopy(ty)) => thir::Expr { ty, kind: thir::ExprKind::Undecided, }, diff --git a/crates/check/src/generics.rs b/crates/check/src/generics.rs index 21616a0f..acc88862 100644 --- a/crates/check/src/generics.rs +++ b/crates/check/src/generics.rs @@ -251,15 +251,10 @@ impl builder::ThirBuilder<'_, '_> { let ty = self .checker .const_value_type(definition, parameter.ty, span); + // One each copy gives makes the arguments open: no copy is made. match self.check_constant_value(argument, Some(ty)) { - Some(thir::CheckedConstant::Known(constant)) => { - given.push(semantic_types::ConstArgument::Value(constant)); - } - // Reported, or each copy gives it. shortcut: given a value - // each copy gives, no copy is made and the call stays - // silent; give it its type once `ConstArguments` can hold a - // per-copy value. - Some(thir::CheckedConstant::PerCopy(_)) | None => failed = true, + Some(constant) => given.push(semantic_types::ConstArgument::Value(constant)), + None => failed = true, // reported } } if failed { diff --git a/crates/check/src/generics/constraints.rs b/crates/check/src/generics/constraints.rs index f1d0a533..81bce3d0 100644 --- a/crates/check/src/generics/constraints.rs +++ b/crates/check/src/generics/constraints.rs @@ -123,15 +123,15 @@ impl builder::ThirBuilder<'_, '_> { return None; } match self.known_constant(checked, span)? { - thir::CheckedConstant::Known(semantic_types::Constant { + semantic_types::CheckedConstant::Known(semantic_types::Constant { value: constant::Value::Bool(holds), .. }) => Some(holds), - thir::CheckedConstant::Known(_) => { + semantic_types::CheckedConstant::Known(_) => { unreachable!("a `bool` constant is a `Value::Bool`") } // Each copy works it out. - thir::CheckedConstant::PerCopy(_) => None, + semantic_types::CheckedConstant::PerCopy(_) => None, } } thir::Symbol::Type(definition) => { diff --git a/crates/check/src/generics/copies.rs b/crates/check/src/generics/copies.rs index e0b64839..e49e03d1 100644 --- a/crates/check/src/generics/copies.rs +++ b/crates/check/src/generics/copies.rs @@ -166,7 +166,10 @@ impl Checker<'_> { /// (`declaration_copy_parameters`): each parameter that stands for a /// type, `` or `const T: type`, is itself (`Type::Parameter`), so /// what depends on it each copy decides; a `const` value's place holds - /// no value (`declare_parameters`). Nothing when it has none. + /// no value: `declare_parameters` gives it its type (`const_value_type`). + /// Not the type here: this runs before the signature is checked, and only + /// that check (`signature_type`) may report the type; it is read again + /// only once that check passed, silently. Nothing when it has none. pub(crate) fn own_arguments(&mut self, definition: DefId) -> ConstArguments { let parameters: Vec> = model::program::declaration_copy_parameters(self.modules, definition).collect(); diff --git a/crates/check/src/locals.rs b/crates/check/src/locals.rs index 4c42fae4..d83454ca 100644 --- a/crates/check/src/locals.rs +++ b/crates/check/src/locals.rs @@ -97,7 +97,7 @@ impl builder::ThirBuilder<'_, '_> { pub(crate) fn check_const_statement( &mut self, declaration: Id, - ) -> Option { + ) -> Option { let ast::Decl::Const { name, ty, value, .. } = self.checker.module().ast.decls[declaration] @@ -123,7 +123,7 @@ impl builder::ThirBuilder<'_, '_> { &mut self, value: Id, declared: Option, - ) -> Option { + ) -> Option { let span = self.checker.module().ast.exprs.span(value); let outer = std::mem::replace(&mut self.in_constant, true); let checked = match declared { @@ -141,14 +141,13 @@ impl builder::ThirBuilder<'_, '_> { &mut self, checked: thir::Expr, span: Span, - ) -> Option { + ) -> Option { match checked.kind { thir::ExprKind::Constant(value) => { let ty = checked.ty; - Some(thir::CheckedConstant::Known(semantic_types::Constant { - ty, - value, - })) + Some(semantic_types::CheckedConstant::Known( + semantic_types::Constant { ty, value }, + )) } thir::ExprKind::Invalid => None, // reported _ => { @@ -156,7 +155,7 @@ impl builder::ThirBuilder<'_, '_> { let unknown = self.body.first_named_variable(&checked.kind); // Each copy knows it, unless it reads what only a run knows. if unknown.is_none() && self.body.holds_undecided(&checked.kind) { - return Some(thir::CheckedConstant::PerCopy(checked.ty)); + return Some(semantic_types::CheckedConstant::PerCopy(checked.ty)); } let types = &self.checker.types; let message = if unknown.is_some() { diff --git a/crates/check/src/statement.rs b/crates/check/src/statement.rs index e2853b00..22f8b913 100644 --- a/crates/check/src/statement.rs +++ b/crates/check/src/statement.rs @@ -12,12 +12,12 @@ use diagnostics::Diagnostic; use model::ConstArguments; use model::DeclarationCopy; use model::constant::Value; +use model::semantic_types::CheckedConstant; use model::semantic_types::ConstArgument; use model::semantic_types::Type; use model::semantic_types::TypeId; use model::thir::Block; use model::thir::Body; -use model::thir::CheckedConstant; use model::thir::ExprKind; use model::thir::FactKind; use model::thir::Local; @@ -151,9 +151,9 @@ impl<'a, 'p> ThirBuilder<'a, 'p> { let given = given.next(); if !matches!(tree.types[parameter.ty], ast::Type::Type) { // A copy is given the value; the own check knows only its - // type, which the signature already resolved, with its facts. + // type, which the signature already read, with its facts. let constant = if let Some(ConstArgument::Value(constant)) = given { - CheckedConstant::Known(constant) + constant } else { let checking = (self.checker.internals.declarations_being_checked.last()) .expect("a declaration is being checked"); diff --git a/crates/driver/lsp/src/checked.rs b/crates/driver/lsp/src/checked.rs index 1fc16026..93fe0cb7 100644 --- a/crates/driver/lsp/src/checked.rs +++ b/crates/driver/lsp/src/checked.rs @@ -9,6 +9,7 @@ use std::path::PathBuf; use lsp_types::CodeAction; use model::DeclarationCopy; use model::ModuleId; +use model::semantic_types::CheckedConstant; use model::semantic_types::ConstArgument; use model::semantic_types::Constant; use model::semantic_types::Type; @@ -16,7 +17,6 @@ use model::semantic_types::TypeId; use model::semantic_types::Types; use model::semantic_types::value_text; use model::thir; -use model::thir::CheckedConstant; use model::thir::FactKind; use model::thir::Local; use model::thir::Symbol; @@ -273,12 +273,17 @@ fn copy_signature( ConstArgument::Type(ty) => { _ = write!(signature, "const {name}: type = {}", text(*ty)); } - ConstArgument::Value(constant) => { + ConstArgument::Value(CheckedConstant::Known(constant)) => { // Its type as written: `usize`, not the integer it is here. let ty = tree.file.slice(tree.types.span(parameter.ty)); let value = value_text(&constant.value, &types[constant.ty]); _ = write!(signature, "const {name}: {ty} = {value}"); } + // As `Types::argument_text` writes it: each copy gives it. + ConstArgument::Value(CheckedConstant::PerCopy(_)) => { + let ty = tree.file.slice(tree.types.span(parameter.ty)); + _ = write!(signature, "const {name}: {ty} = _"); + } } continue; } diff --git a/crates/model/src/program.rs b/crates/model/src/program.rs index 5744385c..02c2601e 100644 --- a/crates/model/src/program.rs +++ b/crates/model/src/program.rs @@ -15,6 +15,7 @@ use crate::DeclarationCopy; use crate::DefId; use crate::ModuleId; use crate::constant::Value; +use crate::semantic_types::CheckedConstant; use crate::semantic_types::ConstArgument; use crate::semantic_types::Constant; use crate::semantic_types::Naming; @@ -238,10 +239,10 @@ pub fn copy_symbol(modules: &[Module], types: &Types, copy: DeclarationCopy) -> return name; } let text = |argument: &ConstArgument| match argument { - ConstArgument::Value(Constant { + ConstArgument::Value(CheckedConstant::Known(Constant { value: Value::Float(bits), .. - }) => format!("{bits:#x}"), + })) => format!("{bits:#x}"), _ => types.argument_text(argument, qualified), }; let texts: Vec = given.iter().map(text).collect(); diff --git a/crates/model/src/semantic_types.rs b/crates/model/src/semantic_types.rs index fe10659c..746614df 100644 --- a/crates/model/src/semantic_types.rs +++ b/crates/model/src/semantic_types.rs @@ -6,6 +6,7 @@ use std::fmt::Display; use std::fmt::Write as _; use std::hash::Hash; use std::hash::Hasher; +use std::mem; use std::ops::Index; use rustc_hash::FxHashMap; @@ -20,11 +21,12 @@ use crate::mir; pub struct TypeId(u32); /// What one `const` parameter is given: a type for `const T: type`, else a -/// value known when compiling. +/// value known when compiling, or in a generic declaration's own check one +/// each copy gives. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub enum ConstArgument { Type(TypeId), - Value(Constant), + Value(CheckedConstant), } /// A struct's functions that are an interface's methods, by its place in @@ -441,9 +443,11 @@ impl Types { ) -> String { match argument { ConstArgument::Type(ty) => self.text(*ty, name_of), - ConstArgument::Value(Constant { ty, value }) => { + ConstArgument::Value(CheckedConstant::Known(Constant { ty, value })) => { value_text(value, &self[*ty]).to_string() } + // As `[_]` is written: each copy gives it. + ConstArgument::Value(CheckedConstant::PerCopy(_)) => "_".to_string(), } } @@ -613,7 +617,9 @@ impl Types { pub fn arguments_open(&self, arguments: ConstArguments) -> bool { (self.arguments(arguments).iter()).any(|argument| match argument { ConstArgument::Type(part) => self.is_open(*part), - ConstArgument::Value(constant) => self.is_open(constant.ty), + ConstArgument::Value(CheckedConstant::Known(constant)) => self.is_open(constant.ty), + // No copy holds a value it does not know. + ConstArgument::Value(CheckedConstant::PerCopy(_)) => true, }) } @@ -635,8 +641,18 @@ impl Types { if !self.is_open(ty) { return ty; } - let part = |types: &mut Types, part: TypeId| types.substitute(part, definition, arguments); - match self[ty].clone() { + let shape = self[ty].clone(); + let mut parts: Vec = self.parts(&shape).collect(); + for part in &mut parts { + *part = self.substitute(*part, definition, arguments); + } + let mut parts = parts.into_iter(); + let mut next = || { + parts + .next() + .expect("a part for each of the shape's (`parts`)") + }; + match shape { Type::Parameter { definition: of, place, @@ -647,14 +663,12 @@ impl Types { Type::Parameter { .. } | Type::Undecided => ty, Type::Function { parameters, - result, origins, variadic, + .. } => { - let parameters = (parameters.iter()) - .map(|¶meter| part(self, parameter)) - .collect(); - let result = part(self, result); + let result = next(); + let parameters = parameters.iter().map(|_| next()).collect(); self.intern(Type::Function { parameters, result, @@ -666,10 +680,10 @@ impl Types { definition: named, arguments: given, } => { - let given: Vec = (self.arguments(given).to_vec().into_iter()) + let given: Vec = (self.arguments(given).iter()) .map(|argument| match argument { - ConstArgument::Type(given) => ConstArgument::Type(part(self, given)), - value @ ConstArgument::Value(_) => value, + ConstArgument::Type(_) => ConstArgument::Type(next()), + value @ ConstArgument::Value(_) => value.clone(), }) .collect(); let arguments = self.const_arguments(&given); @@ -678,28 +692,24 @@ impl Types { arguments, }) } - Type::Array { - element, length, .. - } => { - let element = part(self, element); + Type::Array { length, .. } => { + let element = next(); self.array(element, length) } - Type::Range { element } => { - let element = part(self, element); + Type::Range { .. } => { + let element = next(); self.range(element).unwrap_or(TypeId::UNDECIDED) } - Type::Reference { mutable, target } => { - let target = part(self, target); + Type::Reference { mutable, .. } => { + let target = next(); self.intern(Type::Reference { mutable, target }) } - Type::Slice { mutable, element } => { - let element = part(self, element); + Type::Slice { mutable, .. } => { + let element = next(); self.intern(Type::Slice { mutable, element }) } - Type::RawPointer { - target: Some(target), - } => { - let target = Some(part(self, target)); + Type::RawPointer { target: Some(_) } => { + let target = Some(next()); self.intern(Type::RawPointer { target }) } Type::Invalid @@ -723,15 +733,13 @@ impl Types { /// parameter of `definition` there (`Type::Parameter`) where `pattern`, /// the type of a parameter of `definition`'s own check, names it: the /// part of `actual` in its place. A place already found keeps its type; - /// a part of another shape finds nothing, and the call reports the - /// mismatch. A reference to an array, `&[3]i32`, given for a slice, - /// `&[]T`, gives its element. An undecided part (`Type::Undecided`), as - /// `t[0]` of a `t: T` in a generic body, leaves each parameter its - /// pattern names undecided: each copy finds it. - #[deny( - clippy::wildcard_enum_match_arm, - clippy::match_wildcard_for_single_variants - )] + /// a part of another kind finds nothing, and the call reports the + /// mismatch; one only of another mutability or length still finds it, + /// so the call reports what is wrong with the type it found. A + /// reference to an array, `&[3]i32`, given for a slice, `&[]T`, gives + /// its element. An undecided part (`Type::Undecided`), as `t[0]` of a + /// `t: T` in a generic body, leaves each parameter its pattern names + /// undecided: each copy finds it. pub fn find_parameters( &self, pattern: TypeId, @@ -769,90 +777,19 @@ impl Types { } } } - ( - Type::Function { - parameters, result, .. - }, - Type::Function { - parameters: given, - result: given_result, - .. - }, - ) => { - for (&pattern, &actual) in parameters.iter().zip(given.iter()) { - part(pattern, actual); - } - part(*result, *given_result); - } - ( - &Type::Named { - definition: named, - arguments, - }, - &(Type::Named { - definition: given_definition, - arguments: given, - } - | Type::Struct { - definition: given_definition, - arguments: given, - .. - }), - ) if named == given_definition => { - let pairs = self.arguments(arguments).iter().zip(self.arguments(given)); - for pair in pairs { - if let (&ConstArgument::Type(pattern), &ConstArgument::Type(actual)) = pair { - part(pattern, actual); - } + (&Type::Slice { element, .. }, &Type::Reference { target, .. }) => { + if let Type::Array { element: given, .. } = self[target] { + part(element, given); } } - (Type::Array { element, .. }, Type::Array { element: given, .. }) - | (Type::Range { element }, Type::Range { element: given }) - | (Type::Slice { element, .. }, Type::Slice { element: given, .. }) - | ( - Type::Reference { - target: element, .. - }, - Type::Reference { target: given, .. }, - ) - | ( - Type::RawPointer { - target: Some(element), - }, - Type::RawPointer { - target: Some(given), - }, - ) => part(*element, *given), - (Type::Slice { element, .. }, &Type::Reference { target, .. }) => { - if let Type::Array { element: given, .. } = self[target] { - part(*element, given); + (pattern, actual) if Self::same_kind(pattern, actual) => { + // A function's result comes first: parameters of another + // count still pair it with the result. + for (pattern, actual) in self.parts(pattern).zip(self.parts(actual)) { + part(pattern, actual); } } - ( - Type::Function { .. } - | Type::Named { .. } - | Type::Array { .. } - | Type::Range { .. } - | Type::Slice { .. } - | Type::Reference { .. } - | Type::RawPointer { target: Some(_) }, - _, - ) => {} - ( - Type::Invalid - | Type::Void - | Type::Bool - | Type::Integer(_) - | Type::Float(_) - | Type::CString - | Type::Str - | Type::Alias { .. } - | Type::Struct { .. } - | Type::Interface { .. } - | Type::InterfaceReference { .. } - | Type::RawPointer { target: None }, - _, - ) => unreachable!("an open type holds a type parameter: these do not, or are copies"), + _ => {} } } @@ -868,11 +805,6 @@ impl Types { /// are, or they differ only where one has a type each copy decides /// (`is_decided_per_copy`). Each such part is matched alone, so `T` /// against `i32` in one place and `bool` in another still could. - #[deny( - clippy::wildcard_enum_match_arm, - clippy::match_wildcard_for_single_variants - )] - // TODO: simplify later pub fn could_be_same(&self, a: TypeId, b: TypeId) -> bool { let (a, b) = (self.real(a), self.real(b)); if a == b || self[a].is_decided_per_copy() || self[b].is_decided_per_copy() { @@ -881,151 +813,115 @@ impl Types { if !self.is_open(a) && !self.is_open(b) { return false; } - let part = |a: TypeId, b: TypeId| source::grow_stack(|| self.could_be_same(a, b)); - match (&self[a], &self[b]) { - ( - Type::Function { - parameters, - result, - variadic, - .. - }, - Type::Function { - parameters: given, - result: given_result, - variadic: given_variadic, - .. - }, - ) => { - variadic == given_variadic - && parameters.len() == given.len() - && (parameters.iter().zip(given.iter())).all(|(&a, &b)| part(a, b)) - && part(*result, *given_result) + let (a, b) = (&self[a], &self[b]); + // All but the parts, and their count, must be the same; a kind left + // out here is compared by its parts alone, which can only miss an + // error a copy then reports, never make one up. + let same_rest = Self::same_kind(a, b) + && match (a, b) { + ( + Type::Function { variadic, .. }, + Type::Function { + variadic: given, .. + }, + ) => variadic == given, + (Type::Array { length, .. }, Type::Array { length: given, .. }) => length == given, + ( + Type::Reference { mutable, .. } + | Type::Slice { mutable, .. } + | Type::InterfaceReference { mutable, .. }, + Type::Reference { mutable: given, .. } + | Type::Slice { mutable: given, .. } + | Type::InterfaceReference { mutable: given, .. }, + ) => mutable == given, + ( + Type::Named { arguments, .. } | Type::Struct { arguments, .. }, + Type::Named { + arguments: given, .. + } + | Type::Struct { + arguments: given, .. + }, + ) => (self + .arguments(*arguments) + .iter() + .zip(self.arguments(*given))) + .all(|pair| match pair { + (ConstArgument::Type(_), ConstArgument::Type(_)) => true, // a part + // One parameter's: of one type, so some copy gives it. + ( + ConstArgument::Value(CheckedConstant::PerCopy(_)), + ConstArgument::Value(_), + ) + | ( + ConstArgument::Value(_), + ConstArgument::Value(CheckedConstant::PerCopy(_)), + ) => true, + (a, b) => a == b, + }), + _ => true, + }; + same_rest + && self.parts(a).count() == self.parts(b).count() + && (self.parts(a).zip(self.parts(b))) + .all(|(a, b)| source::grow_stack(|| self.could_be_same(a, b))) + } + + /// Whether the type `ty`, about to be added, is open: it is a type + /// parameter or undecided, or a part of it is open. + fn holds_open(&self, ty: &Type) -> bool { + match ty { + Type::Parameter { .. } | Type::Undecided => true, + Type::Named { arguments, .. } | Type::Struct { arguments, .. } => { + self.arguments_open(*arguments) } + _ => self.parts(ty).any(|part| self.is_open(part)), + } + } + + /// Whether `a` and `b` are of one kind, so their parts (`parts`) pair up + /// in order: a struct and its name are one kind when of one declaration. + fn same_kind(a: &Type, b: &Type) -> bool { + match (a, b) { ( - &(Type::Named { - definition, - arguments, + Type::Named { definition, .. } | Type::Struct { definition, .. }, + Type::Named { + definition: given, .. } | Type::Struct { - definition, - arguments, - .. - }), - &(Type::Named { - definition: given_definition, - arguments: given, - } - | Type::Struct { - definition: given_definition, - arguments: given, - .. - }), - ) => { - definition == given_definition - && (self.arguments(arguments).iter().zip(self.arguments(given))).all(|pair| { - match pair { - (&ConstArgument::Type(a), &ConstArgument::Type(b)) => part(a, b), - (a, b) => a == b, - } - }) - } - ( - &Type::Array { - element, length, .. - }, - &Type::Array { - element: given, - length: given_length, - .. + definition: given, .. }, - ) => length == given_length && part(element, given), - (&Type::Range { element }, &Type::Range { element: given }) - | ( - &Type::RawPointer { - target: Some(element), - }, - &Type::RawPointer { - target: Some(given), - }, - ) => part(element, given), - ( - &Type::Slice { mutable, element }, - &Type::Slice { - mutable: given_mutable, - element: given, - }, - ) - | ( - &Type::Reference { - mutable, - target: element, - }, - &Type::Reference { - mutable: given_mutable, - target: given, - }, - ) - | ( - &Type::InterfaceReference { - mutable, - interface: element, - }, - &Type::InterfaceReference { - mutable: given_mutable, - interface: given, - }, - ) => mutable == given_mutable && part(element, given), - ( - Type::Invalid - | Type::Parameter { .. } - | Type::Undecided - | Type::Void - | Type::Bool - | Type::Integer(_) - | Type::Float(_) - | Type::CString - | Type::Str - | Type::Function { .. } - | Type::Alias { .. } - | Type::Named { .. } - | Type::Struct { .. } - | Type::Array { .. } - | Type::Range { .. } - | Type::Reference { .. } - | Type::Slice { .. } - | Type::Interface { .. } - | Type::InterfaceReference { .. } - | Type::RawPointer { .. }, - _, - ) => false, + ) => definition == given, + _ => mem::discriminant(a) == mem::discriminant(b), } } - /// Whether the type `ty`, about to be added, is open: it is a type - /// parameter or undecided, or a part of it is open. + /// The types the type `ty` is made of, in order, a function's result + /// first: where a type parameter in it can stand. A struct's fields are + /// not among them: its type arguments decide them. #[deny( clippy::wildcard_enum_match_arm, clippy::match_wildcard_for_single_variants )] - fn holds_open(&self, ty: &Type) -> bool { - match ty { - Type::Parameter { .. } | Type::Undecided => true, + fn parts<'a>(&'a self, ty: &'a Type) -> impl Iterator + 'a { + let (first, rest, arguments): (Option, &[TypeId], &[ConstArgument]) = match ty { Type::Invalid + | Type::Parameter { .. } + | Type::Undecided | Type::Void | Type::Bool | Type::Integer(_) | Type::Float(_) | Type::CString | Type::Str - | Type::RawPointer { target: None } => false, + | Type::RawPointer { target: None } => (None, &[], &[]), Type::Function { parameters, result, .. - } => self.is_open(*result) || parameters.iter().any(|&part| self.is_open(part)), + } => (Some(*result), parameters, &[]), Type::Named { arguments, .. } | Type::Struct { arguments, .. } => { - self.arguments_open(*arguments) + (None, &[], self.arguments(*arguments)) } - Type::Interface { methods, .. } => methods.iter().any(|&part| self.is_open(part)), + Type::Interface { methods, .. } => (None, methods, &[]), Type::Alias { real: part, .. } | Type::Array { element: part, .. } | Type::Range { element: part } @@ -1034,8 +930,13 @@ impl Types { | Type::InterfaceReference { interface: part, .. } - | Type::RawPointer { target: Some(part) } => self.is_open(*part), - } + | Type::RawPointer { target: Some(part) } => (Some(*part), &[], &[]), + }; + let types = arguments.iter().filter_map(|argument| match argument { + ConstArgument::Type(part) => Some(*part), + ConstArgument::Value(_) => None, + }); + first.into_iter().chain(rest.iter().copied()).chain(types) } /// The type `id` stands for: itself, or the type an alias names. @@ -1054,6 +955,7 @@ impl Types { clippy::wildcard_enum_match_arm, clippy::match_wildcard_for_single_variants )] + // TODO: simplify later pub fn hash( &self, id: TypeId, @@ -1094,10 +996,13 @@ impl Types { for argument in given { match argument { ConstArgument::Type(ty) => self.hash(*ty, hasher, declaration), - ConstArgument::Value(constant) => { + ConstArgument::Value(CheckedConstant::Known(constant)) => { self.hash(constant.ty, hasher, declaration); constant.value.hash(hasher); } + ConstArgument::Value(CheckedConstant::PerCopy(ty)) => { + self.hash(*ty, hasher, declaration); + } } } } @@ -1172,6 +1077,7 @@ impl Types { clippy::wildcard_enum_match_arm, clippy::match_wildcard_for_single_variants )] + // TODO: simplify later fn write_real_text( &self, out: &mut String, @@ -1297,6 +1203,19 @@ pub struct Constant { pub value: Value, } +/// A constant as a check knows it: a `const` of a body, a `const` +/// parameter, or the value a `const` argument is given. Two `PerCopy` of +/// one type are equal: no copy is made from one (`Types::arguments_open`). +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum CheckedConstant { + /// Its type and value. + Known(Constant), + /// Only its type, in a generic declaration's own check: each copy gives + /// the value, as it does a `const N: usize` parameter's, or `N * 2`. + /// Read, it is `ExprKind::Undecided` of that type. + PerCopy(TypeId), +} + /// `value`, of the type `ty`, as Peeper text: an integer in decimal, read /// through its type's sign, when 128 bits hold it, else every limb in hex /// (`integer_text`); a float as the shortest text that reads back as it, in diff --git a/crates/model/src/semantic_types/tests.rs b/crates/model/src/semantic_types/tests.rs index c52f1d2f..46a45822 100644 --- a/crates/model/src/semantic_types/tests.rs +++ b/crates/model/src/semantic_types/tests.rs @@ -1,4 +1,6 @@ +use super::CheckedConstant; use super::ConstArgument; +use super::Constant; use super::Conversion; use super::Float; use super::Integer; @@ -12,6 +14,7 @@ use super::integers; use crate::ConstArguments; use crate::DefId; use crate::ModuleId; +use crate::constant::Value; use crate::layout::layout; use crate::machine::Machine; use crate::mir; @@ -280,6 +283,26 @@ fn conversions_of_open_types() { assert_eq!(types.conversion(pair, TypeId::BOOL), Conversion::Never); assert_eq!(types.conversion(to_pair, to_triple), Conversion::Never); assert!(!types.could_be_same(pair, triple)); + // Nor is a pointer to a type one to no type known (`*opaque`). + let opaque = types.intern(Type::RawPointer { target: None }); + assert!(!types.could_be_same(raw_parameter, opaque)); +} + +/// A `const` argument each copy gives makes the arguments open, so no +/// copy, which would hold a value it does not know, is made from them; a +/// known one does not. +#[test] +fn per_copy_const_arguments_are_open() { + let mut types = Types::new(64); + let per_copy = ConstArgument::Value(CheckedConstant::PerCopy(TypeId::I32)); + let per_copy = types.const_arguments(&[per_copy]); + assert!(types.arguments_open(per_copy)); + let one = Constant { + ty: TypeId::I32, + value: Value::Integer(bigint::Limbs::new(32, &[1])), + }; + let known = types.const_arguments(&[ConstArgument::Value(CheckedConstant::Known(one))]); + assert!(!types.arguments_open(known)); } /// An interface keeps the id it was named by, so a `&Shape` written before diff --git a/crates/model/src/thir.rs b/crates/model/src/thir.rs index da6b52e0..b061c530 100644 --- a/crates/model/src/thir.rs +++ b/crates/model/src/thir.rs @@ -11,7 +11,7 @@ use crate::DeclarationCopy; use crate::DefId; use crate::ModuleId; use crate::constant::Value; -use crate::semantic_types::Constant; +use crate::semantic_types::CheckedConstant; use crate::semantic_types::ImplementationId; use crate::semantic_types::Naming; use crate::semantic_types::Type; @@ -93,18 +93,6 @@ pub enum Symbol { /// A name declared in a body, by its kind: checked in place with the /// body, never asked for on its own. -/// A constant as a check knows it: a `const` of a body, a `const` -/// parameter, or the value a `const` argument is given. -#[derive(Clone, Debug)] -pub enum CheckedConstant { - /// Its type and value. - Known(Constant), - /// Only its type, in a generic declaration's own check: each copy gives - /// the value, as it does a `const N: usize` parameter's, or `N * 2`. - /// Read, it is `ExprKind::Undecided` of that type. - PerCopy(TypeId), -} - #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Local { /// A parameter or `let`: it holds a value at run time. diff --git a/docs/generics.md b/docs/generics.md index 6c68eae1..e4f8bbd6 100644 --- a/docs/generics.md +++ b/docs/generics.md @@ -35,7 +35,7 @@ array or a struct, and what is wrong for it whatever `T` is, is reported: | `for` over a bare `T`, or a reference to one | the body is checked as a range's, its value undecided | | a `where` constraint on a bare `T`, a call run at compile time given an open type | not known (`None`) | | `x...` of a bare `T` in `[_]E{ ... }` or a `...` argument | the array literal is of `Type::Undecided`: its length is each copy's count; a `...` argument still lends it as the parameter's slice; `[N]E{ ... }` keeps its type, and more than `N` values counted now is reported | -| a `const` parameter's value, or a `const` worked out from one (`N * 2`) | `thir::CheckedConstant::PerCopy`: its type is known; read, it is `ExprKind::Undecided` of that type | +| a `const` parameter's value, or a `const` worked out from one (`N * 2`) | `semantic_types::CheckedConstant::PerCopy`: its type is known; read, it is `ExprKind::Undecided` of that type; given to a `const` parameter, `ConstArgument::Value` holds it, which makes the arguments open, so no copy is made | | a field of `Box` | the written field type, re-read with `T` bound (`field_types_given`) | An open struct, such as `Box` inside a generic body, stays diff --git a/test_programs/generic_functions/negative_generic_functions.peep b/test_programs/generic_functions/negative_generic_functions.peep index df882cd5..7d2a3773 100644 --- a/test_programs/generic_functions/negative_generic_functions.peep +++ b/test_programs/generic_functions/negative_generic_functions.peep @@ -127,6 +127,10 @@ fn Double(value: i32) -> i32 { return value * 2; } +fn Same(const K: i32) -> i32 { + return K; +} + // Never called: a `const` parameter's value is each copy's, but its type is // known, so what is wrong for that type is reported. fn WrongForEveryCount(const N: i32) { @@ -137,4 +141,8 @@ fn WrongForEveryCount(const N: i32) { let ran: bool = RUN; //~ error[T0001]: mismatched types: expected `bool`, found `i32` const ABOVE: bool = N > 2; let above: i32 = ABOVE; //~ error[T0001]: mismatched types: expected `i32`, found `bool` + // Given to another `const` parameter, it makes no copy of `Same`. + const PASSED: i32 = Same(N); + let passed: bool = PASSED; //~ error[T0001]: mismatched types: expected `bool`, found `i32` + let returned: bool = Same(N * 2); //~ error[T0001]: mismatched types: expected `bool`, found `i32` } From 9c3100db26845fd9eebb198c9d59e6d8c3e4c709 Mon Sep 17 00:00:00 2001 From: itsfuad Date: Fri, 20 Nov 2026 18:31:17 +0600 Subject: [PATCH 21/24] Hold an array length as a constant a copy may give An array's length is a CheckedConstant, the same hole a const argument uses. A spread counted by each copy, as [_]i32{1, x...} with x of a type parameter, gives an array of i32 whose length is CheckedConstant::PerCopy (written [_]i32), not an undecided type, so what does not depend on the length is checked once in the generic body's own check. Types::values walks the values a type holds, beside Types::parts, so open, could-be-same, hash and text treat an array's length and a struct's const arguments alike. .len reads the length through constant_expr, as any const value. Layout reads the total count only for a type whose lengths are all known. --- crates/check/src/arrays.rs | 43 +++-- crates/check/src/declaration.rs | 7 +- crates/check/src/expression/literals.rs | 35 ++-- crates/check/src/expression/names.rs | 22 +-- crates/check/src/lib.rs | 18 ++ crates/lower/src/aggregates.rs | 17 +- crates/lower/src/expression.rs | 33 ++-- crates/lower/src/lib.rs | 6 +- crates/model/src/layout.rs | 2 +- crates/model/src/semantic_types.rs | 158 +++++++++++------- crates/model/src/semantic_types/arrays.rs | 50 +++++- crates/model/src/semantic_types/tests.rs | 58 ++++--- docs/generics.md | 2 +- .../negative_generic_functions.peep | 15 ++ .../run_generic_spread_arrays.out | 7 + .../run_generic_spread_arrays.peep | 48 ++++++ 16 files changed, 346 insertions(+), 175 deletions(-) create mode 100644 test_programs/generic_functions/run_generic_spread_arrays.out create mode 100644 test_programs/generic_functions/run_generic_spread_arrays.peep diff --git a/crates/check/src/arrays.rs b/crates/check/src/arrays.rs index 93a658c5..8a5287a6 100644 --- a/crates/check/src/arrays.rs +++ b/crates/check/src/arrays.rs @@ -11,7 +11,6 @@ use crate::Checker; use crate::builder; use arena::Id; use arena::List; -use bigint::Limbs; use diagnostics::suggest::nearest_name; use model::constant::Value; use model::semantic_types; @@ -38,7 +37,8 @@ pub(crate) fn resolve_array_type( return semantic_types::TypeId::INVALID; } let element = checker.resolve_value_type(element); - checker.array_type(element, value[0], span) + let length = checker.types.array_length(value[0]); + checker.array_type(element, length, span) } /// `[N]T{ entries }`, written at `span`, or `[_]T{ entries }`, whose @@ -69,11 +69,11 @@ pub(crate) fn check_array_literal( ty if ty == semantic_types::TypeId::INVALID => { (semantic_types::TypeId::INVALID, None, span) } - ty => match builder.checker.types[ty] { - semantic_types::Type::Array { - element, length, .. - } => (element, Some((ty, length)), span), - _ => unreachable!("an array literal's written type is an array type"), + ty => match builder.checker.types[ty].elements() { + Some((element, Some(length))) => (element, Some((ty, length)), span), + _ => unreachable!( + "an array literal's written type is an array type with its length written" + ), }, } } @@ -114,7 +114,6 @@ pub(crate) fn check_length( .report_unknown(diagnostics::UNKNOWN_FIELD, field.span, message, meant); return thir::Expr::INVALID; } - let usize = builder.checker.types.usize; // An array's length is folded only where computing the array runs // nothing: a variable or constant, its fields and dereferences, and // elements at constant indexes, which are checked here. A call, a @@ -135,23 +134,19 @@ pub(crate) fn check_length( _ => break false, } }; - // A slice's or a `&str`'s length is known only when the program runs: - // read from the value, so through the reference to it, as an array's - // that must still be computed. - let length = builder.checker.types[viewed] - .elements() - .and_then(|(_, length)| length); - let Some(length) = length.filter(|_| runs_nothing) else { - let value = builder.through_pointer(value, builder.body.exprs.span(value)); - return thir::Expr { - ty: usize, - kind: thir::ExprKind::Length(value), - }; - }; - let length = Limbs::new(builder.checker.target.pointer_bits, &[length]); + // An array's length is its type's constant, each copy's when only its + // type is known; a slice's or a `&str`'s is known only when the program + // runs: read from the value, so through the reference to it, as an + // array's that must still be computed. + if runs_nothing + && let semantic_types::Type::Array { length, .. } = &builder.checker.types[viewed] + { + return crate::constant_expr(Some(length.clone())); + } + let value = builder.through_pointer(value, builder.body.exprs.span(value)); thir::Expr { - ty: usize, - kind: thir::ExprKind::Constant(Value::Integer(length)), + ty: builder.checker.types.usize, + kind: thir::ExprKind::Length(value), } } diff --git a/crates/check/src/declaration.rs b/crates/check/src/declaration.rs index 41628c63..68a812f0 100644 --- a/crates/check/src/declaration.rs +++ b/crates/check/src/declaration.rs @@ -296,7 +296,12 @@ impl Checker<'_> { /// `[length]element`, written at `span` (`element_type`), holding at /// most `MOST_HOLDERS` references and slices and fitting the target; /// an open one's copies are checked for both. - pub(crate) fn array_type(&mut self, element: TypeId, length: u64, span: Span) -> TypeId { + pub(crate) fn array_type( + &mut self, + element: TypeId, + length: CheckedConstant, + span: Span, + ) -> TypeId { let Some(element) = self.element_type(element) else { return TypeId::INVALID; }; diff --git a/crates/check/src/expression/literals.rs b/crates/check/src/expression/literals.rs index b438de43..a7476612 100644 --- a/crates/check/src/expression/literals.rs +++ b/crates/check/src/expression/literals.rs @@ -7,6 +7,7 @@ use arena::Id; use diagnostics::Diagnostic; use diagnostics::fix::Fix; use model::constant::Value; +use model::semantic_types::CheckedConstant; use model::semantic_types::Conversion; use model::semantic_types::Type; use model::semantic_types::TypeId; @@ -35,6 +36,14 @@ pub(crate) struct EntryCount { } impl EntryCount { + /// As many values as each copy finds. + fn per_copy() -> EntryCount { + EntryCount { + per_copy: true, + ..EntryCount::known(0) + } + } + /// `known` values, all counted now. fn known(known: u64) -> EntryCount { EntryCount { @@ -292,7 +301,7 @@ impl ThirBuilder<'_, '_> { /// entries give `count` values; `None` after reporting that they do not /// fit it (`arrays::check_array_literal`). `[_]` cannot count a spread /// counted when the program runs, and one each copy counts makes its - /// length, so its type, each copy's (`TypeId::UNDECIDED`). + /// length each copy's (`CheckedConstant::PerCopy`). pub(crate) fn array_literal_type( &mut self, written: Span, @@ -313,7 +322,10 @@ impl ThirBuilder<'_, '_> { .error(diagnostics::TYPE_MISMATCH, message, spread); None } - (None, None) if per_copy => Some(TypeId::UNDECIDED), + (None, None) if per_copy => { + let length = CheckedConstant::PerCopy(self.checker.types.usize); + Some(self.checker.array_type(element, length, written)) + } (None, None) => { if !self .checker @@ -321,7 +333,8 @@ impl ThirBuilder<'_, '_> { { return None; } - Some(self.checker.array_type(element, known as u64, written)) + let length = self.checker.types.array_length(known as u64); + Some(self.checker.array_type(element, length, written)) } (Some((ty, length)), later) => { let length = u128::from(length); @@ -375,12 +388,10 @@ impl ThirBuilder<'_, '_> { }; match types[ty] { Type::Invalid => return None, - Type::Array { - element: from, - length, - .. - } if gives(from) => { - return Some((spread, EntryCount::known(length))); + Type::Array { element: from, .. } if gives(from) => { + let length = types[ty].elements().and_then(|(_, length)| length); + let count = length.map_or(EntryCount::per_copy(), EntryCount::known); + return Some((spread, count)); } Type::Slice { mutable, @@ -420,11 +431,7 @@ impl ThirBuilder<'_, '_> { } Type::Range { element: from, .. } if gives(from) => {} _ if types[ty].is_decided_per_copy() => { - let count = EntryCount { - per_copy: true, - ..EntryCount::known(0) - }; - return Some((spread, count)); + return Some((spread, EntryCount::per_copy())); } _ => { let (expected, found) = self.checker.type_texts(element, ty); diff --git a/crates/check/src/expression/names.rs b/crates/check/src/expression/names.rs index 7ce7dcdd..06432092 100644 --- a/crates/check/src/expression/names.rs +++ b/crates/check/src/expression/names.rs @@ -23,11 +23,11 @@ impl builder::ThirBuilder<'_, '_> { }; } Some(thir::Symbol::Local(thir::Local::Constant(constant))) => { - return constant_expr(self.body.constants[constant].clone()); + return crate::constant_expr(self.body.constants[constant].clone()); } Some(thir::Symbol::Constant(constant)) => { let constant = self.checker.constant(constant, span); - return constant_expr(constant.map(semantic_types::CheckedConstant::Known)); + return crate::constant_expr(constant.map(semantic_types::CheckedConstant::Known)); } Some(thir::Symbol::Function(_)) => { self.checker.not_supported(span, "functions as values"); @@ -47,21 +47,3 @@ impl builder::ThirBuilder<'_, '_> { thir::Expr::INVALID } } - -/// The value of a constant as an expression: each copy's, when only its -/// type is known. -fn constant_expr(constant: Option) -> thir::Expr { - match constant { - Some(semantic_types::CheckedConstant::Known(semantic_types::Constant { ty, value })) => { - thir::Expr { - ty, - kind: thir::ExprKind::Constant(value), - } - } - Some(semantic_types::CheckedConstant::PerCopy(ty)) => thir::Expr { - ty, - kind: thir::ExprKind::Undecided, - }, - None => thir::Expr::INVALID, - } -} diff --git a/crates/check/src/lib.rs b/crates/check/src/lib.rs index b7f5fc83..fd41bf25 100644 --- a/crates/check/src/lib.rs +++ b/crates/check/src/lib.rs @@ -25,6 +25,22 @@ mod ranges; mod raw_pointers; mod slices; mod structs; +/// The value of a constant as an expression: each copy's, when only its +/// type is known. +pub(crate) fn constant_expr(constant: Option) -> thir::Expr { + match constant { + Some(CheckedConstant::Known(Constant { ty, value })) => thir::Expr { + ty, + kind: thir::ExprKind::Constant(value), + }, + Some(CheckedConstant::PerCopy(ty)) => thir::Expr { + ty, + kind: thir::ExprKind::Undecided, + }, + None => thir::Expr::INVALID, + } +} + /// Why a call of `callee` with `given` arguments is wrong, when it takes /// `fixed` of them, or at least that many when `variadic`. pub(crate) fn argument_count_message( @@ -59,6 +75,7 @@ use model::DeclarationCopy; use model::DefId; use model::ModuleId; use model::machine::Machine; +use model::semantic_types::CheckedConstant; use model::semantic_types::ConstArgument; use model::semantic_types::Constant; use model::semantic_types::ImplementationId; @@ -66,6 +83,7 @@ use model::semantic_types::Naming; use model::semantic_types::Type; use model::semantic_types::TypeId; use model::semantic_types::Types; +use model::thir; use model::thir::Fact; use model::thir::FactKind; use model::thir::Symbol; diff --git a/crates/lower/src/aggregates.rs b/crates/lower/src/aggregates.rs index 609ce933..5eb1cada 100644 --- a/crates/lower/src/aggregates.rs +++ b/crates/lower/src/aggregates.rs @@ -81,11 +81,11 @@ impl Lowering<'_> { ) -> Option<()> { let semantic_types::Type::Array { element, length, .. - } = self.types[ty] + } = &self.types[ty] else { unreachable!("an array literal makes an array") }; - let element = self.types.real(element); + let (element, length) = (self.types.real(*element), length.laid_out_length()); let (size, _) = layout::layout(self.types, element, self.target); let parts: Vec> = self.thir.children.lists.items(parts).collect(); // Each part's value, and how many elements it gives: a number when @@ -113,9 +113,9 @@ impl Lowering<'_> { Part::Value(self.settled(value, part_type, called_later, span)) } }; - let count = match self.types[part_type] { + let count = match &self.types[part_type] { _ if !spread => Ok(1), - semantic_types::Type::Array { length, .. } => Ok(length), + semantic_types::Type::Array { length, .. } => Ok(length.laid_out_length()), _ => match self.part_count(&value, part_type, wide, span) { mir::Operand::Constant { bits, .. } => Ok(bits[0]), counted => { @@ -761,12 +761,15 @@ impl Lowering<'_> { }; let mut place = self.place_of(array)?; let viewed = self.types.real(self.thir.exprs[array].ty); - let (element, length) = match self.types[viewed] { + let (element, length) = match &self.types[viewed] { semantic_types::Type::Array { element, length, .. - } => (element, expression::Length::Known(length)), + } => ( + *element, + expression::Length::Known(length.laid_out_length()), + ), // Its elements are behind its first word. - semantic_types::Type::Slice { element, .. } => { + &semantic_types::Type::Slice { element, .. } => { let length = self.second_word(place.clone()); let read = self.load(self.usize, length, span); place = place.then(mir::Step::Through); diff --git a/crates/lower/src/expression.rs b/crates/lower/src/expression.rs index e15ff056..9564714f 100644 --- a/crates/lower/src/expression.rs +++ b/crates/lower/src/expression.rs @@ -250,7 +250,7 @@ impl Lowering<'_> { // copied, and a `&mut []` stays usable. let place = self.place_of(value)?; if !self.types[value_type].is_slice_shaped() { - let semantic_types::Type::Array { length, .. } = self.types[value_type] else { + let semantic_types::Type::Array { length, .. } = &self.types[value_type] else { unreachable!("`.len` is the length of an array, slice or `&str`") }; // A register, not a constant: the checker took this length as @@ -260,7 +260,7 @@ impl Lowering<'_> { self.store( self.usize, slot.clone(), - mir::Operand::integer(self.usize, length), + mir::Operand::integer(self.usize, length.laid_out_length()), span, ); return Some(Value::Register(self.load(self.usize, slot, span))); @@ -361,16 +361,17 @@ impl Lowering<'_> { unreachable!("the caller found an index") }; let viewed = self.types.real(self.thir.exprs[array].ty); - let (element, checked, count) = match self.types[viewed] { + let (element, checked, count) = match &self.types[viewed] { semantic_types::Type::Array { element, length, .. } if let Some(at) = self.known_position(index) => { let at = mir::Operand::integer(self.usize, at); - (element, at, Some(length)) + (*element, at, Some(length.laid_out_length())) } semantic_types::Type::Array { element, length, .. } => { + let (element, length) = (*element, length.laid_out_length()); let value = self.lower_expr(index)?.register(); let message = messages::array_index_message(length); let index_type = self.types.real(self.thir.exprs[index].ty); @@ -384,7 +385,7 @@ impl Lowering<'_> { ); (element, checked, Some(length)) } - semantic_types::Type::Slice { element, .. } => { + &semantic_types::Type::Slice { element, .. } => { let value = self.lower_expr(index)?.register(); // The slice's words are the place before its elements' step. let slice = mir::Place { @@ -1029,16 +1030,18 @@ impl Lowering<'_> { match (&self.types[borrowed_type], &self.types[ty]) { // A slice of an array's elements, or a slice's elements lent again. (_, semantic_types::Type::Slice { .. }) => { - let (elements, size, length) = - if let semantic_types::Type::Array { length, .. } = self.types[borrowed_type] { - let (size, _) = layout::layout(self.types, borrowed_type, self.target); - let length = mir::Operand::integer(self.usize, length); - (place, Some(size), length) - } else { - let length = self.second_word(place.clone()); - let length = self.load(self.usize, length, span); - (place.then(mir::Step::Through), None, length) - }; + let (elements, size, length) = if let semantic_types::Type::Array { + length, .. + } = &self.types[borrowed_type] + { + let (size, _) = layout::layout(self.types, borrowed_type, self.target); + let length = mir::Operand::integer(self.usize, length.laid_out_length()); + (place, Some(size), length) + } else { + let length = self.second_word(place.clone()); + let length = self.load(self.usize, length, span); + (place.then(mir::Step::Through), None, length) + }; let address = self.borrow(elements, size, mutable, &mir::SLICE_WORDS, span); self.slice_words(address, length, to, span); } diff --git a/crates/lower/src/lib.rs b/crates/lower/src/lib.rs index 0ba21b4f..c40d1232 100644 --- a/crates/lower/src/lib.rs +++ b/crates/lower/src/lib.rs @@ -592,7 +592,7 @@ impl Lowering<'_> { semantic_types::Type::Array { internals, .. } => { let base = self.types.real(internals.base); let (size, _) = layout::layout(self.types, base, self.target); - for index in 0..internals.count { + for index in 0..internals.laid_out_count() { self.add_holders(base, at + index * size, holders); } } @@ -732,7 +732,9 @@ impl Lowering<'_> { // Its base is no array: a pointer, slice or struct in it // counts the depth. let element = self.debug_type(internals.base, depth); - let lengths = self.types.array_lengths(ty).collect(); + let lengths = (self.types.array_lengths(ty)) + .map(semantic_types::CheckedConstant::laid_out_length) + .collect(); let (size, _) = layout::layout(self.types, ty, self.target); mir::DebugType::Array { element, diff --git a/crates/model/src/layout.rs b/crates/model/src/layout.rs index 92582add..b2735046 100644 --- a/crates/model/src/layout.rs +++ b/crates/model/src/layout.rs @@ -59,7 +59,7 @@ pub fn layout(types: &Types, ty: TypeId, target: &Machine) -> (u64, u64) { } Type::Array { internals, .. } => { let (size, align) = layout(types, internals.base, target); - (size.saturating_mul(internals.count), align) + (size.saturating_mul(internals.laid_out_count()), align) } Type::Invalid | Type::Void diff --git a/crates/model/src/semantic_types.rs b/crates/model/src/semantic_types.rs index 746614df..c05d8aa4 100644 --- a/crates/model/src/semantic_types.rs +++ b/crates/model/src/semantic_types.rs @@ -64,8 +64,18 @@ pub struct StructInternals { pub struct ArrayInternals { /// What the arrays in arrays end in, never an array. pub base: TypeId, - /// How many of `base` there are in all. - pub count: u64, + /// How many of `base` there are in all; none when a length is each + /// copy's (`CheckedConstant::PerCopy`). + count: Option, +} + +impl ArrayInternals { + /// How many of `base` there are in all, in a type that is laid out. + pub fn laid_out_count(self) -> u64 { + // An open type is never laid out: no copy is made from it. + self.count + .expect("only a type whose lengths are all known is laid out") + } } /// A float type: IEEE 754 single or double precision. @@ -153,7 +163,8 @@ pub enum Type { /// another. Array { element: TypeId, - length: u64, + /// A `usize` constant. + length: CheckedConstant, internals: ArrayInternals, }, /// `range[element]`: the integers from a start toward an end, a step @@ -270,14 +281,15 @@ impl Type { } } - /// The element type of an array or a slice, with an array's length; a - /// slice's is known only when the program runs. + /// The element type of an array or a slice, with its length when known + /// now: a slice's is known only when the program runs, and an array's + /// may be each copy's. pub fn elements(&self) -> Option<(TypeId, Option)> { - match *self { + match self { Type::Array { element, length, .. - } => Some((element, Some(length))), - Type::Slice { element, .. } => Some((element, None)), + } => Some((*element, length.known_length())), + Type::Slice { element, .. } => Some((*element, None)), _ => None, } } @@ -443,14 +455,21 @@ impl Types { ) -> String { match argument { ConstArgument::Type(ty) => self.text(*ty, name_of), - ConstArgument::Value(CheckedConstant::Known(Constant { ty, value })) => { - value_text(value, &self[*ty]).to_string() - } - // As `[_]` is written: each copy gives it. - ConstArgument::Value(CheckedConstant::PerCopy(_)) => "_".to_string(), + ConstArgument::Value(value) => self.value_text(value).to_string(), } } + /// `value` as Peeper text: `_` when each copy gives it, as `[_]` is + /// written. + fn value_text<'v>(&'v self, value: &'v CheckedConstant) -> impl Display + 'v { + fmt::from_fn(move |out| match value { + CheckedConstant::Known(Constant { ty, value }) => { + write!(out, "{}", value_text(value, &self[*ty])) + } + CheckedConstant::PerCopy(_) => out.write_str("_"), + }) + } + /// The parameters a reference returned by a function of type `signature` /// may point into. pub fn origins(&self, signature: TypeId) -> &[u32] { @@ -531,7 +550,7 @@ impl Types { pub fn holders_in(&self, id: TypeId) -> usize { match &self[id] { Type::Struct { internals, .. } => internals.holders, - Type::Array { internals, .. } => usize::try_from(internals.count) + Type::Array { internals, .. } => usize::try_from(internals.laid_out_count()) .unwrap_or(usize::MAX) .saturating_mul(self.holders_in(internals.base)), Type::Interface { .. } => 1, @@ -617,12 +636,19 @@ impl Types { pub fn arguments_open(&self, arguments: ConstArguments) -> bool { (self.arguments(arguments).iter()).any(|argument| match argument { ConstArgument::Type(part) => self.is_open(*part), - ConstArgument::Value(CheckedConstant::Known(constant)) => self.is_open(constant.ty), - // No copy holds a value it does not know. - ConstArgument::Value(CheckedConstant::PerCopy(_)) => true, + ConstArgument::Value(value) => self.value_open(value), }) } + /// Whether `value` is open: each copy gives it, as no copy holds a + /// value it does not know, or its type is open. + fn value_open(&self, value: &CheckedConstant) -> bool { + match value { + CheckedConstant::Known(constant) => self.is_open(constant.ty), + CheckedConstant::PerCopy(_) => true, + } + } + /// `ty` with each type parameter of `definition` (`Type::Parameter`) /// replaced by the type `arguments` give in its place: the type of the /// declaration's copy for open `arguments`, which no copy is made for. @@ -814,9 +840,9 @@ impl Types { return false; } let (a, b) = (&self[a], &self[b]); - // All but the parts, and their count, must be the same; a kind left - // out here is compared by its parts alone, which can only miss an - // error a copy then reports, never make one up. + // All but the parts and values, and their count, must be the same; a + // kind left out here is compared by its parts and values alone, which + // can only miss an error a copy then reports, never make one up. let same_rest = Self::same_kind(a, b) && match (a, b) { ( @@ -825,7 +851,6 @@ impl Types { variadic: given, .. }, ) => variadic == given, - (Type::Array { length, .. }, Type::Array { length: given, .. }) => length == given, ( Type::Reference { mutable, .. } | Type::Slice { mutable, .. } @@ -834,49 +859,26 @@ impl Types { | Type::Slice { mutable: given, .. } | Type::InterfaceReference { mutable: given, .. }, ) => mutable == given, - ( - Type::Named { arguments, .. } | Type::Struct { arguments, .. }, - Type::Named { - arguments: given, .. - } - | Type::Struct { - arguments: given, .. - }, - ) => (self - .arguments(*arguments) - .iter() - .zip(self.arguments(*given))) - .all(|pair| match pair { - (ConstArgument::Type(_), ConstArgument::Type(_)) => true, // a part - // One parameter's: of one type, so some copy gives it. - ( - ConstArgument::Value(CheckedConstant::PerCopy(_)), - ConstArgument::Value(_), - ) - | ( - ConstArgument::Value(_), - ConstArgument::Value(CheckedConstant::PerCopy(_)), - ) => true, - (a, b) => a == b, - }), _ => true, }; + // A value each copy gives is of one type, so some copy gives the other. + let values_could_be_same = (self.values(a).zip(self.values(b))).all(|pair| match pair { + (CheckedConstant::PerCopy(_), _) | (_, CheckedConstant::PerCopy(_)) => true, + (a, b) => a == b, + }); same_rest + && values_could_be_same && self.parts(a).count() == self.parts(b).count() && (self.parts(a).zip(self.parts(b))) .all(|(a, b)| source::grow_stack(|| self.could_be_same(a, b))) } /// Whether the type `ty`, about to be added, is open: it is a type - /// parameter or undecided, or a part of it is open. + /// parameter or undecided, or a part or value of it is open. fn holds_open(&self, ty: &Type) -> bool { - match ty { - Type::Parameter { .. } | Type::Undecided => true, - Type::Named { arguments, .. } | Type::Struct { arguments, .. } => { - self.arguments_open(*arguments) - } - _ => self.parts(ty).any(|part| self.is_open(part)), - } + matches!(ty, Type::Parameter { .. } | Type::Undecided) + || self.parts(ty).any(|part| self.is_open(part)) + || self.values(ty).any(|value| self.value_open(value)) } /// Whether `a` and `b` are of one kind, so their parts (`parts`) pair up @@ -939,6 +941,25 @@ impl Types { first.into_iter().chain(rest.iter().copied()).chain(types) } + /// The values the type `ty` is made of, in order: an array's length, a + /// struct's `const` arguments. Each is the same kind of hole wherever it + /// stands (`CheckedConstant::PerCopy`), so what is open and what could + /// be the same reads them alike for every kind. + fn values<'a>(&'a self, ty: &'a Type) -> impl Iterator + 'a { + let (length, arguments): (Option<&CheckedConstant>, &[ConstArgument]) = match ty { + Type::Array { length, .. } => (Some(length), &[]), + Type::Named { arguments, .. } | Type::Struct { arguments, .. } => { + (None, self.arguments(*arguments)) + } + _ => (None, &[]), + }; + let values = arguments.iter().filter_map(|argument| match argument { + ConstArgument::Type(_) => None, + ConstArgument::Value(value) => Some(value), + }); + length.into_iter().chain(values) + } + /// The type `id` stands for: itself, or the type an alias names. pub fn real(&self, id: TypeId) -> TypeId { match self.types[id.0 as usize].ty { @@ -996,12 +1017,8 @@ impl Types { for argument in given { match argument { ConstArgument::Type(ty) => self.hash(*ty, hasher, declaration), - ConstArgument::Value(CheckedConstant::Known(constant)) => { - self.hash(constant.ty, hasher, declaration); - constant.value.hash(hasher); - } - ConstArgument::Value(CheckedConstant::PerCopy(ty)) => { - self.hash(*ty, hasher, declaration); + ConstArgument::Value(value) => { + self.hash_value(value, hasher, declaration); } } } @@ -1016,7 +1033,7 @@ impl Types { // the type after it. self.array_lengths(id).count().hash(hasher); for length in self.array_lengths(id) { - length.hash(hasher); + self.hash_value(length, hasher, declaration); } self.hash(internals.base, hasher, declaration); } @@ -1050,6 +1067,23 @@ impl Types { } } + /// Feeds `value`, a value a type holds (`values`), to `hasher`, as + /// `hash` feeds a type. + fn hash_value( + &self, + value: &CheckedConstant, + hasher: &mut H, + declaration: impl Fn(DefId, &mut H) + Copy, + ) { + match value { + CheckedConstant::Known(constant) => { + self.hash(constant.ty, hasher, declaration); + constant.value.hash(hasher); + } + CheckedConstant::PerCopy(ty) => self.hash(*ty, hasher, declaration), + } + } + /// The type `id` as a program writes it, a declared type or an alias by its name, /// which `name_of` gives for its declaration or type parameter /// (`Naming`): an alias is followed by the @@ -1142,7 +1176,7 @@ impl Types { Type::Undecided => out.push_str("{undecided}"), Type::Array { internals, .. } => { for length in self.array_lengths(id) { - _ = write!(out, "[{length}]"); + _ = write!(out, "[{}]", self.value_text(length)); } self.write_real_text(out, internals.base, name_of); } diff --git a/crates/model/src/semantic_types/arrays.rs b/crates/model/src/semantic_types/arrays.rs index be5ddfa9..9bc2d176 100644 --- a/crates/model/src/semantic_types/arrays.rs +++ b/crates/model/src/semantic_types/arrays.rs @@ -1,18 +1,23 @@ //! `[N]T`: arrays, and the arrays in arrays they can be. use super::ArrayInternals; +use super::CheckedConstant; +use super::Constant; use super::Type; use super::TypeId; use super::Types; +use crate::constant::Value; impl Types { - /// The type `[length]element`. - pub fn array(&mut self, element: TypeId, length: u64) -> TypeId { + /// The type `[length]element`, `length` a `usize` constant + /// (`array_length`), or one each copy gives (`CheckedConstant::PerCopy`). + pub fn array(&mut self, element: TypeId, length: CheckedConstant) -> TypeId { let (base, inner) = match self[element] { Type::Array { internals, .. } => (internals.base, internals.count), - _ => (self.real(element), 1), + _ => (self.real(element), Some(1)), }; - let count = inner.saturating_mul(length); + let count = inner.zip(length.known_length()); + let count = count.map(|(inner, length)| inner.saturating_mul(length)); self.intern(Type::Array { element, length, @@ -20,17 +25,48 @@ impl Types { }) } + /// The array length `length`, a `usize` constant. + pub fn array_length(&self, length: u64) -> CheckedConstant { + let Type::Integer(usize) = self[self.usize] else { + unreachable!("`usize` is an integer type") + }; + CheckedConstant::Known(Constant { + ty: self.usize, + value: Value::Integer(bigint::Limbs::new(usize.bits, &[length])), + }) + } + /// The lengths of the arrays in arrays that `id` is, outermost first; /// none for any other type. - pub fn array_lengths(&self, mut id: TypeId) -> impl Iterator { - std::iter::from_fn(move || match self[id] { + pub fn array_lengths(&self, mut id: TypeId) -> impl Iterator { + std::iter::from_fn(move || match &self[id] { Type::Array { element, length, .. } => { - id = element; + id = *element; Some(length) } _ => None, }) } } + +impl CheckedConstant { + /// Its value as an array length, a `usize`, when known now. + pub(crate) fn known_length(&self) -> Option { + match self { + CheckedConstant::Known(Constant { + value: Value::Integer(length), + .. + }) => Some(length.as_slice()[0]), + _ => None, + } + } + + /// Its value as the length of an array in a type that is laid out. + pub fn laid_out_length(&self) -> u64 { + // An open type is never laid out: no copy is made from it. + self.known_length() + .expect("only a type whose lengths are all known is laid out") + } +} diff --git a/crates/model/src/semantic_types/tests.rs b/crates/model/src/semantic_types/tests.rs index 46a45822..8976689b 100644 --- a/crates/model/src/semantic_types/tests.rs +++ b/crates/model/src/semantic_types/tests.rs @@ -101,7 +101,7 @@ fn conversions() { mutable: false, target: TypeId::I64, }); - let array = types.array(TypeId::I32, 3); + let array = types.array(TypeId::I32, types.array_length(3)); let to_array = types.intern(Type::Reference { mutable: false, target: array, @@ -236,7 +236,7 @@ fn conversions_of_open_types() { }); let reference = |types: &mut Types, mutable, target| types.intern(Type::Reference { mutable, target }); - let pair = types.array(parameter, 2); + let pair = types.array(parameter, types.array_length(2)); let to_pair = reference(&mut types, false, pair); let mutable_parameter = reference(&mut types, true, parameter); let shared_parameter = reference(&mut types, false, parameter); @@ -249,7 +249,7 @@ fn conversions_of_open_types() { }; let parameters = view(&mut types, parameter); let numbers = view(&mut types, TypeId::I32); - let triple = types.array(TypeId::I32, 3); + let triple = types.array(TypeId::I32, types.array_length(3)); let to_triple = reference(&mut types, false, triple); // For every copy. assert_eq!( @@ -277,7 +277,7 @@ fn conversions_of_open_types() { types.conversion(raw_parameter, raw_i32), Conversion::Undecided ); - let bools = types.array(TypeId::BOOL, 2); + let bools = types.array(TypeId::BOOL, types.array_length(2)); assert!(types.could_be_same(pair, bools)); // In none: an array is never a `bool`, and lengths do not change. assert_eq!(types.conversion(pair, TypeId::BOOL), Conversion::Never); @@ -521,13 +521,18 @@ fn equal_types_have_equal_ids() { #[test] fn arrays_in_arrays_keep_their_base_and_count() { let mut types = Types::new(64); - let row = types.array(TypeId::I32, 3); - let grid = types.array(row, 2); + let row = types.array(TypeId::I32, types.array_length(3)); + let grid = types.array(row, types.array_length(2)); let Type::Array { internals, .. } = types[grid] else { panic!("an array"); }; - assert_eq!((internals.base, internals.count), (TypeId::I32, 6)); - assert_eq!(types.array_lengths(grid).collect::>(), [2, 3]); + assert_eq!((internals.base, internals.count), (TypeId::I32, Some(6))); + assert_eq!( + (types.array_lengths(grid)) + .map(CheckedConstant::known_length) + .collect::>(), + [Some(2), Some(3)] + ); assert_eq!(types.array_lengths(TypeId::I32).count(), 0); let row_alias = types.intern(Type::Alias { definition: DefId { @@ -536,20 +541,31 @@ fn arrays_in_arrays_keep_their_base_and_count() { }, real: row, }); - let through_alias = types.array(row_alias, 2); + let through_alias = types.array(row_alias, types.array_length(2)); let Type::Array { internals, .. } = types[through_alias] else { panic!("an array"); }; - assert_eq!((internals.base, internals.count), (TypeId::I32, 6)); + assert_eq!((internals.base, internals.count), (TypeId::I32, Some(6))); let count_of = |types: &Types, ty| match types[ty] { Type::Array { internals, .. } => internals.count, _ => panic!("an array"), }; - let huge = types.array(TypeId::I32, u64::MAX); - let past = types.array(huge, 2); - assert_eq!(count_of(&types, past), u64::MAX); - let empty = types.array(past, 0); - assert_eq!(count_of(&types, empty), 0); + let huge = types.array(TypeId::I32, types.array_length(u64::MAX)); + let past = types.array(huge, types.array_length(2)); + assert_eq!(count_of(&types, past), Some(u64::MAX)); + let empty = types.array(past, types.array_length(0)); + assert_eq!(count_of(&types, empty), Some(0)); + let open = types.array(TypeId::I32, CheckedConstant::PerCopy(types.usize)); + let rows = types.array(open, types.array_length(2)); + assert_eq!(count_of(&types, rows), None); + assert!(types.is_open(rows)); + // A length each copy gives is the same hole as a `const` argument's: + // some copy gives any length, never another element. + let three = types.array(TypeId::I32, types.array_length(3)); + let bools = types.array(TypeId::BOOL, types.array_length(3)); + assert!(types.could_be_same(open, three)); + assert!(!types.could_be_same(open, bools)); + assert_eq!(types.text(open, |_| ""), "[_]i32"); } /// An array holds one set of loan holders per element, however deep, and a @@ -580,27 +596,27 @@ fn arrays_hold_each_elements_holders() { mutable_holder: false, }, }); - let refs = types.array(shared, 3); + let refs = types.array(shared, types.array_length(3)); assert_eq!( (types.holders_in(refs), types.holds_loans(refs)), (3, Some(false)) ); - let row = types.array(mutable, 3); - let grid = types.array(row, 2); + let row = types.array(mutable, types.array_length(3)); + let grid = types.array(row, types.array_length(2)); assert_eq!( (types.holders_in(grid), types.holds_loans(grid)), (6, Some(true)) ); - let pairs = types.array(pair, 2); + let pairs = types.array(pair, types.array_length(2)); assert_eq!( (types.holders_in(pairs), types.holds_loans(pairs)), (4, Some(false)) ); - let numbers = types.array(TypeId::I32, 3); + let numbers = types.array(TypeId::I32, types.array_length(3)); assert_eq!( (types.holders_in(numbers), types.holds_loans(numbers)), (0, None) ); - let huge = types.array(refs, u64::MAX); + let huge = types.array(refs, types.array_length(u64::MAX)); assert_eq!(types.holders_in(huge), usize::MAX); } diff --git a/docs/generics.md b/docs/generics.md index e4f8bbd6..d1bfb123 100644 --- a/docs/generics.md +++ b/docs/generics.md @@ -34,7 +34,7 @@ array or a struct, and what is wrong for it whatever `T` is, is reported: | printing a bare `T`, or a reference to one | the value is left out | | `for` over a bare `T`, or a reference to one | the body is checked as a range's, its value undecided | | a `where` constraint on a bare `T`, a call run at compile time given an open type | not known (`None`) | -| `x...` of a bare `T` in `[_]E{ ... }` or a `...` argument | the array literal is of `Type::Undecided`: its length is each copy's count; a `...` argument still lends it as the parameter's slice; `[N]E{ ... }` keeps its type, and more than `N` values counted now is reported | +| `x...` of a bare `T` in `[_]E{ ... }` or a `...` argument | the array literal's length is each copy's count (`ArrayLength::PerCopy`, written `[_]i32`): its element type is checked once, and its `.len` is undecided; a `...` argument still lends it as the parameter's slice; `[N]E{ ... }` keeps its type, and more than `N` values counted now is reported | | a `const` parameter's value, or a `const` worked out from one (`N * 2`) | `semantic_types::CheckedConstant::PerCopy`: its type is known; read, it is `ExprKind::Undecided` of that type; given to a `const` parameter, `ConstArgument::Value` holds it, which makes the arguments open, so no copy is made | | a field of `Box` | the written field type, re-read with `T` bound (`field_types_given`) | diff --git a/test_programs/generic_functions/negative_generic_functions.peep b/test_programs/generic_functions/negative_generic_functions.peep index 7d2a3773..c4a2be16 100644 --- a/test_programs/generic_functions/negative_generic_functions.peep +++ b/test_programs/generic_functions/negative_generic_functions.peep @@ -146,3 +146,18 @@ fn WrongForEveryCount(const N: i32) { let passed: bool = PASSED; //~ error[T0001]: mismatched types: expected `bool`, found `i32` let returned: bool = Same(N * 2); //~ error[T0001]: mismatched types: expected `bool`, found `i32` } + +// A spread each copy counts gives an array of `i32`s whose length only each +// copy knows: what does not depend on the length is checked once, here. +fn SpreadInto(x: T) -> i32 { + let a = [_]i32{1, x...}; + let first: bool = a[0]; //~ error[T0001]: mismatched types: expected `bool`, found `i32` + let wrong: [3]bool = a; //~ error[T0001]: mismatched types: expected `[3]bool`, found `[_]i32` + for value in a { + let flag: bool = value; //~ error[T0001]: mismatched types: expected `bool`, found `i32` + } + let view: &[]i32 = &a; + let three: [3]i32 = a; + const LENGTH: usize = a.len; + return view[0] + three[0]; +} diff --git a/test_programs/generic_functions/run_generic_spread_arrays.out b/test_programs/generic_functions/run_generic_spread_arrays.out new file mode 100644 index 00000000..dde31684 --- /dev/null +++ b/test_programs/generic_functions/run_generic_spread_arrays.out @@ -0,0 +1,7 @@ +3 +4 +3 +3 +6 +2 +13 diff --git a/test_programs/generic_functions/run_generic_spread_arrays.peep b/test_programs/generic_functions/run_generic_spread_arrays.peep new file mode 100644 index 00000000..9aaf6baa --- /dev/null +++ b/test_programs/generic_functions/run_generic_spread_arrays.peep @@ -0,0 +1,48 @@ +//@ run + +// `[_]i32{1, x...}` where `x` is of a type parameter: how many values the +// spread gives, each copy finds, so the array's length is each copy's +// (`[_]i32`). Its elements are `i32` in every copy, so what does not depend +// on the length is checked once, in the function's own check. + +fn Count(value: U) -> usize { + return 1; +} + +fn Spread(x: T) -> usize { + let a = [_]i32{1, x...}; + // Each copy folds its own length. + const LENGTH: usize = a.len; + // Its elements are `i32`, whatever the length. + let first: i32 = a[0]; + // Spread again, held in arrays, lent as a slice. + let again = [_]i32{a..., 9}; + let grid = [2][3]i32{a, a}; + let view: &[]i32 = &a; + let mut total = 0; + for value in a { + total = total + value; + } + println(LENGTH); + println(again.len); + println(grid[1][2]); + println(view.len); + println(total); + return Count(a) + first as usize; +} + +fn References(rest: T, y: &i32) -> i32 { + let all = [_]&i32{y, rest...}; + let mut sum = 0; + for each in all { + sum = sum + each.*; + } + return sum; +} + +fn main() { + println(Spread([2]i32{2, 3})); + let four = 4; + let five = 5; + println(References([2]&i32{&four, &five}, &four)); +} From ac42d9b892d5b4f1ca8de745125779a4361e3062 Mon Sep 17 00:00:00 2001 From: itsfuad Date: Fri, 20 Nov 2026 20:14:59 +0600 Subject: [PATCH 22/24] Let a const value's type name a type parameter A call finds a type parameter from a `const` argument as from any other, then checks the value against the type the call gives, so `fn Positive(const n: T)` is accepted instead of refused with T0043. A value's type may name only the type parameters before it, as a call gives those first. A value of a type each copy gives, such as `const Y: U = 3` in a generic body, is now known per copy; it crashed layout before. When a call has an error, each place it gives nothing keeps the function's own parameter, so later values' types still line up. Hover shows a copy's const value with the type the copy gives: `i32` for `T`, and `u64` for a `usize`, as its other parameters show. --- crates/check/src/arrays.rs | 25 ++++--- crates/check/src/functions.rs | 17 +++-- crates/check/src/generics.rs | 70 +++++++++++++------ crates/check/src/locals.rs | 27 ++++--- crates/driver/lsp/src/checked.rs | 10 ++- crates/driver/lsp/src/tests.rs | 15 +++- docs/generics.md | 2 +- scripts/cross-concepts.py | 2 +- .../negative_const_parameters.peep | 3 +- .../negative_generic_const_values.peep | 26 +++++++ .../run_generic_const_values.out | 10 +++ .../run_generic_const_values.peep | 54 ++++++++++++++ .../run_i686_generic_const_values.out | 10 +++ .../run_i686_generic_const_values.peep | 55 +++++++++++++++ 14 files changed, 268 insertions(+), 58 deletions(-) create mode 100644 test_programs/generic_functions/negative_generic_const_values.peep create mode 100644 test_programs/generic_functions/run_generic_const_values.out create mode 100644 test_programs/generic_functions/run_generic_const_values.peep create mode 100644 test_programs/generic_functions/run_i686_generic_const_values.out create mode 100644 test_programs/generic_functions/run_i686_generic_const_values.peep diff --git a/crates/check/src/arrays.rs b/crates/check/src/arrays.rs index 8a5287a6..2071ebc7 100644 --- a/crates/check/src/arrays.rs +++ b/crates/check/src/arrays.rs @@ -260,21 +260,24 @@ mod tests { ); } - /// A `const` value's type is read again at each call, which cannot know a - /// type parameter yet, so one naming it through an array is refused. + /// A `const` value's type may name a type parameter through an array: + /// each call gives it the type. Only one before the value, as a call + /// gives those first. #[test] fn const_array_of_a_type_parameter() { - let text = "fn Typed(const T: type, const a: [2]T) {}"; - let ((), reported) = testing::with_functions(text, |checker, functions| { - let (definition, name) = functions[0]; - checker.function_type(definition, name); - }); + let check = |text| { + let ((), reported) = testing::with_functions(text, |checker, functions| { + let (definition, name) = functions[0]; + checker.function_type(definition, name); + }); + reported + }; + assert_eq!(check("fn Typed(const T: type, const a: [2]T) {}"), []); assert_eq!( - reported, + check("fn Typed(const a: [2]T, const T: type) {}"), [( - "T0043", - "`const` values whose type names a type parameter are not supported yet" - .to_string(), + "P0005", + "a `const` value's type names only the type parameters before it".to_string(), "[2]T".to_string() )] ); diff --git a/crates/check/src/functions.rs b/crates/check/src/functions.rs index d18fb188..dcd987a4 100644 --- a/crates/check/src/functions.rs +++ b/crates/check/src/functions.rs @@ -242,6 +242,8 @@ impl Checker<'_> { let tree = &self.module().ast; let mut parameters = Vec::with_capacity(signature.parameters.len()); let mut variadic = false; + // Where the next `const` parameter is among those a copy is made for. + let mut copy_place = signature.type_parameters.len(); for (position, parameter) in tree.children.lists.items(signature.parameters).enumerate() { let parameter = tree.children.params[parameter]; if let Some(default) = parameter.default { @@ -254,6 +256,7 @@ impl Checker<'_> { let message = "a `const` parameter is one value known when compiling, so it takes no `mut` or `...`"; return self.error(diagnostics::INVALID_DECLARATION, message, span); } + copy_place += 1; if let ast::Type::Type = tree.types[parameter.ty] { continue; } @@ -261,11 +264,15 @@ impl Checker<'_> { if ty == semantic_types::TypeId::INVALID { return ty; // reported } - // A value's type is read again at each call (`const_value_type`), - // which cannot know a type parameter yet: only the copy does. - if self.types.is_open(ty) { - return self - .not_supported(span, "`const` values whose type names a type parameter"); + // A call gives the value's type its parameters before the + // value's own (`copy_called`): a type it names comes first. + let checking = (self.internals.declarations_being_checked.last()) + .expect("a declaration is being checked"); + let count = model::program::copy_parameters(tree, signature).count(); + let named = self.types.parameters_named(ty, checking.definition, count); + if named[copy_place - 1..].contains(&true) { + let message = "a `const` value's type names only the type parameters before it"; + return self.error(diagnostics::INVALID_DECLARATION, message, span); } continue; } diff --git a/crates/check/src/generics.rs b/crates/check/src/generics.rs index acc88862..33e913ad 100644 --- a/crates/check/src/generics.rs +++ b/crates/check/src/generics.rs @@ -125,8 +125,9 @@ impl builder::ThirBuilder<'_, '_> { }; return Some((Callee::Function(function), pattern)); } - // Each written parameter's type in the function's own type, which - // leaves out the `const` ones; `None` for those. + // Each written parameter's type in the function's own type, a + // `const` value's too (`const_value_type`); `None` for a type, `const + // T: type`. let semantic_types::Type::Function { parameters: pattern_parameters, .. @@ -134,10 +135,16 @@ impl builder::ThirBuilder<'_, '_> { else { unreachable!("a function's type is a function type") }; - let mut pattern_parameters = pattern_parameters.iter().skip(first).copied(); + let mut pattern_parameters = pattern_parameters.clone().into_iter().skip(first); let parameter_types: Vec> = (written_parameters.iter()) - .map(|(_, parameter)| (!parameter.constant).then(|| pattern_parameters.next())) - .map(Option::flatten) + .map(|&(_, parameter)| match tree.types[parameter.ty] { + _ if !parameter.constant => pattern_parameters.next(), + ast::Type::Type => None, + _ => Some( + self.checker + .const_value_type(definition, parameter.ty, span), + ), + }) .collect(); // Its type parameters, ``, which take no argument of their own: // the types written at the call, or else found from the arguments. @@ -178,7 +185,7 @@ impl builder::ThirBuilder<'_, '_> { // as `check_variadic` checks them; find it from them when a // function needs it. let Some(parameter_type) = parameter_type else { - continue; // `const` + continue; // a type, `const T: type` }; if place >= arguments.len() || matches!(tree.types[parameter.ty], ast::Type::Variadic { .. }) @@ -188,7 +195,11 @@ impl builder::ThirBuilder<'_, '_> { { continue; } - let checked = self.check_expr(arguments[place], None); + let checked = if parameter.constant { + self.check_in_constant(arguments[place], None) + } else { + self.check_expr(arguments[place], None) + }; if checked.ty == semantic_types::TypeId::VOID { let written = self.checker.module().ast.exprs.span(arguments[place]); let message = "this expression has no value to pass"; @@ -214,16 +225,19 @@ impl builder::ThirBuilder<'_, '_> { *named |= found; } } - let mut given = Vec::with_capacity(names.len() + const_parameters.len()); + // What the call gives each parameter, in its place; where it gives + // nothing, after an error, the parameter itself (`own_arguments`), + // so a `const` value's type below still reads each place it names. + let own = self.checker.own_arguments(definition); + let own = self.checker.types.arguments(own).to_vec(); + let mut given = Vec::with_capacity(own.len()); for ((name, found), named) in names.iter().zip(types_found).zip(named) { - match found { - Some(ty) => { - let ty = self.checker.type_argument(ty, span); - failed |= ty == semantic_types::TypeId::INVALID; - given.push(semantic_types::ConstArgument::Type(ty)); - } - None if failed => {} - None => { + if let Some(ty) = found { + let ty = self.checker.type_argument(ty, span); + failed |= ty == semantic_types::TypeId::INVALID; + given.push(semantic_types::ConstArgument::Type(ty)); + } else { + if !failed { let hint = if named { String::new() } else { @@ -236,6 +250,7 @@ impl builder::ThirBuilder<'_, '_> { .error(diagnostics::INVALID_OPERATION, message, span); failed = true; } + given.push(own[given.len()].clone()); } } for (place, parameter) in const_parameters { @@ -248,13 +263,28 @@ impl builder::ThirBuilder<'_, '_> { )); continue; } + // Its type for this call: what the call gives the parameters + // before it, each one it may name (`signature_type`). + let value_type = parameter_types[place].expect("a `const` value has a type"); + let mut before = given.clone(); + before.extend_from_slice(&own[given.len()..]); + let before = self.checker.types.const_arguments(&before); let ty = self .checker - .const_value_type(definition, parameter.ty, span); + .types + .substitute(value_type, definition, before); + let checked = match checked_early.get_mut(place).and_then(Option::take) { + Some(checked) => self.require(checked, argument, ty), + None => self.check_in_constant(argument, Some(ty)), + }; + let written = self.checker.module().ast.exprs.span(argument); + let value = self.known_constant(checked, written); // One each copy gives makes the arguments open: no copy is made. - match self.check_constant_value(argument, Some(ty)) { - Some(constant) => given.push(semantic_types::ConstArgument::Value(constant)), - None => failed = true, // reported + if let Some(constant) = value { + given.push(semantic_types::ConstArgument::Value(constant)); + } else { + failed = true; // reported + given.push(own[given.len()].clone()); } } if failed { diff --git a/crates/check/src/locals.rs b/crates/check/src/locals.rs index d83454ca..a57fa682 100644 --- a/crates/check/src/locals.rs +++ b/crates/check/src/locals.rs @@ -112,26 +112,27 @@ impl builder::ThirBuilder<'_, '_> { .error(diagnostics::INVALID_OPERATION, message, name.span); return None; }; - self.check_constant_value(value, declared) + let checked = self.check_in_constant(value, declared); + let span = self.checker.module().ast.exprs.span(value); + self.known_constant(checked, span) } - /// `value`, of the type `declared` when given, as a value known at - /// compile time: a constant's, or a `const` parameter's argument - /// (`copy_called`). Calls in it run now. `None` after an error, or when - /// it is known only when the program runs, reported. - pub(crate) fn check_constant_value( + /// `value`, of the type `declared` when given, checked as a value known + /// at compile time is, a constant's or a `const` parameter's argument + /// (`copy_called`): calls in it run now. Not yet a constant + /// (`known_constant`). + pub(crate) fn check_in_constant( &mut self, value: Id, declared: Option, - ) -> Option { - let span = self.checker.module().ast.exprs.span(value); + ) -> thir::Expr { let outer = std::mem::replace(&mut self.in_constant, true); let checked = match declared { Some(ty) => self.check_required(value, ty), None => self.check_expr(value, None), }; self.in_constant = outer; - self.known_constant(checked, span) + checked } /// `checked`, worked out with `in_constant`, as a constant; reported at @@ -153,8 +154,12 @@ impl builder::ThirBuilder<'_, '_> { _ => { let file = self.checker.module().ast.file.clone(); let unknown = self.body.first_named_variable(&checked.kind); - // Each copy knows it, unless it reads what only a run knows. - if unknown.is_none() && self.body.holds_undecided(&checked.kind) { + // Each copy knows it, unless it reads what only a run knows: + // one that holds what each copy decides, or is of a type each + // copy gives, as `3` given for a `T`. + let per_copy = self.body.holds_undecided(&checked.kind) + || self.checker.types.is_open(checked.ty); + if unknown.is_none() && per_copy { return Some(semantic_types::CheckedConstant::PerCopy(checked.ty)); } let types = &self.checker.types; diff --git a/crates/driver/lsp/src/checked.rs b/crates/driver/lsp/src/checked.rs index 93fe0cb7..feae3923 100644 --- a/crates/driver/lsp/src/checked.rs +++ b/crates/driver/lsp/src/checked.rs @@ -273,16 +273,14 @@ fn copy_signature( ConstArgument::Type(ty) => { _ = write!(signature, "const {name}: type = {}", text(*ty)); } + // Of the type this copy gives it: `i32`, not the `T` written. ConstArgument::Value(CheckedConstant::Known(constant)) => { - // Its type as written: `usize`, not the integer it is here. - let ty = tree.file.slice(tree.types.span(parameter.ty)); let value = value_text(&constant.value, &types[constant.ty]); - _ = write!(signature, "const {name}: {ty} = {value}"); + _ = write!(signature, "const {name}: {} = {value}", text(constant.ty)); } // As `Types::argument_text` writes it: each copy gives it. - ConstArgument::Value(CheckedConstant::PerCopy(_)) => { - let ty = tree.file.slice(tree.types.span(parameter.ty)); - _ = write!(signature, "const {name}: {ty} = _"); + ConstArgument::Value(CheckedConstant::PerCopy(ty)) => { + _ = write!(signature, "const {name}: {} = _", text(*ty)); } } continue; diff --git a/crates/driver/lsp/src/tests.rs b/crates/driver/lsp/src/tests.rs index 0c2f96a0..81b45d2f 100644 --- a/crates/driver/lsp/src/tests.rs +++ b/crates/driver/lsp/src/tests.rs @@ -888,6 +888,8 @@ where let copied: Item = value; return copied; } +fn Above(const n: T) -> bool { return n > 0; } +fn Calls() -> bool { return Above(5); } "; let main = "import \"app:utils\"; fn main() { @@ -969,10 +971,19 @@ fn main() { assert_eq!( hover(&server, utils, "Pick", 2), shown( - "fn Pick(const N: usize = 0, value: i32) -> i32\n\n// from\nfn Pick(const N: usize, value: i32) -> i32 { /* ... */ }", + "fn Pick(const N: u64 = 0, value: i32) -> i32\n\n// from\nfn Pick(const N: usize, value: i32) -> i32 { /* ... */ }", 4 ) ); + // A value's type is the one the copy gives: `usize` is a `u64` + // here, and the `T` of `Above` an `i32`. + assert_eq!( + hover(&server, utils, "Above", 1), + shown( + "fn Above(const n: i32 = 5) -> bool\n\n// from\nfn Above(const n: T) -> bool { /* ... */ }", + 24 + ) + ); assert_eq!( hover(&server, utils, "Keep", 1), shown( @@ -1014,7 +1025,7 @@ fn main() { let declarations = facts .iter() .filter(|fact| matches!(fact.kind, CachedKind::Declaration { .. })); - assert_eq!(declarations.count(), 9); // `Caller` calls two, `Fits` asks two + assert_eq!(declarations.count(), 10); // `Caller` calls two, `Fits` asks two, `Calls` one } // What a body with no type for its `T` reports is not shown. assert_eq!(server.checked[&folder].results.diagnostics().count(), 0); diff --git a/docs/generics.md b/docs/generics.md index d1bfb123..4378f2b7 100644 --- a/docs/generics.md +++ b/docs/generics.md @@ -35,7 +35,7 @@ array or a struct, and what is wrong for it whatever `T` is, is reported: | `for` over a bare `T`, or a reference to one | the body is checked as a range's, its value undecided | | a `where` constraint on a bare `T`, a call run at compile time given an open type | not known (`None`) | | `x...` of a bare `T` in `[_]E{ ... }` or a `...` argument | the array literal's length is each copy's count (`ArrayLength::PerCopy`, written `[_]i32`): its element type is checked once, and its `.len` is undecided; a `...` argument still lends it as the parameter's slice; `[N]E{ ... }` keeps its type, and more than `N` values counted now is reported | -| a `const` parameter's value, or a `const` worked out from one (`N * 2`) | `semantic_types::CheckedConstant::PerCopy`: its type is known; read, it is `ExprKind::Undecided` of that type; given to a `const` parameter, `ConstArgument::Value` holds it, which makes the arguments open, so no copy is made | +| a `const` parameter's value, or a `const` worked out from one (`N * 2`) | `semantic_types::CheckedConstant::PerCopy`: its type is known; read, it is `ExprKind::Undecided` of that type; given to a `const` parameter, `ConstArgument::Value` holds it, which makes the arguments open, so no copy is made; a value of a type each copy gives, as `3` for a `const n: T`, is one too. A call finds `T` from a `const n: T` argument as from any other, and checks the value as that type | | a field of `Box` | the written field type, re-read with `T` bound (`field_types_given`) | An open struct, such as `Box` inside a generic body, stays diff --git a/scripts/cross-concepts.py b/scripts/cross-concepts.py index 28f2bb2b..77c7d8d7 100755 --- a/scripts/cross-concepts.py +++ b/scripts/cross-concepts.py @@ -45,7 +45,7 @@ r"\bimplementation\(", r"\binterface_method\("], "raw_pointers": [r"Type::RawPointer\b", r"\breached_through_pointer\("], "printing": [r"\bprintable\(", r"\bcheck_print\("], - "constants": [r"\bknown_constant\(", r"\bcheck_constant_value\(", r"\bin_constant\b"], + "constants": [r"\bknown_constant\(", r"\bcheck_in_constant\(", r"\bin_constant\b"], } # The syntax kinds each concept owns. SYNTAX = { diff --git a/test_programs/const_parameters/negative_const_parameters.peep b/test_programs/const_parameters/negative_const_parameters.peep index fc2486d2..48cb0110 100644 --- a/test_programs/const_parameters/negative_const_parameters.peep +++ b/test_programs/const_parameters/negative_const_parameters.peep @@ -14,7 +14,8 @@ fn Nested(kinds: &[2]type) { //~ error[P0011]: `type` is the type of a `const` p } fn Changed(const mut n: i32) {} //~ error[P0005]: a `const` parameter is one value known when compiling, so it takes no `mut` or `...` fn Many(const n: ...i32) {} //~ error[P0005]: a `const` parameter is one value known when compiling, so it takes no `mut` or `...` -fn Typed(const T: type, const value: T) {} //~ error[T0043]: `const` values whose type names a type parameter are not supported yet +// A call gives a value's type the parameters before it. +fn Typed(const value: T, const T: type) {} //~ error[P0005]: a `const` value's type names only the type parameters before it struct Point { x: i32 } fn Scaled(const factor: i64, x: i64) -> i64 { return x * factor; } diff --git a/test_programs/generic_functions/negative_generic_const_values.peep b/test_programs/generic_functions/negative_generic_const_values.peep new file mode 100644 index 00000000..3448a73c --- /dev/null +++ b/test_programs/generic_functions/negative_generic_const_values.peep @@ -0,0 +1,26 @@ +// A `const` value whose type names a type parameter: the value is checked +// as one of the type the call gives it, and must be known when compiling. + +fn Positive(const n: T) -> bool { + return n > 0; +} + +fn Same(const a: T, const b: T) -> T { + return a; +} + +// Each value's type is read with what the call gives the places before +// it, even after one of them has an error. +fn Two(const T: type, const a: T, const U: type, const b: U) -> i32 { + return 1; +} + +fn main() { + let runtime = 3; + Positive::(300); //~ error[L0003]: literal `300` does not fit `u8` + Positive::(1); //~ error[T0001]: mismatched types: expected `bool`, found `i32` + Positive(runtime); //~ error[T0004]: the value of a constant must be known at compile time + Same(1, true); //~ error[T0001]: mismatched types: expected `i32`, found `bool` + Two(i32, true, u8, 300); //~ error[T0001]: mismatched types: expected `i32`, found `bool` + //~ error[L0003]: literal `300` does not fit `u8` +} diff --git a/test_programs/generic_functions/run_generic_const_values.out b/test_programs/generic_functions/run_generic_const_values.out new file mode 100644 index 00000000..965c8b0d --- /dev/null +++ b/test_programs/generic_functions/run_generic_const_values.out @@ -0,0 +1,10 @@ +true +false +true +true +4 +40 +18 +false +true +21 diff --git a/test_programs/generic_functions/run_generic_const_values.peep b/test_programs/generic_functions/run_generic_const_values.peep new file mode 100644 index 00000000..2281109d --- /dev/null +++ b/test_programs/generic_functions/run_generic_const_values.peep @@ -0,0 +1,54 @@ +//@ run + +// A `const` value whose type names a type parameter: `const n: T`. A call +// finds `T` from it as from any argument, or from the arguments before it, +// and checks the value as one of that type; each copy is given the value. + +fn Positive(const n: T) -> bool { + return n > 0; +} + +fn Fill(const value: T) -> [3]T { + return [3]T{value, value, value}; +} + +// The type is a `const` parameter before the value. +fn Scale(const T: type, const factor: T, x: T) -> T { + return factor * x; +} + +// `T` is found from `x` first, so the `3` is a `u8`. +fn Twice(x: T, const k: T) -> T { + return x * k; +} + +// A value each copy gives passed on: the inner call's copy is made in each. +fn Inner(const n: T) -> bool { + return Positive(n); +} + +// The value given for the outer `U`: each copy converts the `3`. +fn Outer(x: U) -> bool { + return Positive::(3); +} + +// A `const` of a type each copy gives, in a generic body. +fn Three(x: U) -> U { + const THREE: U = 3; + return THREE * x; +} + +fn main() { + println(Positive(5)); + println(Positive(-2)); + println(Positive(2.5)); + println(Positive::(7)); + let filled = Fill(4); + println(filled[2]); + println(Scale(i64, 10, 4)); + let small: u8 = 6; + println(Twice(small, 3)); + println(Inner(-1)); + println(Outer(1.5)); + println(Three(7)); +} diff --git a/test_programs/generic_functions/run_i686_generic_const_values.out b/test_programs/generic_functions/run_i686_generic_const_values.out new file mode 100644 index 00000000..965c8b0d --- /dev/null +++ b/test_programs/generic_functions/run_i686_generic_const_values.out @@ -0,0 +1,10 @@ +true +false +true +true +4 +40 +18 +false +true +21 diff --git a/test_programs/generic_functions/run_i686_generic_const_values.peep b/test_programs/generic_functions/run_i686_generic_const_values.peep new file mode 100644 index 00000000..2f2ab682 --- /dev/null +++ b/test_programs/generic_functions/run_i686_generic_const_values.peep @@ -0,0 +1,55 @@ +//@ run +//@ target: i686-linux + +// A `const` value whose type names a type parameter: `const n: T`. A call +// finds `T` from it as from any argument, or from the arguments before it, +// and checks the value as one of that type; each copy is given the value. + +fn Positive(const n: T) -> bool { + return n > 0; +} + +fn Fill(const value: T) -> [3]T { + return [3]T{value, value, value}; +} + +// The type is a `const` parameter before the value. +fn Scale(const T: type, const factor: T, x: T) -> T { + return factor * x; +} + +// `T` is found from `x` first, so the `3` is a `u8`. +fn Twice(x: T, const k: T) -> T { + return x * k; +} + +// A value each copy gives passed on: the inner call's copy is made in each. +fn Inner(const n: T) -> bool { + return Positive(n); +} + +// The value given for the outer `U`: each copy converts the `3`. +fn Outer(x: U) -> bool { + return Positive::(3); +} + +// A `const` of a type each copy gives, in a generic body. +fn Three(x: U) -> U { + const THREE: U = 3; + return THREE * x; +} + +fn main() { + println(Positive(5)); + println(Positive(-2)); + println(Positive(2.5)); + println(Positive::(7)); + let filled = Fill(4); + println(filled[2]); + println(Scale(i64, 10, 4)); + let small: u8 = 6; + println(Twice(small, 3)); + println(Inner(-1)); + println(Outer(1.5)); + println(Three(7)); +} From bd4a449950c0fb827872b5d955e3951581054012 Mon Sep 17 00:00:00 2001 From: itsfuad Date: Fri, 20 Nov 2026 21:24:59 +0600 Subject: [PATCH 23/24] Stop only the copies that grew too deep One copy nesting past COPY_DEPTH_LIMIT set a flag for the whole compile, after which no queued copy was built and no compile-time run went on: an unrelated generic's errors went unreported, and a later constant failed without a message. Each copy now keeps the first copy it grew from, its root, and only copies grown from a root that went too deep are skipped, which still stops a family that doubles at each depth at its first copy too deep. --- crates/check/src/functions/bodies.rs | 2 +- crates/check/src/generics/copies.rs | 31 +++++++++++++------ crates/check/src/lib.rs | 15 ++++++--- .../compile_time/negative_endless_copies.peep | 11 ++++++- 4 files changed, 42 insertions(+), 17 deletions(-) diff --git a/crates/check/src/functions/bodies.rs b/crates/check/src/functions/bodies.rs index ceb71262..34230ae7 100644 --- a/crates/check/src/functions/bodies.rs +++ b/crates/check/src/functions/bodies.rs @@ -112,7 +112,7 @@ impl Checker<'_> { // cycle, not one that only may. let (mut reached, mut pending) = (FxHashSet::default(), vec![function]); while let Some(next) = pending.pop() { - if self.internals.copies_too_deep { + if self.grew_too_deep(next) { return None; // reported } if !reached.insert(next) { diff --git a/crates/check/src/generics/copies.rs b/crates/check/src/generics/copies.rs index e49e03d1..2acdc8ed 100644 --- a/crates/check/src/generics/copies.rs +++ b/crates/check/src/generics/copies.rs @@ -71,13 +71,14 @@ impl Checker<'_> { .last() .expect("a use is being checked") .copy(); - let (depth, reported_in) = match self.internals.copies.get(&made_inside) { - Some(inside) => (inside.depth + 1, inside.reported_in), - None => (1, self.current_module()), + let (depth, root, reported_in) = match self.internals.copies.get(&made_inside) { + Some(inside) => (inside.depth + 1, inside.root, inside.reported_in), + None => (1, copy, self.current_module()), }; if depth > COPY_DEPTH_LIMIT { - // Reported once: the declaration that made the copy has the error. - if std::mem::replace(&mut self.internals.copies_too_deep, true) { + // Reported once for each root: the declaration that made the + // copy has the error. + if !self.internals.roots_too_deep.insert(root) { return semantic_types::TypeId::INVALID; } let name = model::program::declared_path(self.modules, copy.definition); @@ -92,6 +93,7 @@ impl Checker<'_> { Copied { ty: None, depth, + root, reported_in, used_in: self.current_module(), used_at, @@ -154,12 +156,21 @@ impl Checker<'_> { /// A copy of a function whose body the compile has not built /// (`build_function`), the newest first; building one may make more. - /// None once copies nested too deep. + /// One grown from a root whose copies nested too deep is skipped. pub fn next_copy(&mut self) -> Option { - self.internals - .copies_to_build - .pop() - .filter(|_| !self.internals.copies_too_deep) + while let Some(copy) = self.internals.copies_to_build.pop() { + if !self.grew_too_deep(copy) { + return Some(copy); + } + } + None + } + + /// Whether `copy` grew from a root whose copies nested too deep + /// (`COPY_DEPTH_LIMIT`), reported: its body is not built. + pub(crate) fn grew_too_deep(&self, copy: DeclarationCopy) -> bool { + (self.internals.copies.get(©)) + .is_some_and(|copied| self.internals.roots_too_deep.contains(&copied.root)) } /// What the declaration `definition` is checked with outside any copy diff --git a/crates/check/src/lib.rs b/crates/check/src/lib.rs index fd41bf25..9466b6b1 100644 --- a/crates/check/src/lib.rs +++ b/crates/check/src/lib.rs @@ -88,6 +88,7 @@ use model::thir::Fact; use model::thir::FactKind; use model::thir::Symbol; use rustc_hash::FxHashMap; +use rustc_hash::FxHashSet; use scope::Scope; use source::Span; use tree::ast; @@ -135,10 +136,11 @@ struct CheckerInternals { /// The field types of each struct given an open type, which has no copy /// to hold them, read once (`field_types_given`). open_struct_fields: FxHashMap>, - /// Whether copies nested too deep (`COPY_DEPTH_LIMIT`): then no copy's - /// body is built any more, as a function that makes two copies inside - /// each would make twice as many at each depth. - copies_too_deep: bool, + /// The roots (`Copied::root`) whose copies nested too deep + /// (`COPY_DEPTH_LIMIT`): no copy grown from one is built any more, as a + /// function that makes two copies inside each would make twice as many + /// at each depth. Copies grown from other roots still are. + roots_too_deep: FxHashSet, } /// A copy of a declaration with type or `const` parameters @@ -150,6 +152,9 @@ struct Copied { /// The copies it is made inside, each in the one before, counting /// itself: 1 for one a declaration given nothing makes. depth: u32, + /// The copy at depth 1 it grew from: itself, or the root of the one + /// it is made inside. + root: DeclarationCopy, /// The module whose check made it, or the copy it is made inside: what /// the check of a function copy's body finds is reported there. Its own /// check's errors go to the use's module, as the use's. @@ -269,7 +274,7 @@ impl<'p> Checker<'p> { copies: FxHashMap::default(), copies_to_build: Vec::new(), open_struct_fields: FxHashMap::default(), - copies_too_deep: false, + roots_too_deep: FxHashSet::default(), }, } } diff --git a/test_programs/compile_time/negative_endless_copies.peep b/test_programs/compile_time/negative_endless_copies.peep index ae65cc60..8fd2eb2b 100644 --- a/test_programs/compile_time/negative_endless_copies.peep +++ b/test_programs/compile_time/negative_endless_copies.peep @@ -1,10 +1,19 @@ // Each copy of `Grow` makes two copies for new types: without a limit, -// twice as many at each depth, so the first copy too deep stops them all. +// twice as many at each depth, so the first copy too deep stops every copy +// grown from the same first one. fn Grow(const T: type) { Grow(*T); //~ error[T0013]: `Grow` makes a new copy of itself inside each copy, without end: copies nest 64 deep here Grow([1]T); } +// Copies grown from other first ones are still checked, before and after. +fn Wrong(value: T) { + let flag: bool = value; //~ error[T0001]: mismatched types: expected `bool`, found `i32` + //~ error[T0001]: mismatched types: expected `bool`, found `f64` +} + fn main() { + Wrong(1); Grow(i32); + Wrong(2.5); } From 7886f2c1f08f6401ca3e1276adfa71fbb9b83427 Mon Sep 17 00:00:00 2001 From: itsfuad Date: Fri, 20 Nov 2026 21:25:00 +0600 Subject: [PATCH 24/24] Test each operator and spread count in generic copies Each operator on a `T` runs for the copies whose types take it and is refused for each copy whose type does not; a spread into a written array length fills it in the copy that fits and is reported for one too short and one too long. --- .../negative_generic_functions.peep | 35 +++++++++++++++++++ .../run_generic_functions.out | 3 ++ .../run_generic_functions.peep | 11 ++++++ .../run_generic_spread_arrays.out | 1 + .../run_generic_spread_arrays.peep | 7 ++++ .../run_i686_generic_functions.out | 3 ++ .../run_i686_generic_functions.peep | 11 ++++++ 7 files changed, 71 insertions(+) diff --git a/test_programs/generic_functions/negative_generic_functions.peep b/test_programs/generic_functions/negative_generic_functions.peep index c4a2be16..df6de9ab 100644 --- a/test_programs/generic_functions/negative_generic_functions.peep +++ b/test_programs/generic_functions/negative_generic_functions.peep @@ -32,6 +32,34 @@ fn Add(a: T, b: T) -> T { return a + b; //~ error[T0004]: operator `+` cannot be applied to `bool` } +// Each operator, checked for each copy whose type it does not take. +fn Negate(a: T) -> T { + return -a; //~ error[T0004]: operator `-` cannot be applied to `bool` +} + +fn Less(a: T, b: T) -> bool { + return a < b; //~ error[T0004]: operator `<` cannot be applied to `bool` +} + +fn Shift(a: T) -> T { + return a << 1; //~ error[T0004]: operator `<<` cannot be applied to `f64` +} + +fn And(a: T, b: T) -> bool { + return a && b; //~ error[T0004]: operator `&&` cannot be applied to `i32` +} + +fn Not(a: T) -> T { + return !a; //~ error[T0004]: operator `!` cannot be applied to `f64` +} + +// A spread's count, each copy's: too few and too many. +fn Exactly(x: T) -> i32 { + let three = [3]i32{ x... }; //~ error[T0001]: `[3]i32` needs 3 values, found 2 + //~ error[T0001]: `[3]i32` needs 3 values, found 4 + return three[0]; +} + fn Total(values: ...i32) -> i32 { return 0; } @@ -89,6 +117,13 @@ fn main() { Id(); //~ error[T0006]: `Id` takes 1 argument, but 0 were given Id(1, 2); //~ error[T0006]: `Id` takes 1 argument, but 2 were given Add(true, false); + Negate(true); + Less(true, false); + Shift(1.5); + And(1, 2); + Not(2.5); + Exactly([2]i32{ 1, 2 }); + Exactly([4]i32{ 1, 2, 3, 4 }); let wide: f64 = Id(1); //~ error[T0001]: mismatched types: expected `f64`, found `i32` let shape: Shape = Square.{ side = 1 }; Id(Nothing()); //~ error[T0004]: this expression has no value to pass diff --git a/test_programs/generic_functions/run_generic_functions.out b/test_programs/generic_functions/run_generic_functions.out index d4015b72..4f15fbb1 100644 --- a/test_programs/generic_functions/run_generic_functions.out +++ b/test_programs/generic_functions/run_generic_functions.out @@ -12,3 +12,6 @@ other 1 int 7 1 other 4 10 11 +-3 7 12 6 +2 -7 10 -4 +true false true diff --git a/test_programs/generic_functions/run_generic_functions.peep b/test_programs/generic_functions/run_generic_functions.peep index 8445765d..372b789f 100644 --- a/test_programs/generic_functions/run_generic_functions.peep +++ b/test_programs/generic_functions/run_generic_functions.peep @@ -98,6 +98,16 @@ fn Sizes(value: T) -> i64 { return (KNOWN + OWN) as i64 + CAST; } +// Each operator on `T`, for the copies whose types take it. +fn Operators(a: T, b: T) -> bool { + println(-a, a + b, a * b, a << 1); + return a < b; +} + +fn Logic(a: T, b: T) -> T { + return !a && b; +} + fn main() { println(Id(1), Id(2.5), Id(true), Id("text")); let big: i64 = 9; @@ -126,4 +136,5 @@ fn main() { Kind(narrow); Kind(Point.{ x = 1 }); println(Sizes(true), Sizes(1u16)); + println(Operators(3, 4), Operators(-2i64, -5i64), Logic(false, true)); } diff --git a/test_programs/generic_functions/run_generic_spread_arrays.out b/test_programs/generic_functions/run_generic_spread_arrays.out index dde31684..acf445bf 100644 --- a/test_programs/generic_functions/run_generic_spread_arrays.out +++ b/test_programs/generic_functions/run_generic_spread_arrays.out @@ -5,3 +5,4 @@ 6 2 13 +3 diff --git a/test_programs/generic_functions/run_generic_spread_arrays.peep b/test_programs/generic_functions/run_generic_spread_arrays.peep index 9aaf6baa..0a15b6ff 100644 --- a/test_programs/generic_functions/run_generic_spread_arrays.peep +++ b/test_programs/generic_functions/run_generic_spread_arrays.peep @@ -40,9 +40,16 @@ fn References(rest: T, y: &i32) -> i32 { return sum; } +// A written length the spread fills exactly, in the copy whose array fits. +fn Exactly(x: T) -> i32 { + let three = [3]i32{ 1, x... }; + return three[2]; +} + fn main() { println(Spread([2]i32{2, 3})); let four = 4; let five = 5; println(References([2]&i32{&four, &five}, &four)); + println(Exactly([2]i32{ 2, 3 })); } diff --git a/test_programs/generic_functions/run_i686_generic_functions.out b/test_programs/generic_functions/run_i686_generic_functions.out index bf561e8f..6139cc7f 100644 --- a/test_programs/generic_functions/run_i686_generic_functions.out +++ b/test_programs/generic_functions/run_i686_generic_functions.out @@ -11,3 +11,6 @@ int 32 4 other 1 int 7 1 other 4 +-3 7 12 6 +2 -7 10 -4 +true false true diff --git a/test_programs/generic_functions/run_i686_generic_functions.peep b/test_programs/generic_functions/run_i686_generic_functions.peep index 427844b3..dc758f25 100644 --- a/test_programs/generic_functions/run_i686_generic_functions.peep +++ b/test_programs/generic_functions/run_i686_generic_functions.peep @@ -85,6 +85,16 @@ fn Twice(value: T) -> T { // A call on constants runs when compiling. const SEVEN: i32 = Id(7); +// Each operator on `T`, for the copies whose types take it. +fn Operators(a: T, b: T) -> bool { + println(-a, a + b, a * b, a << 1); + return a < b; +} + +fn Logic(a: T, b: T) -> T { + return !a && b; +} + fn main() { println(Id(1), Id(2.5), Id(true), Id("text")); let big: i64 = 9; @@ -112,4 +122,5 @@ fn main() { let narrow: u7 = 1; Kind(narrow); Kind(Point.{ x = 1 }); + println(Operators(3, 4), Operators(-2i64, -5i64), Logic(false, true)); }