diff --git a/.github/workflows/github-release.yml b/.github/workflows/github-release.yml index 623e3613..9f57be65 100644 --- a/.github/workflows/github-release.yml +++ b/.github/workflows/github-release.yml @@ -83,7 +83,7 @@ jobs: mkdir artifacts mv target/release/ezno${{ matrix.executable-extension }} artifacts/ezno-${{ needs.get-build-info.outputs.new-ezno-version }}-${{ matrix.platform_name }}${{ matrix.executable-extension }} - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: name: build-artifacts path: artifacts/* diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7a68abb8..94a16890 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -48,15 +48,16 @@ cargo run -p ezno-parser --example lex path/to/file.ts - Check source is valid with `cargo check --workspace` - Check that code is formatted in accordance with the specification with `cargo fmt --all --check` - Run all tests `cargo test --workspace --verbose` +- Use `cargo clippy -- --allow warnings` to find blocking lints ### The notify! macro The checker crate has the `crate::utils::notify!` macro, which can be used to trace information when the `EZNO_DEBUG` environment variable is set. + ## *Rules* for contributions -- Won't merge PRs that introduce new errors. However will merge PRs which pick up or find existing issues - Code **must** be formatted with `cargo format` inline with the current format configuration -- Use `cargo clippy` as guidance for design but warning lints are not a blocker +- It **must** pass `cargo clippy -- --allow warnings`. In many cases adding `allow` to items is fine ## Oxc diff --git a/README.md b/README.md index 79c3971b..faf74e71 100644 --- a/README.md +++ b/README.md @@ -1,34 +1,30 @@ A JavaScript compiler and TypeScript checker written in Rust with a focus on static analysis and runtime performance. -You can *try* what it current [supports today](./checker/specification/specification.md) with `npx` +> [!IMPORTANT] +> Ezno is in active development and **currently does not support enough features to check existing projects**. Check out the [getting started guide](./checker/docs/getting-started.md) for experimenting with what it current [supports today](./checker/specification/specification.md). -```shell -npx ezno check file.ts -``` - -Or download the binary with `npm install ezno`, `cargo install ezno` or on [GitHub releases](https://github.com/kaleidawave/ezno/releases). [Or try it in Oxc](https://gist.github.com/kaleidawave/5dcb9ec03deef1161ebf0c9d6e4b88d8)! +Read about Ezno +- [Introducing Ezno](https://kaleidawave.github.io/posts/introducing-ezno/) +- [Ezno in '23](https://kaleidawave.github.io/posts/ezno-23/) +- [A preview of the checker](https://kaleidawave.github.io/posts/a-preview-of-the-checker/) -![project lines of code](https://projects.kaleidawave.workers.dev/project/ezno/badge) + What Ezno is - A type checker for JavaScript, usable as a library or with *optional* compiler infrastructure (parser, CLI, LSP, etc) -- Fully typed programs, guaranteeing type safety (as long as definitions are sound) +- Fully typed programs with guaranteed type safety (as long as definitions are sound) - Types aimed at soundness and tracing for better static analysis -- A *imperative* type system, with event tracing and evaluating function side effects. Equivalent to an interpreter, but with types rather than values -- A collection of experiments of types. Some features work well, others are in the prototype stage. Some are specific to JavaScript, others could be applied to other dynamic languages -- A challenge to the status quo of DCE, type checking and compilation through deeper static analysis beyond syntax analysis +- A *imperative* type system that tracks and evaluates the side effects of functions and control flow structures. It is similar to an interpreter, but acts with types instead of *values* +- A collection of experiments of types. Many are being worked out and are in the prototype stage. Some of the new behaviors benefit JavaScript specifically and others could be applied to other languages +- A challenge to the status quo of type checking, optimisations and compilation through deeper static analysis beyond syntax analysis +- [A high level library](https://docs.rs/ezno-checker/latest/ezno_checker/) that allows [type checking to be added to other tools!](https://github.com/web-infra-dev/oxc/tree/main/crates/oxc_type_synthesis) - Written in Rust +- [**Efficient**](https://kaleidawave.github.io/posts/a-preview-of-the-checker/#checking-performance) What Ezno is not -- **eNZo, Z goes before the N** (pronounce as 'Fresno' without the 'fr') 😀 -- 1:1 / parity with TSC, it has different behaviors **but** should work in existing projects using TSC (check out [stc](https://github.com/dudykr/stc) that is aimed at 1:1) -- A binary executable generator. It takes in JavaScript (or TS/Ezno superset) and does similar methods to traditional compilers, but at the end emits JavaScript. However the event intermediate representation could be used in the future to generate a lower level format -- Usable, [still a way to go until it can check actual programs](https://github.com/kaleidawave/ezno/milestone/1). See the [specification](./checker/specification/specification.md) for what is currently implemented in the checker - -Read some more detailed posts -- [Introducing Ezno](https://kaleidawave.github.io/posts/introducing-ezno/) -- [Ezno '23](https://kaleidawave.github.io/posts/ezno-23/) -- [A preview of the checker](https://kaleidawave.github.io/posts/a-preview-of-the-checker/) +- **eNZo, the Z is in front of the N** (pronounce as 'Fresno' without the 'fr') 😀 +- Be on parity with TSC or 1:1, it has some different behaviors **but** should work in existing projects using TSC (check out [stc](https://github.com/dudykr/stc) that is written in Rust and is aimed at replicating TSC) +- A binary executable generator. It takes in JavaScript (or a TypeScript or Ezno superset) and does similar processes to traditional compilers, but at the end emits JavaScript. However in the future it could generate a lower level format using its event representation --- @@ -41,7 +37,7 @@ This project is a workspace consisting of a few crates: -Also checkout [oxc_type_synthesis](https://github.com/web-infra-dev/oxc/tree/main/crates/oxc_type_synthesis), a crate which allows using the type checker through [oxc](https://github.com/web-infra-dev/oxc/tree/main)! +Also checkout [oxc_type_synthesis](https://github.com/web-infra-dev/oxc/tree/main/crates/oxc_type_synthesis), a crate which allows using the type checker inside [oxc](https://github.com/web-infra-dev/oxc/tree/main)! ## Help contribute diff --git a/checker/docs/getting-started.md b/checker/docs/getting-started.md new file mode 100644 index 00000000..75a6c2f0 --- /dev/null +++ b/checker/docs/getting-started.md @@ -0,0 +1,18 @@ +Ezno is work in progress. It doesn't currently support all the features of JavaScript and TypeScript **but** it has a fairly large [specification of features that it supports today](../specification/specification.md). While it isn't worth it trying it on existing codebases ATM as it likely will blow up. You can try out the snippets in the specification and other small pieces of code today. + +You can try the `check` command of ezno using `npx` + +```shell +npx ezno check file.ts +``` + +Or download the binary with `npm install ezno`, `cargo install ezno` or on [GitHub releases](https://github.com/kaleidawave/ezno/releases). + +You can use the `print_type` function to see the type of expressions. + +```tsx +const x = 6; +print_type(x + 8) +``` + +If you find any unexpected exceptions, please leave an issue 😁 diff --git a/checker/specification/specification.md b/checker/specification/specification.md index bbefa9e1..4d9c6fb6 100644 --- a/checker/specification/specification.md +++ b/checker/specification/specification.md @@ -1,6 +1,6 @@ ## Specification -See [./README.md](README.md) for details +See [./README.md](README.md) for details about how `specification.md` works ### Variables diff --git a/checker/src/behavior/assignments.rs b/checker/src/behavior/assignments.rs index aa8e8fce..4080056d 100644 --- a/checker/src/behavior/assignments.rs +++ b/checker/src/behavior/assignments.rs @@ -1,8 +1,6 @@ -use source_map::{Span, SpanWithSource}; +use source_map::SpanWithSource; -use crate::{ - context::facts::Publicity, types::properties::PropertyKey, CheckingData, Environment, TypeId, -}; +use crate::{context::facts::Publicity, types::properties::PropertyKey, TypeId}; use super::operations::{Logical, MathematicalAndBitwise}; diff --git a/checker/src/behavior/constant_functions.rs b/checker/src/behavior/constant_functions.rs index dda6ea6b..de6222da 100644 --- a/checker/src/behavior/constant_functions.rs +++ b/checker/src/behavior/constant_functions.rs @@ -1,13 +1,10 @@ -use source_map::{Span, SpanWithSource}; +use source_map::SpanWithSource; use crate::{ context::get_on_ctx, subtyping::check_satisfies, - types::{ - functions::SynthesisedArgument, poly_types::generic_type_arguments::TypeArgumentStore, - printing::debug_effects, - }, - types::{poly_types::FunctionTypeArguments, printing::print_type, Type, TypeStore}, + types::{functions::SynthesisedArgument, printing::debug_effects}, + types::{printing::print_type, Type, TypeStore}, Constant, Environment, TypeId, }; @@ -181,7 +178,7 @@ pub(crate) fn call_constant_function( } "set_prototype" => { if let [first, second] = arguments { - let prototype = environment + let _prototype = environment .facts .prototypes .insert(first.to_type().unwrap(), second.to_type().unwrap()); diff --git a/checker/src/behavior/functions.rs b/checker/src/behavior/functions.rs index 2698cf48..9d74708a 100644 --- a/checker/src/behavior/functions.rs +++ b/checker/src/behavior/functions.rs @@ -4,16 +4,14 @@ use std::{ mem, }; -use source_map::{SourceId, Span, SpanWithSource}; +use source_map::{SourceId, SpanWithSource}; -use super::variables::VariableMutability; use crate::{ context::{ - environment::FunctionScope, - facts::{Facts, Publicity}, - get_value_of_variable, CanReferenceThis, Context, ContextType, Syntax, + environment::FunctionScope, facts::Facts, get_value_of_variable, CanReferenceThis, + ContextType, Syntax, }, - events::{Event, RootReference}, + events::RootReference, types::{ self, classes::ClassValue, @@ -22,8 +20,7 @@ use crate::{ properties::{PropertyKey, PropertyValue}, Constructor, FunctionType, PolyNature, TypeStore, }, - ASTImplementation, CheckingData, Environment, FunctionId, ReadFromFS, Scope, Type, TypeId, - VariableId, + CheckingData, Environment, FunctionId, ReadFromFS, Scope, Type, TypeId, VariableId, }; #[derive(Clone, Copy, Debug, Default, binary_serialize_derive::BinarySerializable)] @@ -307,10 +304,10 @@ where A: crate::ASTImplementation, F: SynthesisableFunction, { - let is_async = behavior.is_async(); - let is_generator = behavior.is_generator(); + let _is_async = behavior.is_async(); + let _is_generator = behavior.is_generator(); - let (mut behavior, scope, constructor, location, expected_parameters, expected_return) = + let (mut behavior, scope, constructor, location, expected_parameters, _expected_return) = match behavior { FunctionRegisterBehavior::Constructor { super_type, prototype, properties } => ( FunctionBehavior::Constructor { @@ -350,7 +347,7 @@ where ) } FunctionRegisterBehavior::ExpressionFunction { - expecting, + expecting: _, is_async, is_generator, location, @@ -373,7 +370,7 @@ where None, ), FunctionRegisterBehavior::StatementFunction { - hoisted, + hoisted: _, is_async, is_generator, location, @@ -394,23 +391,8 @@ where None, None, ), - FunctionRegisterBehavior::ObjectMethod { is_async, is_generator } => ( - FunctionBehavior::Method { - is_async, - is_generator, - free_this_id: TypeId::ERROR_TYPE, - }, - FunctionScope::MethodFunction { - free_this_type: TypeId::ERROR_TYPE, - is_async, - is_generator, - }, - None, - None, - None, - None, - ), - FunctionRegisterBehavior::ClassMethod { is_async, is_generator, super_type } => ( + FunctionRegisterBehavior::ClassMethod { is_async, is_generator, super_type: _ } + | FunctionRegisterBehavior::ObjectMethod { is_async, is_generator } => ( FunctionBehavior::Method { is_async, is_generator, @@ -510,7 +492,11 @@ where // TODO what is the union, shouldn't it be the this_constraint? *this_type = new_conditional_type; } - FunctionScope::Constructor { extends, type_of_super, ref mut this_object_type } => { + FunctionScope::Constructor { + extends: _, + type_of_super: _, + ref mut this_object_type, + } => { crate::utils::notify!("Setting 'this' type here"); if let Some((prototype, properties)) = constructor { let new_this_object_type = types::create_this_before_function_synthesis( @@ -558,7 +544,7 @@ where let returned = if function.has_body() { function.body(&mut function_environment, checking_data); // Temporary move events to satisfy borrow checker - let mut events = mem::take(&mut function_environment.facts.events); + let events = mem::take(&mut function_environment.facts.events); let returned = crate::events::helpers::get_return_from_events( &mut events.iter(), @@ -612,18 +598,18 @@ where context.variable_names.extend(function_environment.variable_names); // TODO temp ... - for (on, mut properties) in facts.current_properties { + for (on, properties) in facts.current_properties { match context.facts.current_properties.entry(on) { - Entry::Occupied(mut occupied) => {} + Entry::Occupied(_occupied) => {} Entry::Vacant(vacant) => { vacant.insert(properties); } } } - for (on, mut properties) in facts.closure_current_values { + for (on, properties) in facts.closure_current_values { match context.facts.closure_current_values.entry(on) { - Entry::Occupied(mut occupied) => {} + Entry::Occupied(_occupied) => {} Entry::Vacant(vacant) => { vacant.insert(properties); } diff --git a/checker/src/behavior/iteration.rs b/checker/src/behavior/iteration.rs index a39c1db7..511d6f68 100644 --- a/checker/src/behavior/iteration.rs +++ b/checker/src/behavior/iteration.rs @@ -1,21 +1,16 @@ -use std::collections::{HashMap, HashSet}; - -use source_map::{BaseSpan, SpanWithSource}; +use std::collections::HashMap; use crate::{ - behavior::{operations::CanonicalEqualityAndInequality, variables::VariableOrImport}, + behavior::operations::CanonicalEqualityAndInequality, context::{calling::Target, environment::Label, get_value_of_variable, CallCheckingBehavior}, events::{ application::ErrorsAndInfo, apply_event, Event, EventResult, InitialVariables, RootReference, }, types::{ - poly_types::{ - generic_type_arguments::{StructureGenericArguments, TypeArgumentStore}, - FunctionTypeArguments, - }, + poly_types::{generic_type_arguments::TypeArgumentStore, FunctionTypeArguments}, printing::print_type, - substitute, Constructor, ObjectNature, PolyNature, TypeArguments, TypeStore, + substitute, Constructor, ObjectNature, PolyNature, TypeStore, }, CheckingData, Constant, Environment, Facts, Scope, Type, TypeId, VariableId, }; @@ -75,14 +70,12 @@ pub fn synthesise_iteration( }, ); - let ( - Facts { variable_current_value, current_properties, mut events, .. }, - _closes_over, - ) = result.unwrap(); + let (Facts { variable_current_value, current_properties, events, .. }, _closes_over) = + result.unwrap(); let loop_facts = Values { variable_values: variable_current_value, - properties_values: current_properties, + _properties_values: current_properties, }; let fixed_iterations = calculate_result_of_loop( @@ -137,14 +130,12 @@ pub fn synthesise_iteration( }, ); - let ( - Facts { variable_current_value, current_properties, mut events, .. }, - _closes_over, - ) = result.unwrap(); + let (Facts { variable_current_value, current_properties, events, .. }, _closes_over) = + result.unwrap(); let loop_facts = Values { variable_values: variable_current_value, - properties_values: current_properties, + _properties_values: current_properties, }; let fixed_iterations = calculate_result_of_loop( @@ -264,14 +255,12 @@ pub fn synthesise_iteration( }, ); - let ( - Facts { variable_current_value, current_properties, mut events, .. }, - _closes_over, - ) = result.unwrap(); + let (Facts { variable_current_value, current_properties, events, .. }, _closes_over) = + result.unwrap(); let loop_facts = Values { variable_values: variable_current_value, - properties_values: current_properties, + _properties_values: current_properties, }; let fixed_iterations = calculate_result_of_loop( @@ -300,7 +289,7 @@ pub fn synthesise_iteration( todo!() } } - IterationBehavior::ForIn { lhs, rhs } => { + IterationBehavior::ForIn { lhs: _, rhs } => { // TODO for of Object.keys ??? let on = A::synthesise_multiple_expression( rhs, @@ -333,7 +322,7 @@ pub fn synthesise_iteration( todo!() } } - IterationBehavior::ForOf { lhs, rhs } => todo!(), + IterationBehavior::ForOf { lhs: _, rhs: _ } => todo!(), } } @@ -436,7 +425,7 @@ pub(crate) fn run_iteration_block( if let Event::ReadsReference { reference: RootReference::Variable(variable_id), reflects_dependency: Some(free_variable_id), - position, + position: _, } = event { let value_before_iterations = get_value_of_variable( @@ -493,7 +482,7 @@ pub(crate) fn run_iteration_block( } IterationKind::Properties(on) => { if let Type::Object(ObjectNature::RealDeal) = types.get_type_by_id(on) { - for (publicity, property, _value) in environment.get_properties_on_type(on) { + for (_publicity, property, _value) in environment.get_properties_on_type(on) { // TODO enumerable crate::utils::notify!("Property: {:?}", property); } @@ -566,7 +555,7 @@ fn evaluate_iterations( /// TODO Cow struct Values { pub variable_values: HashMap, - pub properties_values: HashMap< + pub _properties_values: HashMap< TypeId, Vec<( crate::context::facts::Publicity, @@ -653,7 +642,7 @@ fn calculate_result_of_loop( // TODO what about properties etc if let Type::RootPolyType(PolyNature::FreeVariable { reference: less_than_reference, - based_on, + based_on: _, }) = reference_ty { if let RootReference::Variable(possible_changing_variable_id) = less_than_reference { @@ -661,10 +650,10 @@ fn calculate_result_of_loop( // TODO temp let roof: TypeId = if let Type::RootPolyType(PolyNature::FreeVariable { reference: RootReference::Variable(roof_id), - based_on, + based_on: _, }) = roof_ty { - let changed = if let Some((_start, end)) = + let changed = if let Some((_start, _end)) = loop_variables.as_ref().and_then(|vs| vs.get(roof_id).copied()) { crate::utils::notify!("Found loop variables"); @@ -717,7 +706,7 @@ fn calculate_result_of_loop( // Looking at incrementor if let Type::Constructor(Constructor::BinaryOperator { lhs: assignment, - operator, + operator: _, rhs: increments_by, }) = value_after_running_expressions_in_loop { diff --git a/checker/src/behavior/modules.rs b/checker/src/behavior/modules.rs index 5335481e..26f280b9 100644 --- a/checker/src/behavior/modules.rs +++ b/checker/src/behavior/modules.rs @@ -1,10 +1,7 @@ use super::variables::VariableMutability; -use crate::{ - behavior::variables::VariableOrImport, context::facts::Facts, Diagnostic, TypeId, VariableId, -}; -use derive_enum_from_into::EnumFrom; +use crate::{context::facts::Facts, TypeId, VariableId}; + use source_map::Span; -use std::{collections::HashMap, default, path::PathBuf}; #[derive(Debug)] pub struct NamePair<'a> { diff --git a/checker/src/behavior/operations.rs b/checker/src/behavior/operations.rs index 87a0a14f..4b24df19 100644 --- a/checker/src/behavior/operations.rs +++ b/checker/src/behavior/operations.rs @@ -1,7 +1,5 @@ -use std::marker::PhantomData; - use derive_enum_from_into::EnumFrom; -use source_map::{Span, SpanWithSource}; +use source_map::SpanWithSource; use crate::{ diagnostics::{TypeCheckError, TypeStringRepresentation}, @@ -9,7 +7,7 @@ use crate::{ cast_as_number, cast_as_string, is_type_truthy_falsy, new_logical_or_type, Constructor, StructureGenerics, TypeStore, }, - ASTImplementation, CheckingData, Constant, Decidable, Environment, Type, TypeId, + CheckingData, Constant, Decidable, Environment, Type, TypeId, }; #[derive(Clone, Copy, Debug, binary_serialize_derive::BinarySerializable)] @@ -57,7 +55,7 @@ pub fn evaluate_pure_binary_operation_handle_errors< ); match result { Ok(result) => result, - Err(err) => { + Err(_err) => { let ctx = &environment.as_general_context(); checking_data.diagnostics_container.add_error( TypeCheckError::InvalidMathematicalOrBitwiseOperation { @@ -386,41 +384,6 @@ pub fn evaluate_logical_operation_with_expression< checking_data: &mut CheckingData, environment: &mut Environment, ) -> Result { - enum TypeOrSynthesisable<'a, A: crate::ASTImplementation> { - Type(TypeId), - Expression(&'a A::Expression<'a>), - } - - // impl<'a, A: crate::ASTImplementation> SynthesisableConditional for TypeOrSynthesisable<'a, M> { - // type ExpressionResult = TypeId; - - // fn synthesise_condition( - // self, - // environment: &mut Environment, - // checking_data: &mut CheckingData, - // ) -> Self::ExpressionResult { - // match self { - // TypeOrSynthesisable::Type(ty) => ty, - // TypeOrSynthesisable::Expression(expr, _) => { - // A::synthesise_expression(expr, TypeId::ANY_TYPE, environment, checking_data) - // } - // } - // } - - // fn conditional_expression_result( - // condition: TypeId, - // truthy_result: Self::ExpressionResult, - // falsy_result: Self::ExpressionResult, - // types: &mut TypeStore, - // ) -> Self::ExpressionResult { - // types.new_conditional_type(condition, truthy_result, falsy_result) - // } - - // fn default_result() -> Self::ExpressionResult { - // unreachable!() - // } - // } - match operator { Logical::And => Ok(environment.new_conditional_context( lhs, diff --git a/checker/src/behavior/template_literal.rs b/checker/src/behavior/template_literal.rs index 455d1828..293d0f07 100644 --- a/checker/src/behavior/template_literal.rs +++ b/checker/src/behavior/template_literal.rs @@ -1,11 +1,9 @@ -use std::marker::PhantomData; - use source_map::{Span, SpanWithSource}; use crate::{ behavior::objects::ObjectBuilder, types::{calling::CallingInput, cast_as_string, SynthesisedArgument}, - CheckingData, Constant, Environment, Instance, Type, TypeId, + CheckingData, Constant, Environment, Type, TypeId, }; #[derive(Copy, Clone)] diff --git a/checker/src/behavior/variables.rs b/checker/src/behavior/variables.rs index 395f452f..bc8063c4 100644 --- a/checker/src/behavior/variables.rs +++ b/checker/src/behavior/variables.rs @@ -1,4 +1,4 @@ -use source_map::{Span, SpanWithSource}; +use source_map::SpanWithSource; use crate::context::{environment::ContextLocation, AssignmentError}; use crate::{types::TypeId, CheckingData, VariableId}; @@ -43,11 +43,10 @@ impl VariableOrImport { pub(crate) fn get_mutability(&self) -> VariableMutability { match self { - VariableOrImport::Variable { mutability, declared_at, .. } => *mutability, - VariableOrImport::MutableImport { of, constant, import_specified_at } => { - VariableMutability::Constant - } - VariableOrImport::ConstantImport { to, import_specified_at } => { + VariableOrImport::Variable { mutability, .. } => *mutability, + // TODO I think ? + VariableOrImport::MutableImport { of: _, constant: _, import_specified_at: _ } + | VariableOrImport::ConstantImport { to: _, import_specified_at: _ } => { VariableMutability::Constant } } @@ -93,7 +92,7 @@ pub fn check_variable_initialization, pub(crate) mutable_bases: HashMap, } impl Bases { - pub(crate) fn does_type_have_mutable_base(&self, on: TypeId) -> bool { + pub(crate) fn _does_type_have_mutable_base(&self, _on: TypeId) -> bool { todo!() } - pub(crate) fn merge(&mut self, mut bases: Bases, context_id: ContextId) { + pub(crate) fn merge(&mut self, bases: Bases, context_id: ContextId) { self.immutable_bases.extend(bases.immutable_bases); for (ty, (ctx_ceil, base)) in bases.mutable_bases { let existing = if ctx_ceil.0 == context_id { @@ -35,7 +35,8 @@ impl Bases { } /// INTERFACE extends HAPPEN AFTER THE TYPE HAS BEEN CRATED - pub(crate) fn connect_extends(&mut self, on: TypeId, ty: TypeId) { + #[allow(unused)] + pub fn connect_extends(&mut self, on: TypeId, ty: TypeId) { let res = self.immutable_bases.insert(on, ty); debug_assert!(res.is_none()); } diff --git a/checker/src/context/calling.rs b/checker/src/context/calling.rs index 4b53ccd3..116ac5de 100644 --- a/checker/src/context/calling.rs +++ b/checker/src/context/calling.rs @@ -26,7 +26,7 @@ impl CallCheckingBehavior for CheckThings { &mut environment.facts } - fn in_recursive_cycle(&self, function_id: FunctionId) -> bool { + fn in_recursive_cycle(&self, _function_id: FunctionId) -> bool { // cannot get in a loop from checking false } diff --git a/checker/src/context/environment.rs b/checker/src/context/environment.rs index d3dfd951..3eba3e59 100644 --- a/checker/src/context/environment.rs +++ b/checker/src/context/environment.rs @@ -1,13 +1,11 @@ use source_map::{SourceId, Span, SpanWithSource}; -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use crate::{ behavior::{ - self, assignments::{Assignable, AssignmentKind, Reference}, functions, modules::{Exported, ImportKind, NamePair}, - objects::ObjectBuilder, operations::{ evaluate_logical_operation_with_expression, evaluate_pure_binary_operation_handle_errors, MathematicalAndBitwise, @@ -23,15 +21,13 @@ use crate::{ subtyping::{type_is_subtype, SubTypeResult}, PolyNature, Type, TypeStore, }, - ASTImplementation, CheckingData, Decidable, Instance, RootContext, TypeCombinable, TypeId, - VariableId, + CheckingData, Decidable, Instance, RootContext, TypeCombinable, TypeId, }; use super::{ - calling::CheckThings, - facts::{Facts, Publicity}, - get_on_ctx, get_value_of_variable, AssignmentError, ClosedOverReferencesInScope, Context, - ContextType, Environment, GeneralContext, SetPropertyError, + calling::CheckThings, facts::Publicity, get_on_ctx, get_value_of_variable, AssignmentError, + ClosedOverReferencesInScope, Context, ContextType, Environment, GeneralContext, + SetPropertyError, }; pub type ContextLocation = Option; @@ -450,7 +446,7 @@ impl<'a> Environment<'a> { if let Some((_, _, variable)) = variable_in_map { match variable { - VariableOrImport::Variable { mutability, declared_at, context } => { + VariableOrImport::Variable { mutability, declared_at, context: _ } => { match mutability { VariableMutability::Constant => { Err(AssignmentError::Constant(*declared_at)) @@ -472,7 +468,7 @@ impl<'a> Environment<'a> { store, ); - if let SubTypeResult::IsNotSubType(mismatches) = result { + if let SubTypeResult::IsNotSubType(_mismatches) = result { return Err(AssignmentError::DoesNotMeetConstraint { variable_type: TypeStringRepresentation::from_type_id( reassignment_constraint, @@ -527,10 +523,15 @@ impl<'a> Environment<'a> { } } - pub(crate) fn get_environment_type(&self) -> &Scope { + #[must_use] + pub fn get_environment_type(&self) -> &Scope { &self.context_type.scope } + pub fn get_environment_type_mut(&mut self) -> &mut Scope { + &mut self.context_type.scope + } + /// TODO decidable & private? #[must_use] pub fn property_in(&self, on: TypeId, property: &PropertyKey) -> bool { @@ -571,10 +572,6 @@ impl<'a> Environment<'a> { existing } - pub(crate) fn get_environment_type_mut(&mut self) -> &mut Scope { - &mut self.context_type.scope - } - pub(crate) fn get_parent(&self) -> GeneralContext { match self.context_type.parent { GeneralContext::Syntax(syn) => GeneralContext::Syntax(syn), @@ -697,7 +694,7 @@ impl<'a> Environment<'a> { // let treat_as_in_same_scope = (og_var.is_constant && self.is_immutable(current_value)); // TODO in_root temp fix - if let (Some(boundary), false) = (crossed_boundary, in_root) { + if let (Some(_boundary), false) = (crossed_boundary, in_root) { let based_on = match og_var.get_mutability() { VariableMutability::Constant => { let constraint = checking_data @@ -772,7 +769,7 @@ impl<'a> Environment<'a> { if let Event::ReadsReference { reference: other_reference, reflects_dependency: Some(dep), - position, + position: _, } = event { if reference == *other_reference { @@ -811,7 +808,7 @@ impl<'a> Environment<'a> { Ok(VariableWithValue(og_var.clone(), type_id)) } else { // TODO recursively in - if let VariableOrImport::MutableImport { of, constant: false, import_specified_at } = + if let VariableOrImport::MutableImport { of, constant: false, import_specified_at: _ } = og_var.clone() { let current_value = get_value_of_variable( @@ -1014,7 +1011,7 @@ impl<'a> Environment<'a> { falling_through_structures += 1; } } - Scope::Conditional { is_switch: Some(label @ Some(_)), .. } + Scope::Conditional { is_switch: Some(_label @ Some(_)), .. } if !is_continue && looking_for_label.is_some() => { todo!("switch break") @@ -1070,7 +1067,7 @@ impl<'a> Environment<'a> { }; self.facts.variable_current_value.insert(id, *item); let existing = self.variables.insert(default_name.to_owned(), v); - if let Some(existing) = existing { + if let Some(_existing) = existing { todo!("diagnostic") } } else { @@ -1111,9 +1108,9 @@ impl<'a> Environment<'a> { self.facts.variable_current_value.insert(k, v); true } - VariableMutability::Mutable { reassignment_constraint } => { - false - } + VariableMutability::Mutable { + reassignment_constraint: _, + } => false, }; let v = VariableOrImport::MutableImport { @@ -1124,7 +1121,7 @@ impl<'a> Environment<'a> { .with_source(self.get_source()), }; let existing = self.variables.insert(part.r#as.to_owned(), v); - if let Some(existing) = existing { + if let Some(_existing) = existing { todo!("diagnostic") } if also_export { diff --git a/checker/src/context/facts.rs b/checker/src/context/facts.rs index f402b889..f87f6971 100644 --- a/checker/src/context/facts.rs +++ b/checker/src/context/facts.rs @@ -1,4 +1,4 @@ -use std::{borrow::Cow, collections::HashMap}; +use std::collections::HashMap; use source_map::SpanWithSource; diff --git a/checker/src/context/mod.rs b/checker/src/context/mod.rs index d7f675a0..b40a4913 100644 --- a/checker/src/context/mod.rs +++ b/checker/src/context/mod.rs @@ -18,24 +18,21 @@ use source_map::{Span, SpanWithSource}; use crate::{ behavior::{ - self, - functions::{ClosureChain, ClosureId, FunctionBehavior, FunctionRegisterBehavior}, + functions::ClosureChain, modules::Exported, - operations::MathematicalAndBitwise, variables::{VariableMutability, VariableOrImport}, }, diagnostics::{ CannotRedeclareVariable, TypeCheckError, TypeCheckWarning, TypeStringRepresentation, }, - events::{Event, RootReference}, - subtyping::{type_is_subtype, BasicEquality}, + events::RootReference, types::{ - self, create_this_before_function_synthesis, get_constraint, - poly_types::{generic_type_arguments::StructureGenericArguments, FunctionTypeArguments}, + get_constraint, + poly_types::generic_type_arguments::StructureGenericArguments, properties::{PropertyKey, PropertyValue}, - Constructor, FunctionType, PolyNature, Type, TypeId, TypeStore, + FunctionType, PolyNature, Type, TypeId, TypeStore, }, - ASTImplementation, CheckingData, Constant, FunctionId, ReadFromFS, VariableId, + CheckingData, FunctionId, VariableId, }; use self::{ @@ -44,9 +41,8 @@ use self::{ }; pub use environment::Scope; pub(crate) use environment::Syntax; -use map_vec::Map; + use std::{ - borrow::Cow, collections::{ hash_map::{self, Entry}, HashMap, HashSet, @@ -362,8 +358,8 @@ impl Context { let variable = VariableOrImport::Variable { mutability, declared_at, context: None }; let entry = self.variables.entry(name.to_owned()); - if let Entry::Vacant(empty) = entry { - let existing_variable = self.variables.insert(name.to_owned(), variable); + if let Entry::Vacant(_empty) = entry { + let _existing_variable = self.variables.insert(name.to_owned(), variable); let parameter_ty = if let Some(annotation) = annotation { if let Type::RootPolyType(_) = types.get_type_by_id(annotation) { // TODO this can only be used once, two parameters cannot have same type as the can @@ -498,7 +494,7 @@ impl Context { } /// Only on current environment, doesn't walk - fn get_this_constraint(&self) -> Option { + fn _get_this_constraint(&self) -> Option { match self.as_general_context() { GeneralContext::Syntax(syn) => match &syn.context_type.scope { // Special handling here @@ -518,7 +514,7 @@ impl Context { | Scope::DefinitionModule { .. } | Scope::Module { .. } => None, }, - GeneralContext::Root(root) => None, + GeneralContext::Root(_root) => None, } } @@ -577,7 +573,7 @@ impl Context { let reversed_flattened_properties = self .parents_iter() .filter_map(|ctx| { - let id = get_on_ctx!(ctx.context_id); + let _id = get_on_ctx!(ctx.context_id); let properties = get_on_ctx!(ctx.facts.current_properties.get(&base)); properties.map(|v| v.iter().rev()) }) @@ -608,7 +604,7 @@ impl Context { ) -> Option> { fn get_property( env: &GeneralContext, - types: &TypeStore, + _types: &TypeStore, on: TypeId, under: (Publicity, &PropertyKey), ) -> Option { @@ -656,7 +652,7 @@ impl Context { // TODO need actual method for these, aka lowest - if let Type::SpecialObject(obj) = types.get_type_by_id(on) { + if let Type::SpecialObject(_obj) = types.get_type_by_id(on) { todo!() } else { let under = match under { @@ -690,7 +686,7 @@ impl Context { // TODO temp declaration // TODO should check the TypeId::is_primitive... via aliases + open_poly - pub(crate) fn is_immutable(&self, value: TypeId) -> bool { + pub(crate) fn _is_immutable(&self, _value: TypeId) -> bool { todo!() // let is_frozen = self.is_frozen(value); @@ -784,12 +780,11 @@ impl Context { let mut new_environment = self.new_lexical_environment(scope); let res = cb(&mut new_environment, checking_data); - let context_id = new_environment.context_id; let super::Environment { context_id, variables, - named_types, + named_types: _, context_type: environment::Syntax { scope, @@ -802,7 +797,7 @@ impl Context { can_reference_this, bases, variable_names, - object_constraints, + object_constraints: _, deferred_function_constraints, mut facts, possibly_mutated_objects, @@ -997,7 +992,7 @@ impl Context { .collect() }); - if let Some(extends) = extends { + if let Some(_extends) = extends { todo!("synthesise, fold into Type::And and create alias type") } @@ -1115,8 +1110,8 @@ impl Context { pub(crate) fn get_value_of_this( &mut self, - types: &TypeStore, - position: &SpanWithSource, + _types: &TypeStore, + _position: &SpanWithSource, ) -> TypeId { self.parents_iter() .find_map(|env| { @@ -1224,18 +1219,6 @@ impl<'a, T: Clone> Logical<&'a T> { } } -// TODO temp -impl Logical { - #[allow(clippy::wrong_self_convention)] - pub(crate) fn to_type(self) -> TypeId { - match self { - Logical::Pure(ty) => ty, - Logical::Or { .. } => todo!(), - Logical::Implies { .. } => todo!(), - } - } -} - pub enum SetPropertyError { NotWriteable, DoesNotMeetConstraint { @@ -1246,7 +1229,7 @@ pub enum SetPropertyError { /// TODO mutable let imports pub(crate) fn get_value_of_variable<'a>( - mut facts: impl Iterator, + facts: impl Iterator, on: VariableId, closures: Option<&impl ClosureChain>, ) -> Option { diff --git a/checker/src/context/root.rs b/checker/src/context/root.rs index 7d8e2060..5578322f 100644 --- a/checker/src/context/root.rs +++ b/checker/src/context/root.rs @@ -1,8 +1,8 @@ -use super::{facts::Facts, ClosedOverReferencesInScope, Context, ContextId, ContextType}; +use super::{ClosedOverReferencesInScope, Context, ContextId, ContextType}; use crate::{ behavior::modules::{Exported, SynthesisedModule}, types::TypeId, - CheckingData, Environment, GeneralContext, + CheckingData, GeneralContext, }; use source_map::SourceId; use std::{collections::HashMap, iter::FromIterator}; @@ -38,11 +38,11 @@ impl ContextType for Root { } } -const HEADER: &[u8] = b"EZNO\0CONTEXT\0FILE"; +const _CONTEXT_FILE_HEADER: &[u8] = b"EZNO\0CONTEXT\0FILE"; impl RootContext { /// Merges two [`RootEnvironments`]. May be used for multiple `.d.ts` files - pub(crate) fn union(&mut self, other: Self) { + pub(crate) fn _union(&mut self, other: Self) { // TODO this is bad, some things need to merge, inserting over existing will be bad self.variables.extend(other.variables); todo!() @@ -112,11 +112,12 @@ impl RootContext { /// TODO working things out: /// - strings could reference a big string - pub(crate) fn serialize(self) -> Vec { + #[must_use] + pub fn serialize(self) -> Vec { todo!() } - pub(crate) fn deserialize(source: &[u8], backing_source: SourceId) -> Result { + pub fn deserialize(_source: &[u8], _backing_source: SourceId) -> Result { todo!() // let mut ctx = Root::new_with_primitive_references(); diff --git a/checker/src/diagnostics.rs b/checker/src/diagnostics.rs index 8ab17715..05b86112 100644 --- a/checker/src/diagnostics.rs +++ b/checker/src/diagnostics.rs @@ -7,11 +7,11 @@ use crate::{ diagnostics, types::{ poly_types::generic_type_arguments::StructureGenericArguments, - printing::print_type_with_generics, StructureGenerics, + printing::print_type_with_generics, }, }; use serde::Serialize; -use source_map::{SourceId, Span, SpanWithSource}; +use source_map::{SourceId, SpanWithSource}; use std::{ fmt::{self, Debug, Display}, iter, @@ -213,6 +213,8 @@ impl TypeStringRepresentation { crate::context::Logical::Or { left, right } => { let left = Self::from_property_constraint(*left, None, ctx, types, debug_mode); let right = Self::from_property_constraint(*right, None, ctx, types, debug_mode); + + #[allow(irrefutable_let_patterns)] if let (TypeStringRepresentation::Type(mut l), TypeStringRepresentation::Type(r)) = (left, right) { @@ -243,7 +245,7 @@ impl Display for TypeStringRepresentation { pub(crate) struct NoEnvironmentSpecified; impl From for Diagnostic { - fn from(error: NoEnvironmentSpecified) -> Self { + fn from(_error: NoEnvironmentSpecified) -> Self { Diagnostic::Global { reason: "No environment".to_owned(), kind: DiagnosticKind::Error } } } @@ -252,14 +254,12 @@ impl From for Diagnostic { // Contained here in a module to separate user facing mod defined_errors_and_warnings { use crate::{ - behavior::{self, operations::MathematicalAndBitwise}, - context::AssignmentError, + behavior::operations::MathematicalAndBitwise, context::AssignmentError, types::calling::FunctionCallingError, }; - use source_map::{Span, SpanWithSource}; + use source_map::SpanWithSource; use crate::Diagnostic; - use std::path; use super::{ NotInLoopOrCouldNotFindLabel, PropertyRepresentation, TypeStringRepresentation, TDZ, @@ -267,6 +267,7 @@ mod defined_errors_and_warnings { /// Reasons for errors, intermediate type for generating [Diagnostic]s /// e.g. cannot Call, cannot equate, duplicate key etc + #[allow(unused)] pub(crate) enum TypeCheckError<'a> { FunctionCallingError(FunctionCallingError), PropertyDoesNotExist { @@ -382,7 +383,7 @@ mod defined_errors_and_warnings { fn from(error: TypeCheckError<'_>) -> Self { let kind = super::DiagnosticKind::Error; match error { - TypeCheckError::CouldNotFindVariable { variable, possibles, position } => { + TypeCheckError::CouldNotFindVariable { variable, possibles: _, position } => { Diagnostic::Position { reason: format!( "Could not find variable {variable} in scope", @@ -454,7 +455,7 @@ mod defined_errors_and_warnings { )], } } - FunctionCallingError::ExcessArguments { count, position } => { + FunctionCallingError::ExcessArguments { count: _, position } => { Diagnostic::Position { reason: "Excess argument".into(), position, @@ -469,9 +470,9 @@ mod defined_errors_and_warnings { } } FunctionCallingError::ReferenceRestrictionDoesNotMatch { - reference, - requirement, - found, + reference: _, + requirement: _, + found: _, } => todo!(), // Diagnostic::Position { // reason: format!( @@ -554,7 +555,7 @@ mod defined_errors_and_warnings { attribute_name, attribute_type, value_type, - attribute_type_site: variable_site, + attribute_type_site: _variable_site, value_site, } => Diagnostic::Position { reason: format!( @@ -604,9 +605,9 @@ mod defined_errors_and_warnings { } } TypeCheckError::InvalidJSXInterpolatedValue { - interpolation_site, - expected, - found, + interpolation_site: _, + expected: _, + found: _, } => todo!(), TypeCheckError::RestParameterAnnotationShouldBeArrayType(pos) => { Diagnostic::Position { @@ -620,7 +621,7 @@ mod defined_errors_and_warnings { position: at, kind, }, - TypeCheckError::ReDeclaredVariable { name, position: pos } => todo!(), + TypeCheckError::ReDeclaredVariable { name: _, position: _pos } => todo!(), TypeCheckError::FunctionDoesNotMeetConstraint { function_constraint, function_type, diff --git a/checker/src/events/application.rs b/checker/src/events/application.rs index 273d4450..08c50f59 100644 --- a/checker/src/events/application.rs +++ b/checker/src/events/application.rs @@ -8,10 +8,9 @@ use crate::{ context::{calling::Target, get_value_of_variable, CallCheckingBehavior, SetPropertyError}, diagnostics::{TypeStringRepresentation, TDZ}, types::{ - curry_arguments, functions::SynthesisedArgument, - get_constraint, is_type_truthy_falsy, - poly_types::{generic_type_arguments::TypeArgumentStore, FunctionTypeArguments}, + is_type_truthy_falsy, + poly_types::FunctionTypeArguments, properties::{get_property, set_property, PropertyValue}, substitute, Constructor, StructureGenerics, TypeId, TypeStore, }, @@ -129,7 +128,7 @@ pub(crate) fn apply_event( } }; - let gc = environment.as_general_context(); + let _gc = environment.as_general_context(); // crate::utils::notify!( // "[Event::Setter] {}[{}] = {}", @@ -162,8 +161,10 @@ pub(crate) fn apply_event( set_property(on, publicity, &under, &new, environment, target, types, position); if let Err(err) = result { - if let SetPropertyError::DoesNotMeetConstraint { property_constraint, reason } = - err + if let SetPropertyError::DoesNotMeetConstraint { + property_constraint, + reason: _, + } = err { let value_type = if let PropertyValue::Value(id) = new { TypeStringRepresentation::from_type_id( @@ -190,7 +191,14 @@ pub(crate) fn apply_event( } } } - Event::CallsType { on, with, reflects_dependency, timing, called_with_new, position } => { + Event::CallsType { + on, + with, + reflects_dependency, + timing, + called_with_new, + position: _, + } => { let on = substitute(on, type_arguments, environment, types); let with = with @@ -360,7 +368,12 @@ pub(crate) fn apply_event( return Some(EventResult::Return(substituted_returned, returned_position)); } // TODO Needs a position (or not?) - Event::CreateObject { referenced_in_scope_as, prototype, position, is_function_this } => { + Event::CreateObject { + referenced_in_scope_as, + prototype, + position: _, + is_function_this, + } => { // TODO let is_under_dyn = true; @@ -397,8 +410,8 @@ pub(crate) fn apply_event( type_arguments.set_id_from_reference(referenced_in_scope_as, new_object_id); } - Event::Break { position, carry } => return Some(EventResult::Break { carry }), - Event::Continue { position, carry } => return Some(EventResult::Continue { carry }), + Event::Break { position: _, carry } => return Some(EventResult::Break { carry }), + Event::Continue { position: _, carry } => return Some(EventResult::Continue { carry }), Event::Iterate { kind, iterate_over, initial } => { // TODO this might clash let initial = initial diff --git a/checker/src/events/helpers.rs b/checker/src/events/helpers.rs index 5c52c3de..d16fe65b 100644 --- a/checker/src/events/helpers.rs +++ b/checker/src/events/helpers.rs @@ -1,9 +1,5 @@ use super::Event; -use crate::{ - context::environment, - types::{new_logical_or_type, TypeStore}, - CheckingData, Environment, TypeId, -}; +use crate::{types::new_logical_or_type, CheckingData, Environment, TypeId}; pub(crate) enum ReturnedTypeFromBlock { // aka no return @@ -62,7 +58,7 @@ pub(crate) fn get_return_from_events<'a, T: crate::ReadFromFS, A: crate::ASTImpl } return ReturnedTypeFromBlock::Returned(*returned); } - Event::Conditionally { condition: on, events_if_truthy, else_events, position } => { + Event::Conditionally { condition: on, events_if_truthy, else_events, position: _ } => { let return_if_truthy = get_return_from_events( &mut events_if_truthy.iter(), checking_data, @@ -85,7 +81,7 @@ pub(crate) fn get_return_from_events<'a, T: crate::ReadFromFS, A: crate::ASTImpl } ( ReturnedTypeFromBlock::ContinuedExecution, - ReturnedTypeFromBlock::ReturnedIf { when, returns }, + ReturnedTypeFromBlock::ReturnedIf { when: _, returns: _ }, ) => { todo!("Expend rest of iterator") // ReturnedTypeFromBlock::ReturnedIf { @@ -100,23 +96,23 @@ pub(crate) fn get_return_from_events<'a, T: crate::ReadFromFS, A: crate::ASTImpl todo!() } ( - v @ ReturnedTypeFromBlock::ReturnedIf { .. }, + _v @ ReturnedTypeFromBlock::ReturnedIf { .. }, ReturnedTypeFromBlock::ContinuedExecution, ) => { todo!() // return v } ( - ReturnedTypeFromBlock::ReturnedIf { when, returns }, + ReturnedTypeFromBlock::ReturnedIf { when: _, returns: _ }, ReturnedTypeFromBlock::ReturnedIf { .. }, ) => todo!(), ( - ReturnedTypeFromBlock::ReturnedIf { when, returns }, + ReturnedTypeFromBlock::ReturnedIf { when: _, returns: _ }, ReturnedTypeFromBlock::Returned(_), ) => todo!(), ( - ReturnedTypeFromBlock::Returned(true_returned), - ReturnedTypeFromBlock::ReturnedIf { when, returns }, + ReturnedTypeFromBlock::Returned(_true_returned), + ReturnedTypeFromBlock::ReturnedIf { when: _, returns: _ }, ) => { todo!("expend iterator") // TODO could be simpler, aka a chain @@ -187,7 +183,7 @@ pub(crate) fn get_return_from_events<'a, T: crate::ReadFromFS, A: crate::ASTImpl pub(crate) fn extract_throw_events(events: Vec, thrown: &mut Vec) -> Vec { let mut new_events = Vec::new(); for event in events { - if let Event::Throw(value, position) = event { + if let Event::Throw(value, _position) = event { thrown.push(value); } else { // TODO nested grouping diff --git a/checker/src/events/mod.rs b/checker/src/events/mod.rs index 57d1c309..453b1547 100644 --- a/checker/src/events/mod.rs +++ b/checker/src/events/mod.rs @@ -3,12 +3,11 @@ //! Events is the general name for the IR. Effect = Events of a function use crate::{ - behavior::{functions::ThisValue, iteration::IterationKind}, - context::{calling::Target, facts::Publicity, get_on_ctx, CallCheckingBehavior}, + behavior::iteration::IterationKind, + context::{facts::Publicity, get_on_ctx}, types::{ calling::CalledWithNew, properties::{PropertyKey, PropertyValue}, - TypeArguments, }, FunctionId, GeneralContext, SpanWithSource, VariableId, }; @@ -16,12 +15,8 @@ use crate::{ pub(crate) mod application; pub(crate) mod helpers; pub(crate) use application::apply_event; -use source_map::Span; -use crate::{ - types::functions::SynthesisedArgument, - types::{poly_types::FunctionTypeArguments, TypeId}, -}; +use crate::{types::functions::SynthesisedArgument, types::TypeId}; #[derive(Debug, Clone, PartialEq, Eq, Hash, binary_serialize_derive::BinarySerializable)] pub enum RootReference { diff --git a/checker/src/lib.rs b/checker/src/lib.rs index bdab12d5..3a0a1bea 100644 --- a/checker/src/lib.rs +++ b/checker/src/lib.rs @@ -1,16 +1,5 @@ #![doc = include_str!("../README.md")] -#![allow( - unreachable_code, - unused_variables, - unused_imports, - unused_mut, - dead_code, - irrefutable_let_patterns, - deprecated, - clippy::new_without_default, - clippy::too_many_lines, - clippy::result_unit_err -)] +#![allow(deprecated, clippy::new_without_default, clippy::too_many_lines, clippy::result_unit_err)] pub mod behavior; pub mod context; @@ -30,7 +19,7 @@ pub const INTERNAL_DEFINITION_FILE: &str = include_str!("../definitions/internal #[cfg(feature = "ezno-parser")] pub mod synthesis; -use context::{environment, Names}; +use context::Names; use diagnostics::{TypeCheckError, TypeCheckWarning}; pub(crate) use serialization::BinarySerializable; @@ -38,17 +27,14 @@ use behavior::{ functions::SynthesisableFunction, modules::{Exported, InvalidModule, SynthesisedModule}, }; -use indexmap::IndexMap; + use source_map::{FileSystem, MapFileStore, SpanWithSource, WithPathMap}; use std::{ collections::{HashMap, HashSet}, path::{Path, PathBuf}, }; -use types::{ - subtyping::{check_satisfies, type_is_subtype, BasicEquality, SubTypeResult}, - TypeStore, -}; +use types::{subtyping::check_satisfies, TypeStore}; pub use context::{GeneralContext, RootContext}; pub use diagnostics::{Diagnostic, DiagnosticKind, DiagnosticsContainer}; @@ -72,13 +58,13 @@ pub use source_map::{self, SourceId, Span}; /// TODO could files and `synthesised_modules` be merged? (with a change to the source map crate) pub struct ModuleData<'a, FileReader, ModuleAST: ASTImplementation> { pub(crate) file_reader: &'a FileReader, - pub(crate) current_working_directory: PathBuf, + pub(crate) _current_working_directory: PathBuf, /// Set after started pub(crate) entry_point: Option, /// Contains the text content of files (for source maps and diagnostics) pub(crate) files: MapFileStore, /// To catch cyclic imports - pub(crate) currently_checking_modules: HashSet, + pub(crate) _currently_checking_modules: HashSet, /// The result of checking. Includes exported variables and facts pub(crate) synthesised_modules: HashMap>, } @@ -174,7 +160,7 @@ pub trait ASTImplementation: Sized { impl<'a, T: crate::ReadFromFS, ModuleAST: ASTImplementation> ModuleData<'a, T, ModuleAST> { pub(crate) fn new( - mut file_resolver: &'a T, + file_resolver: &'a T, current_working_directory: PathBuf, files: Option>, ) -> Self { @@ -182,10 +168,10 @@ impl<'a, T: crate::ReadFromFS, ModuleAST: ASTImplementation> ModuleData<'a, T, M files: files.unwrap_or_default(), entry_point: None, synthesised_modules: Default::default(), - currently_checking_modules: Default::default(), + _currently_checking_modules: Default::default(), // custom_module_resolvers, file_reader: file_resolver, - current_working_directory, + _current_working_directory: current_working_directory, } } @@ -443,7 +429,7 @@ pub fn check_project( } let entry_content = (checking_data.modules.file_reader)(entry_point.as_ref()); - let module = if let Some(content) = entry_content { + let _module = if let Some(content) = entry_content { let source = checking_data.modules.files.new_source_id(entry_point.clone(), content.clone()); @@ -472,9 +458,9 @@ pub fn check_project( diagnostics_container, type_mappings, modules, - options, + options: _, types, - unimplemented_items, + unimplemented_items: _, } = checking_data; if diagnostics_container.has_error() { diff --git a/checker/src/options.rs b/checker/src/options.rs index e7c122f8..7aa2201f 100644 --- a/checker/src/options.rs +++ b/checker/src/options.rs @@ -1,5 +1,3 @@ -use std::any::Any; - /// Options for type checking /// TODO figure out compat with tsc #[derive(serde::Deserialize)] diff --git a/checker/src/serialization.rs b/checker/src/serialization.rs index 3a14493d..45172ba4 100644 --- a/checker/src/serialization.rs +++ b/checker/src/serialization.rs @@ -7,7 +7,7 @@ use std::{ convert::TryInto, }; -use source_map::{SourceId, Span, SpanWithSource}; +use source_map::{SourceId, SpanWithSource}; /// TODO not sure about iterator /// This is automated by the derive macro TODO link @@ -23,7 +23,7 @@ impl BinarySerializable for String { buf.extend_from_slice(self.as_bytes()); } - fn deserialize>(iter: &mut I, source: SourceId) -> Self { + fn deserialize>(iter: &mut I, _source: SourceId) -> Self { let len = iter.next().unwrap(); iter.by_ref().take(len as usize).map(|v| v as char).collect::() } @@ -33,7 +33,7 @@ impl BinarySerializable for String { impl BinarySerializable for () { fn serialize(self, _buf: &mut Vec) {} - fn deserialize>(iter: &mut I, source: SourceId) -> Self {} + fn deserialize>(_iter: &mut I, _source: SourceId) -> Self {} } impl BinarySerializable for u8 { @@ -41,7 +41,7 @@ impl BinarySerializable for u8 { buf.push(self); } - fn deserialize>(iter: &mut I, source: SourceId) -> Self { + fn deserialize>(iter: &mut I, _source: SourceId) -> Self { iter.next().unwrap() } } @@ -242,7 +242,7 @@ impl BinarySerializable for crate::TypeId { buf.extend_from_slice(&self.0.to_le_bytes()); } - fn deserialize>(iter: &mut I, source: SourceId) -> Self { + fn deserialize>(iter: &mut I, _source: SourceId) -> Self { Self(u16::from_le_bytes([iter.next().unwrap(), iter.next().unwrap()])) } } @@ -252,7 +252,7 @@ impl BinarySerializable for ordered_float::NotNan { buf.extend_from_slice(&self.into_inner().to_le_bytes()); } - fn deserialize>(iter: &mut I, source: SourceId) -> Self { + fn deserialize>(iter: &mut I, _source: SourceId) -> Self { Self::new(f64::from_le_bytes([ iter.next().unwrap(), iter.next().unwrap(), @@ -272,7 +272,7 @@ impl BinarySerializable for bool { buf.push(u8::from(self)); } - fn deserialize>(iter: &mut I, source: SourceId) -> Self { + fn deserialize>(iter: &mut I, _source: SourceId) -> Self { iter.next().unwrap() == 1 } } diff --git a/checker/src/structures/jsx.rs b/checker/src/structures/jsx.rs index c68eae84..39ff2681 100644 --- a/checker/src/structures/jsx.rs +++ b/checker/src/structures/jsx.rs @@ -1,25 +1,5 @@ -use std::collections::HashMap; - use crate::TypeId; -// /// TODO not sure might be TypeId -// #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] -// pub enum TagNamedMapping { -// CustomElement(TypeId), -// Inbuilt(TypeId), -// } - -struct Things { - elements_values: HashMap, - reverse: HashMap, -} - -struct Element { - // TODO also doubles as properties - attributes: HashMap, - children: Vec, -} - pub enum ForwardInterpolationSpot { Attribute { name: TypeId }, NodeChild { idx: usize }, diff --git a/checker/src/synthesis/assignments.rs b/checker/src/synthesis/assignments.rs index 339aff6c..67a2f39f 100644 --- a/checker/src/synthesis/assignments.rs +++ b/checker/src/synthesis/assignments.rs @@ -1,16 +1,14 @@ use std::borrow::Cow; -use ordered_float::NotNan; use parser::{ - ast::LHSOfAssignment, expressions::assignments::VariableOrPropertyAccess, ASTNode, - VariableIdentifier, + ast::LHSOfAssignment, expressions::assignments::VariableOrPropertyAccess, VariableIdentifier, }; use crate::{ behavior::assignments::{Assignable, Reference}, context::{facts::Publicity, Environment}, synthesis::expressions::synthesise_expression, - types::{properties::PropertyKey, Constant}, + types::properties::PropertyKey, CheckingData, TypeId, }; @@ -47,8 +45,8 @@ pub(super) fn synthesise_lhs_of_assignment_to_reference( parser::ObjectDestructuringField::Map { from, name, - default_value, - position, + default_value: _, + position: _, } => { // TODO into function match name.get_ast_ref() { @@ -100,7 +98,7 @@ pub(super) fn synthesise_lhs_of_assignment_to_reference( fn synthesise_object_shorthand_assignable( name: &parser::VariableIdentifier, - checking_data: &CheckingData, + _checking_data: &CheckingData, environment: &crate::context::Context>, ) -> Assignable { match name { diff --git a/checker/src/synthesis/block.rs b/checker/src/synthesis/block.rs index 84e0f5c1..df3249ad 100644 --- a/checker/src/synthesis/block.rs +++ b/checker/src/synthesis/block.rs @@ -1,12 +1,9 @@ use parser::{ - declarations::VariableDeclaration, Declaration, ExpressionOrStatementPosition, Statement, - StatementOrDeclaration, VariableIdentifier, + Declaration, ExpressionOrStatementPosition, Statement, StatementOrDeclaration, + VariableIdentifier, }; -use crate::{ - behavior::modules::Exported, context::Environment, diagnostics::TypeCheckError, CheckingData, - Scope, TypeId, -}; +use crate::{context::Environment, diagnostics::TypeCheckError, CheckingData, Scope, TypeId}; use super::{ classes::synthesise_class_declaration, declarations::synthesise_variable_declaration, @@ -80,7 +77,7 @@ pub(crate) fn synthesise_declaration( &mut checking_data.types, None, ); - if let Err(err) = result { + if let Err(_err) = result { // TODO is this an issue? checking_data .diagnostics_container @@ -97,7 +94,7 @@ pub(crate) fn synthesise_declaration( | Declaration::TypeAlias(_) | Declaration::Import(_) => {} Declaration::Export(exported) => match &exported.on { - parser::declarations::ExportDeclaration::Variable { exported, position } => { + parser::declarations::ExportDeclaration::Variable { exported, position: _ } => { match exported { // Skipped as this is done earlier parser::declarations::export::Exportable::Class(class) => { diff --git a/checker/src/synthesis/classes.rs b/checker/src/synthesis/classes.rs index 23aa4541..02a277da 100644 --- a/checker/src/synthesis/classes.rs +++ b/checker/src/synthesis/classes.rs @@ -1,34 +1,20 @@ -use std::iter; - use parser::{ declarations::{classes::ClassMember, ClassDeclaration}, functions::MethodHeader, - property_key::PublicOrPrivate, - Decorated, Expression, GenericTypeConstraint, PropertyKey as ParserPropertyKey, TypeAnnotation, + PropertyKey as ParserPropertyKey, }; use crate::{ behavior::functions::{ function_to_property, ClassPropertiesToRegister, FunctionRegisterBehavior, GetterSetter, }, - context::{ - environment, - facts::Publicity, - Environment, {Context, ContextType}, - }, - synthesis::{ - parser_property_key_to_checker_property_key, type_annotations::synthesise_type_annotation, - }, - types::{ - classes::{ClassValue, PropertyFunctionProperty}, - poly_types::GenericTypeParameters, - properties::PropertyKey, - FunctionType, SynthesisedParameters, - }, - ASTImplementation, CheckingData, PropertyValue, Scope, Type, TypeId, + context::{facts::Publicity, Environment}, + synthesis::parser_property_key_to_checker_property_key, + types::{classes::ClassValue, properties::PropertyKey, FunctionType}, + CheckingData, PropertyValue, Scope, Type, TypeId, }; -use super::{block::synthesise_block, expressions::synthesise_expression, EznoParser}; +use super::{block::synthesise_block, expressions::synthesise_expression}; /// Doesn't have any metadata yet /// @@ -43,7 +29,7 @@ pub(super) fn synthesise_class_declaration< ) -> TypeId { { // TODO what about no name - let name = P::as_option_str(&class.name).unwrap().to_owned(); + let _name = P::as_option_str(&class.name).unwrap().to_owned(); // TODO type needs to be hoisted // let parameters = // if let Some(ref type_parameters) = class.type_parameters { todo!() } else { None }; @@ -61,7 +47,7 @@ pub(super) fn synthesise_class_declaration< let class_prototype = checking_data.types.register_type(Type::Object(crate::types::ObjectNature::RealDeal)); - let mut class_constructor = class.members.iter().find_map(|member| { + let class_constructor = class.members.iter().find_map(|member| { if let ClassMember::Constructor(c) = &member.on { Some(c) } else { @@ -74,7 +60,7 @@ pub(super) fn synthesise_class_declaration< // Property keys on `static` items let mut static_property_keys: Vec> = Vec::new(); - for (idx, member) in class.members.iter().enumerate() { + for (_idx, member) in class.members.iter().enumerate() { match &member.on { ClassMember::Method(None, method) => { let publicity = match method.name.get_ast_ref() { diff --git a/checker/src/synthesis/declarations.rs b/checker/src/synthesis/declarations.rs index 8f8c71dd..bf6746d1 100644 --- a/checker/src/synthesis/declarations.rs +++ b/checker/src/synthesis/declarations.rs @@ -24,7 +24,7 @@ pub(super) fn synthesise_variable_declaration( } VariableDeclaration::LetDeclaration { declarations, - keyword: parser::Keyword(_, position), + keyword: parser::Keyword(_, _position), .. } => { for variable_declaration in declarations { diff --git a/checker/src/synthesis/definitions.rs b/checker/src/synthesis/definitions.rs index c215f851..ad2f12d4 100644 --- a/checker/src/synthesis/definitions.rs +++ b/checker/src/synthesis/definitions.rs @@ -2,16 +2,16 @@ use parser::ASTNode; use crate::{ context::{Names, RootContext}, - synthesis::{functions::synthesise_function_annotation, EznoParser}, + synthesis::{ + functions::synthesise_function_annotation, type_annotations::synthesise_type_annotation, + }, Environment, Facts, TypeId, }; -const DEFINITION_VAR_IS_CONSTANT: bool = true; - /// Interprets a definition module (.d.ts) and produces a [Environment]. Consumes the [`TypeDefinitionModule`] /// TODO remove unwraps here and add to the existing error handler pub(super) fn type_definition_file( - mut definition: parser::TypeDefinitionModule, + definition: parser::TypeDefinitionModule, checking_data: &mut crate::CheckingData, root: &RootContext, ) -> (Names, Facts) { @@ -22,10 +22,6 @@ pub(super) fn type_definition_file( TypeDeclaration, TypeDefinitionModuleDeclaration, }; - use crate::{ - diagnostics::TypeCheckError, synthesis::type_annotations::synthesise_type_annotation, - }; - let mut idx_to_types = HashMap::new(); let source = definition.source; let mut env = root.new_lexical_environment(crate::Scope::DefinitionModule { source }); @@ -45,7 +41,7 @@ pub(super) fn type_definition_file( ); idx_to_types.insert(interface.on.position.start, ty); } - TypeDefinitionModuleDeclaration::Class(class) => { + TypeDefinitionModuleDeclaration::Class(_class) => { todo!(); // ( // class.type_id, @@ -98,7 +94,7 @@ pub(super) fn type_definition_file( context: decorators_to_context(&func.decorators), }; - let res = env.register_variable_handle_error( + let _res = env.register_variable_handle_error( func.name.as_str(), // TODO func.get_position().with_source(source), @@ -107,9 +103,9 @@ pub(super) fn type_definition_file( ); } TypeDefinitionModuleDeclaration::Variable(DeclareVariableDeclaration { - keyword, + keyword: _, declarations, - position, + position: _, decorators, }) => { for declaration in &declarations { @@ -145,15 +141,15 @@ pub(super) fn type_definition_file( // TODO handle locals differently, (maybe squash ast as well) TypeDefinitionModuleDeclaration::LocalTypeAlias(TypeAlias { type_name, - type_expression, + type_expression: _, .. }) | TypeDefinitionModuleDeclaration::TypeAlias(TypeAlias { type_name, - type_expression, + type_expression: _, .. }) => { - let TypeDeclaration { name, type_parameters, .. } = &type_name; + let TypeDeclaration { type_parameters, .. } = &type_name; // To remove when implementing #[allow(clippy::redundant_pattern_matching)] @@ -186,8 +182,8 @@ pub(super) fn type_definition_file( TypeDefinitionModuleDeclaration::LocalVariableDeclaration(_) => { unimplemented!() } - TypeDefinitionModuleDeclaration::Comment(comment) => {} - TypeDefinitionModuleDeclaration::Class(class) => { + TypeDefinitionModuleDeclaration::Comment(_comment) => {} + TypeDefinitionModuleDeclaration::Class(_class) => { todo!(); // let existing_type = // checking_data.type_mappings.get_type_declaration(&class.type_id).unwrap(); diff --git a/checker/src/synthesis/expressions.rs b/checker/src/synthesis/expressions.rs index af702ce8..5a2a118f 100644 --- a/checker/src/synthesis/expressions.rs +++ b/checker/src/synthesis/expressions.rs @@ -1,24 +1,18 @@ -use std::{borrow::Cow, convert::TryInto, marker::PhantomData}; +use std::{borrow::Cow, convert::TryInto}; use parser::{ expressions::{ - assignments::LHSOfAssignment, object_literal::{ObjectLiteral, ObjectLiteralMember}, MultipleExpression, SpecialOperators, SpreadExpression, SuperReference, TemplateLiteral, }, functions::MethodHeader, - operators::{ - BinaryAssignmentOperator, BinaryOperator, UnaryOperator, UnaryPrefixAssignmentOperator, - }, + operators::{BinaryOperator, UnaryOperator, UnaryPrefixAssignmentOperator}, ASTNode, Expression, }; use crate::{ behavior::{ - functions::{ - register_arrow_function, register_expression_function, FunctionRegisterBehavior, - SynthesisableFunction, - }, + functions::{register_arrow_function, register_expression_function}, variables::VariableWithValue, }, synthesis::parser_property_key_to_checker_property_key, @@ -38,10 +32,9 @@ use crate::{ template_literal::synthesise_template_literal, }, context::facts::Publicity, - diagnostics::{TypeCheckError, TypeCheckWarning, TypeStringRepresentation}, - events::Event, + diagnostics::TypeCheckWarning, types::{calling::CalledWithNew, functions::SynthesisedArgument}, - types::{properties::PropertyKind, Constant, TypeId}, + types::{Constant, TypeId}, CheckingData, Environment, Instance, SpecialExpressions, }; @@ -81,7 +74,7 @@ pub(super) fn synthesise_expression( Expression::StringLiteral(value, ..) => { return checking_data.types.new_constant_type(Constant::String(value.clone())) } - Expression::RegexLiteral { pattern, flags, position } => { + Expression::RegexLiteral { pattern, flags: _, position: _ } => { // TODO flags return checking_data.types.new_constant_type(Constant::Regexp(pattern.clone())); } @@ -118,7 +111,7 @@ pub(super) fn synthesise_expression( expression_type, ) } - SpreadExpression::Spread(expr, position) => { + SpreadExpression::Spread(_expr, position) => { { checking_data.raise_unimplemented_error( "Spread elements", @@ -195,7 +188,7 @@ pub(super) fn synthesise_expression( expecting, )), Expression::TemplateLiteral(TemplateLiteral { tag, parts, position }) => { - let mut parts_iter = parts.iter().map(|part| match part { + let parts_iter = parts.iter().map(|part| match part { parser::expressions::TemplateLiteralPart::Static(value) => { crate::behavior::template_literal::TemplateLiteralPart::Static(value.as_str()) } @@ -351,7 +344,12 @@ pub(super) fn synthesise_expression( // TODO synthesise anyway? and use mappings // TODO more expressions match &**operand { - Expression::PropertyAccess { parent, property, is_optional, position } => { + Expression::PropertyAccess { + parent, + property, + is_optional: _, + position: _, + } => { let on = synthesise_expression( parent, environment, @@ -372,7 +370,7 @@ pub(super) fn synthesise_expression( parser::PropertyReference::Cursor(_) => todo!(), } } - Expression::Index { indexee, indexer, is_optional, position } => { + Expression::Index { indexee, indexer, is_optional: _, position: _ } => { let being_indexed = synthesise_expression( indexee, environment, @@ -425,9 +423,6 @@ pub(super) fn synthesise_expression( ); } Expression::BinaryAssignmentOperation { lhs, operator, rhs, position } => { - use crate::behavior::assignments::AssignmentKind; - use parser::operators::BinaryAssignmentOperator; - let lhs: Assignable = Assignable::Reference(synthesise_access_to_reference( lhs, environment, @@ -574,8 +569,8 @@ pub(super) fn synthesise_expression( let position = pos.with_source(environment.get_source()); Instance::RValue(environment.get_value_of_this(&checking_data.types, &position)) } - Expression::SuperExpression(reference, position) => match reference { - SuperReference::Call { arguments } => { + Expression::SuperExpression(reference, _position) => match reference { + SuperReference::Call { arguments: _ } => { todo!(); // let constructor = @@ -626,8 +621,8 @@ pub(super) fn synthesise_expression( // Instance::RValue(ty) } - SuperReference::PropertyAccess { property } => todo!(), - SuperReference::Index { indexer } => todo!(), + SuperReference::PropertyAccess { property: _ } => todo!(), + SuperReference::Index { indexer: _ } => todo!(), }, Expression::NewTarget(..) => todo!(), Expression::FunctionCall { function, type_arguments, arguments, position, .. } => { @@ -716,9 +711,9 @@ pub(super) fn synthesise_expression( Expression::ClassExpression(class) => { Instance::RValue(synthesise_class_declaration(class, environment, checking_data)) } - Expression::Cursor { cursor_id, position } => todo!(), + Expression::Cursor { cursor_id: _, position: _ } => todo!(), Expression::SpecialOperators(operator, position) => match operator { - SpecialOperators::AsExpression { value, type_annotation, .. } => { + SpecialOperators::AsExpression { value, .. } => { checking_data.diagnostics_container.add_warning( TypeCheckWarning::IgnoringAsExpression( position.with_source(environment.get_source()), @@ -727,7 +722,9 @@ pub(super) fn synthesise_expression( return synthesise_expression(value, environment, checking_data, expecting); } - SpecialOperators::IsExpression { value, is_keyword, type_annotation } => todo!(), + SpecialOperators::IsExpression { value: _, is_keyword: _, type_annotation: _ } => { + todo!() + } SpecialOperators::SatisfiesExpression { value, type_annotation, .. } => { let value = synthesise_expression(value, environment, checking_data, expecting); let satisfying = @@ -894,7 +891,7 @@ fn synthesise_arguments( arguments .iter() .filter_map(|argument| match argument { - SpreadExpression::Spread(expr, _) => { + SpreadExpression::Spread(_expr, _) => { todo!() // Some(synthesisedFunctionArgument::Spread(synthesise_expression( // expr, @@ -905,7 +902,7 @@ fn synthesise_arguments( // ))) } SpreadExpression::NonSpread(expr) => { - let non_param = expr.get_non_parenthesized(); + let _non_param = expr.get_non_parenthesized(); // if matches!( // non_param, // Expression::ArrowFunction(_) diff --git a/checker/src/synthesis/extensions/is_expression.rs b/checker/src/synthesis/extensions/is_expression.rs index 9a7b141a..0b68d611 100644 --- a/checker/src/synthesis/extensions/is_expression.rs +++ b/checker/src/synthesis/extensions/is_expression.rs @@ -13,16 +13,16 @@ pub(crate) fn synthesise_is_expression( checking_data: &mut CheckingData, ) -> TypeId { // TODO expecting - let matcher = synthesise_multiple_expression( + let _matcher = synthesise_multiple_expression( &is_expression.matcher, environment, checking_data, TypeId::ANY_TYPE, ); - let mut returned = TypeId::UNDEFINED_TYPE; + let returned = TypeId::UNDEFINED_TYPE; for (condition, code) in &is_expression.branches { - let requirement = synthesise_type_annotation(condition, environment, checking_data); + let _requirement = synthesise_type_annotation(condition, environment, checking_data); // TODO need to test subtyping and subtype here // TODO move proofs here diff --git a/checker/src/synthesis/extensions/jsx.rs b/checker/src/synthesis/extensions/jsx.rs index 9e17be20..0a9b3aa3 100644 --- a/checker/src/synthesis/extensions/jsx.rs +++ b/checker/src/synthesis/extensions/jsx.rs @@ -2,23 +2,13 @@ use std::borrow::Cow; -use parser::{ - ASTNode, Expression, JSXAttribute, JSXElement, JSXNode, JSXRoot, - PropertyKey as ParserPropertyKey, -}; +use parser::{ASTNode, Expression, JSXAttribute, JSXElement, JSXNode, JSXRoot}; use crate::{ behavior::objects::ObjectBuilder, call_type_handle_errors, - context::Logical, - diagnostics::{TypeCheckError, TypeStringRepresentation}, synthesis::expressions::synthesise_expression, - types::{ - calling::CallingInput, - properties::PropertyKey, - subtyping::{type_is_subtype, BasicEquality, SubTypeResult}, - SynthesisedArgument, - }, + types::{calling::CallingInput, properties::PropertyKey, SynthesisedArgument}, CheckingData, Constant, Environment, TypeId, }; @@ -42,7 +32,7 @@ pub(crate) fn synthesise_jsx_element( // TODO temp, to be worked out const JSX_NAME: &str = "JSXH"; - let tag_name = element.tag_name.as_str(); + let _tag_name = element.tag_name.as_str(); let tag_name_as_cst_ty = checking_data.types.new_constant_type(Constant::String(element.tag_name.clone())); @@ -368,7 +358,7 @@ fn synthesise_jsx_child( ) -> TypeId { match child { JSXNode::Element(element) => synthesise_jsx_element(element, environment, checking_data), - JSXNode::InterpolatedExpression(expression, expression_position) => { + JSXNode::InterpolatedExpression(expression, _expression_position) => { if matches!(&**expression, Expression::Comment(..)) { return TypeId::UNDEFINED_TYPE; } @@ -425,10 +415,10 @@ fn synthesise_attribute( ) -> (PropertyKey<'static>, TypeId) { let (key, value) = match attribute { // TODO check property exists ...? - JSXAttribute::Static(name, value, attribute_id) => { + JSXAttribute::Static(name, value, _attribute_id) => { (name, checking_data.types.new_constant_type(crate::Constant::String(value.clone()))) } - JSXAttribute::Dynamic(name, expression, attribute_id) => { + JSXAttribute::Dynamic(name, expression, _attribute_id) => { if let Expression::ExpressionFunction(_) = &**expression { // TODO temp context environment.context_type.location = Some("client".to_owned()); diff --git a/checker/src/synthesis/functions.rs b/checker/src/synthesis/functions.rs index 5c4f7ab1..ad6b30ab 100644 --- a/checker/src/synthesis/functions.rs +++ b/checker/src/synthesis/functions.rs @@ -1,13 +1,10 @@ //! Function tings. Contains parameter synthesis, function body synthesis -use std::{env, mem}; - use parser::{ - expressions::ExpressionOrBlock, ASTNode, Block, FunctionBase, FunctionBased, - GenericTypeConstraint, Statement, StatementOrDeclaration, TypeAnnotation, VariableField, - VariableIdentifier, WithComment, + expressions::ExpressionOrBlock, ASTNode, Block, FunctionBased, GenericTypeConstraint, + TypeAnnotation, VariableField, VariableIdentifier, WithComment, }; -use source_map::{SourceId, Span, SpanWithSource}; +use source_map::{SourceId, SpanWithSource}; use crate::{ behavior::functions::{FunctionBehavior, SynthesisableFunction}, @@ -181,7 +178,7 @@ pub(crate) fn synthesise_type_parameters( ) } GenericTypeConstraint::ExtendsKeyOf(_, _) => todo!(), - GenericTypeConstraint::Spread { name, default } => todo!(), + GenericTypeConstraint::Spread { name: _, default: _ } => todo!(), }) .collect() } @@ -256,7 +253,7 @@ pub(super) fn synthesise_type_annotation_function_parameters( .map(|reference| synthesise_type_annotation(reference, environment, checking_data)) .or_else(|| { // See comments-as-type-annotation - if let WithComment::PostfixComment(item, possible_declaration, position) = + if let WithComment::PostfixComment(_item, possible_declaration, position) = ¶meter.name { comment_as_type_annotation( @@ -332,7 +329,7 @@ fn synthesise_function_parameters( }) .collect(); - for parameter in &ast_parameters.rest_parameter { + for _parameter in &ast_parameters.rest_parameter { todo!() // super::variables::hoist_variable_identifier(¶meter.name, environment, is_constant); } @@ -359,7 +356,7 @@ fn get_parameter_name( ) -> String { match parameter { VariableField::Name(name) => name.as_str().to_owned(), - VariableField::Array(items, _) => "todo".to_owned(), + VariableField::Array(_items, _) => "todo".to_owned(), VariableField::Object(_, _) => "todo".to_owned(), } } diff --git a/checker/src/synthesis/hoisting.rs b/checker/src/synthesis/hoisting.rs index 87d545bb..d56d9315 100644 --- a/checker/src/synthesis/hoisting.rs +++ b/checker/src/synthesis/hoisting.rs @@ -2,21 +2,18 @@ use std::{collections::HashMap, iter}; use parser::{ declarations::{export::Exportable, DeclareVariableDeclaration, ExportDeclaration}, - tsx_keywords::Var, ASTNode, Declaration, Decorated, ExpressionOrStatementPosition, Statement, StatementOrDeclaration, VariableIdentifier, WithComment, }; -use source_map::{Span, SpanWithSource}; use crate::{ behavior::{ functions::synthesise_hoisted_statement_function, - modules::{Exported, ImportKind, NamePair}, + modules::{ImportKind, NamePair}, variables::VariableMutability, }, context::Environment, - diagnostics::TypeCheckError, - CheckingData, Constant, ReadFromFS, TypeId, + CheckingData, ReadFromFS, TypeId, }; use super::{ @@ -170,7 +167,7 @@ pub(crate) fn hoist_statements( } // Second stage - for (idx, item) in items.iter().enumerate() { + for (_idx, item) in items.iter().enumerate() { match item { StatementOrDeclaration::Statement(stmt) => { if let Statement::VarVariable(_) = stmt { @@ -255,8 +252,8 @@ pub(crate) fn hoist_statements( parser::Declaration::DeclareVariable(DeclareVariableDeclaration { keyword: _, declarations, - position, - decorators, + position: _, + decorators: _, }) => { for declaration in declarations { let constraint = get_annotation_from_declaration( @@ -282,7 +279,7 @@ pub(crate) fn hoist_statements( } parser::Declaration::Export(exported) => match &exported.on { - parser::declarations::ExportDeclaration::Variable { exported, position } => { + parser::declarations::ExportDeclaration::Variable { exported, position: _ } => { match exported { Exportable::Function(func) => { // TODO unsynthesised function? ... @@ -472,9 +469,9 @@ pub(super) fn hoist_variable_declaration( ) { match declaration { parser::declarations::VariableDeclaration::ConstDeclaration { - keyword, + keyword: _, declarations, - position, + position: _, } => { for declaration in declarations { let constraint = @@ -494,9 +491,9 @@ pub(super) fn hoist_variable_declaration( } } parser::declarations::VariableDeclaration::LetDeclaration { - keyword, + keyword: _, declarations, - position, + position: _, } => { for declaration in declarations { let constraint = @@ -533,7 +530,7 @@ fn get_annotation_from_declaration< )) } // TODO only under config - else if let WithComment::PostfixComment(item, possible_declaration, position) = + else if let WithComment::PostfixComment(_item, possible_declaration, position) = &declaration.name { comment_as_type_annotation( @@ -563,8 +560,6 @@ pub(crate) fn comment_as_type_annotation( environment: &mut crate::context::Context>, checking_data: &mut CheckingData, ) -> Option<(TypeId, source_map::SpanWithSource)> { - use parser::ASTNode; - let source = environment.get_source(); let offset = Some(position.end - 2 - possible_declaration.len() as u32); let annotation = parser::TypeAnnotation::from_string( diff --git a/checker/src/synthesis/interfaces.rs b/checker/src/synthesis/interfaces.rs index 03f23398..75dc63f8 100644 --- a/checker/src/synthesis/interfaces.rs +++ b/checker/src/synthesis/interfaces.rs @@ -5,13 +5,9 @@ use parser::{ use crate::{ behavior::functions::{self, GetterSetter, ThisValue}, - context::{ - facts::Publicity, - Environment, {Context, ContextType}, - }, + context::{facts::Publicity, Context, Environment}, synthesis::parser_property_key_to_checker_property_key, types::{ - poly_types::GenericTypeParameter, properties::{PropertyKey, PropertyValue}, FunctionType, Type, }, @@ -22,7 +18,7 @@ use super::{ functions::synthesise_function_annotation, type_annotations::synthesise_type_annotation, }; -fn get_extends( +fn _get_extends( interface: &InterfaceDeclaration, environment: &mut Environment, checking_data: &mut CheckingData, @@ -58,7 +54,7 @@ pub(crate) enum InterfaceValue { pub(crate) enum ParserPropertyKeyType<'a> { ClassProperty(&'a ParserPropertyKey), - ObjectProperty(&'a ParserPropertyKey), + // ObjectProperty(&'a ParserPropertyKey), Type(TypeId), } @@ -81,10 +77,10 @@ impl SynthesiseInterfaceBehavior for OnToType { }, parser_property_key_to_checker_property_key(key, environment, checking_data), ), - ParserPropertyKeyType::ObjectProperty(key) => ( - Publicity::Public, - parser_property_key_to_checker_property_key(key, environment, checking_data), - ), + // ParserPropertyKeyType::ObjectProperty(key) => ( + // Publicity::Public, + // parser_property_key_to_checker_property_key(key, environment, checking_data), + // ), ParserPropertyKeyType::Type(ty) => (Publicity::Public, PropertyKey::Type(ty)), }; let ty = match value { @@ -133,7 +129,7 @@ pub(super) fn synthesise_signatures { @@ -178,9 +174,9 @@ pub(super) fn synthesise_signatures { let value = synthesise_type_annotation(type_annotation, environment, checking_data); @@ -192,11 +188,11 @@ pub(super) fn synthesise_signatures { // TODO think this is okay let key = synthesise_type_annotation(indexer_type, environment, checking_data); @@ -209,33 +205,33 @@ pub(super) fn synthesise_signatures checking_data.raise_unimplemented_error( "interface constructor", position.with_source(environment.get_source()), ), InterfaceMember::Caller { - parameters, - type_parameters, - return_type, - is_readonly, + parameters: _, + type_parameters: _, + return_type: _, + is_readonly: _, position, } => checking_data.raise_unimplemented_error( "interface caller", position.with_source(environment.get_source()), ), InterfaceMember::Rule { - parameter, - rule, - matching_type, - optionality, - is_readonly, - output_type, + parameter: _, + rule: _, + matching_type: _, + optionality: _, + is_readonly: _, + output_type: _, position, } => checking_data.raise_unimplemented_error( "interface rule", diff --git a/checker/src/synthesis/mod.rs b/checker/src/synthesis/mod.rs index 60898aad..69517c04 100644 --- a/checker/src/synthesis/mod.rs +++ b/checker/src/synthesis/mod.rs @@ -22,10 +22,8 @@ use parser::{ASTNode, PropertyKey as ParserPropertyKey}; use source_map::SourceId; use crate::{ - behavior::modules::Exported, - context::{environment, Context, ContextType, Names}, - types::{properties::PropertyKey, TypeStore}, - CheckingData, Constant, Diagnostic, Environment, Facts, RootContext, TypeId, + context::Names, types::properties::PropertyKey, CheckingData, Diagnostic, Environment, Facts, + RootContext, TypeId, }; use self::{ @@ -33,7 +31,6 @@ use self::{ expressions::{synthesise_expression, synthesise_multiple_expression}, hoisting::hoist_variable_declaration, type_annotations::synthesise_type_annotation, - variables::register_variable, }; pub(super) fn parser_property_key_to_checker_property_key< @@ -99,11 +96,11 @@ impl<'a> From> for Performs<'a> { fn from(value: Option<&'a parser::types::AnnotationPerforms>) -> Self { match value { Some(parser::types::AnnotationPerforms::PerformsConst { - performs_keyword, + performs_keyword: _, identifier, }) => Performs::Const(identifier.clone()), Some(parser::types::AnnotationPerforms::PerformsStatements { - performs_keyword, + performs_keyword: _, statements, }) => Performs::Block(statements), None => Performs::None, @@ -152,7 +149,7 @@ impl crate::ASTImplementation for EznoParser { fn synthesise_module<'a, T: crate::ReadFromFS>( module: &Self::Module<'a>, - source_id: SourceId, + _source_id: SourceId, module_environment: &mut Environment, checking_data: &mut crate::CheckingData, ) { @@ -239,11 +236,7 @@ pub mod interactive { DiagnosticsContainer, RootContext, TypeId, }; - use super::{ - block::{synthesise_block, synthesise_declaration}, - expressions::{synthesise_expression, synthesise_multiple_expression}, - statements::synthesise_statement, - }; + use super::{block::synthesise_block, expressions::synthesise_multiple_expression}; pub struct State<'a, T: crate::ReadFromFS> { checking_data: CheckingData<'a, T, super::EznoParser>, @@ -256,7 +249,7 @@ pub mod interactive { type_definition_files: HashSet, ) -> Result)> { let mut root = RootContext::new_with_primitive_references(); - let entry_point = PathBuf::from("CLI"); + let _entry_point = PathBuf::from("CLI"); let mut checking_data = CheckingData::new(Default::default(), resolver, Default::default()); diff --git a/checker/src/synthesis/statements.rs b/checker/src/synthesis/statements.rs index 294721f3..c0d2eea8 100644 --- a/checker/src/synthesis/statements.rs +++ b/checker/src/synthesis/statements.rs @@ -2,24 +2,14 @@ use super::{ expressions::synthesise_multiple_expression, synthesise_block, variables::register_variable, }; use crate::{ - behavior::{ - assignments::Reference, - iteration::{synthesise_iteration, IterationBehavior}, - operations::CanonicalEqualityAndInequality, - }, - context::{calling::Target, environment, ClosedOverReferencesInScope, ContextId, Scope}, + behavior::iteration::{synthesise_iteration, IterationBehavior}, + context::Scope, diagnostics::TypeCheckError, - events::{apply_event, Event, RootReference}, synthesis::EznoParser, - types::{poly_types::FunctionTypeArguments, Constructor, PolyNature}, - CheckingData, Constant, Environment, TypeId, -}; -use map_vec::Map; -use parser::{ - expressions::MultipleExpression, - statements::{ConditionalElseStatement, UnconditionalElseStatement}, - ASTNode, BlockOrSingleStatement, Expression, Statement, + CheckingData, Environment, TypeId, }; + +use parser::{expressions::MultipleExpression, ASTNode, BlockOrSingleStatement, Statement}; use std::collections::HashMap; pub type ExportedItems = HashMap; @@ -137,7 +127,12 @@ pub(super) fn synthesise_statement( }, ), Statement::ForLoop(stmt) => match &stmt.condition { - parser::statements::ForLoopCondition::ForOf { keyword, variable, of, position } => { + parser::statements::ForLoopCondition::ForOf { + keyword: _, + variable, + of, + position: _, + } => { synthesise_iteration( IterationBehavior::ForOf { lhs: variable.get_ast_ref(), rhs: of }, information.and_then(|info| info.label), @@ -152,7 +147,12 @@ pub(super) fn synthesise_statement( }, ); } - parser::statements::ForLoopCondition::ForIn { keyword, variable, r#in, position } => { + parser::statements::ForLoopCondition::ForIn { + keyword: _, + variable, + r#in, + position: _, + } => { synthesise_iteration( IterationBehavior::ForIn { lhs: variable.get_ast_ref(), rhs: r#in }, information.and_then(|info| info.label), @@ -171,7 +171,7 @@ pub(super) fn synthesise_statement( initialiser, condition, afterthought, - position, + position: _, } => synthesise_iteration( IterationBehavior::For { initialiser, condition, afterthought }, information.and_then(|info| info.label), @@ -183,13 +183,13 @@ pub(super) fn synthesise_statement( ), }, Statement::Block(ref block) => { - let (result, _, _) = environment.new_lexical_environment_fold_into_parent( + let (_result, _, _) = environment.new_lexical_environment_fold_into_parent( Scope::Block {}, checking_data, |environment, checking_data| synthesise_block(&block.0, environment, checking_data), ); } - Statement::Cursor(cursor_id, _) => { + Statement::Cursor(_cursor_id, _) => { todo!("Dump environment data somewhere") } Statement::Continue(label, position) => { @@ -216,7 +216,7 @@ pub(super) fn synthesise_statement( let thrown_position = stmt.2.with_source(environment.get_source()); environment.throw_value(thrown_value, thrown_position); } - Statement::Labelled { position, name, statement } => { + Statement::Labelled { position: _, name, statement } => { // Labels on invalid statements is caught at parse time synthesise_statement( @@ -244,7 +244,7 @@ pub(super) fn synthesise_statement( crate::Scope::Block {}, checking_data, |environment, checking_data| { - if let Some((clause, r#type)) = &stmt.exception_var { + if let Some((clause, _type)) = &stmt.exception_var { // TODO clause.type_annotation register_variable( clause.get_ast_ref(), diff --git a/checker/src/synthesis/type_annotations.rs b/checker/src/synthesis/type_annotations.rs index b1309de0..d5e34c30 100644 --- a/checker/src/synthesis/type_annotations.rs +++ b/checker/src/synthesis/type_annotations.rs @@ -20,20 +20,19 @@ use std::{convert::TryInto, iter::FromIterator}; -use indexmap::IndexSet; use parser::{ type_annotations::{ AnnotationWithBinder, CommonTypes, SpreadKind, TypeCondition, TypeConditionResult, }, ASTNode, TypeAnnotation, }; -use source_map::{SourceId, SpanWithSource}; +use source_map::SpanWithSource; use crate::{ behavior::objects::ObjectBuilder, context::facts::Publicity, - diagnostics::{TypeCheckError, TypeCheckWarning}, - subtyping::{self, type_is_subtype, BasicEquality, SubTypeResult}, + diagnostics::TypeCheckError, + subtyping::{type_is_subtype, BasicEquality, SubTypeResult}, synthesis::functions::synthesise_function_annotation, types::{ get_constraint, @@ -45,8 +44,6 @@ use crate::{ CheckingData, Environment, }; -use crate::context::{Context, ContextType}; - /// Turns a [`parser::TypeAnnotation`] into [`TypeId`] /// /// [`CheckingData`] contains [Memory] and [`crate::ErrorAndWarningHandler`] @@ -112,7 +109,7 @@ pub(super) fn synthesise_type_annotation( }, TypeAnnotation::Union(type_annotations, _) => { // TODO remove duplicates here maybe - let mut iterator = type_annotations + let iterator = type_annotations .iter() .map(|type_annotation| { synthesise_type_annotation(type_annotation, environment, checking_data) @@ -125,7 +122,7 @@ pub(super) fn synthesise_type_annotation( .expect("Empty union") } TypeAnnotation::Intersection(type_annotations, _) => { - let mut iterator = type_annotations + let iterator = type_annotations .iter() .map(|type_annotation| { synthesise_type_annotation(type_annotation, environment, checking_data) @@ -188,7 +185,7 @@ pub(super) fn synthesise_type_annotation( &checking_data.types, ); - if let SubTypeResult::IsNotSubType(matches) = result { + if let SubTypeResult::IsNotSubType(_matches) = result { let error = crate::diagnostics::TypeCheckError::GenericArgumentDoesNotMeetRestriction { parameter_restriction: crate::diagnostics::TypeStringRepresentation::from_type_id( *parameter_restriction, @@ -270,7 +267,7 @@ pub(super) fn synthesise_type_annotation( ) } TypeAnnotation::Readonly(type_annotation, _) => { - let underlying_type = + let _underlying_type = synthesise_type_annotation(type_annotation, environment, checking_data); todo!(); @@ -307,7 +304,7 @@ pub(super) fn synthesise_type_annotation( parameters: _, return_type: _, new_keyword: _, - position, + position: _, } => unimplemented!(), // Object literals are first turned into types as if they were interface declarations and then // returns reference to object literal @@ -406,7 +403,7 @@ pub(super) fn synthesise_type_annotation( } } TypeAnnotation::KeyOf(_, _) => unimplemented!(), - TypeAnnotation::Conditional { condition, resolve_true, resolve_false, position } => { + TypeAnnotation::Conditional { condition, resolve_true, resolve_false, position: _ } => { fn synthesise_condition(result: &TypeConditionResult) -> &TypeAnnotation { match result { TypeConditionResult::Reference(reference) => reference, @@ -461,9 +458,9 @@ fn synthesise_type_condition( checking_data: &mut CheckingData, ) -> TypeId { match condition { - TypeCondition::Extends { ty, extends, position } => { - let item = synthesise_type_annotation(ty, environment, checking_data); - let extends = synthesise_type_annotation(extends, environment, checking_data); + TypeCondition::Extends { ty, extends, position: _ } => { + let _item = synthesise_type_annotation(ty, environment, checking_data); + let _extends = synthesise_type_annotation(extends, environment, checking_data); todo!(); // let ty = Type::Constructor(Constructor::BinaryOperator { // operator: crate::structures::operators::CanonicalBinaryOperator::InstanceOf, @@ -473,6 +470,6 @@ fn synthesise_type_condition( // checking_data.types.register_type(ty) } // TODO requires a kind of strict instance of ??? - TypeCondition::Is { ty, is, position } => todo!(), + TypeCondition::Is { ty: _, is: _, position: _ } => todo!(), } } diff --git a/checker/src/synthesis/variables.rs b/checker/src/synthesis/variables.rs index d83e5d21..9a5c29c2 100644 --- a/checker/src/synthesis/variables.rs +++ b/checker/src/synthesis/variables.rs @@ -1,18 +1,17 @@ use std::borrow::Cow; -use ordered_float::NotNan; use parser::{ declarations::VariableDeclarationItem, ASTNode, ArrayDestructuringField, ObjectDestructuringField, VariableField, VariableIdentifier, }; -use super::{expressions::synthesise_expression, type_annotations::synthesise_type_annotation}; +use super::expressions::synthesise_expression; use crate::{ behavior::variables::VariableMutability, context::{facts::Publicity, Context, ContextType}, diagnostics::{TypeCheckError, TypeStringRepresentation}, synthesis::parser_property_key_to_checker_property_key, - types::{printing::print_type, properties::PropertyKey, Constant}, + types::{printing::print_type, properties::PropertyKey}, CheckingData, Environment, PropertyValue, TypeId, }; @@ -61,8 +60,8 @@ pub(crate) fn register_variable { for (idx, field) in items.iter().enumerate() { match field { - ArrayDestructuringField::Spread(pos, variable) => { - let ty = register_variable_identifier( + ArrayDestructuringField::Spread(_pos, variable) => { + let _ty = register_variable_identifier( variable, environment, checking_data, @@ -94,8 +93,10 @@ pub(crate) fn register_variable todo!(), - crate::context::Logical::Or { left, right } => todo!(), - crate::context::Logical::Implies { on, antecedent } => todo!(), + crate::context::Logical::Or { left: _, right: _ } => todo!(), + crate::context::Logical::Implies { on: _, antecedent: _ } => { + todo!() + } } } else { checking_data @@ -147,14 +148,14 @@ pub(crate) fn register_variable { - let ty = register_variable_identifier( + let _ty = register_variable_identifier( variable, environment, checking_data, behavior.clone(), constraint, ); - if let Some(constraint) = constraint { + if let Some(_constraint) = constraint { // TODO // checking_data // .type_mappings @@ -163,8 +164,8 @@ pub(crate) fn register_variable { - let property_constraint = constraint.map(|constraint| { + ObjectDestructuringField::Map { from, name, default_value: _, position: _ } => { + let _property_constraint = constraint.map(|constraint| { let under = parser_property_key_to_checker_property_key( from, environment, @@ -183,8 +184,10 @@ pub(crate) fn register_variable todo!(), - crate::context::Logical::Or { left, right } => todo!(), - crate::context::Logical::Implies { on, antecedent } => todo!(), + crate::context::Logical::Or { left: _, right: _ } => todo!(), + crate::context::Logical::Implies { on: _, antecedent: _ } => { + todo!() + } } } else { checking_data @@ -244,7 +247,7 @@ pub(super) fn synthesise_variable_declaration_item< >( variable_declaration: &VariableDeclarationItem, environment: &mut Environment, - is_constant: bool, + _is_constant: bool, checking_data: &mut CheckingData, exported: Option, ) { diff --git a/checker/src/type_mappings.rs b/checker/src/type_mappings.rs index 2f853baa..a48fae9c 100644 --- a/checker/src/type_mappings.rs +++ b/checker/src/type_mappings.rs @@ -1,16 +1,13 @@ -use std::{ - collections::{HashMap, HashSet}, - path::PathBuf, -}; +use std::{collections::HashMap, path::PathBuf}; -use source_map::{SourceId, Span, SpanWithSource}; +use source_map::{SourceId, SpanWithSource}; use super::range_map::RangeMap; use crate::{ behavior::variables::VariableWithValue, types::{TypeId, TypeStore}, - FunctionId, GeneralContext, VariableId, + GeneralContext, VariableId, }; /// [`TypeMappings`] is used to retaining information between passes, including the synthesise and checking passes /// This for use in the both use in the compiler and compiler plugins @@ -48,9 +45,9 @@ impl TypeMappings { #[must_use] pub fn print_type_mappings( &self, - source: &str, - env: &GeneralContext, - types: &TypeStore, + _source: &str, + _env: &GeneralContext, + _types: &TypeStore, ) -> String { todo!() // let mut buf = "Expression type mappings:\n".to_owned(); diff --git a/checker/src/types/calling.rs b/checker/src/types/calling.rs index 1c549d51..1202de12 100644 --- a/checker/src/types/calling.rs +++ b/checker/src/types/calling.rs @@ -1,21 +1,18 @@ -use source_map::{SourceId, Span, SpanWithSource}; -use std::{collections::HashMap, iter, vec}; +use source_map::{SourceId, SpanWithSource}; +use std::vec; use crate::{ behavior::{ constant_functions::{call_constant_function, ConstantFunctionError, ConstantOutput}, functions::{FunctionBehavior, ThisValue}, }, - context::{ - calling::CheckThings, get_value_of_variable, CallCheckingBehavior, ContextType, - Environment, Logical, SetPropertyError, - }, + context::{calling::CheckThings, CallCheckingBehavior, ContextType, Environment, Logical}, diagnostics::{TypeCheckError, TypeStringRepresentation, TDZ}, events::{application::ErrorsAndInfo, apply_event, Event, EventResult, RootReference}, - subtyping::{type_is_subtype, BasicEquality, NonEqualityReason, SubTypeResult}, + subtyping::{type_is_subtype, BasicEquality, SubTypeResult}, types::{ functions::SynthesisedArgument, poly_types::generic_type_arguments::TypeArgumentStore, - printing::print_type, substitute, ObjectNature, + substitute, ObjectNature, }, types::{FunctionType, Type}, FunctionId, SpecialExpressions, TypeId, @@ -61,7 +58,7 @@ pub fn call_type_handle_errors { @@ -179,7 +176,7 @@ fn call_logical( todo!("recursive function type") } } - Logical::Or { left, right } => todo!(), + Logical::Or { left: _, right: _ } => todo!(), Logical::Implies { on, antecedent } => call_logical( *on, types, @@ -216,7 +213,7 @@ fn get_logical_callable_from_type( } Type::RootPolyType(_) | Type::Constructor(_) => todo!(), - Type::AliasTo { to, name, parameters } => { + Type::AliasTo { to, name: _, parameters } => { if parameters.is_some() { todo!() } @@ -257,7 +254,7 @@ fn create_generic_function_call( // All properties // Functions free variables etc match argument { - SynthesisedArgument::NonSpread { ty, position } => { + SynthesisedArgument::NonSpread { ty, position: _ } => { match types.get_type_by_id(*ty) { Type::Interface { .. } | Type::AliasTo { .. } @@ -422,7 +419,7 @@ impl FunctionType { #[allow(clippy::too_many_arguments)] pub(crate) fn call( &self, - CallingInput { called_with_new, mut this_value, call_site_type_arguments, call_site }: CallingInput, + CallingInput { called_with_new, this_value, call_site_type_arguments, call_site }: CallingInput, parent_type_arguments: Option, arguments: &[SynthesisedArgument], environment: &mut Environment, @@ -536,7 +533,7 @@ impl FunctionType { false, ); - if let Err(ref err) = call { + if let Err(ref _err) = call { crate::utils::notify!("Calling function with dependent argument failed"); } @@ -592,7 +589,7 @@ impl FunctionType { }; match self.behavior { - FunctionBehavior::ArrowFunction { is_async } => {} + FunctionBehavior::ArrowFunction { is_async: _ } => {} FunctionBehavior::Method { free_this_id, .. } => { let value_of_this = if let Some(value) = this_value.get_passed() { value @@ -608,9 +605,9 @@ impl FunctionType { .type_arguments .insert(free_this_id, vec![(value_of_this, SpanWithSource::NULL_SPAN, 0)]); } - FunctionBehavior::Function { is_async, is_generator, free_this_id } => { + FunctionBehavior::Function { is_async: _, is_generator: _, free_this_id } => { match called_with_new { - CalledWithNew::New { on } => { + CalledWithNew::New { on: _ } => { crate::utils::notify!("TODO set prototype"); // if let Some(prototype) = non_super_prototype { // let this_ty = environment.create_this(prototype, types); @@ -623,7 +620,7 @@ impl FunctionType { vec![(value_of_this, SpanWithSource::NULL_SPAN, 0)], ); } - CalledWithNew::SpecialSuperCall { this_type } => todo!(), + CalledWithNew::SpecialSuperCall { this_type: _ } => todo!(), CalledWithNew::None => { // TODO let value_of_this = this_value.get(environment, types, &call_site); @@ -635,7 +632,7 @@ impl FunctionType { } } } - FunctionBehavior::Constructor { non_super_prototype, this_object_type } => { + FunctionBehavior::Constructor { non_super_prototype: _, this_object_type: _ } => { if let CalledWithNew::None = called_with_new { errors .errors @@ -671,9 +668,9 @@ impl FunctionType { } let SeedingContext { - type_arguments: mut found, - mut type_restrictions, - mut locally_held_functions, + type_arguments: found, + type_restrictions, + locally_held_functions: _, argument_position_and_parameter_idx: _, } = self.synthesise_arguments::( arguments, @@ -689,7 +686,7 @@ impl FunctionType { for (item, values) in found { // TODO only first ?? - let (mut value, argument_position, param) = + let (value, argument_position, param) = values.into_iter().next().expect("no type argument ...?"); if let Some(restrictions_for_item) = type_restrictions.get(&item) { @@ -702,7 +699,7 @@ impl FunctionType { let result = type_is_subtype(*restriction, value, &mut behavior, environment, types); - if let SubTypeResult::IsNotSubType(err) = result { + if let SubTypeResult::IsNotSubType(_err) = result { let argument_type = TypeStringRepresentation::from_type_id( value, &environment.as_general_context(), @@ -755,7 +752,7 @@ impl FunctionType { } // Evaluate effects directly into environment - let mut early_return = behavior.new_function_target(self.id, |target| { + let early_return = behavior.new_function_target(self.id, |target| { type_arguments.closure_id = if self.closed_over_variables.is_empty() { None } else { @@ -823,9 +820,9 @@ impl FunctionType { if let CalledWithNew::New { .. } = called_with_new { // TODO ridiculous early return primitive rule match self.behavior { - FunctionBehavior::ArrowFunction { is_async } => todo!(), - FunctionBehavior::Method { is_async, is_generator, .. } => todo!(), - FunctionBehavior::Function { is_async, is_generator, free_this_id } => { + FunctionBehavior::ArrowFunction { is_async: _ } => todo!(), + FunctionBehavior::Method { .. } => todo!(), + FunctionBehavior::Function { is_async: _, is_generator: _, free_this_id } => { let new_instance_type = type_arguments .local_arguments .remove(&free_this_id) @@ -840,7 +837,7 @@ impl FunctionType { found_dependent_argument: false, }); } - FunctionBehavior::Constructor { non_super_prototype, this_object_type } => { + FunctionBehavior::Constructor { non_super_prototype: _, this_object_type } => { crate::utils::notify!("Registered this {:?}", this_object_type); let new_instance_type = type_arguments .local_arguments @@ -892,6 +889,7 @@ impl FunctionType { let argument = arguments.get(parameter_idx); let argument_type_and_pos = argument.map(|argument| { + #[allow(irrefutable_let_patterns)] if let SynthesisedArgument::NonSpread { ty, position: pos } = argument { (ty, pos) } else { @@ -926,7 +924,7 @@ impl FunctionType { types, ); - if let SubTypeResult::IsNotSubType(reasons) = result { + if let SubTypeResult::IsNotSubType(_reasons) = result { errors.errors.push(FunctionCallingError::InvalidArgumentType { parameter_type: TypeStringRepresentation::from_type_id( parameter.ty, @@ -988,9 +986,10 @@ impl FunctionType { } if self.parameters.parameters.len() < arguments.len() { if let Some(ref rest_parameter) = self.parameters.rest_parameter { - for (idx, argument) in + for (_idx, argument) in arguments.iter().enumerate().skip(self.parameters.parameters.len()) { + #[allow(irrefutable_let_patterns)] let SynthesisedArgument::NonSpread { ty: argument_type, position: argument_pos, @@ -1022,7 +1021,7 @@ impl FunctionType { types, ); - if let SubTypeResult::IsNotSubType(reasons) = result { + if let SubTypeResult::IsNotSubType(_reasons) = result { errors.errors.push(FunctionCallingError::InvalidArgumentType { parameter_type: TypeStringRepresentation::from_type_id( rest_parameter.item_type, diff --git a/checker/src/types/casts.rs b/checker/src/types/casts.rs index 5aae1ea9..4cab3076 100644 --- a/checker/src/types/casts.rs +++ b/checker/src/types/casts.rs @@ -44,6 +44,6 @@ pub(crate) fn cast_as_boolean(cst: &Constant, strict_casts: bool) -> Result true, Constant::Boolean(value) => *value, Constant::NaN | Constant::Undefined | Constant::Null => false, - Constant::Symbol { key } => todo!(), + Constant::Symbol { key: _ } => todo!(), }) } diff --git a/checker/src/types/classes.rs b/checker/src/types/classes.rs index 8aee87ad..f334035a 100644 --- a/checker/src/types/classes.rs +++ b/checker/src/types/classes.rs @@ -1,8 +1,6 @@ use crate::{ - behavior::functions::{ClassPropertiesToRegister, GetterSetter}, - context::facts::Publicity, - events::Event, - ASTImplementation, CheckingData, Environment, PropertyValue, TypeId, + behavior::functions::ClassPropertiesToRegister, context::facts::Publicity, events::Event, + CheckingData, Environment, PropertyValue, TypeId, }; use super::properties::PropertyKey; @@ -45,7 +43,7 @@ pub struct RegisterClassPropertiesEvent { pub class_prototype: TypeId, } -fn register_properties_into_store( +fn _register_properties_into_store( environment: &mut Environment, class_prototype: TypeId, properties: ClassPropertiesToRegister<'_, A>, @@ -70,7 +68,7 @@ fn register_properties_into_store bool { +pub fn is_primitive(ty: TypeId, _types: &TypeStore) -> bool { if matches!(ty, TypeId::BOOLEAN_TYPE | TypeId::NUMBER_TYPE | TypeId::STRING_TYPE) { return true; } @@ -456,7 +455,7 @@ pub enum PropertyError { pub(crate) fn is_explicit_generic(on: TypeId, types: &TypeStore) -> bool { if let Type::RootPolyType(PolyNature::Generic { .. }) = types.get_type_by_id(on) { true - } else if let Type::Constructor(Constructor::Property { on, under, result }) = + } else if let Type::Constructor(Constructor::Property { on, under, result: _ }) = types.get_type_by_id(on) { is_explicit_generic(*on, types) @@ -474,9 +473,9 @@ pub(crate) fn get_constraint(on: TypeId, types: &TypeStore) -> Option { Type::RootPolyType(nature) => { let based_on = match nature { PolyNature::Parameter { fixed_to } => fixed_to, - PolyNature::Generic { name, eager_fixed } => eager_fixed, + PolyNature::Generic { name: _, eager_fixed } => eager_fixed, PolyNature::Open(ty) => ty, - PolyNature::FreeVariable { reference, based_on } => based_on, + PolyNature::FreeVariable { reference: _, based_on } => based_on, PolyNature::RecursiveFunction(_, return_ty) => return_ty, }; @@ -542,7 +541,7 @@ pub(crate) fn get_constraint(on: TypeId, types: &TypeStore) -> Option { Some(TypeId::NUMBER_TYPE) } } - Constructor::UnaryOperator { operand, operator } => { + Constructor::UnaryOperator { operand: _, operator: _ } => { todo!() // if *constraint == TypeId::ANY_TYPE && mutable_context { // let (operand, operator) = (operand.clone(), operator.clone()); @@ -559,7 +558,7 @@ pub(crate) fn get_constraint(on: TypeId, types: &TypeStore) -> Option { // Some(*constraint) // } } - Constructor::Image { on, with, result } => { + Constructor::Image { on: _, with: _, result } => { Some(result) // TODO temp // if let PolyPointer::Fixed(result) = result { @@ -598,7 +597,7 @@ pub(crate) fn get_constraint(on: TypeId, types: &TypeStore) -> Option { // } // } } - Constructor::Property { on, under, result } => { + Constructor::Property { on: _, under: _, result } => { crate::utils::notify!("Here, result of a property get"); Some(result) diff --git a/checker/src/types/others.rs b/checker/src/types/others.rs index a900bc03..75fa9480 100644 --- a/checker/src/types/others.rs +++ b/checker/src/types/others.rs @@ -15,7 +15,7 @@ pub(crate) fn create_object_for_type( ) -> TypeId { let mut obj = ObjectBuilder::new(None, types, &mut environment.facts); // env.facts.new_object(None, types, false); match types.get_type_by_id(ty) { - Type::AliasTo { to, name, parameters } => todo!(), + Type::AliasTo { to: _, name: _, parameters: _ } => todo!(), ty @ (Type::And(left, right) | Type::Or(left, right)) => { let kind = if matches!(ty, Type::And(..)) { "and" } else { "or" }; let (left, right) = (*left, *right); @@ -47,7 +47,7 @@ pub(crate) fn create_object_for_type( } Type::RootPolyType(_) => todo!(), Type::Constructor(_) => todo!(), - Type::Interface { name, parameters, nominal } => { + Type::Interface { name, parameters: _, nominal: _ } => { let name = name.clone(); // TODO: Do we need positions for the following appends? diff --git a/checker/src/types/poly_types/generics/generic_structure.rs b/checker/src/types/poly_types/generics/generic_structure.rs index 5409a72a..c9439c98 100644 --- a/checker/src/types/poly_types/generics/generic_structure.rs +++ b/checker/src/types/poly_types/generics/generic_structure.rs @@ -1,5 +1,5 @@ use super::generic_type_arguments::FunctionTypeArguments; -use crate::{CheckingData, DiagnosticsContainer, TypeId}; +use crate::TypeId; /// A instance of a generic typed object #[derive(Clone, Debug)] @@ -32,12 +32,7 @@ impl From> for GenericStructureArgumentValue { } } -impl GenericStructureTypeArguments { - pub(crate) fn get_value_for_id(&self, id: TypeId) -> Option<&GenericStructureTypeArgument> { - self.0.iter().find(|item| item.matching_id == id) - } -} - +#[allow(unused)] #[derive(Clone, Debug)] pub struct GenericStructureTypeArgument { pub(crate) matching_id: TypeId, @@ -47,7 +42,7 @@ pub struct GenericStructureTypeArgument { } impl From for FunctionTypeArguments { - fn from(instance_of_generics_arguments: GenericStructureTypeArguments) -> Self { + fn from(_instance_of_generics_arguments: GenericStructureTypeArguments) -> Self { todo!() // TypeArguments { // structure_arguments: todo!(), diff --git a/checker/src/types/poly_types/generics/generic_type_arguments.rs b/checker/src/types/poly_types/generics/generic_type_arguments.rs index fb0755af..c46e596d 100644 --- a/checker/src/types/poly_types/generics/generic_type_arguments.rs +++ b/checker/src/types/poly_types/generics/generic_type_arguments.rs @@ -4,12 +4,11 @@ use crate::{ behavior::functions::{ClosureChain, ClosureId}, context::facts::Facts, - types::TypeStore, - CheckingData, TypeId, + TypeId, }; use map_vec::Map as SmallMap; -use source_map::{Span, SpanWithSource}; +use source_map::SpanWithSource; use std::{fmt::Debug, iter::FromIterator}; @@ -98,7 +97,7 @@ pub(crate) trait TypeArgumentStore { } impl ClosureChain for FunctionTypeArguments { - fn get_fact_from_closure(&self, fact: &Facts, mut cb: T) -> Option + fn get_fact_from_closure(&self, _fact: &Facts, cb: T) -> Option where T: Fn(ClosureId) -> Option, { @@ -161,7 +160,7 @@ impl TypeArgumentStore for FunctionTypeArguments { // TODO temp: for type alias specialisation impl TypeArgumentStore for SmallMap { fn get_structure_argument(&self, id: TypeId) -> Option { - self.get(&id).map(|(value, pos)| *value) + self.get(&id).map(|(value, _pos)| *value) } fn get_local_argument(&self, id: TypeId) -> Option { @@ -195,7 +194,7 @@ impl TypeArgumentStore for StructureGenericArguments { self.type_arguments.get(&id).map(|(ty, _)| *ty) } - fn get_local_argument(&self, id: TypeId) -> Option { + fn get_local_argument(&self, _id: TypeId) -> Option { None } diff --git a/checker/src/types/poly_types/generics/generic_type_parameters.rs b/checker/src/types/poly_types/generics/generic_type_parameters.rs index feae4d4a..2be463e0 100644 --- a/checker/src/types/poly_types/generics/generic_type_parameters.rs +++ b/checker/src/types/poly_types/generics/generic_type_parameters.rs @@ -102,7 +102,7 @@ impl PartialEq for GenericTypeParameter { // } /// TODO remove intermediate function -fn get_type_from_arguments_using_generic_type_parameter_id( +fn _get_type_from_arguments_using_generic_type_parameter_id( type_id: TypeId, type_arguments: &FunctionTypeArguments, ) -> TypeId { diff --git a/checker/src/types/poly_types/generics/mod.rs b/checker/src/types/poly_types/generics/mod.rs index c0431171..0adf4255 100644 --- a/checker/src/types/poly_types/generics/mod.rs +++ b/checker/src/types/poly_types/generics/mod.rs @@ -4,16 +4,12 @@ pub mod generic_structure; pub mod generic_type_arguments; pub mod generic_type_parameters; -use std::collections::HashMap; - pub use generic_structure::*; pub(crate) use generic_type_arguments::FunctionTypeArguments; pub use generic_type_parameters::*; use source_map::SpanWithSource; -use crate::{types::FunctionType, CheckingData, FunctionId, TypeId}; - -pub(crate) struct UnmatchedGenericsError; +use crate::{types::FunctionType, FunctionId, TypeId}; /// When comparing parameters to arguments this sets type arguments pub(crate) struct SeedingContext { @@ -55,10 +51,4 @@ impl SeedingContext { self.type_arguments.insert(on, vec![arg]); }; } - - /// TODO remove - pub(crate) fn set_this(&mut self, arg: TypeId) { - self.type_arguments - .insert(TypeId::ANY_INFERRED_FREE_THIS, vec![(arg, SpanWithSource::NULL_SPAN, 0)]); - } } diff --git a/checker/src/types/poly_types/substitution.rs b/checker/src/types/poly_types/substitution.rs index f6003b0a..807cf878 100644 --- a/checker/src/types/poly_types/substitution.rs +++ b/checker/src/types/poly_types/substitution.rs @@ -2,7 +2,7 @@ use crate::{ behavior::{ - functions::{ClosureId, ThisValue}, + functions::ThisValue, operations::{ evaluate_equality_inequality_operation, evaluate_mathematical_operation, evaluate_pure_unary_operator, @@ -46,7 +46,7 @@ pub(crate) fn substitute( }; curry_arguments(arguments, types, id) } - Type::FunctionReference(f, t) => curry_arguments(arguments, types, id), + Type::FunctionReference(_f, _t) => curry_arguments(arguments, types, id), Type::And(lhs, rhs) => { let rhs = *rhs; let lhs = substitute(*lhs, arguments, environment, types); @@ -112,7 +112,7 @@ pub(crate) fn substitute( condition, truthy_result, else_result, - result_union, + result_union: _, } => { let condition = substitute(condition, arguments, environment, types); @@ -234,7 +234,7 @@ pub(crate) fn substitute( } Constructor::StructureGenerics(StructureGenerics { on, - arguments: mut structure_arguments, + arguments: structure_arguments, }) => { let type_arguments = structure_arguments .type_arguments @@ -290,8 +290,8 @@ pub(crate) fn substitute( Constructor::TypeOperator(..) => todo!(), Constructor::TypeRelationOperator(op) => match op { crate::types::TypeRelationOperator::Extends { ty, extends } => { - let ty = substitute(ty, arguments, environment, types); - let extends = substitute(extends, arguments, environment, types); + let _ty = substitute(ty, arguments, environment, types); + let _extends = substitute(extends, arguments, environment, types); todo!(); // TODO special behavior that doesn't have errors... diff --git a/checker/src/types/printing.rs b/checker/src/types/printing.rs index 6ab1a5d1..927c4f7a 100644 --- a/checker/src/types/printing.rs +++ b/checker/src/types/printing.rs @@ -1,8 +1,5 @@ use iterator_endiate::EndiateIteratorExt; -use std::{ - collections::{HashMap, HashSet}, - fmt::Write, -}; +use std::collections::HashSet; use super::{properties::PropertyKey, PolyNature, Type, TypeArguments, TypeId, TypeStore}; use crate::{ @@ -52,7 +49,7 @@ fn print_type_into_buf( let ty = types.get_type_by_id(id); match ty { - Type::AliasTo { to, name, parameters } => { + Type::AliasTo { to: _, name, parameters: _ } => { buf.push_str(name); } Type::And(a, b) => { @@ -114,7 +111,7 @@ fn print_type_into_buf( condition, truthy_result, else_result, - result_union, + result_union: _, } => { if debug { write!(buf, "[? {id:? }").unwrap(); @@ -170,10 +167,10 @@ fn print_type_into_buf( } print_type_into_buf(*rhs, buf, cycles, args, types, ctx, debug); } - Constructor::UnaryOperator { operator, operand } => todo!(), + Constructor::UnaryOperator { operator: _, operand: _ } => todo!(), Constructor::TypeOperator(_) => todo!(), Constructor::TypeRelationOperator(_) => todo!(), - Constructor::Image { on, with, result } => { + Constructor::Image { on: _, with: _, result } => { // TODO arguments and stuff buf.push_str("[func result] "); print_type_into_buf(*result, buf, cycles, args, types, ctx, debug); @@ -207,7 +204,7 @@ fn print_type_into_buf( print_type_into_buf(*result, buf, cycles, args, types, ctx, debug); } } - constructor => { + _constructor => { let base = get_constraint(id, types).unwrap(); print_type_into_buf(base, buf, cycles, args, types, ctx, debug); } @@ -258,7 +255,7 @@ fn print_type_into_buf( // // let ty = memory.get_fixed_constraint(constraint); // // TypeDisplay::fmt(ty, buf, indent, cycles, memory); // } - if let Some(ref default) = param.default { + if let Some(ref _default) = param.default { todo!() } if not_at_end { @@ -324,8 +321,8 @@ fn print_type_into_buf( buf.push_str(" }"); } Type::SpecialObject(special_object) => match special_object { - crate::behavior::objects::SpecialObjects::Promise { events } => todo!(), - crate::behavior::objects::SpecialObjects::Generator { position } => todo!(), + crate::behavior::objects::SpecialObjects::Promise { events: () } => todo!(), + crate::behavior::objects::SpecialObjects::Generator { position: () } => todo!(), crate::behavior::objects::SpecialObjects::Proxy { handler, over } => { // Copies from node behavior buf.push_str("Proxy [ "); @@ -346,7 +343,7 @@ fn print_type_into_buf( print_type_into_buf(value, buf, cycles, args, types, ctx, debug); } crate::behavior::variables::VariableMutability::Mutable { - reassignment_constraint, + reassignment_constraint: _, } => todo!(), }; if not_at_end { @@ -426,15 +423,17 @@ pub(crate) fn print_property_key_into_buf( } pub fn debug_effects( - mut buf: &mut String, + buf: &mut String, events: &[Event], types: &TypeStore, ctx: &GeneralContext, debug: bool, ) { + use std::fmt::Write; + for event in events { match event { - Event::ReadsReference { reference, reflects_dependency, position } => { + Event::ReadsReference { reference, reflects_dependency, position: _ } => { let name = reference.get_name(ctx); buf.write_fmt(format_args!("read '{name}' into {reflects_dependency:?}")).unwrap(); } @@ -444,7 +443,7 @@ pub fn debug_effects( buf.push_str(" = "); print_type_into_buf(*value, buf, &mut HashSet::new(), None, types, ctx, debug); } - Event::Getter { on, under, reflects_dependency, publicity, position } => { + Event::Getter { on, under, reflects_dependency, publicity: _, position: _ } => { buf.push_str("read "); print_type_into_buf(*on, buf, &mut HashSet::new(), None, types, ctx, debug); if let PropertyKey::String(_) = under { @@ -461,7 +460,7 @@ pub fn debug_effects( ); buf.write_fmt(format_args!(" into {reflects_dependency:?}")).unwrap(); } - Event::Setter { on, under, new, initialization, publicity, position } => { + Event::Setter { on, under, new, initialization, publicity: _, position: _ } => { if *initialization { buf.write_fmt(format_args!("initialise {:?} with ", *on)).unwrap(); if let PropertyValue::Value(new) = new { @@ -503,11 +502,11 @@ pub fn debug_effects( } Event::CallsType { on, - with, - reflects_dependency, + with: _, + reflects_dependency: _, timing, - called_with_new, - position, + called_with_new: _, + position: _, } => { buf.push_str("call "); print_type_into_buf(*on, buf, &mut HashSet::new(), None, types, ctx, debug); @@ -522,7 +521,7 @@ pub fn debug_effects( buf.push_str("throw "); print_type_into_buf(*value, buf, &mut HashSet::new(), None, types, ctx, debug); } - Event::Conditionally { condition, events_if_truthy, else_events, position } => { + Event::Conditionally { condition, events_if_truthy, else_events, position: _ } => { buf.push_str("if "); print_type_into_buf(*condition, buf, &mut HashSet::new(), None, types, ctx, debug); buf.push_str(" then "); @@ -532,14 +531,14 @@ pub fn debug_effects( debug_effects(buf, else_events, types, ctx, debug); } } - Event::Return { returned, returned_position } => { + Event::Return { returned, returned_position: _ } => { buf.push_str("return "); print_type_into_buf(*returned, buf, &mut HashSet::new(), None, types, ctx, debug); } Event::CreateObject { - prototype, + prototype: _, referenced_in_scope_as, - position, + position: _, is_function_this, } => { if *is_function_this { @@ -555,7 +554,7 @@ pub fn debug_effects( Event::Continue { .. } => { buf.push_str("continue"); } - Event::Iterate { iterate_over, initial: _, kind } => { + Event::Iterate { iterate_over, initial: _, kind: _ } => { buf.push_str("iterate\n"); debug_effects(buf, iterate_over, types, ctx, debug); buf.push_str("end"); diff --git a/checker/src/types/properties.rs b/checker/src/types/properties.rs index b08dea70..78849611 100644 --- a/checker/src/types/properties.rs +++ b/checker/src/types/properties.rs @@ -2,20 +2,19 @@ use std::borrow::Cow; use crate::{ behavior::functions::ThisValue, - context::{environment, facts::Publicity, CallCheckingBehavior, Logical, SetPropertyError}, + context::{facts::Publicity, CallCheckingBehavior, Logical, SetPropertyError}, diagnostics::TypeStringRepresentation, events::Event, - subtyping::{type_is_subtype, type_is_subtype_of_property, SubTypeResult}, + subtyping::{type_is_subtype_of_property, SubTypeResult}, types::{ calling::CallingInput, get_constraint, - poly_types::generic_type_arguments::StructureGenericArguments, printing::print_type, - substitute, FunctionType, ObjectNature, StructureGenerics, + poly_types::generic_type_arguments::StructureGenericArguments, substitute, FunctionType, + ObjectNature, StructureGenerics, }, Constant, Environment, TypeId, }; -use ordered_float::NotNan; -use source_map::{SourceId, Span, SpanWithSource}; +use source_map::{SourceId, SpanWithSource}; use super::{calling::CalledWithNew, Constructor, Type, TypeStore}; @@ -54,7 +53,7 @@ impl<'a> PropertyKey<'a> { Constant::String(s) => PropertyKey::String(Cow::Owned(s.to_owned())), Constant::Boolean(_) => todo!(), Constant::Regexp(_) => todo!(), - Constant::Symbol { key } => todo!(), + Constant::Symbol { key: _ } => todo!(), Constant::Undefined => todo!(), Constant::Null => todo!(), Constant::NaN => todo!(), @@ -74,11 +73,11 @@ impl<'a> PropertyKey<'a> { } impl crate::serialization::BinarySerializable for PropertyKey<'static> { - fn serialize(self, buf: &mut Vec) { + fn serialize(self, _buf: &mut Vec) { todo!() } - fn deserialize>(iter: &mut I, source: SourceId) -> Self { + fn deserialize>(_iter: &mut I, _source: SourceId) -> Self { todo!() } } @@ -149,22 +148,14 @@ pub(crate) fn get_property( types: &mut TypeStore, position: SpanWithSource, ) -> Option<(PropertyKind, TypeId)> { - enum GetResult { - AccessIntroducesDependence(TypeId), - /// These always return the same value - FromAObject(TypeId), - } - if on == TypeId::ERROR_TYPE || matches!(under, PropertyKey::Type(under) if under == TypeId::ERROR_TYPE) { return Some((PropertyKind::Direct, TypeId::ERROR_TYPE)); } - // TODO rearrange here - - let value: GetResult = if let Some(constraint) = get_constraint(on, types) { - GetResult::AccessIntroducesDependence(evaluate_get_on_poly( + if let Some(constraint) = get_constraint(on, types) { + evaluate_get_on_poly( constraint, on, publicity, @@ -173,7 +164,8 @@ pub(crate) fn get_property( top_environment, behavior, types, - )?) + position, + ) } else if top_environment.possibly_mutated_objects.contains(&on) { let items = top_environment.get_object_constraints(on); let constraint = if items.len() == 1 { @@ -183,7 +175,7 @@ pub(crate) fn get_property( } else { todo!("build and type") }; - GetResult::AccessIntroducesDependence(evaluate_get_on_poly( + evaluate_get_on_poly( constraint, on, publicity, @@ -192,40 +184,15 @@ pub(crate) fn get_property( top_environment, behavior, types, - )?) + position, + ) } else { // if environment.get_poly_base(under, types).is_some() { // todo!() // } // TODO - return get_from_an_object(on, publicity, under, top_environment, behavior, types); - }; - - let reflects_dependency = match value { - GetResult::AccessIntroducesDependence(s) => Some(s), - GetResult::FromAObject(_) => None, - }; - - behavior.get_latest_facts(top_environment).events.push(Event::Getter { - on, - under: under.into_owned(), - reflects_dependency, - publicity, - position, - }); - - let (GetResult::AccessIntroducesDependence(value) | GetResult::FromAObject(value)) = value - else { - unreachable!() - }; - - // Carry the frozen part - // if let Some(frozen) = environment.is_frozen(on) { - // environment.facts.frozen.insert(value, frozen); - // } - - // TODO generic - Some((PropertyKind::Direct, value)) + get_from_an_object(on, publicity, under, top_environment, behavior, types) + } } fn get_from_an_object( @@ -251,12 +218,12 @@ fn get_from_an_object( let ty = types.get_type_by_id(value); match ty { // TODO function :: bind_this - Type::Function(func, state) => { + Type::Function(func, _state) => { let func = types .register_type(Type::Function(*func, ThisValue::Passed(on))); Some((PropertyKind::Direct, func)) } - Type::FunctionReference(func, this_argument) => { + Type::FunctionReference(func, _this_argument) => { crate::utils::notify!("TODO temp reference function business"); let func = types.register_type(Type::FunctionReference( *func, @@ -282,7 +249,7 @@ fn get_from_an_object( StructureGenerics { on: sg_on, arguments }, )) => { // TODO not great... need less overhead - if let Type::Function(f, p) = types.get_type_by_id(*sg_on) { + if let Type::Function(f, _p) = types.get_type_by_id(*sg_on) { let arguments = arguments.clone(); let f = types .register_type(Type::Function(*f, ThisValue::Passed(on))); @@ -300,7 +267,7 @@ fn get_from_an_object( Type::Constructor(constructor) => { unreachable!("Interesting property on {:?}", constructor); } - Type::AliasTo { to, name, parameters } => { + Type::AliasTo { to: _, name: _, parameters: _ } => { todo!() } } @@ -359,18 +326,19 @@ fn get_from_an_object( resolve_property_on_logical(result, types, on, environment, behavior) } -// https://github.com/kaleidawave/ezno/pull/88 #[allow(clippy::too_many_arguments)] +#[allow(clippy::needless_pass_by_value)] fn evaluate_get_on_poly( constraint: TypeId, on: TypeId, publicity: Publicity, under: PropertyKey, - with: Option, - environment: &mut Environment, - behavior: &E, + _with: Option, + top_environment: &mut Environment, + behavior: &mut E, types: &mut TypeStore, -) -> Option { + position: SpanWithSource, +) -> Option<(PropertyKind, TypeId)> { fn resolve_logical_with_poly( fact: Logical, on: TypeId, @@ -507,11 +475,21 @@ fn evaluate_get_on_poly( } } - let fact = environment.get_property_unbound(constraint, publicity, under.clone(), types)?; + let fact = top_environment.get_property_unbound(constraint, publicity, under.clone(), types)?; // crate::utils::notify!("unbound is is {:?}", fact); - resolve_logical_with_poly(fact, on, under, None, environment, types) + let value = resolve_logical_with_poly(fact, on, under.clone(), None, top_environment, types)?; + + behavior.get_latest_facts(top_environment).events.push(Event::Getter { + on, + under: under.into_owned(), + reflects_dependency: Some(value), + publicity, + position, + }); + + Some((PropertyKind::Direct, value)) } /// Aka a assignment to a property, **INCLUDING initialization of a new one** @@ -636,7 +614,7 @@ pub(crate) fn set_property( } }, Logical::Or { .. } => todo!(), - Logical::Implies { on: implies_on, antecedent } => { + Logical::Implies { on: _implies_on, antecedent: _ } => { crate::utils::notify!("Check that `implies_on` could be a setter here"); let facts = behavior.get_latest_facts(environment); facts.current_properties.entry(on).or_default().push(( diff --git a/checker/src/types/store.rs b/checker/src/types/store.rs index 8c00d129..c131abb7 100644 --- a/checker/src/types/store.rs +++ b/checker/src/types/store.rs @@ -1,14 +1,11 @@ use std::collections::{HashMap, HashSet}; use crate::{ - behavior::{ - functions::{ClosureId, FunctionBehavior}, - operations::{CanonicalEqualityAndInequality, MathematicalAndBitwise}, - }, + behavior::functions::{ClosureId, FunctionBehavior}, context::{get_on_ctx, Context, ContextType, Logical}, types::FunctionType, types::{PolyNature, Type}, - Constant, FunctionId, GeneralContext, TypeId, + FunctionId, GeneralContext, TypeId, }; use super::{ @@ -22,9 +19,10 @@ pub struct TypeStore { types: Vec, pub(crate) functions: HashMap, - pub(crate) dependent_dependencies: HashMap>, - - pub(crate) specialisations: HashMap>, + // TODO + pub(crate) _dependent_dependencies: HashMap>, + // TODO + pub(crate) _specialisations: HashMap>, /// can be used for tree shaking pub called_functions: HashSet, @@ -36,7 +34,7 @@ pub struct TypeStore { impl Default for TypeStore { fn default() -> Self { // These have to be in the order of TypeId - let mut types = vec![ + let types = vec![ Type::Interface { name: "error".to_owned(), parameters: None, nominal: true }, Type::Interface { name: "never".to_owned(), parameters: None, nominal: true }, Type::Interface { name: "any".to_owned(), parameters: None, nominal: true }, @@ -93,8 +91,8 @@ impl Default for TypeStore { Self { types: types.clone(), functions: HashMap::new(), - dependent_dependencies: Default::default(), - specialisations: Default::default(), + _dependent_dependencies: Default::default(), + _specialisations: Default::default(), called_functions: Default::default(), closure_counter: 0, } @@ -305,10 +303,10 @@ impl TypeStore { antecedent: arguments.clone(), }) } - Type::Constructor(constructor) => { + Type::Constructor(_constructor) => { // Don't think any properties exist on this poly type // TODO None here - let constraint = get_constraint(on, self).unwrap(); + let _constraint = get_constraint(on, self).unwrap(); // TODO might need to send more information here, rather than forgetting via .get_type self.get_fact_about_type(ctx, on, resolver, data) } diff --git a/checker/src/types/subtyping.rs b/checker/src/types/subtyping.rs index e3bbb60d..1df46ee1 100644 --- a/checker/src/types/subtyping.rs +++ b/checker/src/types/subtyping.rs @@ -1,21 +1,18 @@ //! Type subtyping / order / subtype checking. -use source_map::{BaseSpan, SourceId, Span, SpanWithSource}; +use source_map::SpanWithSource; use crate::{ context::{Environment, GeneralContext, Logical}, types::{ - poly_types::generic_type_arguments::TypeArgumentStore, printing::print_type, FunctionType, - TypeStore, + poly_types::generic_type_arguments::TypeArgumentStore, printing::print_type, TypeStore, }, - FunctionId, PropertyValue, TypeId, + PropertyValue, TypeId, }; use super::{ - get_constraint, - poly_types::{generic_type_arguments::StructureGenericArguments, SeedingContext}, - properties::PropertyKey, - Constructor, PolyNature, StructureGenerics, Type, TypeArguments, + get_constraint, properties::PropertyKey, Constructor, PolyNature, StructureGenerics, Type, + TypeArguments, }; pub use super::{BasicEquality, NonEqualityReason, PropertyError, SubTypeResult, SubtypeBehavior}; @@ -244,7 +241,7 @@ fn type_is_subtype2( environment, restriction_mode, ); - let left = print_type(base_type, types, &environment.as_general_context(), true); + let _left = print_type(base_type, types, &environment.as_general_context(), true); // crate::utils::notify!("Left object {}", left); @@ -379,7 +376,7 @@ fn type_is_subtype2( // TODO temp fix for general parameters if let Type::Object(_) = right_ty { - for (publicity, property, value) in environment.get_properties_on_type(ty) { + for (_publicity, property, value) in environment.get_properties_on_type(ty) { // Assume every property on itself is either number or 'length' match property { PropertyKey::String(a) if a == "length" => { @@ -464,12 +461,12 @@ fn type_is_subtype2( Constructor::TypeOperator(_) => todo!(), Constructor::TypeRelationOperator(_) => todo!(), Constructor::ConditionalResult { - condition, - truthy_result, - else_result, - result_union, + condition: _, + truthy_result: _, + else_result: _, + result_union: _, } => todo!(), - Constructor::Image { on, with, result } => todo!(), + Constructor::Image { on: _, with: _, result: _ } => todo!(), Constructor::Property { on, under, result: _ } => { // Ezno custom behavior // TODO might be based of T @@ -550,7 +547,7 @@ fn type_is_subtype2( SubTypeResult::IsNotSubType(NonEqualityReason::Mismatch) } Type::And(_, _) => todo!(), - Type::Or(left, right) => { + Type::Or(_left, _right) => { unreachable!() // TODO fails if RHS is also OR type :( // let right = *right; @@ -718,13 +715,8 @@ fn check_properties( } } -type ReadableSubTypeErrorMessage = Vec; - impl NonEqualityReason { - pub(crate) fn into_error_message( - self, - environment: &GeneralContext, - ) -> ReadableSubTypeErrorMessage { + pub(crate) fn _into_error_message(self, _environment: &GeneralContext) -> Vec { match self { NonEqualityReason::GenericParameterMismatch | NonEqualityReason::MissingParameter diff --git a/checker/src/utils.rs b/checker/src/utils.rs index 377c651c..f3b9abbe 100644 --- a/checker/src/utils.rs +++ b/checker/src/utils.rs @@ -1,61 +1,3 @@ -pub(crate) fn format_list(mut iterator: impl ExactSizeIterator) -> String { - use std::fmt::Write; - - match iterator.len() { - 0 => String::new(), - 1 => iterator.next().unwrap().to_string(), - 2 => format!("{} and {}", iterator.next().unwrap(), iterator.next().unwrap()), - val => { - let mut buf = String::new(); - for value in iterator.by_ref().take(val - 1) { - write!(&mut buf, "{value}, ").unwrap(); - } - write!(&mut buf, "and {}", iterator.next().unwrap()).unwrap(); - buf - } - } -} - -// A trait for special handing when displaying user readable types -// pub trait TypeDisplay { -// /// TODO might need environment information rather than memory...? -// /// - type ids -> names (maybe that goes on memory..., prefer environment) -// /// - -// fn fmt( -// &self, -// buf: &mut String, -// indent: usize, -// cycles: &mut HashSet, -// environment: &GeneralContext, -// store: &TypeStore, -// ) { -// // TODO temp -// todo!("fmt not implemented") -// } - -// fn to_string(&self, environment: &GeneralContext) -> String { -// let mut buf = String::new(); -// TypeDisplay::fmt(self, &mut buf, 0, &mut HashSet::new(), environment); -// buf -// } -// } - -// impl TypeDisplay for Option { -// fn fmt( -// &self, -// buf: &mut String, -// indent: usize, -// cycles: &mut HashSet, -// environment: &GeneralContext, -// store: &TypeStore, -// ) { -// match self { -// Some(ty) => TypeDisplay::fmt(ty, buf, indent, cycles, environment), -// None => buf.push_str("any"), -// } -// } -// } - static IS_DEBUG_MODE: std::sync::Mutex> = std::sync::Mutex::new(None); pub(crate) fn is_debug_mode() -> bool { @@ -64,6 +6,7 @@ pub(crate) fn is_debug_mode() -> bool { }) } +/// For `notify!` macro below pub fn shorten(s: &str) -> &str { &s[s.find("src").expect("file not under 'src' folder")..] } @@ -90,8 +33,6 @@ macro_rules! notify { } }; } -use std::fmt::Display; - pub(crate) use notify; pub trait ExtendedZipTrait: Iterator + Sized { diff --git a/src/js-based-plugin/index.mjs b/src/js-based-plugin/index.mjs index 962aacfb..827e6643 100644 --- a/src/js-based-plugin/index.mjs +++ b/src/js-based-plugin/index.mjs @@ -11,7 +11,7 @@ function emitDiagnostics(on, diagnostics, plugin) { lineSplits.push(lineSplits.at(-1) + line.length + 1) } for (const diagnostic of diagnostics) { - const line = lineSplits.findIndex(count => count >= diagnostic.position.start); + const line = lineSplits.findIndex(count => count > diagnostic.position.start); const column = diagnostic.position.start - lineSplits[line - 1]; // Unfortunately don't get to set an end point, level or any labels plugin.warn(diagnostic.reason, { line, column })