From 091794c3cfe7c3447df466778f2a63527eed8e39 Mon Sep 17 00:00:00 2001 From: Pedro H C Francisco <75535904+MineTechOficial@users.noreply.github.com> Date: Fri, 4 Oct 2024 20:21:07 -0300 Subject: [PATCH 01/12] Fixed export package-definitions not including cached modules Signed-off-by: Pedro H C Francisco <75535904+MineTechOficial@users.noreply.github.com> --- compiler-core/src/build.rs | 4 +- compiler-core/src/build/module_loader.rs | 2 +- .../src/build/module_loader/tests.rs | 3 ++ compiler-core/src/build/package_compiler.rs | 37 +++++++++++++------ compiler-core/src/build/package_loader.rs | 15 ++++---- .../src/build/package_loader/tests.rs | 6 ++- compiler-core/src/build/project_compiler.rs | 22 +++++++---- compiler-core/src/docs/tests.rs | 4 +- compiler-core/src/package_interface.rs | 33 ++++++++++------- compiler-core/src/package_interface/tests.rs | 1 + compiler-core/src/parse/extra.rs | 2 +- 11 files changed, 83 insertions(+), 46 deletions(-) diff --git a/compiler-core/src/build.rs b/compiler-core/src/build.rs index 6132d0e7c9c..7f5b6dffad9 100644 --- a/compiler-core/src/build.rs +++ b/compiler-core/src/build.rs @@ -20,6 +20,7 @@ use crate::ast::{ CallArg, CustomType, DefinitionLocation, Pattern, TypeAst, TypedArg, TypedDefinition, TypedExpr, TypedFunction, TypedPattern, TypedStatement, }; +use crate::package_interface; use crate::type_::Type; use crate::{ ast::{Definition, SrcSpan, TypedModule}, @@ -208,6 +209,7 @@ fn mode_includes_tests() { pub struct Package { pub config: PackageConfig, pub modules: Vec, + pub cached_metadata: Vec, } impl Package { @@ -225,7 +227,7 @@ impl Package { } } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct Module { pub name: EcoString, pub code: EcoString, diff --git a/compiler-core/src/build/module_loader.rs b/compiler-core/src/build/module_loader.rs index 43ee3bc6977..029a24879db 100644 --- a/compiler-core/src/build/module_loader.rs +++ b/compiler-core/src/build/module_loader.rs @@ -84,7 +84,7 @@ where } } - Ok(Input::Cached(self.cached(name, meta))) + Ok(Input::Cached((self.cached(name, meta.clone()), meta))) } /// Read the timestamp file from the artefact directory for the given diff --git a/compiler-core/src/build/module_loader/tests.rs b/compiler-core/src/build/module_loader/tests.rs index 19b296e2873..29cc5b7fb94 100644 --- a/compiler-core/src/build/module_loader/tests.rs +++ b/compiler-core/src/build/module_loader/tests.rs @@ -3,6 +3,7 @@ use crate::{ build::SourceFingerprint, io::{memory::InMemoryFileSystem, FileSystemWriter}, line_numbers::LineNumbers, + package_interface, }; use std::time::Duration; @@ -212,11 +213,13 @@ fn write_cache( ) { let line_numbers = LineNumbers::new(source); let cache_metadata = CacheMetadata { + name: "".into(), mtime: SystemTime::UNIX_EPOCH + Duration::from_secs(seconds), codegen_performed, dependencies: vec![], fingerprint: SourceFingerprint::new(source), line_numbers, + interface: package_interface::ModuleInterface::default(), }; let path = Utf8Path::new(path); fs.write_bytes(&path, &cache_metadata.to_binary()).unwrap(); diff --git a/compiler-core/src/build/package_compiler.rs b/compiler-core/src/build/package_compiler.rs index 76546ff5e5a..ca55ac4a4c5 100644 --- a/compiler-core/src/build/package_compiler.rs +++ b/compiler-core/src/build/package_compiler.rs @@ -1,5 +1,6 @@ use crate::analyse::{ModuleAnalyzerConstructor, TargetSupport}; use crate::line_numbers::{self, LineNumbers}; +use crate::package_interface::{self, ModuleInterface}; use crate::type_::PRELUDE_MODULE_NAME; use crate::{ ast::{SrcSpan, TypedModule, UntypedModule}, @@ -22,6 +23,7 @@ use crate::{ }; use askama::Template; use ecow::EcoString; +use std::borrow::BorrowMut; use std::collections::HashSet; use std::{collections::HashMap, fmt::write, time::SystemTime}; use vec1::Vec1; @@ -104,7 +106,7 @@ where stale_modules: &mut StaleTracker, incomplete_modules: &mut HashSet, telemetry: &dyn Telemetry, - ) -> Outcome, Error> { + ) -> Outcome<(Vec, Vec), Error> { let span = tracing::info_span!("compile", package = %self.config.name.as_str()); let _enter = span.enter(); @@ -168,6 +170,8 @@ where } } + println!("{:?}", loaded.cached_metadata); + // Type check the modules that are new or have changed tracing::info!(count=%loaded.to_compile.len(), "analysing_modules"); let outcome = analyse( @@ -182,9 +186,12 @@ where incomplete_modules, ); - let modules = match outcome { + let mut modules = match outcome { Outcome::Ok(modules) => modules, - Outcome::PartialFailure(_, _) | Outcome::TotalFailure(_) => return outcome, + Outcome::PartialFailure(modules, err) => { + return Outcome::PartialFailure((modules, loaded.cached_metadata), err) + } + Outcome::TotalFailure(err) => return Outcome::TotalFailure(err), }; tracing::debug!("performing_code_generation"); @@ -197,7 +204,7 @@ where return error.into(); } - Outcome::Ok(modules) + Outcome::Ok((modules, loaded.cached_metadata)) } fn compile_erlang_to_beam(&mut self, modules: &HashSet) -> Result<(), Error> { @@ -304,11 +311,13 @@ where let name = format!("{}.cache_meta", &module_name); let path = artefact_dir.join(name); let info = CacheMetadata { + name: module.name.clone(), mtime: module.mtime, codegen_performed: self.perform_codegen, dependencies: module.dependencies.clone(), fingerprint: SourceFingerprint::new(&module.code), line_numbers: module.ast.type_info.line_numbers.clone(), + interface: package_interface::ModuleInterface::from_module(module), }; self.io.write_bytes(&path, &info.to_binary())?; @@ -594,28 +603,28 @@ pub(crate) fn module_name(package_path: &Utf8Path, full_module_path: &Utf8Path) #[derive(Debug)] pub(crate) enum Input { New(UncompiledModule), - Cached(CachedModule), + Cached((CachedModule, CacheMetadata)), } impl Input { pub fn name(&self) -> &EcoString { match self { Input::New(m) => &m.name, - Input::Cached(m) => &m.name, + Input::Cached(m) => &m.0.name, } } pub fn source_path(&self) -> &Utf8Path { match self { Input::New(m) => &m.path, - Input::Cached(m) => &m.source_path, + Input::Cached(m) => &m.0.source_path, } } pub fn dependencies(&self) -> Vec { match self { Input::New(m) => m.dependencies.iter().map(|(n, _)| n.clone()).collect(), - Input::Cached(m) => m.dependencies.iter().map(|(n, _)| n.clone()).collect(), + Input::Cached(m) => m.0.dependencies.iter().map(|(n, _)| n.clone()).collect(), } } @@ -645,13 +654,15 @@ pub(crate) struct CachedModule { pub line_numbers: LineNumbers, } -#[derive(Debug, serde::Serialize, serde::Deserialize)] -pub(crate) struct CacheMetadata { +#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)] +pub struct CacheMetadata { + pub name: EcoString, pub mtime: SystemTime, pub codegen_performed: bool, pub dependencies: Vec<(EcoString, SrcSpan)>, pub fingerprint: SourceFingerprint, pub line_numbers: LineNumbers, + pub interface: package_interface::ModuleInterface, } impl CacheMetadata { @@ -664,10 +675,11 @@ impl CacheMetadata { } } -#[derive(Debug, Default, PartialEq, Eq)] +#[derive(Debug, Default)] pub(crate) struct Loaded { pub to_compile: Vec, pub cached: Vec, + pub cached_metadata: Vec, } impl Loaded { @@ -675,11 +687,12 @@ impl Loaded { Self { to_compile: vec![], cached: vec![], + cached_metadata: vec![], } } } -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone)] pub(crate) struct UncompiledModule { pub path: Utf8PathBuf, pub name: EcoString, diff --git a/compiler-core/src/build/package_loader.rs b/compiler-core/src/build/package_loader.rs index 77259cac29f..700a9630361 100644 --- a/compiler-core/src/build/package_loader.rs +++ b/compiler-core/src/build/package_loader.rs @@ -148,19 +148,20 @@ where // A cached module with dependencies that are stale must be // recompiled as the changes in the dependencies may have affect // the output, making the cache invalid. - Input::Cached(info) if self.stale_modules.includes_any(&info.dependencies) => { - tracing::debug!(module = %info.name, "module_to_be_compiled"); - self.stale_modules.add(info.name.clone()); - let module = self.load_and_parse(info)?; + Input::Cached(info) if self.stale_modules.includes_any(&info.0.dependencies) => { + tracing::debug!(module = %info.0.name, "module_to_be_compiled"); + self.stale_modules.add(info.0.name.clone()); + let module = self.load_and_parse(info.0)?; loaded.to_compile.push(module); } // A cached module with no stale dependencies can be used as-is // and does not need to be recompiled. Input::Cached(info) => { - tracing::debug!(module = %info.name, "module_to_load_from_cache"); - let module = self.load_cached_module(info)?; + tracing::debug!(module = %info.0.name, "module_to_load_from_cache"); + let module = self.load_cached_module(info.0)?; loaded.cached.push(module); + loaded.cached_metadata.push(info.1); } } } @@ -324,7 +325,7 @@ where src: module.code.clone(), } } - Input::Cached(cached_module) => { + Input::Cached((cached_module, _)) => { let (_, location) = cached_module .dependencies .iter() diff --git a/compiler-core/src/build/package_loader/tests.rs b/compiler-core/src/build/package_loader/tests.rs index a29ec58bad5..e2916dba4e0 100644 --- a/compiler-core/src/build/package_loader/tests.rs +++ b/compiler-core/src/build/package_loader/tests.rs @@ -5,7 +5,7 @@ use super::*; use crate::{ build::SourceFingerprint, io::{memory::InMemoryFileSystem, FileSystemWriter}, - line_numbers, + line_numbers, package_interface, parse::extra::ModuleExtra, warning::NullWarningEmitterIO, Warning, @@ -39,11 +39,13 @@ fn write_cache( let line_numbers = line_numbers::LineNumbers::new(src); let mtime = SystemTime::UNIX_EPOCH + Duration::from_secs(seconds); let cache_metadata = CacheMetadata { + name: name.into(), mtime, codegen_performed: true, dependencies: deps, fingerprint: SourceFingerprint::new(src), line_numbers: line_numbers.clone(), + interface: package_interface::ModuleInterface::default(), }; let path = Utf8Path::new("/artefact").join(format!("{name}.cache_meta")); fs.write_bytes(&path, &cache_metadata.to_binary()).unwrap(); @@ -62,7 +64,7 @@ fn write_cache( warnings: vec![], minimum_required_version: Version::new(0, 1, 0), }; - let path = Utf8Path::new("/artefact").join(format!("{name}.cache")); + let path: Utf8PathBuf = Utf8Path::new("/artefact").join(format!("{name}.cache")); fs.write_bytes( &path, &metadata::ModuleEncoder::new(&cache).encode().unwrap(), diff --git a/compiler-core/src/build/project_compiler.rs b/compiler-core/src/build/project_compiler.rs index 95554558e71..2367dae3786 100644 --- a/compiler-core/src/build/project_compiler.rs +++ b/compiler-core/src/build/project_compiler.rs @@ -21,7 +21,7 @@ use crate::{ use ecow::EcoString; use hexpm::version::Version; use itertools::Itertools; -use pubgrub::range::Range; +use pubgrub::{package, range::Range}; use std::{ cmp, collections::{HashMap, HashSet}, @@ -208,7 +208,11 @@ where pub fn compile_root_package(&mut self) -> Outcome { let config = self.config.clone(); self.compile_gleam_package(&config, true, self.paths.root().to_path_buf()) - .map(|modules| Package { config, modules }) + .map(|(modules, cached_metadata)| Package { + config, + modules, + cached_metadata, + }) } /// Checks that version file found in the build directory matches the @@ -288,7 +292,9 @@ where // longer need to have the package borrowed from self.packages. let package = self.packages.get(name).expect("Missing package").clone(); let result = match usable_build_tools(&package)?.as_slice() { - &[BuildTool::Gleam] => self.compile_gleam_dep_package(&package), + &[BuildTool::Gleam] => self + .compile_gleam_dep_package(&package) + .map(|(modules, _)| modules), &[BuildTool::Rebar3] => self.compile_rebar3_dep_package(&package).map(|_| vec![]), &[BuildTool::Mix] => self.compile_mix_dep_package(&package).map(|_| vec![]), &[BuildTool::Mix, BuildTool::Rebar3] => self @@ -489,7 +495,7 @@ where fn compile_gleam_dep_package( &mut self, package: &ManifestPackage, - ) -> Result, Error> { + ) -> Result<(Vec, Vec), Error> { // TODO: Test let package_root = match &package.source { // If the path is relative it is relative to the root of the @@ -520,7 +526,7 @@ where config: &PackageConfig, is_root: bool, root_path: Utf8PathBuf, - ) -> Outcome, Error> { + ) -> Outcome<(Vec, Vec), Error> { let out_path = self.paths .build_directory_for_package(self.mode(), self.target(), &config.name); @@ -590,14 +596,16 @@ where }; // Compile project to Erlang or JavaScript source code - compiler.compile( + let outcome = compiler.compile( &mut self.warnings, &mut self.importable_modules, &mut self.defined_modules, &mut self.stale_modules, &mut self.incomplete_modules, self.telemetry, - ) + ); + + outcome } } diff --git a/compiler-core/src/docs/tests.rs b/compiler-core/src/docs/tests.rs index 8469cea2be1..e8f3922b955 100644 --- a/compiler-core/src/docs/tests.rs +++ b/compiler-core/src/docs/tests.rs @@ -63,7 +63,7 @@ fn compile_with_markdown_pages( ) .unwrap(); - for module in &mut modules { + for module in &mut modules.0 { module.attach_doc_and_module_comments(); } @@ -79,7 +79,7 @@ fn compile_with_markdown_pages( super::generate_html( &paths, &config, - &modules, + &modules.0, &docs_pages, pages_fs, SystemTime::UNIX_EPOCH, diff --git a/compiler-core/src/package_interface.rs b/compiler-core/src/package_interface.rs index 936902ddb82..33435add491 100644 --- a/compiler-core/src/package_interface.rs +++ b/compiler-core/src/package_interface.rs @@ -2,7 +2,7 @@ use std::{collections::HashMap, ops::Deref}; use ecow::EcoString; use itertools::Itertools; -use serde::Serialize; +use serde::{Deserialize, Serialize}; #[cfg(test)] mod tests; @@ -28,7 +28,7 @@ pub struct PackageInterface { modules: HashMap, } -#[derive(Serialize, Debug)] +#[derive(Deserialize, Serialize, Debug, Clone, Default)] #[serde(rename_all = "kebab-case")] pub struct ModuleInterface { /// A vector with the lines composing the module's documentation (that is @@ -48,7 +48,7 @@ pub struct ModuleInterface { functions: HashMap, } -#[derive(Serialize, Debug)] +#[derive(Deserialize, Serialize, Debug, Clone)] #[serde(rename_all = "kebab-case")] pub struct TypeDefinitionInterface { /// The definition's documentation comment (that is every line preceded by @@ -71,7 +71,7 @@ pub struct TypeDefinitionInterface { constructors: Vec, } -#[derive(Serialize, Debug)] +#[derive(Deserialize, Serialize, Debug, Clone)] #[serde(rename_all = "kebab-case")] pub struct TypeConstructorInterface { /// The constructor's documentation comment (that is every line preceded by @@ -95,7 +95,7 @@ pub struct TypeConstructorInterface { parameters: Vec, } -#[derive(Serialize, Debug)] +#[derive(Deserialize, Serialize, Debug, Clone)] #[serde(rename_all = "kebab-case")] pub struct TypeAliasInterface { /// The constructor's documentation comment (that is every line preceded by @@ -118,7 +118,7 @@ pub struct TypeAliasInterface { alias: TypeInterface, } -#[derive(Serialize, Debug)] +#[derive(Deserialize, Serialize, Debug, Clone)] #[serde(rename_all = "kebab-case")] pub struct ConstantInterface { /// The constant's documentation comment (that is every line preceded by @@ -135,7 +135,7 @@ pub struct ConstantInterface { /// A module's function. This differs from a simple `Fn` type as its arguments /// can be labelled. -#[derive(Serialize, Debug)] +#[derive(Deserialize, Serialize, Debug, Clone)] #[serde(rename_all = "kebab-case")] pub struct FunctionInterface { /// The function's documentation comment (that is every line preceded by @@ -151,7 +151,7 @@ pub struct FunctionInterface { } /// Informations about how a value is implemented. -#[derive(Debug, Serialize, Copy, Clone)] +#[derive(Debug, Deserialize, Serialize, Copy, Clone)] #[serde(rename_all = "kebab-case")] pub struct ImplementationsInterface { /// Set to `true` if the const/function has a pure Gleam implementation @@ -273,7 +273,7 @@ impl ImplementationsInterface { } } -#[derive(Serialize, Debug)] +#[derive(Deserialize, Serialize, Debug, Clone)] #[serde(rename_all = "kebab-case")] pub struct DeprecationInterface { /// The reason for the deprecation. @@ -291,8 +291,8 @@ impl DeprecationInterface { } } -#[derive(Serialize, Debug)] -#[serde(tag = "kind")] +#[derive(Deserialize, Serialize, Debug, Clone)] +// #[serde(tag = "kind")] #[serde(rename_all = "kebab-case")] pub enum TypeInterface { /// A tuple type like `#(Int, Float)`. @@ -339,7 +339,7 @@ pub enum TypeInterface { }, } -#[derive(Serialize, Debug)] +#[derive(Deserialize, Serialize, Debug, Clone)] #[serde(rename_all = "kebab-case")] pub struct ParameterInterface { /// If the parameter is labelled this will hold the label's name. @@ -372,13 +372,20 @@ impl PackageInterface { .iter() .filter(|module| !package.config.is_internal_module(module.name.as_str())) .map(|module| (module.name.clone(), ModuleInterface::from_module(module))) + .chain( + package + .cached_metadata + .clone() + .into_iter() + .map(|module| (module.name.clone(), module.interface)), + ) .collect(), } } } impl ModuleInterface { - fn from_module(module: &Module) -> ModuleInterface { + pub fn from_module(module: &Module) -> ModuleInterface { let mut types = HashMap::new(); let mut type_aliases = HashMap::new(); let mut constants = HashMap::new(); diff --git a/compiler-core/src/package_interface/tests.rs b/compiler-core/src/package_interface/tests.rs index 5495a848db9..8bf9fbffdf4 100644 --- a/compiler-core/src/package_interface/tests.rs +++ b/compiler-core/src/package_interface/tests.rs @@ -172,6 +172,7 @@ fn package_from_module(module: Module) -> Package { .expect("internals glob")]), }, modules: vec![module], + cached_metadata: vec![], } } diff --git a/compiler-core/src/parse/extra.rs b/compiler-core/src/parse/extra.rs index b6e2cb6a060..72003014daf 100644 --- a/compiler-core/src/parse/extra.rs +++ b/compiler-core/src/parse/extra.rs @@ -4,7 +4,7 @@ use ecow::EcoString; use crate::ast::SrcSpan; -#[derive(Debug, PartialEq, Eq, Default)] +#[derive(Debug, PartialEq, Eq, Default, Clone)] pub struct ModuleExtra { pub module_comments: Vec, pub doc_comments: Vec, From c72c488328804d450a957042a679ee69a7209b0a Mon Sep 17 00:00:00 2001 From: Pedro H C Francisco <75535904+MineTechOficial@users.noreply.github.com> Date: Fri, 4 Oct 2024 20:30:33 -0300 Subject: [PATCH 02/12] Added snapshots Signed-off-by: Pedro H C Francisco <75535904+MineTechOficial@users.noreply.github.com> --- ...ge_interface__tests__generic_function.snap | 22 +++--- ...rted_aliased_type_keeps_original_name.snap | 37 +++++----- ...ckage_interface__tests__imported_type.snap | 28 ++++---- ...rface__tests__multiple_type_variables.snap | 72 ++++++++++--------- ...ts__package_documentation_is_included.snap | 11 +-- ...ckage_interface__tests__prelude_types.snap | 44 ++++++------ ...ackage_interface__tests__type_aliases.snap | 22 +++--- ...e_interface__tests__type_constructors.snap | 32 +++++---- ...rated_tests__alias_unqualified_import.snap | 5 +- ...enerated_tests__erlang_app_generation.snap | 2 +- ...iler__generated_tests__erlang_bug_752.snap | 4 +- ...mpiler__generated_tests__erlang_empty.snap | 2 +- ..._generated_tests__erlang_escape_names.snap | 5 +- ...piler__generated_tests__erlang_import.snap | 5 +- ...ests__erlang_import_shadowing_prelude.snap | 5 +- ...piler__generated_tests__erlang_nested.snap | 3 +- ...sts__erlang_nested_qualified_constant.snap | 4 +- ..._compiler__generated_tests__hello_joe.snap | 3 +- ...d_tests__import_shadowed_name_warning.snap | 5 +- ...__generated_tests__imported_constants.snap | 5 +- ...enerated_tests__imported_external_fns.snap | 5 +- ...d_tests__imported_record_constructors.snap | 5 +- ...ler__generated_tests__javascript_d_ts.snap | 2 +- ...er__generated_tests__javascript_empty.snap | 2 +- ...r__generated_tests__javascript_import.snap | 4 +- ..._tests__not_overwriting_erlang_module.snap | 3 +- ...__generated_tests__variable_or_module.snap | 5 +- 27 files changed, 178 insertions(+), 164 deletions(-) diff --git a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__generic_function.snap b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__generic_function.snap index 95fa12696c7..c4879c53903 100644 --- a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__generic_function.snap +++ b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__generic_function.snap @@ -40,16 +40,18 @@ expression: "\npub type Wob(a) { Wob }\n@deprecated(\"deprecation message\")\npu }, "parameters": [], "return": { - "kind": "named", - "name": "Wob", - "package": "my_package", - "module": "my/module", - "parameters": [ - { - "kind": "variable", - "id": 0 - } - ] + "named": { + "name": "Wob", + "package": "my_package", + "module": "my/module", + "parameters": [ + { + "variable": { + "id": 0 + } + } + ] + } } } } diff --git a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__imported_aliased_type_keeps_original_name.snap b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__imported_aliased_type_keeps_original_name.snap index daf91d5e956..b2fe7cb9228 100644 --- a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__imported_aliased_type_keeps_original_name.snap +++ b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__imported_aliased_type_keeps_original_name.snap @@ -25,24 +25,27 @@ expression: "\nimport other_module.{type Element as Alias} as module_alias\npub }, "parameters": [], "return": { - "kind": "named", - "name": "Element", - "package": "other_package", - "module": "other_module", - "parameters": [ - { - "kind": "named", - "name": "Element", - "package": "other_package", - "module": "other_module", - "parameters": [ - { - "kind": "variable", - "id": 0 + "named": { + "name": "Element", + "package": "other_package", + "module": "other_module", + "parameters": [ + { + "named": { + "name": "Element", + "package": "other_package", + "module": "other_module", + "parameters": [ + { + "variable": { + "id": 0 + } + } + ] } - ] - } - ] + } + ] + } } } } diff --git a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__imported_type.snap b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__imported_type.snap index 63ec92f1715..1688b9ed14d 100644 --- a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__imported_type.snap +++ b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__imported_type.snap @@ -25,19 +25,21 @@ expression: "\nimport other_module.{type Element}\npub fn main() -> Element(Int) }, "parameters": [], "return": { - "kind": "named", - "name": "Element", - "package": "other_package", - "module": "other_module", - "parameters": [ - { - "kind": "named", - "name": "Int", - "package": "", - "module": "gleam", - "parameters": [] - } - ] + "named": { + "name": "Element", + "package": "other_package", + "module": "other_module", + "parameters": [ + { + "named": { + "name": "Int", + "package": "", + "module": "gleam", + "parameters": [] + } + } + ] + } } } } diff --git a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__multiple_type_variables.snap b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__multiple_type_variables.snap index aca6ea2295b..2e4e4e31d9b 100644 --- a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__multiple_type_variables.snap +++ b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__multiple_type_variables.snap @@ -34,52 +34,60 @@ expression: "\npub type Box(a, b)\npub fn some_type_variables(a: a, b: b, c: Box { "label": null, "type": { - "kind": "variable", - "id": 0 + "variable": { + "id": 0 + } } }, { "label": null, "type": { - "kind": "variable", - "id": 1 + "variable": { + "id": 1 + } } }, { "label": null, "type": { - "kind": "named", - "name": "Box", - "package": "my_package", - "module": "my/module", - "parameters": [ - { - "kind": "variable", - "id": 2 - }, - { - "kind": "variable", - "id": 3 - } - ] + "named": { + "name": "Box", + "package": "my_package", + "module": "my/module", + "parameters": [ + { + "variable": { + "id": 2 + } + }, + { + "variable": { + "id": 3 + } + } + ] + } } } ], "return": { - "kind": "named", - "name": "Box", - "package": "my_package", - "module": "my/module", - "parameters": [ - { - "kind": "variable", - "id": 0 - }, - { - "kind": "variable", - "id": 3 - } - ] + "named": { + "name": "Box", + "package": "my_package", + "module": "my/module", + "parameters": [ + { + "variable": { + "id": 0 + } + }, + { + "variable": { + "id": 3 + } + } + ] + } } } } diff --git a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__package_documentation_is_included.snap b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__package_documentation_is_included.snap index 45bb53a4bbe..d10ff70c315 100644 --- a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__package_documentation_is_included.snap +++ b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__package_documentation_is_included.snap @@ -28,11 +28,12 @@ expression: "\n//// Some package\n//// documentation!\n\npub fn main() { 1 }\n" }, "parameters": [], "return": { - "kind": "named", - "name": "Int", - "package": "", - "module": "gleam", - "parameters": [] + "named": { + "name": "Int", + "package": "", + "module": "gleam", + "parameters": [] + } } } } diff --git a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__prelude_types.snap b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__prelude_types.snap index e58344a5f0f..94b92e3b696 100644 --- a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__prelude_types.snap +++ b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__prelude_types.snap @@ -23,11 +23,12 @@ expression: "\npub const float = 1.1\npub const string = \"\"\npub const int = 1 "can-run-on-javascript": true }, "type": { - "kind": "named", - "name": "Bool", - "package": "", - "module": "gleam", - "parameters": [] + "named": { + "name": "Bool", + "package": "", + "module": "gleam", + "parameters": [] + } } }, "float": { @@ -41,11 +42,12 @@ expression: "\npub const float = 1.1\npub const string = \"\"\npub const int = 1 "can-run-on-javascript": true }, "type": { - "kind": "named", - "name": "Float", - "package": "", - "module": "gleam", - "parameters": [] + "named": { + "name": "Float", + "package": "", + "module": "gleam", + "parameters": [] + } } }, "int": { @@ -59,11 +61,12 @@ expression: "\npub const float = 1.1\npub const string = \"\"\npub const int = 1 "can-run-on-javascript": true }, "type": { - "kind": "named", - "name": "Int", - "package": "", - "module": "gleam", - "parameters": [] + "named": { + "name": "Int", + "package": "", + "module": "gleam", + "parameters": [] + } } }, "string": { @@ -77,11 +80,12 @@ expression: "\npub const float = 1.1\npub const string = \"\"\npub const int = 1 "can-run-on-javascript": true }, "type": { - "kind": "named", - "name": "String", - "package": "", - "module": "gleam", - "parameters": [] + "named": { + "name": "String", + "package": "", + "module": "gleam", + "parameters": [] + } } } }, diff --git a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_aliases.snap b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_aliases.snap index 978b8459f9e..8a10551bd2c 100644 --- a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_aliases.snap +++ b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_aliases.snap @@ -15,16 +15,18 @@ expression: pub type Wibble(a) = List(a) "deprecation": null, "parameters": 1, "alias": { - "kind": "named", - "name": "List", - "package": "", - "module": "gleam", - "parameters": [ - { - "kind": "variable", - "id": 0 - } - ] + "named": { + "name": "List", + "package": "", + "module": "gleam", + "parameters": [ + { + "variable": { + "id": 0 + } + } + ] + } } } }, diff --git a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_constructors.snap b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_constructors.snap index 115ad135a49..01f95cf0fe0 100644 --- a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_constructors.snap +++ b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_constructors.snap @@ -23,18 +23,20 @@ expression: "\npub type Box(a, b) {\n Box(b, Int)\n OtherBox(message: String, { "label": null, "type": { - "kind": "variable", - "id": 1 + "variable": { + "id": 1 + } } }, { "label": null, "type": { - "kind": "named", - "name": "Int", - "package": "", - "module": "gleam", - "parameters": [] + "named": { + "name": "Int", + "package": "", + "module": "gleam", + "parameters": [] + } } } ] @@ -46,18 +48,20 @@ expression: "\npub type Box(a, b) {\n Box(b, Int)\n OtherBox(message: String, { "label": "message", "type": { - "kind": "named", - "name": "String", - "package": "", - "module": "gleam", - "parameters": [] + "named": { + "name": "String", + "package": "", + "module": "gleam", + "parameters": [] + } } }, { "label": "a", "type": { - "kind": "variable", - "id": 0 + "variable": { + "id": 0 + } } } ] diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__alias_unqualified_import.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__alias_unqualified_import.snap index fdcb22afa7b..f8f0a477f2f 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__alias_unqualified_import.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__alias_unqualified_import.snap @@ -1,13 +1,12 @@ --- source: test-package-compiler/src/generated_tests.rs -assertion_line: 8 expression: "./cases/alias_unqualified_import" --- //// /out/lib/the_package/_gleam_artefacts/one.cache <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one.cache_meta -<77 byte binary> +<231 byte binary> //// /out/lib/the_package/_gleam_artefacts/one.erl -module(one). @@ -28,7 +27,7 @@ id(X) -> <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<88 byte binary> +<217 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_app_generation.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_app_generation.snap index 1daa51c17aa..a6e0cfd9f39 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_app_generation.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_app_generation.snap @@ -6,7 +6,7 @@ expression: "./cases/erlang_app_generation" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/main.cache_meta -<49 byte binary> +<101 byte binary> //// /out/lib/the_package/_gleam_artefacts/main.erl -module(main). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_bug_752.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_bug_752.snap index ceb2c58b67a..fd2ea7426c9 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_bug_752.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_bug_752.snap @@ -6,7 +6,7 @@ expression: "./cases/erlang_bug_752" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one.cache_meta -<57 byte binary> +<170 byte binary> //// /out/lib/the_package/_gleam_artefacts/one.erl -module(one). @@ -23,7 +23,7 @@ expression: "./cases/erlang_bug_752" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<84 byte binary> +<291 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_empty.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_empty.snap index 974c1958f24..f2940d8b307 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_empty.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_empty.snap @@ -6,7 +6,7 @@ expression: "./cases/erlang_empty" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/empty.cache_meta -<49 byte binary> +<102 byte binary> //// /out/lib/the_package/_gleam_artefacts/empty.erl -module(empty). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_escape_names.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_escape_names.snap index 8ec302b788d..ab3df4c253d 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_escape_names.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_escape_names.snap @@ -1,13 +1,12 @@ --- source: test-package-compiler/src/generated_tests.rs -assertion_line: 63 expression: "./cases/erlang_escape_names" --- //// /out/lib/the_package/_gleam_artefacts/one.cache <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one.cache_meta -<61 byte binary> +<167 byte binary> //// /out/lib/the_package/_gleam_artefacts/one.erl -module(one). @@ -25,7 +24,7 @@ expression: "./cases/erlang_escape_names" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<136 byte binary> +<501 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_import.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_import.snap index 92a86d91ff2..992cf024ca7 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_import.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_import.snap @@ -1,13 +1,12 @@ --- source: test-package-compiler/src/generated_tests.rs -assertion_line: 74 expression: "./cases/erlang_import" --- //// /out/lib/the_package/_gleam_artefacts/one.cache <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one.cache_meta -<88 byte binary> +<261 byte binary> //// /out/lib/the_package/_gleam_artefacts/one.erl -module(one). @@ -26,7 +25,7 @@ unbox(X) -> <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<57 byte binary> +<202 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_import_shadowing_prelude.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_import_shadowing_prelude.snap index ee8b537bf47..703b5acd44e 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_import_shadowing_prelude.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_import_shadowing_prelude.snap @@ -1,13 +1,12 @@ --- source: test-package-compiler/src/generated_tests.rs -assertion_line: 85 expression: "./cases/erlang_import_shadowing_prelude" --- //// /out/lib/the_package/_gleam_artefacts/one.cache <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one.cache_meta -<61 byte binary> +<165 byte binary> //// /out/lib/the_package/_gleam_artefacts/one.erl -module(one). @@ -24,7 +23,7 @@ expression: "./cases/erlang_import_shadowing_prelude" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<88 byte binary> +<217 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_nested.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_nested.snap index 2e4120d7dc7..75d0a5daf34 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_nested.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_nested.snap @@ -1,13 +1,12 @@ --- source: test-package-compiler/src/generated_tests.rs -assertion_line: 96 expression: "./cases/erlang_nested" --- //// /out/lib/the_package/_gleam_artefacts/one@two.cache <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one@two.cache_meta -<57 byte binary> +<186 byte binary> //// /out/lib/the_package/_gleam_artefacts/one@two.erl -module(one@two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_nested_qualified_constant.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_nested_qualified_constant.snap index 5f3afcf4381..aa8e750bd1e 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_nested_qualified_constant.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_nested_qualified_constant.snap @@ -6,7 +6,7 @@ expression: "./cases/erlang_nested_qualified_constant" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one@two.cache_meta -<57 byte binary> +<157 byte binary> //// /out/lib/the_package/_gleam_artefacts/one@two.erl -module(one@two). @@ -23,7 +23,7 @@ expression: "./cases/erlang_nested_qualified_constant" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<100 byte binary> +<218 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__hello_joe.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__hello_joe.snap index b083da9fc15..08393a4bdfa 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__hello_joe.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__hello_joe.snap @@ -1,13 +1,12 @@ --- source: test-package-compiler/src/generated_tests.rs -assertion_line: 118 expression: "./cases/hello_joe" --- //// /out/lib/the_package/_gleam_artefacts/hello_joe.cache <.cache binary> //// /out/lib/the_package/_gleam_artefacts/hello_joe.cache_meta -<57 byte binary> +<188 byte binary> //// /out/lib/the_package/_gleam_artefacts/hello_joe.erl -module(hello_joe). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__import_shadowed_name_warning.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__import_shadowed_name_warning.snap index d11b9f3c9fe..0ac1dc65044 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__import_shadowed_name_warning.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__import_shadowed_name_warning.snap @@ -1,13 +1,12 @@ --- source: test-package-compiler/src/generated_tests.rs -assertion_line: 151 expression: "./cases/import_shadowed_name_warning" --- //// /out/lib/the_package/_gleam_artefacts/one.cache <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one.cache_meta -<57 byte binary> +<138 byte binary> //// /out/lib/the_package/_gleam_artefacts/one.erl -module(one). @@ -24,7 +23,7 @@ expression: "./cases/import_shadowed_name_warning" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<120 byte binary> +<297 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_constants.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_constants.snap index 7e75585172b..606bec30122 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_constants.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_constants.snap @@ -1,13 +1,12 @@ --- source: test-package-compiler/src/generated_tests.rs -assertion_line: 162 expression: "./cases/imported_constants" --- //// /out/lib/the_package/_gleam_artefacts/one.cache <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one.cache_meta -<89 byte binary> +<495 byte binary> //// /out/lib/the_package/_gleam_artefacts/one.erl -module(one). @@ -28,7 +27,7 @@ expression: "./cases/imported_constants" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<324 byte binary> +<2520 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_external_fns.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_external_fns.snap index addd2e3dc03..5e06e611290 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_external_fns.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_external_fns.snap @@ -1,13 +1,12 @@ --- source: test-package-compiler/src/generated_tests.rs -assertion_line: 173 expression: "./cases/imported_external_fns" --- //// /out/lib/the_package/_gleam_artefacts/one.cache <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one.cache_meta -<53 byte binary> +<176 byte binary> //// /out/lib/the_package/_gleam_artefacts/one.erl -module(one). @@ -25,7 +24,7 @@ thing() -> <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<319 byte binary> +<1227 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_record_constructors.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_record_constructors.snap index b78b38fdd5c..3c23ff05409 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_record_constructors.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_record_constructors.snap @@ -1,13 +1,12 @@ --- source: test-package-compiler/src/generated_tests.rs -assertion_line: 184 expression: "./cases/imported_record_constructors" --- //// /out/lib/the_package/_gleam_artefacts/one@one.cache <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one@one.cache_meta -<89 byte binary> +<507 byte binary> //// /out/lib/the_package/_gleam_artefacts/one@one.erl -module(one@one). @@ -28,7 +27,7 @@ expression: "./cases/imported_record_constructors" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<491 byte binary> +<3990 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_d_ts.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_d_ts.snap index 653d750f927..010ab823e75 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_d_ts.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_d_ts.snap @@ -6,7 +6,7 @@ expression: "./cases/javascript_d_ts" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/hello.cache_meta -<73 byte binary> +<259 byte binary> //// /out/lib/the_package/gleam.d.mts export * from "../prelude.d.mts"; diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_empty.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_empty.snap index e0b9a3d176a..3fb1d18e25d 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_empty.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_empty.snap @@ -6,7 +6,7 @@ expression: "./cases/javascript_empty" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/empty.cache_meta -<49 byte binary> +<102 byte binary> //// /out/lib/the_package/empty.mjs export {} diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_import.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_import.snap index e79a95a7735..538eba5dc38 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_import.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_import.snap @@ -6,13 +6,13 @@ expression: "./cases/javascript_import" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one@two.cache_meta -<57 byte binary> +<157 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.cache <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<80 byte binary> +<198 byte binary> //// /out/lib/the_package/gleam.d.mts export * from "../prelude.d.mts"; diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__not_overwriting_erlang_module.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__not_overwriting_erlang_module.snap index 3c66525567f..a4bf06ed4c4 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__not_overwriting_erlang_module.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__not_overwriting_erlang_module.snap @@ -1,13 +1,12 @@ --- source: test-package-compiler/src/generated_tests.rs -assertion_line: 237 expression: "./cases/not_overwriting_erlang_module" --- //// /out/lib/the_package/_gleam_artefacts/app@code.cache <.cache binary> //// /out/lib/the_package/_gleam_artefacts/app@code.cache_meta -<65 byte binary> +<121 byte binary> //// /out/lib/the_package/_gleam_artefacts/app@code.erl -module(app@code). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__variable_or_module.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__variable_or_module.snap index 4613c8e0385..488ce88bc99 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__variable_or_module.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__variable_or_module.snap @@ -1,13 +1,12 @@ --- source: test-package-compiler/src/generated_tests.rs -assertion_line: 316 expression: "./cases/variable_or_module" --- //// /out/lib/the_package/_gleam_artefacts/main.cache <.cache binary> //// /out/lib/the_package/_gleam_artefacts/main.cache_meta -<118 byte binary> +<439 byte binary> //// /out/lib/the_package/_gleam_artefacts/main.erl -module(main). @@ -30,7 +29,7 @@ record_field(Power) -> <.cache binary> //// /out/lib/the_package/_gleam_artefacts/power.cache_meta -<77 byte binary> +<368 byte binary> //// /out/lib/the_package/_gleam_artefacts/power.erl -module(power). From 4789222ac8db5fe157576681547f5458f1508e76 Mon Sep 17 00:00:00 2001 From: Pedro H C Francisco <75535904+mine-tech-oficial@users.noreply.github.com> Date: Sat, 5 Oct 2024 12:20:25 -0300 Subject: [PATCH 03/12] Simplified struct type --- compiler-core/src/build/module_loader.rs | 2 +- compiler-core/src/build/package_compiler.rs | 8 ++++---- compiler-core/src/build/package_loader.rs | 18 +++++++++--------- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/compiler-core/src/build/module_loader.rs b/compiler-core/src/build/module_loader.rs index 029a24879db..fef60167d2f 100644 --- a/compiler-core/src/build/module_loader.rs +++ b/compiler-core/src/build/module_loader.rs @@ -84,7 +84,7 @@ where } } - Ok(Input::Cached((self.cached(name, meta.clone()), meta))) + Ok(Input::Cached(self.cached(name, meta.clone()), meta)) } /// Read the timestamp file from the artefact directory for the given diff --git a/compiler-core/src/build/package_compiler.rs b/compiler-core/src/build/package_compiler.rs index ca55ac4a4c5..844a268924f 100644 --- a/compiler-core/src/build/package_compiler.rs +++ b/compiler-core/src/build/package_compiler.rs @@ -603,28 +603,28 @@ pub(crate) fn module_name(package_path: &Utf8Path, full_module_path: &Utf8Path) #[derive(Debug)] pub(crate) enum Input { New(UncompiledModule), - Cached((CachedModule, CacheMetadata)), + Cached(CachedModule, CacheMetadata), } impl Input { pub fn name(&self) -> &EcoString { match self { Input::New(m) => &m.name, - Input::Cached(m) => &m.0.name, + Input::Cached(m, _) => &m.name, } } pub fn source_path(&self) -> &Utf8Path { match self { Input::New(m) => &m.path, - Input::Cached(m) => &m.0.source_path, + Input::Cached(m, _) => &m.source_path, } } pub fn dependencies(&self) -> Vec { match self { Input::New(m) => m.dependencies.iter().map(|(n, _)| n.clone()).collect(), - Input::Cached(m) => m.0.dependencies.iter().map(|(n, _)| n.clone()).collect(), + Input::Cached(m, _) => m.dependencies.iter().map(|(n, _)| n.clone()).collect(), } } diff --git a/compiler-core/src/build/package_loader.rs b/compiler-core/src/build/package_loader.rs index 700a9630361..dd5f56e2eb5 100644 --- a/compiler-core/src/build/package_loader.rs +++ b/compiler-core/src/build/package_loader.rs @@ -148,20 +148,20 @@ where // A cached module with dependencies that are stale must be // recompiled as the changes in the dependencies may have affect // the output, making the cache invalid. - Input::Cached(info) if self.stale_modules.includes_any(&info.0.dependencies) => { - tracing::debug!(module = %info.0.name, "module_to_be_compiled"); - self.stale_modules.add(info.0.name.clone()); - let module = self.load_and_parse(info.0)?; + Input::Cached(info, _) if self.stale_modules.includes_any(&info.dependencies) => { + tracing::debug!(module = %info.name, "module_to_be_compiled"); + self.stale_modules.add(info.name.clone()); + let module = self.load_and_parse(info)?; loaded.to_compile.push(module); } // A cached module with no stale dependencies can be used as-is // and does not need to be recompiled. - Input::Cached(info) => { - tracing::debug!(module = %info.0.name, "module_to_load_from_cache"); - let module = self.load_cached_module(info.0)?; + Input::Cached(info, meta) => { + tracing::debug!(module = %info.name, "module_to_load_from_cache"); + let module = self.load_cached_module(info)?; loaded.cached.push(module); - loaded.cached_metadata.push(info.1); + loaded.cached_metadata.push(meta); } } } @@ -325,7 +325,7 @@ where src: module.code.clone(), } } - Input::Cached((cached_module, _)) => { + Input::Cached(cached_module, _) => { let (_, location) = cached_module .dependencies .iter() From 09d3e9e2b3f015e307eee3b0ba1ed41fa0e15a6d Mon Sep 17 00:00:00 2001 From: Pedro H C Francisco <75535904+mine-tech-oficial@users.noreply.github.com> Date: Sat, 5 Oct 2024 12:24:01 -0300 Subject: [PATCH 04/12] Removed temporary debugging --- compiler-core/src/build/package_compiler.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/compiler-core/src/build/package_compiler.rs b/compiler-core/src/build/package_compiler.rs index 844a268924f..c7532329b66 100644 --- a/compiler-core/src/build/package_compiler.rs +++ b/compiler-core/src/build/package_compiler.rs @@ -170,8 +170,6 @@ where } } - println!("{:?}", loaded.cached_metadata); - // Type check the modules that are new or have changed tracing::info!(count=%loaded.to_compile.len(), "analysing_modules"); let outcome = analyse( From e67e3c56abcf21918c064872ff284feb2b043720 Mon Sep 17 00:00:00 2001 From: Pedro H C Francisco <75535904+mine-tech-oficial@users.noreply.github.com> Date: Tue, 8 Oct 2024 15:58:20 -0300 Subject: [PATCH 05/12] Removed package interface from cache and made cached modules be recompiled on export. Removed redundant traits --- compiler-cli/src/export.rs | 2 +- compiler-core/src/build.rs | 6 +- compiler-core/src/build/module_loader.rs | 2 +- .../src/build/module_loader/tests.rs | 2 - compiler-core/src/build/package_compiler.rs | 28 +++----- compiler-core/src/build/package_loader.rs | 22 +++--- .../src/build/package_loader/tests.rs | 2 - compiler-core/src/build/project_compiler.rs | 14 ++-- compiler-core/src/config.rs | 2 +- compiler-core/src/docs/tests.rs | 4 +- compiler-core/src/package_interface.rs | 31 ++++---- ...ge_interface__tests__generic_function.snap | 22 +++--- ...rted_aliased_type_keeps_original_name.snap | 37 +++++----- ...ckage_interface__tests__imported_type.snap | 28 ++++---- ...rface__tests__multiple_type_variables.snap | 72 +++++++++---------- ...ts__package_documentation_is_included.snap | 11 ++- ...ckage_interface__tests__prelude_types.snap | 44 ++++++------ ...ackage_interface__tests__type_aliases.snap | 22 +++--- ...e_interface__tests__type_constructors.snap | 32 ++++----- compiler-core/src/package_interface/tests.rs | 1 - compiler-core/src/parse/extra.rs | 2 +- ...rated_tests__alias_unqualified_import.snap | 4 +- ...enerated_tests__erlang_app_generation.snap | 2 +- ...iler__generated_tests__erlang_bug_752.snap | 4 +- ...mpiler__generated_tests__erlang_empty.snap | 2 +- ..._generated_tests__erlang_escape_names.snap | 4 +- ...piler__generated_tests__erlang_import.snap | 4 +- ...ests__erlang_import_shadowing_prelude.snap | 4 +- ...piler__generated_tests__erlang_nested.snap | 2 +- ...sts__erlang_nested_qualified_constant.snap | 4 +- ..._compiler__generated_tests__hello_joe.snap | 2 +- ...d_tests__import_shadowed_name_warning.snap | 4 +- ...__generated_tests__imported_constants.snap | 4 +- ...enerated_tests__imported_external_fns.snap | 4 +- ...d_tests__imported_record_constructors.snap | 4 +- ...ler__generated_tests__javascript_d_ts.snap | 2 +- ...er__generated_tests__javascript_empty.snap | 2 +- ...r__generated_tests__javascript_import.snap | 4 +- ..._tests__not_overwriting_erlang_module.snap | 2 +- ...__generated_tests__variable_or_module.snap | 4 +- 40 files changed, 201 insertions(+), 247 deletions(-) diff --git a/compiler-cli/src/export.rs b/compiler-cli/src/export.rs index 9b58293e2c4..c34035e5a65 100644 --- a/compiler-cli/src/export.rs +++ b/compiler-cli/src/export.rs @@ -130,7 +130,7 @@ pub fn package_interface(path: Utf8PathBuf) -> Result<()> { // Build the project let mut built = crate::build::main( Options { - mode: Mode::Prod, + mode: Mode::PackageInterface, target: None, codegen: Codegen::All, compile: Compile::All, diff --git a/compiler-core/src/build.rs b/compiler-core/src/build.rs index 7f5b6dffad9..917f741b0ef 100644 --- a/compiler-core/src/build.rs +++ b/compiler-core/src/build.rs @@ -185,6 +185,7 @@ pub enum Mode { Dev, Prod, Lsp, + PackageInterface, } impl Mode { @@ -193,7 +194,7 @@ impl Mode { pub fn includes_tests(&self) -> bool { match self { Self::Dev | Self::Lsp => true, - Self::Prod => false, + Self::Prod | Self::PackageInterface => false, } } } @@ -209,7 +210,6 @@ fn mode_includes_tests() { pub struct Package { pub config: PackageConfig, pub modules: Vec, - pub cached_metadata: Vec, } impl Package { @@ -227,7 +227,7 @@ impl Package { } } -#[derive(Debug, Clone)] +#[derive(Debug)] pub struct Module { pub name: EcoString, pub code: EcoString, diff --git a/compiler-core/src/build/module_loader.rs b/compiler-core/src/build/module_loader.rs index fef60167d2f..43ee3bc6977 100644 --- a/compiler-core/src/build/module_loader.rs +++ b/compiler-core/src/build/module_loader.rs @@ -84,7 +84,7 @@ where } } - Ok(Input::Cached(self.cached(name, meta.clone()), meta)) + Ok(Input::Cached(self.cached(name, meta))) } /// Read the timestamp file from the artefact directory for the given diff --git a/compiler-core/src/build/module_loader/tests.rs b/compiler-core/src/build/module_loader/tests.rs index 29cc5b7fb94..411dddd5cdc 100644 --- a/compiler-core/src/build/module_loader/tests.rs +++ b/compiler-core/src/build/module_loader/tests.rs @@ -213,13 +213,11 @@ fn write_cache( ) { let line_numbers = LineNumbers::new(source); let cache_metadata = CacheMetadata { - name: "".into(), mtime: SystemTime::UNIX_EPOCH + Duration::from_secs(seconds), codegen_performed, dependencies: vec![], fingerprint: SourceFingerprint::new(source), line_numbers, - interface: package_interface::ModuleInterface::default(), }; let path = Utf8Path::new(path); fs.write_bytes(&path, &cache_metadata.to_binary()).unwrap(); diff --git a/compiler-core/src/build/package_compiler.rs b/compiler-core/src/build/package_compiler.rs index c7532329b66..e4365c31000 100644 --- a/compiler-core/src/build/package_compiler.rs +++ b/compiler-core/src/build/package_compiler.rs @@ -106,7 +106,7 @@ where stale_modules: &mut StaleTracker, incomplete_modules: &mut HashSet, telemetry: &dyn Telemetry, - ) -> Outcome<(Vec, Vec), Error> { + ) -> Outcome, Error> { let span = tracing::info_span!("compile", package = %self.config.name.as_str()); let _enter = span.enter(); @@ -186,9 +186,7 @@ where let mut modules = match outcome { Outcome::Ok(modules) => modules, - Outcome::PartialFailure(modules, err) => { - return Outcome::PartialFailure((modules, loaded.cached_metadata), err) - } + Outcome::PartialFailure(modules, err) => return Outcome::PartialFailure(modules, err), Outcome::TotalFailure(err) => return Outcome::TotalFailure(err), }; @@ -202,7 +200,7 @@ where return error.into(); } - Outcome::Ok((modules, loaded.cached_metadata)) + Outcome::Ok(modules) } fn compile_erlang_to_beam(&mut self, modules: &HashSet) -> Result<(), Error> { @@ -309,13 +307,11 @@ where let name = format!("{}.cache_meta", &module_name); let path = artefact_dir.join(name); let info = CacheMetadata { - name: module.name.clone(), mtime: module.mtime, codegen_performed: self.perform_codegen, dependencies: module.dependencies.clone(), fingerprint: SourceFingerprint::new(&module.code), line_numbers: module.ast.type_info.line_numbers.clone(), - interface: package_interface::ModuleInterface::from_module(module), }; self.io.write_bytes(&path, &info.to_binary())?; @@ -601,28 +597,28 @@ pub(crate) fn module_name(package_path: &Utf8Path, full_module_path: &Utf8Path) #[derive(Debug)] pub(crate) enum Input { New(UncompiledModule), - Cached(CachedModule, CacheMetadata), + Cached(CachedModule), } impl Input { pub fn name(&self) -> &EcoString { match self { Input::New(m) => &m.name, - Input::Cached(m, _) => &m.name, + Input::Cached(m) => &m.name, } } pub fn source_path(&self) -> &Utf8Path { match self { Input::New(m) => &m.path, - Input::Cached(m, _) => &m.source_path, + Input::Cached(m) => &m.source_path, } } pub fn dependencies(&self) -> Vec { match self { Input::New(m) => m.dependencies.iter().map(|(n, _)| n.clone()).collect(), - Input::Cached(m, _) => m.dependencies.iter().map(|(n, _)| n.clone()).collect(), + Input::Cached(m) => m.dependencies.iter().map(|(n, _)| n.clone()).collect(), } } @@ -652,15 +648,13 @@ pub(crate) struct CachedModule { pub line_numbers: LineNumbers, } -#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)] +#[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct CacheMetadata { - pub name: EcoString, pub mtime: SystemTime, pub codegen_performed: bool, pub dependencies: Vec<(EcoString, SrcSpan)>, pub fingerprint: SourceFingerprint, pub line_numbers: LineNumbers, - pub interface: package_interface::ModuleInterface, } impl CacheMetadata { @@ -673,11 +667,10 @@ impl CacheMetadata { } } -#[derive(Debug, Default)] +#[derive(Debug, Default, PartialEq, Eq)] pub(crate) struct Loaded { pub to_compile: Vec, pub cached: Vec, - pub cached_metadata: Vec, } impl Loaded { @@ -685,12 +678,11 @@ impl Loaded { Self { to_compile: vec![], cached: vec![], - cached_metadata: vec![], } } } -#[derive(Debug, PartialEq, Eq, Clone)] +#[derive(Debug, PartialEq, Eq)] pub(crate) struct UncompiledModule { pub path: Utf8PathBuf, pub name: EcoString, diff --git a/compiler-core/src/build/package_loader.rs b/compiler-core/src/build/package_loader.rs index dd5f56e2eb5..c7bb8e6d4fb 100644 --- a/compiler-core/src/build/package_loader.rs +++ b/compiler-core/src/build/package_loader.rs @@ -148,7 +148,7 @@ where // A cached module with dependencies that are stale must be // recompiled as the changes in the dependencies may have affect // the output, making the cache invalid. - Input::Cached(info, _) if self.stale_modules.includes_any(&info.dependencies) => { + Input::Cached(info) if self.stale_modules.includes_any(&info.dependencies) => { tracing::debug!(module = %info.name, "module_to_be_compiled"); self.stale_modules.add(info.name.clone()); let module = self.load_and_parse(info)?; @@ -157,12 +157,18 @@ where // A cached module with no stale dependencies can be used as-is // and does not need to be recompiled. - Input::Cached(info, meta) => { - tracing::debug!(module = %info.name, "module_to_load_from_cache"); - let module = self.load_cached_module(info)?; - loaded.cached.push(module); - loaded.cached_metadata.push(meta); - } + Input::Cached(info) => match self.mode { + Mode::PackageInterface => { + tracing::debug!(module = %info.name, "module_to_be_compiled"); + let module = self.load_and_parse(info)?; + loaded.to_compile.push(module); + } + _ => { + tracing::debug!(module = %info.name, "module_to_load_from_cache"); + let module = self.load_cached_module(info)?; + loaded.cached.push(module); + } + }, } } @@ -325,7 +331,7 @@ where src: module.code.clone(), } } - Input::Cached(cached_module, _) => { + Input::Cached(cached_module) => { let (_, location) = cached_module .dependencies .iter() diff --git a/compiler-core/src/build/package_loader/tests.rs b/compiler-core/src/build/package_loader/tests.rs index e2916dba4e0..5eb2c763c53 100644 --- a/compiler-core/src/build/package_loader/tests.rs +++ b/compiler-core/src/build/package_loader/tests.rs @@ -39,13 +39,11 @@ fn write_cache( let line_numbers = line_numbers::LineNumbers::new(src); let mtime = SystemTime::UNIX_EPOCH + Duration::from_secs(seconds); let cache_metadata = CacheMetadata { - name: name.into(), mtime, codegen_performed: true, dependencies: deps, fingerprint: SourceFingerprint::new(src), line_numbers: line_numbers.clone(), - interface: package_interface::ModuleInterface::default(), }; let path = Utf8Path::new("/artefact").join(format!("{name}.cache_meta")); fs.write_bytes(&path, &cache_metadata.to_binary()).unwrap(); diff --git a/compiler-core/src/build/project_compiler.rs b/compiler-core/src/build/project_compiler.rs index 2367dae3786..dc08b8fd742 100644 --- a/compiler-core/src/build/project_compiler.rs +++ b/compiler-core/src/build/project_compiler.rs @@ -208,11 +208,7 @@ where pub fn compile_root_package(&mut self) -> Outcome { let config = self.config.clone(); self.compile_gleam_package(&config, true, self.paths.root().to_path_buf()) - .map(|(modules, cached_metadata)| Package { - config, - modules, - cached_metadata, - }) + .map(|modules| Package { config, modules }) } /// Checks that version file found in the build directory matches the @@ -292,9 +288,7 @@ where // longer need to have the package borrowed from self.packages. let package = self.packages.get(name).expect("Missing package").clone(); let result = match usable_build_tools(&package)?.as_slice() { - &[BuildTool::Gleam] => self - .compile_gleam_dep_package(&package) - .map(|(modules, _)| modules), + &[BuildTool::Gleam] => self.compile_gleam_dep_package(&package), &[BuildTool::Rebar3] => self.compile_rebar3_dep_package(&package).map(|_| vec![]), &[BuildTool::Mix] => self.compile_mix_dep_package(&package).map(|_| vec![]), &[BuildTool::Mix, BuildTool::Rebar3] => self @@ -495,7 +489,7 @@ where fn compile_gleam_dep_package( &mut self, package: &ManifestPackage, - ) -> Result<(Vec, Vec), Error> { + ) -> Result, Error> { // TODO: Test let package_root = match &package.source { // If the path is relative it is relative to the root of the @@ -526,7 +520,7 @@ where config: &PackageConfig, is_root: bool, root_path: Utf8PathBuf, - ) -> Outcome<(Vec, Vec), Error> { + ) -> Outcome<(Vec), Error> { let out_path = self.paths .build_directory_for_package(self.mode(), self.target(), &config.name); diff --git a/compiler-core/src/config.rs b/compiler-core/src/config.rs index b583fa58a5e..1f814cfbd4e 100644 --- a/compiler-core/src/config.rs +++ b/compiler-core/src/config.rs @@ -137,7 +137,7 @@ impl PackageConfig { pub fn dependencies_for(&self, mode: Mode) -> Result { match mode { Mode::Dev | Mode::Lsp => self.all_drect_dependencies(), - Mode::Prod => Ok(self.dependencies.clone()), + Mode::Prod | Mode::PackageInterface => Ok(self.dependencies.clone()), } } diff --git a/compiler-core/src/docs/tests.rs b/compiler-core/src/docs/tests.rs index e8f3922b955..8469cea2be1 100644 --- a/compiler-core/src/docs/tests.rs +++ b/compiler-core/src/docs/tests.rs @@ -63,7 +63,7 @@ fn compile_with_markdown_pages( ) .unwrap(); - for module in &mut modules.0 { + for module in &mut modules { module.attach_doc_and_module_comments(); } @@ -79,7 +79,7 @@ fn compile_with_markdown_pages( super::generate_html( &paths, &config, - &modules.0, + &modules, &docs_pages, pages_fs, SystemTime::UNIX_EPOCH, diff --git a/compiler-core/src/package_interface.rs b/compiler-core/src/package_interface.rs index 33435add491..12104f4f8bd 100644 --- a/compiler-core/src/package_interface.rs +++ b/compiler-core/src/package_interface.rs @@ -2,7 +2,7 @@ use std::{collections::HashMap, ops::Deref}; use ecow::EcoString; use itertools::Itertools; -use serde::{Deserialize, Serialize}; +use serde::Serialize; #[cfg(test)] mod tests; @@ -28,7 +28,7 @@ pub struct PackageInterface { modules: HashMap, } -#[derive(Deserialize, Serialize, Debug, Clone, Default)] +#[derive(Serialize, Debug)] #[serde(rename_all = "kebab-case")] pub struct ModuleInterface { /// A vector with the lines composing the module's documentation (that is @@ -48,7 +48,7 @@ pub struct ModuleInterface { functions: HashMap, } -#[derive(Deserialize, Serialize, Debug, Clone)] +#[derive(Serialize, Debug)] #[serde(rename_all = "kebab-case")] pub struct TypeDefinitionInterface { /// The definition's documentation comment (that is every line preceded by @@ -71,7 +71,7 @@ pub struct TypeDefinitionInterface { constructors: Vec, } -#[derive(Deserialize, Serialize, Debug, Clone)] +#[derive(Serialize, Debug)] #[serde(rename_all = "kebab-case")] pub struct TypeConstructorInterface { /// The constructor's documentation comment (that is every line preceded by @@ -95,7 +95,7 @@ pub struct TypeConstructorInterface { parameters: Vec, } -#[derive(Deserialize, Serialize, Debug, Clone)] +#[derive(Serialize, Debug)] #[serde(rename_all = "kebab-case")] pub struct TypeAliasInterface { /// The constructor's documentation comment (that is every line preceded by @@ -118,7 +118,7 @@ pub struct TypeAliasInterface { alias: TypeInterface, } -#[derive(Deserialize, Serialize, Debug, Clone)] +#[derive(Serialize, Debug)] #[serde(rename_all = "kebab-case")] pub struct ConstantInterface { /// The constant's documentation comment (that is every line preceded by @@ -135,7 +135,7 @@ pub struct ConstantInterface { /// A module's function. This differs from a simple `Fn` type as its arguments /// can be labelled. -#[derive(Deserialize, Serialize, Debug, Clone)] +#[derive(Serialize, Debug)] #[serde(rename_all = "kebab-case")] pub struct FunctionInterface { /// The function's documentation comment (that is every line preceded by @@ -151,7 +151,7 @@ pub struct FunctionInterface { } /// Informations about how a value is implemented. -#[derive(Debug, Deserialize, Serialize, Copy, Clone)] +#[derive(Debug, Serialize, Copy, Clone)] #[serde(rename_all = "kebab-case")] pub struct ImplementationsInterface { /// Set to `true` if the const/function has a pure Gleam implementation @@ -273,7 +273,7 @@ impl ImplementationsInterface { } } -#[derive(Deserialize, Serialize, Debug, Clone)] +#[derive(Serialize, Debug)] #[serde(rename_all = "kebab-case")] pub struct DeprecationInterface { /// The reason for the deprecation. @@ -291,8 +291,8 @@ impl DeprecationInterface { } } -#[derive(Deserialize, Serialize, Debug, Clone)] -// #[serde(tag = "kind")] +#[derive(Serialize, Debug)] +#[serde(tag = "kind")] #[serde(rename_all = "kebab-case")] pub enum TypeInterface { /// A tuple type like `#(Int, Float)`. @@ -339,7 +339,7 @@ pub enum TypeInterface { }, } -#[derive(Deserialize, Serialize, Debug, Clone)] +#[derive(Serialize, Debug)] #[serde(rename_all = "kebab-case")] pub struct ParameterInterface { /// If the parameter is labelled this will hold the label's name. @@ -372,13 +372,6 @@ impl PackageInterface { .iter() .filter(|module| !package.config.is_internal_module(module.name.as_str())) .map(|module| (module.name.clone(), ModuleInterface::from_module(module))) - .chain( - package - .cached_metadata - .clone() - .into_iter() - .map(|module| (module.name.clone(), module.interface)), - ) .collect(), } } diff --git a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__generic_function.snap b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__generic_function.snap index c4879c53903..95fa12696c7 100644 --- a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__generic_function.snap +++ b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__generic_function.snap @@ -40,18 +40,16 @@ expression: "\npub type Wob(a) { Wob }\n@deprecated(\"deprecation message\")\npu }, "parameters": [], "return": { - "named": { - "name": "Wob", - "package": "my_package", - "module": "my/module", - "parameters": [ - { - "variable": { - "id": 0 - } - } - ] - } + "kind": "named", + "name": "Wob", + "package": "my_package", + "module": "my/module", + "parameters": [ + { + "kind": "variable", + "id": 0 + } + ] } } } diff --git a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__imported_aliased_type_keeps_original_name.snap b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__imported_aliased_type_keeps_original_name.snap index b2fe7cb9228..daf91d5e956 100644 --- a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__imported_aliased_type_keeps_original_name.snap +++ b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__imported_aliased_type_keeps_original_name.snap @@ -25,27 +25,24 @@ expression: "\nimport other_module.{type Element as Alias} as module_alias\npub }, "parameters": [], "return": { - "named": { - "name": "Element", - "package": "other_package", - "module": "other_module", - "parameters": [ - { - "named": { - "name": "Element", - "package": "other_package", - "module": "other_module", - "parameters": [ - { - "variable": { - "id": 0 - } - } - ] + "kind": "named", + "name": "Element", + "package": "other_package", + "module": "other_module", + "parameters": [ + { + "kind": "named", + "name": "Element", + "package": "other_package", + "module": "other_module", + "parameters": [ + { + "kind": "variable", + "id": 0 } - } - ] - } + ] + } + ] } } } diff --git a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__imported_type.snap b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__imported_type.snap index 1688b9ed14d..63ec92f1715 100644 --- a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__imported_type.snap +++ b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__imported_type.snap @@ -25,21 +25,19 @@ expression: "\nimport other_module.{type Element}\npub fn main() -> Element(Int) }, "parameters": [], "return": { - "named": { - "name": "Element", - "package": "other_package", - "module": "other_module", - "parameters": [ - { - "named": { - "name": "Int", - "package": "", - "module": "gleam", - "parameters": [] - } - } - ] - } + "kind": "named", + "name": "Element", + "package": "other_package", + "module": "other_module", + "parameters": [ + { + "kind": "named", + "name": "Int", + "package": "", + "module": "gleam", + "parameters": [] + } + ] } } } diff --git a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__multiple_type_variables.snap b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__multiple_type_variables.snap index 2e4e4e31d9b..aca6ea2295b 100644 --- a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__multiple_type_variables.snap +++ b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__multiple_type_variables.snap @@ -34,60 +34,52 @@ expression: "\npub type Box(a, b)\npub fn some_type_variables(a: a, b: b, c: Box { "label": null, "type": { - "variable": { - "id": 0 - } + "kind": "variable", + "id": 0 } }, { "label": null, "type": { - "variable": { - "id": 1 - } + "kind": "variable", + "id": 1 } }, { "label": null, "type": { - "named": { - "name": "Box", - "package": "my_package", - "module": "my/module", - "parameters": [ - { - "variable": { - "id": 2 - } - }, - { - "variable": { - "id": 3 - } - } - ] - } + "kind": "named", + "name": "Box", + "package": "my_package", + "module": "my/module", + "parameters": [ + { + "kind": "variable", + "id": 2 + }, + { + "kind": "variable", + "id": 3 + } + ] } } ], "return": { - "named": { - "name": "Box", - "package": "my_package", - "module": "my/module", - "parameters": [ - { - "variable": { - "id": 0 - } - }, - { - "variable": { - "id": 3 - } - } - ] - } + "kind": "named", + "name": "Box", + "package": "my_package", + "module": "my/module", + "parameters": [ + { + "kind": "variable", + "id": 0 + }, + { + "kind": "variable", + "id": 3 + } + ] } } } diff --git a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__package_documentation_is_included.snap b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__package_documentation_is_included.snap index d10ff70c315..45bb53a4bbe 100644 --- a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__package_documentation_is_included.snap +++ b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__package_documentation_is_included.snap @@ -28,12 +28,11 @@ expression: "\n//// Some package\n//// documentation!\n\npub fn main() { 1 }\n" }, "parameters": [], "return": { - "named": { - "name": "Int", - "package": "", - "module": "gleam", - "parameters": [] - } + "kind": "named", + "name": "Int", + "package": "", + "module": "gleam", + "parameters": [] } } } diff --git a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__prelude_types.snap b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__prelude_types.snap index 94b92e3b696..e58344a5f0f 100644 --- a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__prelude_types.snap +++ b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__prelude_types.snap @@ -23,12 +23,11 @@ expression: "\npub const float = 1.1\npub const string = \"\"\npub const int = 1 "can-run-on-javascript": true }, "type": { - "named": { - "name": "Bool", - "package": "", - "module": "gleam", - "parameters": [] - } + "kind": "named", + "name": "Bool", + "package": "", + "module": "gleam", + "parameters": [] } }, "float": { @@ -42,12 +41,11 @@ expression: "\npub const float = 1.1\npub const string = \"\"\npub const int = 1 "can-run-on-javascript": true }, "type": { - "named": { - "name": "Float", - "package": "", - "module": "gleam", - "parameters": [] - } + "kind": "named", + "name": "Float", + "package": "", + "module": "gleam", + "parameters": [] } }, "int": { @@ -61,12 +59,11 @@ expression: "\npub const float = 1.1\npub const string = \"\"\npub const int = 1 "can-run-on-javascript": true }, "type": { - "named": { - "name": "Int", - "package": "", - "module": "gleam", - "parameters": [] - } + "kind": "named", + "name": "Int", + "package": "", + "module": "gleam", + "parameters": [] } }, "string": { @@ -80,12 +77,11 @@ expression: "\npub const float = 1.1\npub const string = \"\"\npub const int = 1 "can-run-on-javascript": true }, "type": { - "named": { - "name": "String", - "package": "", - "module": "gleam", - "parameters": [] - } + "kind": "named", + "name": "String", + "package": "", + "module": "gleam", + "parameters": [] } } }, diff --git a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_aliases.snap b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_aliases.snap index 8a10551bd2c..978b8459f9e 100644 --- a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_aliases.snap +++ b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_aliases.snap @@ -15,18 +15,16 @@ expression: pub type Wibble(a) = List(a) "deprecation": null, "parameters": 1, "alias": { - "named": { - "name": "List", - "package": "", - "module": "gleam", - "parameters": [ - { - "variable": { - "id": 0 - } - } - ] - } + "kind": "named", + "name": "List", + "package": "", + "module": "gleam", + "parameters": [ + { + "kind": "variable", + "id": 0 + } + ] } } }, diff --git a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_constructors.snap b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_constructors.snap index 01f95cf0fe0..115ad135a49 100644 --- a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_constructors.snap +++ b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_constructors.snap @@ -23,20 +23,18 @@ expression: "\npub type Box(a, b) {\n Box(b, Int)\n OtherBox(message: String, { "label": null, "type": { - "variable": { - "id": 1 - } + "kind": "variable", + "id": 1 } }, { "label": null, "type": { - "named": { - "name": "Int", - "package": "", - "module": "gleam", - "parameters": [] - } + "kind": "named", + "name": "Int", + "package": "", + "module": "gleam", + "parameters": [] } } ] @@ -48,20 +46,18 @@ expression: "\npub type Box(a, b) {\n Box(b, Int)\n OtherBox(message: String, { "label": "message", "type": { - "named": { - "name": "String", - "package": "", - "module": "gleam", - "parameters": [] - } + "kind": "named", + "name": "String", + "package": "", + "module": "gleam", + "parameters": [] } }, { "label": "a", "type": { - "variable": { - "id": 0 - } + "kind": "variable", + "id": 0 } } ] diff --git a/compiler-core/src/package_interface/tests.rs b/compiler-core/src/package_interface/tests.rs index 8bf9fbffdf4..5495a848db9 100644 --- a/compiler-core/src/package_interface/tests.rs +++ b/compiler-core/src/package_interface/tests.rs @@ -172,7 +172,6 @@ fn package_from_module(module: Module) -> Package { .expect("internals glob")]), }, modules: vec![module], - cached_metadata: vec![], } } diff --git a/compiler-core/src/parse/extra.rs b/compiler-core/src/parse/extra.rs index 72003014daf..b6e2cb6a060 100644 --- a/compiler-core/src/parse/extra.rs +++ b/compiler-core/src/parse/extra.rs @@ -4,7 +4,7 @@ use ecow::EcoString; use crate::ast::SrcSpan; -#[derive(Debug, PartialEq, Eq, Default, Clone)] +#[derive(Debug, PartialEq, Eq, Default)] pub struct ModuleExtra { pub module_comments: Vec, pub doc_comments: Vec, diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__alias_unqualified_import.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__alias_unqualified_import.snap index f8f0a477f2f..c86ee2fdc42 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__alias_unqualified_import.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__alias_unqualified_import.snap @@ -6,7 +6,7 @@ expression: "./cases/alias_unqualified_import" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one.cache_meta -<231 byte binary> +<77 byte binary> //// /out/lib/the_package/_gleam_artefacts/one.erl -module(one). @@ -27,7 +27,7 @@ id(X) -> <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<217 byte binary> +<88 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_app_generation.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_app_generation.snap index a6e0cfd9f39..1daa51c17aa 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_app_generation.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_app_generation.snap @@ -6,7 +6,7 @@ expression: "./cases/erlang_app_generation" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/main.cache_meta -<101 byte binary> +<49 byte binary> //// /out/lib/the_package/_gleam_artefacts/main.erl -module(main). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_bug_752.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_bug_752.snap index fd2ea7426c9..ceb2c58b67a 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_bug_752.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_bug_752.snap @@ -6,7 +6,7 @@ expression: "./cases/erlang_bug_752" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one.cache_meta -<170 byte binary> +<57 byte binary> //// /out/lib/the_package/_gleam_artefacts/one.erl -module(one). @@ -23,7 +23,7 @@ expression: "./cases/erlang_bug_752" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<291 byte binary> +<84 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_empty.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_empty.snap index f2940d8b307..974c1958f24 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_empty.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_empty.snap @@ -6,7 +6,7 @@ expression: "./cases/erlang_empty" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/empty.cache_meta -<102 byte binary> +<49 byte binary> //// /out/lib/the_package/_gleam_artefacts/empty.erl -module(empty). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_escape_names.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_escape_names.snap index ab3df4c253d..e78455ffbf8 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_escape_names.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_escape_names.snap @@ -6,7 +6,7 @@ expression: "./cases/erlang_escape_names" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one.cache_meta -<167 byte binary> +<61 byte binary> //// /out/lib/the_package/_gleam_artefacts/one.erl -module(one). @@ -24,7 +24,7 @@ expression: "./cases/erlang_escape_names" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<501 byte binary> +<136 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_import.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_import.snap index 992cf024ca7..0b4119957e4 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_import.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_import.snap @@ -6,7 +6,7 @@ expression: "./cases/erlang_import" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one.cache_meta -<261 byte binary> +<88 byte binary> //// /out/lib/the_package/_gleam_artefacts/one.erl -module(one). @@ -25,7 +25,7 @@ unbox(X) -> <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<202 byte binary> +<57 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_import_shadowing_prelude.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_import_shadowing_prelude.snap index 703b5acd44e..5fe05f608a9 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_import_shadowing_prelude.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_import_shadowing_prelude.snap @@ -6,7 +6,7 @@ expression: "./cases/erlang_import_shadowing_prelude" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one.cache_meta -<165 byte binary> +<61 byte binary> //// /out/lib/the_package/_gleam_artefacts/one.erl -module(one). @@ -23,7 +23,7 @@ expression: "./cases/erlang_import_shadowing_prelude" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<217 byte binary> +<88 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_nested.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_nested.snap index 75d0a5daf34..fd4bcc12afd 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_nested.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_nested.snap @@ -6,7 +6,7 @@ expression: "./cases/erlang_nested" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one@two.cache_meta -<186 byte binary> +<57 byte binary> //// /out/lib/the_package/_gleam_artefacts/one@two.erl -module(one@two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_nested_qualified_constant.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_nested_qualified_constant.snap index aa8e750bd1e..5f3afcf4381 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_nested_qualified_constant.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__erlang_nested_qualified_constant.snap @@ -6,7 +6,7 @@ expression: "./cases/erlang_nested_qualified_constant" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one@two.cache_meta -<157 byte binary> +<57 byte binary> //// /out/lib/the_package/_gleam_artefacts/one@two.erl -module(one@two). @@ -23,7 +23,7 @@ expression: "./cases/erlang_nested_qualified_constant" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<218 byte binary> +<100 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__hello_joe.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__hello_joe.snap index 08393a4bdfa..b41af80b864 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__hello_joe.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__hello_joe.snap @@ -6,7 +6,7 @@ expression: "./cases/hello_joe" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/hello_joe.cache_meta -<188 byte binary> +<57 byte binary> //// /out/lib/the_package/_gleam_artefacts/hello_joe.erl -module(hello_joe). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__import_shadowed_name_warning.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__import_shadowed_name_warning.snap index 0ac1dc65044..5cf6a2adfc3 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__import_shadowed_name_warning.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__import_shadowed_name_warning.snap @@ -6,7 +6,7 @@ expression: "./cases/import_shadowed_name_warning" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one.cache_meta -<138 byte binary> +<57 byte binary> //// /out/lib/the_package/_gleam_artefacts/one.erl -module(one). @@ -23,7 +23,7 @@ expression: "./cases/import_shadowed_name_warning" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<297 byte binary> +<120 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_constants.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_constants.snap index 606bec30122..dc0b482e048 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_constants.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_constants.snap @@ -6,7 +6,7 @@ expression: "./cases/imported_constants" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one.cache_meta -<495 byte binary> +<89 byte binary> //// /out/lib/the_package/_gleam_artefacts/one.erl -module(one). @@ -27,7 +27,7 @@ expression: "./cases/imported_constants" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<2520 byte binary> +<324 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_external_fns.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_external_fns.snap index 5e06e611290..ef082865fe7 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_external_fns.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_external_fns.snap @@ -6,7 +6,7 @@ expression: "./cases/imported_external_fns" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one.cache_meta -<176 byte binary> +<53 byte binary> //// /out/lib/the_package/_gleam_artefacts/one.erl -module(one). @@ -24,7 +24,7 @@ thing() -> <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<1227 byte binary> +<319 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_record_constructors.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_record_constructors.snap index 3c23ff05409..b5832c1f7d6 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_record_constructors.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__imported_record_constructors.snap @@ -6,7 +6,7 @@ expression: "./cases/imported_record_constructors" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one@one.cache_meta -<507 byte binary> +<89 byte binary> //// /out/lib/the_package/_gleam_artefacts/one@one.erl -module(one@one). @@ -27,7 +27,7 @@ expression: "./cases/imported_record_constructors" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<3990 byte binary> +<491 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.erl -module(two). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_d_ts.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_d_ts.snap index 010ab823e75..653d750f927 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_d_ts.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_d_ts.snap @@ -6,7 +6,7 @@ expression: "./cases/javascript_d_ts" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/hello.cache_meta -<259 byte binary> +<73 byte binary> //// /out/lib/the_package/gleam.d.mts export * from "../prelude.d.mts"; diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_empty.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_empty.snap index 3fb1d18e25d..e0b9a3d176a 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_empty.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_empty.snap @@ -6,7 +6,7 @@ expression: "./cases/javascript_empty" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/empty.cache_meta -<102 byte binary> +<49 byte binary> //// /out/lib/the_package/empty.mjs export {} diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_import.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_import.snap index 538eba5dc38..e79a95a7735 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_import.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__javascript_import.snap @@ -6,13 +6,13 @@ expression: "./cases/javascript_import" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/one@two.cache_meta -<157 byte binary> +<57 byte binary> //// /out/lib/the_package/_gleam_artefacts/two.cache <.cache binary> //// /out/lib/the_package/_gleam_artefacts/two.cache_meta -<198 byte binary> +<80 byte binary> //// /out/lib/the_package/gleam.d.mts export * from "../prelude.d.mts"; diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__not_overwriting_erlang_module.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__not_overwriting_erlang_module.snap index a4bf06ed4c4..afd26eee2a6 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__not_overwriting_erlang_module.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__not_overwriting_erlang_module.snap @@ -6,7 +6,7 @@ expression: "./cases/not_overwriting_erlang_module" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/app@code.cache_meta -<121 byte binary> +<65 byte binary> //// /out/lib/the_package/_gleam_artefacts/app@code.erl -module(app@code). diff --git a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__variable_or_module.snap b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__variable_or_module.snap index 488ce88bc99..9d2270e288b 100644 --- a/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__variable_or_module.snap +++ b/test-package-compiler/src/snapshots/test_package_compiler__generated_tests__variable_or_module.snap @@ -6,7 +6,7 @@ expression: "./cases/variable_or_module" <.cache binary> //// /out/lib/the_package/_gleam_artefacts/main.cache_meta -<439 byte binary> +<118 byte binary> //// /out/lib/the_package/_gleam_artefacts/main.erl -module(main). @@ -29,7 +29,7 @@ record_field(Power) -> <.cache binary> //// /out/lib/the_package/_gleam_artefacts/power.cache_meta -<368 byte binary> +<77 byte binary> //// /out/lib/the_package/_gleam_artefacts/power.erl -module(power). From 11c1d18609d32e9b9f40e10b08c1427a0cede5c5 Mon Sep 17 00:00:00 2001 From: Pedro H C Francisco <75535904+mine-tech-oficial@users.noreply.github.com> Date: Fri, 18 Oct 2024 17:32:11 -0300 Subject: [PATCH 06/12] Made exporting use as much from cache as possible. --- compiler-cli/src/export.rs | 2 +- compiler-core/build.rs | 10 +- compiler-core/generated/schema_capnp.rs | 468 +++++++++++++++--- compiler-core/schema.capnp | 33 +- compiler-core/src/analyse.rs | 38 +- compiler-core/src/build.rs | 13 +- compiler-core/src/build/package_compiler.rs | 16 +- compiler-core/src/build/package_loader.rs | 23 +- .../src/build/package_loader/tests.rs | 6 +- compiler-core/src/build/project_compiler.rs | 20 +- compiler-core/src/config.rs | 2 +- compiler-core/src/docs.rs | 1 + compiler-core/src/docs/tests.rs | 4 +- compiler-core/src/exhaustiveness.rs | 1 + compiler-core/src/metadata/module_decoder.rs | 36 +- compiler-core/src/metadata/module_encoder.rs | 99 +++- compiler-core/src/metadata/tests.rs | 58 +++ compiler-core/src/package_interface.rs | 220 +++++++- compiler-core/src/package_interface/tests.rs | 1 + compiler-core/src/parse/extra.rs | 2 +- compiler-core/src/type_.rs | 6 + compiler-core/src/type_/environment.rs | 26 + compiler-core/src/type_/prelude.rs | 4 + compiler-core/src/type_/tests.rs | 4 + 24 files changed, 963 insertions(+), 130 deletions(-) diff --git a/compiler-cli/src/export.rs b/compiler-cli/src/export.rs index c34035e5a65..9b58293e2c4 100644 --- a/compiler-cli/src/export.rs +++ b/compiler-cli/src/export.rs @@ -130,7 +130,7 @@ pub fn package_interface(path: Utf8PathBuf) -> Result<()> { // Build the project let mut built = crate::build::main( Options { - mode: Mode::PackageInterface, + mode: Mode::Prod, target: None, codegen: Codegen::All, compile: Compile::All, diff --git a/compiler-core/build.rs b/compiler-core/build.rs index 6f3fb7ce04f..cb2bf0f2c21 100644 --- a/compiler-core/build.rs +++ b/compiler-core/build.rs @@ -1,7 +1,7 @@ fn main() { - // capnpc::CompilerCommand::new() - // .file("schema.capnp") - // .output_path("generated/") - // .run() - // .expect("compiling schema.capnp"); + capnpc::CompilerCommand::new() + .file("schema.capnp") + .output_path("generated/") + .run() + .expect("compiling schema.capnp"); } diff --git a/compiler-core/generated/schema_capnp.rs b/compiler-core/generated/schema_capnp.rs index 6d1958808c4..033464b233b 100644 --- a/compiler-core/generated/schema_capnp.rs +++ b/compiler-core/generated/schema_capnp.rs @@ -430,72 +430,88 @@ pub mod module { !self.reader.get_pointer_field(0).is_null() } #[inline] - pub fn get_types(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { + pub fn get_documentation(self) -> ::capnp::Result<::capnp::text_list::Reader<'a>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1), ::core::option::Option::None) } #[inline] - pub fn has_types(&self) -> bool { + pub fn has_documentation(&self) -> bool { !self.reader.get_pointer_field(1).is_null() } #[inline] - pub fn get_values(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { + pub fn get_types(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(2), ::core::option::Option::None) } #[inline] - pub fn has_values(&self) -> bool { + pub fn has_types(&self) -> bool { !self.reader.get_pointer_field(2).is_null() } #[inline] - pub fn get_accessors(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { + pub fn get_type_aliases(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(3), ::core::option::Option::None) } #[inline] - pub fn has_accessors(&self) -> bool { + pub fn has_type_aliases(&self) -> bool { !self.reader.get_pointer_field(3).is_null() } #[inline] - pub fn get_package(self) -> ::capnp::Result<::capnp::text::Reader<'a>> { + pub fn get_values(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(4), ::core::option::Option::None) } #[inline] - pub fn has_package(&self) -> bool { + pub fn has_values(&self) -> bool { !self.reader.get_pointer_field(4).is_null() } #[inline] - pub fn get_types_constructors(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { + pub fn get_accessors(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(5), ::core::option::Option::None) } #[inline] - pub fn has_types_constructors(&self) -> bool { + pub fn has_accessors(&self) -> bool { !self.reader.get_pointer_field(5).is_null() } #[inline] - pub fn get_line_numbers(self) -> ::capnp::Result> { + pub fn get_package(self) -> ::capnp::Result<::capnp::text::Reader<'a>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(6), ::core::option::Option::None) } #[inline] - pub fn has_line_numbers(&self) -> bool { + pub fn has_package(&self) -> bool { !self.reader.get_pointer_field(6).is_null() } #[inline] - pub fn get_src_path(self) -> ::capnp::Result<::capnp::text::Reader<'a>> { + pub fn get_types_constructors(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(7), ::core::option::Option::None) } #[inline] - pub fn has_src_path(&self) -> bool { + pub fn has_types_constructors(&self) -> bool { !self.reader.get_pointer_field(7).is_null() } #[inline] + pub fn get_line_numbers(self) -> ::capnp::Result> { + ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(8), ::core::option::Option::None) + } + #[inline] + pub fn has_line_numbers(&self) -> bool { + !self.reader.get_pointer_field(8).is_null() + } + #[inline] + pub fn get_src_path(self) -> ::capnp::Result<::capnp::text::Reader<'a>> { + ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(9), ::core::option::Option::None) + } + #[inline] + pub fn has_src_path(&self) -> bool { + !self.reader.get_pointer_field(9).is_null() + } + #[inline] pub fn get_is_internal(self) -> bool { self.reader.get_bool_field(0) } #[inline] pub fn get_required_version(self) -> ::capnp::Result> { - ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(8), ::core::option::Option::None) + ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(10), ::core::option::Option::None) } #[inline] pub fn has_required_version(&self) -> bool { - !self.reader.get_pointer_field(8).is_null() + !self.reader.get_pointer_field(10).is_null() } } @@ -564,116 +580,148 @@ pub mod module { !self.builder.get_pointer_field(0).is_null() } #[inline] - pub fn get_types(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { + pub fn get_documentation(self) -> ::capnp::Result<::capnp::text_list::Builder<'a>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1), ::core::option::Option::None) } #[inline] - pub fn set_types(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { + pub fn set_documentation(&mut self, value: ::capnp::text_list::Reader<'a>) -> ::capnp::Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value, false) } #[inline] - pub fn init_types(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { + pub fn init_documentation(self, size: u32) -> ::capnp::text_list::Builder<'a> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), size) } #[inline] - pub fn has_types(&self) -> bool { + pub fn has_documentation(&self) -> bool { !self.builder.get_pointer_field(1).is_null() } #[inline] - pub fn get_values(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { + pub fn get_types(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(2), ::core::option::Option::None) } #[inline] - pub fn set_values(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { + pub fn set_types(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(2), value, false) } #[inline] - pub fn init_values(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { + pub fn init_types(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(2), size) } #[inline] - pub fn has_values(&self) -> bool { + pub fn has_types(&self) -> bool { !self.builder.get_pointer_field(2).is_null() } #[inline] - pub fn get_accessors(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { + pub fn get_type_aliases(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(3), ::core::option::Option::None) } #[inline] - pub fn set_accessors(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { + pub fn set_type_aliases(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(3), value, false) } #[inline] - pub fn init_accessors(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { + pub fn init_type_aliases(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(3), size) } #[inline] - pub fn has_accessors(&self) -> bool { + pub fn has_type_aliases(&self) -> bool { !self.builder.get_pointer_field(3).is_null() } #[inline] - pub fn get_package(self) -> ::capnp::Result<::capnp::text::Builder<'a>> { + pub fn get_values(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(4), ::core::option::Option::None) } #[inline] + pub fn set_values(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { + ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(4), value, false) + } + #[inline] + pub fn init_values(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { + ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(4), size) + } + #[inline] + pub fn has_values(&self) -> bool { + !self.builder.get_pointer_field(4).is_null() + } + #[inline] + pub fn get_accessors(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { + ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(5), ::core::option::Option::None) + } + #[inline] + pub fn set_accessors(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { + ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(5), value, false) + } + #[inline] + pub fn init_accessors(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { + ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(5), size) + } + #[inline] + pub fn has_accessors(&self) -> bool { + !self.builder.get_pointer_field(5).is_null() + } + #[inline] + pub fn get_package(self) -> ::capnp::Result<::capnp::text::Builder<'a>> { + ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(6), ::core::option::Option::None) + } + #[inline] pub fn set_package(&mut self, value: ::capnp::text::Reader<'_>) { - self.builder.get_pointer_field(4).set_text(value); + self.builder.get_pointer_field(6).set_text(value); } #[inline] pub fn init_package(self, size: u32) -> ::capnp::text::Builder<'a> { - self.builder.get_pointer_field(4).init_text(size) + self.builder.get_pointer_field(6).init_text(size) } #[inline] pub fn has_package(&self) -> bool { - !self.builder.get_pointer_field(4).is_null() + !self.builder.get_pointer_field(6).is_null() } #[inline] pub fn get_types_constructors(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { - ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(5), ::core::option::Option::None) + ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(7), ::core::option::Option::None) } #[inline] pub fn set_types_constructors(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { - ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(5), value, false) + ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(7), value, false) } #[inline] pub fn init_types_constructors(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { - ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(5), size) + ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(7), size) } #[inline] pub fn has_types_constructors(&self) -> bool { - !self.builder.get_pointer_field(5).is_null() + !self.builder.get_pointer_field(7).is_null() } #[inline] pub fn get_line_numbers(self) -> ::capnp::Result> { - ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(6), ::core::option::Option::None) + ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(8), ::core::option::Option::None) } #[inline] pub fn set_line_numbers(&mut self, value: crate::schema_capnp::line_numbers::Reader<'_>) -> ::capnp::Result<()> { - ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(6), value, false) + ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(8), value, false) } #[inline] pub fn init_line_numbers(self, ) -> crate::schema_capnp::line_numbers::Builder<'a> { - ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(6), 0) + ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(8), 0) } #[inline] pub fn has_line_numbers(&self) -> bool { - !self.builder.get_pointer_field(6).is_null() + !self.builder.get_pointer_field(8).is_null() } #[inline] pub fn get_src_path(self) -> ::capnp::Result<::capnp::text::Builder<'a>> { - ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(7), ::core::option::Option::None) + ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(9), ::core::option::Option::None) } #[inline] pub fn set_src_path(&mut self, value: ::capnp::text::Reader<'_>) { - self.builder.get_pointer_field(7).set_text(value); + self.builder.get_pointer_field(9).set_text(value); } #[inline] pub fn init_src_path(self, size: u32) -> ::capnp::text::Builder<'a> { - self.builder.get_pointer_field(7).init_text(size) + self.builder.get_pointer_field(9).init_text(size) } #[inline] pub fn has_src_path(&self) -> bool { - !self.builder.get_pointer_field(7).is_null() + !self.builder.get_pointer_field(9).is_null() } #[inline] pub fn get_is_internal(self) -> bool { @@ -685,19 +733,19 @@ pub mod module { } #[inline] pub fn get_required_version(self) -> ::capnp::Result> { - ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(8), ::core::option::Option::None) + ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(10), ::core::option::Option::None) } #[inline] pub fn set_required_version(&mut self, value: crate::schema_capnp::version::Reader<'_>) -> ::capnp::Result<()> { - ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(8), value, false) + ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(10), value, false) } #[inline] pub fn init_required_version(self, ) -> crate::schema_capnp::version::Builder<'a> { - ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(8), 0) + ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(10), 0) } #[inline] pub fn has_required_version(&self) -> bool { - !self.builder.get_pointer_field(8).is_null() + !self.builder.get_pointer_field(10).is_null() } } @@ -709,15 +757,15 @@ pub mod module { } impl Pipeline { pub fn get_line_numbers(&self) -> crate::schema_capnp::line_numbers::Pipeline { - ::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(6)) + ::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(8)) } pub fn get_required_version(&self) -> crate::schema_capnp::version::Pipeline { - ::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(8)) + ::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(10)) } } mod _private { use capnp::private::layout; - pub const STRUCT_SIZE: layout::StructSize = layout::StructSize { data: 1, pointers: 9 }; + pub const STRUCT_SIZE: layout::StructSize = layout::StructSize { data: 1, pointers: 11 }; pub const TYPE_ID: u64 = 0x9a52_9544_50db_0581; } } @@ -1240,13 +1288,21 @@ pub mod type_value_constructor_parameter { self.reader.total_size() } #[inline] - pub fn get_type(self) -> ::capnp::Result> { + pub fn get_label(self) -> ::capnp::Result<::capnp::text::Reader<'a>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(0), ::core::option::Option::None) } #[inline] - pub fn has_type(&self) -> bool { + pub fn has_label(&self) -> bool { !self.reader.get_pointer_field(0).is_null() } + #[inline] + pub fn get_type(self) -> ::capnp::Result> { + ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1), ::core::option::Option::None) + } + #[inline] + pub fn has_type(&self) -> bool { + !self.reader.get_pointer_field(1).is_null() + } } pub struct Builder<'a> { builder: ::capnp::private::layout::StructBuilder<'a> } @@ -1298,20 +1354,36 @@ pub mod type_value_constructor_parameter { self.builder.into_reader().total_size() } #[inline] - pub fn get_type(self) -> ::capnp::Result> { + pub fn get_label(self) -> ::capnp::Result<::capnp::text::Builder<'a>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(0), ::core::option::Option::None) } #[inline] + pub fn set_label(&mut self, value: ::capnp::text::Reader<'_>) { + self.builder.get_pointer_field(0).set_text(value); + } + #[inline] + pub fn init_label(self, size: u32) -> ::capnp::text::Builder<'a> { + self.builder.get_pointer_field(0).init_text(size) + } + #[inline] + pub fn has_label(&self) -> bool { + !self.builder.get_pointer_field(0).is_null() + } + #[inline] + pub fn get_type(self) -> ::capnp::Result> { + ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1), ::core::option::Option::None) + } + #[inline] pub fn set_type(&mut self, value: crate::schema_capnp::type_::Reader<'_>) -> ::capnp::Result<()> { - ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(0), value, false) + ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value, false) } #[inline] pub fn init_type(self, ) -> crate::schema_capnp::type_::Builder<'a> { - ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(0), 0) + ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), 0) } #[inline] pub fn has_type(&self) -> bool { - !self.builder.get_pointer_field(0).is_null() + !self.builder.get_pointer_field(1).is_null() } } @@ -1323,12 +1395,12 @@ pub mod type_value_constructor_parameter { } impl Pipeline { pub fn get_type(&self) -> crate::schema_capnp::type_::Pipeline { - ::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(0)) + ::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(1)) } } mod _private { use capnp::private::layout; - pub const STRUCT_SIZE: layout::StructSize = layout::StructSize { data: 0, pointers: 1 }; + pub const STRUCT_SIZE: layout::StructSize = layout::StructSize { data: 0, pointers: 2 }; pub const TYPE_ID: u64 = 0xa195_30b0_13c1_53ea; } } @@ -1623,6 +1695,284 @@ pub mod type_constructor { } } +pub mod type_alias_constructor { + #[derive(Copy, Clone)] + pub struct Owned(()); + impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } + impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } + impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; } + + #[derive(Clone, Copy)] + pub struct Reader<'a> { reader: ::capnp::private::layout::StructReader<'a> } + + impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> { + #[inline] + fn type_id() -> u64 { _private::TYPE_ID } + } + impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> { + fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> { + Reader { reader, } + } + } + + impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> { + fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>, default: ::core::option::Option<&'a [capnp::Word]>) -> ::capnp::Result> { + ::core::result::Result::Ok(::capnp::traits::FromStructReader::new(reader.get_struct(default)?)) + } + } + + impl <'a,> ::capnp::traits::IntoInternalStructReader<'a> for Reader<'a,> { + fn into_internal_struct_reader(self) -> ::capnp::private::layout::StructReader<'a> { + self.reader + } + } + + impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> { + fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) { + self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table)) + } + } + + impl <'a,> Reader<'a,> { + pub fn reborrow(&self) -> Reader<'_,> { + Reader { .. *self } + } + + pub fn total_size(&self) -> ::capnp::Result<::capnp::MessageSize> { + self.reader.total_size() + } + #[inline] + pub fn get_publicity(self) -> ::capnp::Result> { + ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(0), ::core::option::Option::None) + } + #[inline] + pub fn has_publicity(&self) -> bool { + !self.reader.get_pointer_field(0).is_null() + } + #[inline] + pub fn get_module(self) -> ::capnp::Result<::capnp::text::Reader<'a>> { + ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1), ::core::option::Option::None) + } + #[inline] + pub fn has_module(&self) -> bool { + !self.reader.get_pointer_field(1).is_null() + } + #[inline] + pub fn get_origin(self) -> ::capnp::Result> { + ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(2), ::core::option::Option::None) + } + #[inline] + pub fn has_origin(&self) -> bool { + !self.reader.get_pointer_field(2).is_null() + } + #[inline] + pub fn get_type(self) -> ::capnp::Result> { + ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(3), ::core::option::Option::None) + } + #[inline] + pub fn has_type(&self) -> bool { + !self.reader.get_pointer_field(3).is_null() + } + #[inline] + pub fn get_arity(self) -> u16 { + self.reader.get_data_field::(0) + } + #[inline] + pub fn get_deprecated(self) -> ::capnp::Result<::capnp::text::Reader<'a>> { + ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(4), ::core::option::Option::None) + } + #[inline] + pub fn has_deprecated(&self) -> bool { + !self.reader.get_pointer_field(4).is_null() + } + #[inline] + pub fn get_documentation(self) -> ::capnp::Result<::capnp::text::Reader<'a>> { + ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(5), ::core::option::Option::None) + } + #[inline] + pub fn has_documentation(&self) -> bool { + !self.reader.get_pointer_field(5).is_null() + } + } + + pub struct Builder<'a> { builder: ::capnp::private::layout::StructBuilder<'a> } + impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> { + #[inline] + fn struct_size() -> ::capnp::private::layout::StructSize { _private::STRUCT_SIZE } + } + impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> { + #[inline] + fn type_id() -> u64 { _private::TYPE_ID } + } + impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> { + fn new(builder: ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > { + Builder { builder, } + } + } + + impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> { + fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) { + self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table)) + } + } + + impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> { + fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size: u32) -> Builder<'a,> { + ::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE)) + } + fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, default: ::core::option::Option<&'a [capnp::Word]>) -> ::capnp::Result> { + ::core::result::Result::Ok(::capnp::traits::FromStructBuilder::new(builder.get_struct(_private::STRUCT_SIZE, default)?)) + } + } + + impl <'a,> ::capnp::traits::SetPointerBuilder for Reader<'a,> { + fn set_pointer_builder<'b>(pointer: ::capnp::private::layout::PointerBuilder<'b>, value: Reader<'a,>, canonicalize: bool) -> ::capnp::Result<()> { pointer.set_struct(&value.reader, canonicalize) } + } + + impl <'a,> Builder<'a,> { + pub fn into_reader(self) -> Reader<'a,> { + ::capnp::traits::FromStructReader::new(self.builder.into_reader()) + } + pub fn reborrow(&mut self) -> Builder<'_,> { + Builder { .. *self } + } + pub fn reborrow_as_reader(&self) -> Reader<'_,> { + ::capnp::traits::FromStructReader::new(self.builder.into_reader()) + } + + pub fn total_size(&self) -> ::capnp::Result<::capnp::MessageSize> { + self.builder.into_reader().total_size() + } + #[inline] + pub fn get_publicity(self) -> ::capnp::Result> { + ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(0), ::core::option::Option::None) + } + #[inline] + pub fn set_publicity(&mut self, value: crate::schema_capnp::publicity::Reader<'_>) -> ::capnp::Result<()> { + ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(0), value, false) + } + #[inline] + pub fn init_publicity(self, ) -> crate::schema_capnp::publicity::Builder<'a> { + ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(0), 0) + } + #[inline] + pub fn has_publicity(&self) -> bool { + !self.builder.get_pointer_field(0).is_null() + } + #[inline] + pub fn get_module(self) -> ::capnp::Result<::capnp::text::Builder<'a>> { + ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1), ::core::option::Option::None) + } + #[inline] + pub fn set_module(&mut self, value: ::capnp::text::Reader<'_>) { + self.builder.get_pointer_field(1).set_text(value); + } + #[inline] + pub fn init_module(self, size: u32) -> ::capnp::text::Builder<'a> { + self.builder.get_pointer_field(1).init_text(size) + } + #[inline] + pub fn has_module(&self) -> bool { + !self.builder.get_pointer_field(1).is_null() + } + #[inline] + pub fn get_origin(self) -> ::capnp::Result> { + ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(2), ::core::option::Option::None) + } + #[inline] + pub fn set_origin(&mut self, value: crate::schema_capnp::src_span::Reader<'_>) -> ::capnp::Result<()> { + ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(2), value, false) + } + #[inline] + pub fn init_origin(self, ) -> crate::schema_capnp::src_span::Builder<'a> { + ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(2), 0) + } + #[inline] + pub fn has_origin(&self) -> bool { + !self.builder.get_pointer_field(2).is_null() + } + #[inline] + pub fn get_type(self) -> ::capnp::Result> { + ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(3), ::core::option::Option::None) + } + #[inline] + pub fn set_type(&mut self, value: crate::schema_capnp::type_::Reader<'_>) -> ::capnp::Result<()> { + ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(3), value, false) + } + #[inline] + pub fn init_type(self, ) -> crate::schema_capnp::type_::Builder<'a> { + ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(3), 0) + } + #[inline] + pub fn has_type(&self) -> bool { + !self.builder.get_pointer_field(3).is_null() + } + #[inline] + pub fn get_arity(self) -> u16 { + self.builder.get_data_field::(0) + } + #[inline] + pub fn set_arity(&mut self, value: u16) { + self.builder.set_data_field::(0, value); + } + #[inline] + pub fn get_deprecated(self) -> ::capnp::Result<::capnp::text::Builder<'a>> { + ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(4), ::core::option::Option::None) + } + #[inline] + pub fn set_deprecated(&mut self, value: ::capnp::text::Reader<'_>) { + self.builder.get_pointer_field(4).set_text(value); + } + #[inline] + pub fn init_deprecated(self, size: u32) -> ::capnp::text::Builder<'a> { + self.builder.get_pointer_field(4).init_text(size) + } + #[inline] + pub fn has_deprecated(&self) -> bool { + !self.builder.get_pointer_field(4).is_null() + } + #[inline] + pub fn get_documentation(self) -> ::capnp::Result<::capnp::text::Builder<'a>> { + ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(5), ::core::option::Option::None) + } + #[inline] + pub fn set_documentation(&mut self, value: ::capnp::text::Reader<'_>) { + self.builder.get_pointer_field(5).set_text(value); + } + #[inline] + pub fn init_documentation(self, size: u32) -> ::capnp::text::Builder<'a> { + self.builder.get_pointer_field(5).init_text(size) + } + #[inline] + pub fn has_documentation(&self) -> bool { + !self.builder.get_pointer_field(5).is_null() + } + } + + pub struct Pipeline { _typeless: ::capnp::any_pointer::Pipeline } + impl ::capnp::capability::FromTypelessPipeline for Pipeline { + fn new(typeless: ::capnp::any_pointer::Pipeline) -> Pipeline { + Pipeline { _typeless: typeless, } + } + } + impl Pipeline { + pub fn get_publicity(&self) -> crate::schema_capnp::publicity::Pipeline { + ::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(0)) + } + pub fn get_origin(&self) -> crate::schema_capnp::src_span::Pipeline { + ::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(2)) + } + pub fn get_type(&self) -> crate::schema_capnp::type_::Pipeline { + ::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(3)) + } + } + mod _private { + use capnp::private::layout; + pub const STRUCT_SIZE: layout::StructSize = layout::StructSize { data: 1, pointers: 6 }; + pub const TYPE_ID: u64 = 0xac58_4722_b0c2_444d; + } +} + pub mod accessors_map { #[derive(Copy, Clone)] pub struct Owned(()); diff --git a/compiler-core/schema.capnp b/compiler-core/schema.capnp index 4a349e6877c..6d335a0c295 100644 --- a/compiler-core/schema.capnp +++ b/compiler-core/schema.capnp @@ -21,15 +21,17 @@ struct Option(Value) { struct Module { name @0 :Text; - types @1 :List(Property(TypeConstructor)); - values @2 :List(Property(ValueConstructor)); - accessors @3 :List(Property(AccessorsMap)); - package @4 :Text; - typesConstructors @5 :List(Property(TypesVariantConstructors)); - lineNumbers @6 :LineNumbers; - srcPath @7 :Text; - isInternal @8 :Bool; - requiredVersion @9 :Version; + documentation @1 :List(Text); + types @2 :List(Property(TypeConstructor)); + typeAliases @3 :List(Property(TypeAliasConstructor)); + values @4 :List(Property(ValueConstructor)); + accessors @5 :List(Property(AccessorsMap)); + package @6 :Text; + typesConstructors @7 :List(Property(TypesVariantConstructors)); + lineNumbers @8 :LineNumbers; + srcPath @9 :Text; + isInternal @10 :Bool; + requiredVersion @11 :Version; } struct Version { @@ -49,7 +51,8 @@ struct TypeValueConstructor { } struct TypeValueConstructorParameter { - type @0 :Type; + label @0 :Text; + type @1 :Type; } struct TypeConstructor { @@ -65,6 +68,16 @@ struct TypeConstructor { documentation @6 :Text; } +struct TypeAliasConstructor { + publicity @0 :Publicity; + module @1 :Text; + origin @2 :SrcSpan; + type @3 :Type; + arity @4 :UInt16; + deprecated @5 :Text; + documentation @6 :Text; +} + struct AccessorsMap { type @0 :Type; accessors @1 :List(Property(RecordAccessor)); diff --git a/compiler-core/src/analyse.rs b/compiler-core/src/analyse.rs index 7a5bff7d7ff..29d418b389a 100644 --- a/compiler-core/src/analyse.rs +++ b/compiler-core/src/analyse.rs @@ -28,8 +28,8 @@ use crate::{ hydrator::Hydrator, prelude::*, AccessorsMap, Deprecation, ModuleInterface, PatternConstructor, RecordAccessor, Type, - TypeConstructor, TypeValueConstructor, TypeValueConstructorField, TypeVariantConstructors, - ValueConstructor, ValueConstructorVariant, Warning, + TypeAliasConstructor, TypeConstructor, TypeValueConstructor, TypeValueConstructorField, + TypeVariantConstructors, ValueConstructor, ValueConstructorVariant, Warning, }, uid::UniqueIdGenerator, warning::TypeWarningEmitter, @@ -296,6 +296,7 @@ impl<'a, A> ModuleAnalyzer<'a, A> { let Environment { module_types: types, module_types_constructors: types_constructors, + module_type_aliases: type_aliases, module_values: values, accessors, names: type_names, @@ -317,14 +318,21 @@ impl<'a, A> ModuleAnalyzer<'a, A> { self.warnings.emit(warning.clone()); } + // println!( + // "Generated module {} has documentation size {}", + // self.module_name, + // documentation.len() + // ); let module = ast::Module { - documentation, + documentation: documentation.clone(), name: self.module_name.clone(), definitions: typed_statements, type_info: ModuleInterface { name: self.module_name, + documentation, types, types_value_constructors: types_constructors, + type_aliases, values, accessors, origin: self.origin, @@ -965,7 +973,10 @@ impl<'a, A> ModuleAnalyzer<'a, A> { } }; - fields.push(TypeValueConstructorField { type_: t.clone() }); + fields.push(TypeValueConstructorField { + label: label.clone().map_or(None, |(_, label)| Some(label.clone())), + type_: t.clone(), + }); // Register the type for this parameter args_types.push(t); @@ -1177,7 +1188,7 @@ impl<'a, A> ModuleAnalyzer<'a, A> { // in some fashion. let mut hydrator = Hydrator::new(); let parameters = self.make_type_vars(args, &mut hydrator, environment); - let tryblock = || { + let mut tryblock = || { hydrator.disallow_new_type_variables(); let type_ = hydrator.type_from_ast(resolved_type, environment, &mut self.problems)?; @@ -1191,14 +1202,27 @@ impl<'a, A> ModuleAnalyzer<'a, A> { TypeConstructor { origin: *location, module: self.module_name.clone(), - parameters, - type_, + parameters: parameters.clone(), + type_: type_.clone(), deprecation: deprecation.clone(), publicity: *publicity, documentation: documentation.as_ref().map(|(_, doc)| doc.clone()), }, )?; + environment.insert_type_alias( + name.clone(), + TypeAliasConstructor { + origin: *location, + module: self.module_name.clone(), + type_: type_.as_ref().clone(), + arity: parameters.len(), + publicity: *publicity, + deprecation: deprecation.clone(), + documentation: documentation.as_ref().map(|(_, doc)| doc.clone()), + }, + )?; + if let Some(name) = hydrator.unused_type_variables().next() { return Err(Error::UnusedTypeAliasParameter { location: *location, diff --git a/compiler-core/src/build.rs b/compiler-core/src/build.rs index 917f741b0ef..5e6225da4af 100644 --- a/compiler-core/src/build.rs +++ b/compiler-core/src/build.rs @@ -185,7 +185,6 @@ pub enum Mode { Dev, Prod, Lsp, - PackageInterface, } impl Mode { @@ -194,7 +193,7 @@ impl Mode { pub fn includes_tests(&self) -> bool { match self { Self::Dev | Self::Lsp => true, - Self::Prod | Self::PackageInterface => false, + Self::Prod => false, } } } @@ -210,6 +209,7 @@ fn mode_includes_tests() { pub struct Package { pub config: PackageConfig, pub modules: Vec, + pub cached_modules: Vec, } impl Package { @@ -227,7 +227,7 @@ impl Package { } } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct Module { pub name: EcoString, pub code: EcoString, @@ -263,6 +263,13 @@ impl Module { .map(|span| Comment::from((span, self.code.as_str())).content.into()) .collect(); + self.ast.type_info.documentation = self.ast.documentation.clone(); + // println!( + // "Module {} has documentation of length {}", + // self.name, + // self.ast.documentation.len() + // ); + // Order statements to avoid misassociating doc comments after the // order has changed during compilation. let mut statements: Vec<_> = self.ast.definitions.iter_mut().collect(); diff --git a/compiler-core/src/build/package_compiler.rs b/compiler-core/src/build/package_compiler.rs index e4365c31000..68704026d6c 100644 --- a/compiler-core/src/build/package_compiler.rs +++ b/compiler-core/src/build/package_compiler.rs @@ -106,7 +106,7 @@ where stale_modules: &mut StaleTracker, incomplete_modules: &mut HashSet, telemetry: &dyn Telemetry, - ) -> Outcome, Error> { + ) -> Outcome<(Vec, Vec), Error> { let span = tracing::info_span!("compile", package = %self.config.name.as_str()); let _enter = span.enter(); @@ -148,7 +148,7 @@ where }; // Load the cached modules that have previously been compiled - for module in loaded.cached.into_iter() { + for module in loaded.cached.clone().into_iter() { // Emit any cached warnings. // Note that `self.cached_warnings` is set to `Ignore` (such as for // dependency packages) then this field will not be populated. @@ -186,7 +186,9 @@ where let mut modules = match outcome { Outcome::Ok(modules) => modules, - Outcome::PartialFailure(modules, err) => return Outcome::PartialFailure(modules, err), + Outcome::PartialFailure(modules, err) => { + return Outcome::PartialFailure((modules, loaded.cached), err) + } Outcome::TotalFailure(err) => return Outcome::TotalFailure(err), }; @@ -199,8 +201,7 @@ where if let Err(error) = self.encode_and_write_metadata(&modules) { return error.into(); } - - Outcome::Ok(modules) + Outcome::Ok((modules, loaded.cached)) } fn compile_erlang_to_beam(&mut self, modules: &HashSet) -> Result<(), Error> { @@ -282,7 +283,7 @@ where Ok(()) } - fn encode_and_write_metadata(&mut self, modules: &[Module]) -> Result<()> { + fn encode_and_write_metadata(&mut self, modules: &Vec) -> Result<()> { if !self.write_metadata { tracing::debug!("package_metadata_writing_disabled"); return Ok(()); @@ -294,7 +295,8 @@ where let artefact_dir = self.out.join(paths::ARTEFACT_DIRECTORY_NAME); tracing::debug!("writing_module_caches"); - for module in modules { + for mut module in modules.clone() { + module.attach_doc_and_module_comments(); let module_name = module.name.replace("/", "@"); // Write metadata file diff --git a/compiler-core/src/build/package_loader.rs b/compiler-core/src/build/package_loader.rs index c7bb8e6d4fb..15063479fe2 100644 --- a/compiler-core/src/build/package_loader.rs +++ b/compiler-core/src/build/package_loader.rs @@ -157,18 +157,11 @@ where // A cached module with no stale dependencies can be used as-is // and does not need to be recompiled. - Input::Cached(info) => match self.mode { - Mode::PackageInterface => { - tracing::debug!(module = %info.name, "module_to_be_compiled"); - let module = self.load_and_parse(info)?; - loaded.to_compile.push(module); - } - _ => { - tracing::debug!(module = %info.name, "module_to_load_from_cache"); - let module = self.load_cached_module(info)?; - loaded.cached.push(module); - } - }, + Input::Cached(info) => { + tracing::debug!(module = %info.name, "module_to_load_from_cache"); + let module = self.load_cached_module(info)?; + loaded.cached.push(module); + } } } @@ -182,6 +175,12 @@ where let bytes = self.io.read_bytes(&path)?; let mut module = metadata::ModuleDecoder::new(self.ids.clone()).read(bytes.as_slice())?; + // println!( + // "Loaded cached module {} has {} types", + // module.name, + // module.types.len() + // ); + // Load warnings if self.cached_warnings.should_use() { let path = dir.join(name.as_ref()).with_extension("cache_warnings"); diff --git a/compiler-core/src/build/package_loader/tests.rs b/compiler-core/src/build/package_loader/tests.rs index 5eb2c763c53..b9e4bf83811 100644 --- a/compiler-core/src/build/package_loader/tests.rs +++ b/compiler-core/src/build/package_loader/tests.rs @@ -5,7 +5,7 @@ use super::*; use crate::{ build::SourceFingerprint, io::{memory::InMemoryFileSystem, FileSystemWriter}, - line_numbers, package_interface, + line_numbers, parse::extra::ModuleExtra, warning::NullWarningEmitterIO, Warning, @@ -52,8 +52,10 @@ fn write_cache( name: name.into(), origin: Origin::Src, package: "my_package".into(), + documentation: vec![], types: Default::default(), types_value_constructors: Default::default(), + type_aliases: Default::default(), values: Default::default(), accessors: Default::default(), line_numbers: line_numbers.clone(), @@ -62,7 +64,7 @@ fn write_cache( warnings: vec![], minimum_required_version: Version::new(0, 1, 0), }; - let path: Utf8PathBuf = Utf8Path::new("/artefact").join(format!("{name}.cache")); + let path = Utf8Path::new("/artefact").join(format!("{name}.cache")); fs.write_bytes( &path, &metadata::ModuleEncoder::new(&cache).encode().unwrap(), diff --git a/compiler-core/src/build/project_compiler.rs b/compiler-core/src/build/project_compiler.rs index dc08b8fd742..10cb2d60f13 100644 --- a/compiler-core/src/build/project_compiler.rs +++ b/compiler-core/src/build/project_compiler.rs @@ -21,7 +21,7 @@ use crate::{ use ecow::EcoString; use hexpm::version::Version; use itertools::Itertools; -use pubgrub::{package, range::Range}; +use pubgrub::range::Range; use std::{ cmp, collections::{HashMap, HashSet}, @@ -208,7 +208,11 @@ where pub fn compile_root_package(&mut self) -> Outcome { let config = self.config.clone(); self.compile_gleam_package(&config, true, self.paths.root().to_path_buf()) - .map(|modules| Package { config, modules }) + .map(|(modules, cachedModules)| Package { + config, + modules, + cached_modules: cachedModules, + }) } /// Checks that version file found in the build directory matches the @@ -288,7 +292,7 @@ where // longer need to have the package borrowed from self.packages. let package = self.packages.get(name).expect("Missing package").clone(); let result = match usable_build_tools(&package)?.as_slice() { - &[BuildTool::Gleam] => self.compile_gleam_dep_package(&package), + &[BuildTool::Gleam] => self.compile_gleam_dep_package(&package).map(|_| vec![]), &[BuildTool::Rebar3] => self.compile_rebar3_dep_package(&package).map(|_| vec![]), &[BuildTool::Mix] => self.compile_mix_dep_package(&package).map(|_| vec![]), &[BuildTool::Mix, BuildTool::Rebar3] => self @@ -489,7 +493,7 @@ where fn compile_gleam_dep_package( &mut self, package: &ManifestPackage, - ) -> Result, Error> { + ) -> Result<(Vec, Vec), Error> { // TODO: Test let package_root = match &package.source { // If the path is relative it is relative to the root of the @@ -520,7 +524,7 @@ where config: &PackageConfig, is_root: bool, root_path: Utf8PathBuf, - ) -> Outcome<(Vec), Error> { + ) -> Outcome<(Vec, Vec), Error> { let out_path = self.paths .build_directory_for_package(self.mode(), self.target(), &config.name); @@ -590,16 +594,14 @@ where }; // Compile project to Erlang or JavaScript source code - let outcome = compiler.compile( + compiler.compile( &mut self.warnings, &mut self.importable_modules, &mut self.defined_modules, &mut self.stale_modules, &mut self.incomplete_modules, self.telemetry, - ); - - outcome + ) } } diff --git a/compiler-core/src/config.rs b/compiler-core/src/config.rs index 1f814cfbd4e..b583fa58a5e 100644 --- a/compiler-core/src/config.rs +++ b/compiler-core/src/config.rs @@ -137,7 +137,7 @@ impl PackageConfig { pub fn dependencies_for(&self, mode: Mode) -> Result { match mode { Mode::Dev | Mode::Lsp => self.all_drect_dependencies(), - Mode::Prod | Mode::PackageInterface => Ok(self.dependencies.clone()), + Mode::Prod => Ok(self.dependencies.clone()), } } diff --git a/compiler-core/src/docs.rs b/compiler-core/src/docs.rs index f689ea33eff..b53e1f9921a 100644 --- a/compiler-core/src/docs.rs +++ b/compiler-core/src/docs.rs @@ -447,6 +447,7 @@ pub fn generate_html( } pub fn generate_json_package_interface(path: Utf8PathBuf, package: &Package) -> OutputFile { + // println!("Generating Package Interface"); OutputFile { path, content: Content::Text( diff --git a/compiler-core/src/docs/tests.rs b/compiler-core/src/docs/tests.rs index 8469cea2be1..e8f3922b955 100644 --- a/compiler-core/src/docs/tests.rs +++ b/compiler-core/src/docs/tests.rs @@ -63,7 +63,7 @@ fn compile_with_markdown_pages( ) .unwrap(); - for module in &mut modules { + for module in &mut modules.0 { module.attach_doc_and_module_comments(); } @@ -79,7 +79,7 @@ fn compile_with_markdown_pages( super::generate_html( &paths, &config, - &modules, + &modules.0, &docs_pages, pages_fs, SystemTime::UNIX_EPOCH, diff --git a/compiler-core/src/exhaustiveness.rs b/compiler-core/src/exhaustiveness.rs index dac96b8c8c7..5283d9e1508 100644 --- a/compiler-core/src/exhaustiveness.rs +++ b/compiler-core/src/exhaustiveness.rs @@ -878,6 +878,7 @@ impl ConstructorSpecialiser { let parameters = parameters .iter() .map(|p| TypeValueConstructorField { + label: None, type_: self.specialise_type(p.type_.as_ref()), }) .collect_vec(); diff --git a/compiler-core/src/metadata/module_decoder.rs b/compiler-core/src/metadata/module_decoder.rs index e9f2a863622..ad3b12bb3a4 100755 --- a/compiler-core/src/metadata/module_decoder.rs +++ b/compiler-core/src/metadata/module_decoder.rs @@ -13,8 +13,9 @@ use crate::{ schema_capnp::{self as schema, *}, type_::{ self, expression::Implementations, AccessorsMap, Deprecation, FieldMap, ModuleInterface, - RecordAccessor, Type, TypeConstructor, TypeValueConstructor, TypeValueConstructorField, - TypeVariantConstructors, ValueConstructor, ValueConstructorVariant, + RecordAccessor, Type, TypeAliasConstructor, TypeConstructor, TypeValueConstructor, + TypeValueConstructorField, TypeVariantConstructors, ValueConstructor, + ValueConstructorVariant, }, uid::UniqueIdGenerator, Result, @@ -64,10 +65,14 @@ impl ModuleDecoder { let message_reader = capnp::serialize_packed::read_message(reader, capnp::message::ReaderOptions::new())?; let reader = message_reader.get_root::>()?; - Ok(ModuleInterface { name: reader.get_name()?.into(), package: reader.get_package()?.into(), + documentation: reader + .get_documentation()? + .iter() + .filter_map(|s| s.ok().map(|s| s.into())) + .collect(), is_internal: reader.get_is_internal(), origin: Origin::Src, values: read_hashmap!(reader.get_values()?, self, value_constructor), @@ -77,6 +82,7 @@ impl ModuleDecoder { self, type_variants_constructors ), + type_aliases: read_hashmap!(reader.get_type_aliases()?, self, type_alias_constructor), accessors: read_hashmap!(reader.get_accessors()?, self, accessors_map), line_numbers: self.line_numbers(&reader.get_line_numbers()?)?, src_path: reader.get_src_path()?.into(), @@ -202,8 +208,32 @@ impl ModuleDecoder { reader: &type_value_constructor_parameter::Reader<'_>, ) -> Result { Ok(TypeValueConstructorField { + label: self.optional_string(reader.get_label()?), type_: self.type_(&reader.get_type()?)?, }) + // unimplemented!() + } + + fn type_alias_constructor( + &mut self, + reader: &type_alias_constructor::Reader<'_>, + ) -> Result { + let type_ = self.type_(&reader.get_type()?)?.as_ref().clone(); + let deprecation = match reader.get_deprecated()? { + "" => Deprecation::NotDeprecated, + message => Deprecation::Deprecated { + message: message.into(), + }, + }; + Ok(TypeAliasConstructor { + publicity: self.publicity(reader.get_publicity()?)?, + module: reader.get_module()?.into(), + origin: self.src_span(&reader.get_origin()?)?, + type_, + arity: reader.get_arity().into(), + deprecation, + documentation: self.optional_string(reader.get_documentation()?), + }) } fn value_constructor( diff --git a/compiler-core/src/metadata/module_encoder.rs b/compiler-core/src/metadata/module_encoder.rs index 2e30090659e..da24c7fe60d 100644 --- a/compiler-core/src/metadata/module_encoder.rs +++ b/compiler-core/src/metadata/module_encoder.rs @@ -8,8 +8,8 @@ use crate::{ schema_capnp::{self as schema, *}, type_::{ self, expression::Implementations, AccessorsMap, Deprecation, FieldMap, RecordAccessor, - Type, TypeConstructor, TypeValueConstructor, TypeVar, TypeVariantConstructors, - ValueConstructor, ValueConstructorVariant, + Type, TypeAliasConstructor, TypeConstructor, TypeValueConstructor, TypeVar, + TypeVariantConstructors, ValueConstructor, ValueConstructorVariant, }, }; use std::{collections::HashMap, ops::Deref, sync::Arc}; @@ -38,11 +38,20 @@ impl<'a> ModuleEncoder<'a> { let mut message = capnp::message::Builder::new_default(); let mut module = message.init_root::>(); + + // println!("Encoding module {}", self.data.name); + // println!( + // "Module {} has documentation size {}", + // self.data.name, + // self.data.documentation.len() + // ); module.set_name(&self.data.name); module.set_package(&self.data.package); module.set_src_path(self.data.src_path.as_str()); module.set_is_internal(self.data.is_internal); + self.set_documentation(&mut module); self.set_module_types(&mut module); + self.set_module_type_aliases(&mut module); self.set_module_values(&mut module); self.set_module_accessors(&mut module); self.set_module_types_constructors(&mut module); @@ -53,6 +62,15 @@ impl<'a> ModuleEncoder<'a> { Ok(buffer) } + fn set_documentation(&mut self, module: &mut module::Builder<'_>) { + let mut documentation = module + .reborrow() + .init_documentation(self.data.documentation.len() as u32); + for (i, doc) in self.data.documentation.iter().enumerate() { + documentation.reborrow().set(i as u32, doc); + } + } + fn set_line_numbers(&mut self, module: &mut module::Builder<'_>) { let mut line_numbers = module.reborrow().init_line_numbers(); line_numbers.set_length(self.data.line_numbers.length); @@ -101,8 +119,23 @@ impl<'a> ModuleEncoder<'a> { fn set_module_types(&mut self, module: &mut module::Builder<'_>) { tracing::trace!("Writing module metadata types"); - let mut types = module.reborrow().init_types(self.data.types.len() as u32); - for (i, (name, type_)) in self.data.types.iter().enumerate() { + let filtered_types: Vec<_> = self + .data + .types + .iter() + .filter(|(name, _)| !self.data.type_aliases.contains_key(*name)) + // .map(|(type_name, type_)| { + // println!( + // "Type {}/{} has documentation {}", + // self.data.name, + // type_name, + // type_.documentation.clone().unwrap_or_default().len(), + // ); + // (type_name, type_) + // }) + .collect(); + let mut types = module.reborrow().init_types(filtered_types.len() as u32); + for (i, (name, type_)) in filtered_types.iter().enumerate() { let mut property = types.reborrow().get(i as u32); property.set_key(name); self.build_type_constructor(property.init_value(), type_) @@ -121,6 +154,32 @@ impl<'a> ModuleEncoder<'a> { } } + fn set_module_type_aliases(&mut self, module: &mut module::Builder<'_>) { + tracing::trace!("Writing module metadata type aliases"); + let mut type_aliases = module + .reborrow() + .init_type_aliases(self.data.type_aliases.len() as u32); + for (i, (name, data)) in self + .data + .type_aliases + .iter() + // .map(|(type_alias_name, type_alias)| { + // println!( + // "Type Alias {}/{} has documentation {}", + // self.data.name, + // type_alias_name, + // type_alias.documentation.clone().unwrap_or_default().len(), + // ); + // (type_alias_name, type_alias) + // }) + .enumerate() + { + let mut property = type_aliases.reborrow().get(i as u32); + property.set_key(name); + self.build_type_aliases(property.init_value(), data) + } + } + fn build_type_variant_constructors( &mut self, mut builder: types_variant_constructors::Builder<'_>, @@ -187,6 +246,29 @@ impl<'a> ModuleEncoder<'a> { ); } + fn build_type_aliases( + &mut self, + mut builder: type_alias_constructor::Builder<'_>, + constructor: &TypeAliasConstructor, + ) { + builder.set_module(&constructor.module); + builder.set_deprecated(match &constructor.deprecation { + Deprecation::NotDeprecated => "", + Deprecation::Deprecated { message } => message, + }); + self.build_publicity(builder.reborrow().init_publicity(), constructor.publicity); + let type_builder = builder.reborrow().init_type(); + self.build_type(type_builder, &constructor.type_); + builder.set_arity(constructor.arity as u16); + builder.set_documentation( + constructor + .documentation + .as_ref() + .map(EcoString::as_str) + .unwrap_or_default(), + ); + } + fn build_type_value_constructor( &mut self, mut builder: type_value_constructor::Builder<'_>, @@ -204,9 +286,16 @@ impl<'a> ModuleEncoder<'a> { fn build_type_value_constructor_parameter( &mut self, - builder: type_value_constructor_parameter::Builder<'_>, + mut builder: type_value_constructor_parameter::Builder<'_>, parameter: &type_::TypeValueConstructorField, ) { + builder.set_label( + parameter + .label + .as_ref() + .map(EcoString::as_str) + .unwrap_or_default(), + ); self.build_type(builder.init_type(), parameter.type_.as_ref()); } diff --git a/compiler-core/src/metadata/tests.rs b/compiler-core/src/metadata/tests.rs index eef3a863700..30aafff4aa0 100644 --- a/compiler-core/src/metadata/tests.rs +++ b/compiler-core/src/metadata/tests.rs @@ -35,9 +35,11 @@ fn constant_module(constant: TypedConstant) -> ModuleInterface { is_internal: true, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a".into(), types: HashMap::new(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), accessors: HashMap::new(), values: [( "one".into(), @@ -89,9 +91,11 @@ fn empty_module() { is_internal: true, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "one/two".into(), types: HashMap::new(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), values: HashMap::new(), accessors: HashMap::new(), line_numbers: LineNumbers::new(""), @@ -108,9 +112,11 @@ fn with_line_numbers() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "one/two".into(), types: HashMap::new(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), values: HashMap::new(), accessors: HashMap::new(), line_numbers: LineNumbers::new( @@ -131,6 +137,7 @@ fn module_with_private_type() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a/b".into(), types: [( "ListIntType".into(), @@ -146,6 +153,7 @@ fn module_with_private_type() { )] .into(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), values: HashMap::new(), accessors: HashMap::new(), line_numbers: LineNumbers::new(""), @@ -162,6 +170,7 @@ fn module_with_app_type() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a/b".into(), types: [( "ListIntType".into(), @@ -177,6 +186,7 @@ fn module_with_app_type() { )] .into(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), values: HashMap::new(), accessors: HashMap::new(), line_numbers: LineNumbers::new(""), @@ -193,6 +203,7 @@ fn module_with_fn_type() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a/b".into(), types: [( "FnType".into(), @@ -208,6 +219,7 @@ fn module_with_fn_type() { )] .into(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), values: HashMap::new(), accessors: HashMap::new(), line_numbers: LineNumbers::new(""), @@ -224,6 +236,7 @@ fn module_with_tuple_type() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a/b".into(), types: [( "TupleType".into(), @@ -239,6 +252,7 @@ fn module_with_tuple_type() { )] .into(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), values: HashMap::new(), accessors: HashMap::new(), line_numbers: LineNumbers::new(""), @@ -261,6 +275,7 @@ fn module_with_generic_type() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a/b".into(), types: [( "TupleType".into(), @@ -276,6 +291,7 @@ fn module_with_generic_type() { )] .into(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), values: HashMap::new(), accessors: HashMap::new(), line_numbers: LineNumbers::new(""), @@ -298,6 +314,7 @@ fn module_with_type_links() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a".into(), types: [( "SomeType".into(), @@ -313,6 +330,7 @@ fn module_with_type_links() { )] .into(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), values: HashMap::new(), accessors: HashMap::new(), line_numbers: LineNumbers::new(""), @@ -335,6 +353,7 @@ fn module_with_type_constructor_documentation() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a".into(), types: [( "SomeType".into(), @@ -350,6 +369,7 @@ fn module_with_type_constructor_documentation() { )] .into(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), values: HashMap::new(), accessors: HashMap::new(), line_numbers: LineNumbers::new(""), @@ -372,6 +392,7 @@ fn module_with_type_constructor_origin() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a".into(), types: [( "SomeType".into(), @@ -390,6 +411,7 @@ fn module_with_type_constructor_origin() { )] .into(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), values: HashMap::new(), accessors: HashMap::new(), line_numbers: LineNumbers::new(""), @@ -408,6 +430,7 @@ fn module_type_to_constructors_mapping() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a".into(), types: HashMap::new(), types_value_constructors: [( @@ -421,6 +444,7 @@ fn module_type_to_constructors_mapping() { }, )] .into(), + type_aliases: HashMap::new(), accessors: HashMap::new(), values: HashMap::new(), line_numbers: LineNumbers::new(""), @@ -438,9 +462,11 @@ fn module_fn_value() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a".into(), types: HashMap::new(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), accessors: HashMap::new(), values: [( "one".into(), @@ -485,9 +511,11 @@ fn deprecated_module_fn_value() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a".into(), types: HashMap::new(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), accessors: HashMap::new(), values: [( "one".into(), @@ -534,9 +562,11 @@ fn private_module_fn_value() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a".into(), types: HashMap::new(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), accessors: HashMap::new(), values: [( "one".into(), @@ -583,9 +613,11 @@ fn module_fn_value_regression() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a/b/c".into(), types: HashMap::new(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), accessors: HashMap::new(), values: [( "one".into(), @@ -631,9 +663,11 @@ fn module_fn_value_with_field_map() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a".into(), types: HashMap::new(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), accessors: HashMap::new(), values: [( "one".into(), @@ -681,9 +715,11 @@ fn record_value() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a".into(), types: HashMap::new(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), accessors: HashMap::new(), values: [( "one".into(), @@ -724,9 +760,11 @@ fn record_value_with_field_map() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a".into(), types: HashMap::new(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), accessors: HashMap::new(), values: [( "one".into(), @@ -768,9 +806,11 @@ fn accessors() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a".into(), types: HashMap::new(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), values: HashMap::new(), accessors: [ ( @@ -982,9 +1022,11 @@ fn constant_var() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a".into(), types: HashMap::new(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), accessors: HashMap::new(), values: [ ( @@ -1202,6 +1244,7 @@ fn deprecated_type() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a/b".into(), types: [( "ListIntType".into(), @@ -1219,6 +1262,7 @@ fn deprecated_type() { )] .into(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), values: HashMap::new(), accessors: HashMap::new(), line_numbers: LineNumbers::new(""), @@ -1235,9 +1279,11 @@ fn module_fn_value_with_external_implementations() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a/b/c".into(), types: HashMap::new(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), accessors: HashMap::new(), values: [( "one".into(), @@ -1283,9 +1329,11 @@ fn internal_module_fn() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a/b/c".into(), types: HashMap::new(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), accessors: HashMap::new(), values: [( "one".into(), @@ -1333,9 +1381,11 @@ fn internal_annotated_module_fn() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a/b/c".into(), types: HashMap::new(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), accessors: HashMap::new(), values: [( "one".into(), @@ -1387,6 +1437,7 @@ fn type_variable_ids_in_constructors_are_shared() { is_internal: false, package: "some_package".into(), origin: Origin::Src, + documentation: vec![], name: "a/b/c".into(), types: HashMap::new(), types_value_constructors: HashMap::from([( @@ -1397,18 +1448,22 @@ fn type_variable_ids_in_constructors_are_shared() { name: "One".into(), parameters: vec![ TypeValueConstructorField { + label: None, type_: type_::generic_var(6), }, TypeValueConstructorField { + label: None, type_: type_::int(), }, TypeValueConstructorField { + label: None, type_: type_::tuple(vec![type_::generic_var(4), type_::generic_var(5)]), }, ], }], }, )]), + type_aliases: HashMap::new(), accessors: HashMap::new(), values: [].into(), line_numbers: LineNumbers::new(""), @@ -1424,12 +1479,15 @@ fn type_variable_ids_in_constructors_are_shared() { name: "One".into(), parameters: vec![ TypeValueConstructorField { + label: None, type_: type_::generic_var(0), }, TypeValueConstructorField { + label: None, type_: type_::int(), }, TypeValueConstructorField { + label: None, type_: type_::tuple(vec![type_::generic_var(1), type_::generic_var(2)]), }, ], diff --git a/compiler-core/src/package_interface.rs b/compiler-core/src/package_interface.rs index 12104f4f8bd..093a5f40597 100644 --- a/compiler-core/src/package_interface.rs +++ b/compiler-core/src/package_interface.rs @@ -8,9 +8,14 @@ use serde::Serialize; mod tests; use crate::{ - ast::{CustomType, Definition, Function, ModuleConstant, Publicity, TypeAlias}, + ast::{CustomType, Definition, Function, ModuleConstant, Publicity, TypeAlias, UntypedModule}, + build::package_compiler::UncompiledModule, io::ordered_map, - type_::{expression::Implementations, Deprecation, Type, TypeVar}, + schema_capnp::publicity, + type_::{ + self, expression::Implementations, Deprecation, Type, TypeAliasConstructor, + TypeConstructor, TypeVar, ValueConstructorVariant, + }, }; use crate::build::{Module, Package}; @@ -372,13 +377,69 @@ impl PackageInterface { .iter() .filter(|module| !package.config.is_internal_module(module.name.as_str())) .map(|module| (module.name.clone(), ModuleInterface::from_module(module))) + .chain( + package + .cached_modules + .iter() + .filter(|module| !package.config.is_internal_module(module.name.as_str())) + .map(|interface| { + ( + interface.name.clone(), + ModuleInterface::from_untyped_module(interface), + ) + }), + ) + // .map(|(name, info)| debug_module(name, info)) .collect(), } } } +// pub fn debug_module(name: EcoString, info: ModuleInterface) -> (EcoString, ModuleInterface) { +// println!( +// "Module {} has documentation size {}", +// name, +// info.documentation.iter().map(|s| s.len()).sum::() +// ); +// info.types.iter().for_each(|(type_name, type_)| { +// println!( +// "Type {}/{} has documentation {}", +// name, +// type_name, +// type_.documentation.clone().unwrap_or_default().len(), +// ) +// }); +// info.type_aliases +// .iter() +// .for_each(|(type_alias_name, type_alias)| { +// println!( +// "Type Alias {}/{} has documentation {}", +// name, +// type_alias_name, +// type_alias.documentation.clone().unwrap_or_default().len(), +// ) +// }); +// info.constants.iter().for_each(|(constant_name, constant)| { +// println!( +// "Constant {}/{} has documentation {}", +// name, +// constant_name, +// constant.documentation.clone().unwrap_or_default().len(), +// ) +// }); +// info.functions.iter().for_each(|(function_name, function)| { +// println!( +// "Function {}/{} has documentation {}", +// name, +// function_name, +// function.documentation.clone().unwrap_or_default().len(), +// ) +// }); +// (name, info) +// } + impl ModuleInterface { - pub fn from_module(module: &Module) -> ModuleInterface { + fn from_module(module: &Module) -> ModuleInterface { let mut types = HashMap::new(); let mut type_aliases = HashMap::new(); let mut constants = HashMap::new(); @@ -553,6 +614,159 @@ impl ModuleInterface { functions, } } + + pub fn from_untyped_module(interface: &type_::ModuleInterface) -> ModuleInterface { + println!( + "Module {} has following types {:#?}, following type constructors {:#?} and following accessors {:#?}", + interface.name, interface.types, interface.types_value_constructors, interface.accessors + ); + let mut types = HashMap::new(); + let mut type_aliases = HashMap::new(); + let mut constants = HashMap::new(); + let mut functions = HashMap::new(); + for (name, constructor) in interface + .types + .iter() + .filter(|(_, c)| c.publicity.is_public()) + { + let mut id_map = IdMap::new(); + + let TypeConstructor { + deprecation, + documentation, + .. + } = constructor; + + for typed_parameter in &constructor.parameters { + id_map.add_type_variable_id(typed_parameter.as_ref()); + } + + let _ = types.insert( + name.clone(), + TypeDefinitionInterface { + documentation: documentation.clone(), + deprecation: DeprecationInterface::from_deprecation(&deprecation), + parameters: interface + .types + .get(&name.clone()) + .map_or(vec![], |t| t.parameters.clone()) + .len(), + constructors: match interface.types_value_constructors.get(&name.clone()) { + Some(constructors) => constructors + .variants + .iter() + .map(|constructor| TypeConstructorInterface { + // TODO: Find documentation + documentation: None, + name: constructor.name.clone(), + parameters: constructor + .parameters + .iter() + .map(|arg| ParameterInterface { + label: arg.label.clone(), + // label: None, + // We share the same id_map between each step so that the + // incremental ids assigned are consisten with each other + type_: from_type_helper(arg.type_.as_ref(), &mut id_map), + }) + .collect(), + }) + .collect(), + None => vec![], + }, + }, + ); + } + + for (name, alias) in interface + .type_aliases + .iter() + .filter(|(_, v)| v.publicity.is_public()) + { + let _ = type_aliases.insert( + name.clone(), + TypeAliasInterface { + documentation: alias.documentation.clone(), + deprecation: DeprecationInterface::from_deprecation(&alias.deprecation), + parameters: alias.arity, + alias: TypeInterface::from_type(&alias.type_), + }, + ); + } + + for (name, value) in interface + .values + .iter() + .filter(|(_, v)| v.publicity.is_public()) + { + match (value.type_.as_ref(), value.variant.clone()) { + ( + Type::Fn { + args: arguments, + retrn: return_type, + }, + ValueConstructorVariant::ModuleFn { + documentation, + implementations, + .. + }, + ) => { + let mut id_map = IdMap::new(); + + let _ = functions.insert( + name.clone(), + FunctionInterface { + implementations: ImplementationsInterface::from_implementations( + &implementations, + ), + deprecation: DeprecationInterface::from_deprecation(&value.deprecation), + documentation, + parameters: arguments + .iter() + .map(|arg| ParameterInterface { + //TODO: Find label + label: None, + type_: from_type_helper(arg.as_ref(), &mut id_map), + }) + .collect(), + return_: from_type_helper(return_type, &mut id_map), + }, + ); + } + + ( + type_, + ValueConstructorVariant::ModuleConstant { + documentation, + implementations, + .. + }, + ) => { + let _ = constants.insert( + name.clone(), + ConstantInterface { + implementations: ImplementationsInterface::from_implementations( + &implementations, + ), + type_: TypeInterface::from_type(type_), + deprecation: DeprecationInterface::from_deprecation(&value.deprecation), + documentation, + }, + ); + } + + _ => {} + } + } + + ModuleInterface { + documentation: interface.documentation.clone(), + types, + type_aliases, + constants, + functions, + } + } } impl TypeInterface { diff --git a/compiler-core/src/package_interface/tests.rs b/compiler-core/src/package_interface/tests.rs index 5495a848db9..19d00315976 100644 --- a/compiler-core/src/package_interface/tests.rs +++ b/compiler-core/src/package_interface/tests.rs @@ -172,6 +172,7 @@ fn package_from_module(module: Module) -> Package { .expect("internals glob")]), }, modules: vec![module], + cached_modules: vec![], } } diff --git a/compiler-core/src/parse/extra.rs b/compiler-core/src/parse/extra.rs index b6e2cb6a060..72003014daf 100644 --- a/compiler-core/src/parse/extra.rs +++ b/compiler-core/src/parse/extra.rs @@ -4,7 +4,7 @@ use ecow::EcoString; use crate::ast::SrcSpan; -#[derive(Debug, PartialEq, Eq, Default)] +#[derive(Debug, PartialEq, Eq, Default, Clone)] pub struct ModuleExtra { pub module_comments: Vec, pub doc_comments: Vec, diff --git a/compiler-core/src/type_.rs b/compiler-core/src/type_.rs index 38b3369e0a4..e24329caa1f 100644 --- a/compiler-core/src/type_.rs +++ b/compiler-core/src/type_.rs @@ -619,8 +619,10 @@ pub struct ModuleInterface { pub name: EcoString, pub origin: Origin, pub package: EcoString, + pub documentation: Vec, pub types: HashMap, pub types_value_constructors: HashMap, + pub type_aliases: HashMap, pub values: HashMap, pub accessors: HashMap, /// Used for mapping to original source locations on disk @@ -701,6 +703,7 @@ pub struct TypeValueConstructor { #[derive(Debug, Clone, PartialEq, Eq)] pub struct TypeValueConstructorField { + pub label: Option, /// This type of this parameter pub type_: Arc, } @@ -1009,8 +1012,11 @@ impl ValueConstructor { pub struct TypeAliasConstructor { pub publicity: Publicity, pub module: EcoString, + pub origin: SrcSpan, pub type_: Type, pub arity: usize, + pub deprecation: Deprecation, + pub documentation: Option, } impl ValueConstructor { diff --git a/compiler-core/src/type_/environment.rs b/compiler-core/src/type_/environment.rs index 9129bb1d856..830b7f58cc8 100644 --- a/compiler-core/src/type_/environment.rs +++ b/compiler-core/src/type_/environment.rs @@ -47,6 +47,9 @@ pub struct Environment<'a> { /// Mapping from types to constructor names in the current module (or the prelude) pub module_types_constructors: HashMap, + /// Mapping from type aliases to constructor names in the current module (or the prelude) + pub module_type_aliases: HashMap, + /// Values defined in the current module (or the prelude) pub module_values: HashMap, @@ -101,6 +104,7 @@ impl<'a> Environment<'a> { target, module_types: prelude.types.clone(), module_types_constructors: prelude.types_value_constructors.clone(), + module_type_aliases: prelude.type_aliases.clone(), module_values: HashMap::new(), imported_modules: HashMap::new(), unused_modules: HashMap::new(), @@ -314,6 +318,28 @@ impl<'a> Environment<'a> { } } + /// Map a type alias in the current scope. + /// Errors if the module already has a type with that name, unless the type is from the + /// prelude. + /// + pub fn insert_type_alias( + &mut self, + type_name: EcoString, + info: TypeAliasConstructor, + ) -> Result<(), Error> { + let name = type_name.clone(); + let location = info.origin; + match self.module_type_aliases.insert(type_name, info) { + None => Ok(()), + Some(prelude_type) if is_prelude_module(&prelude_type.module) => Ok(()), + Some(previous) => Err(Error::DuplicateTypeName { + name, + location, + previous_location: previous.origin, + }), + } + } + pub fn assert_unique_type_name( &mut self, name: &EcoString, diff --git a/compiler-core/src/type_/prelude.rs b/compiler-core/src/type_/prelude.rs index b67595577a8..50c04394724 100644 --- a/compiler-core/src/type_/prelude.rs +++ b/compiler-core/src/type_/prelude.rs @@ -206,8 +206,10 @@ pub fn build_prelude(ids: &UniqueIdGenerator) -> ModuleInterface { name: PRELUDE_MODULE_NAME.into(), package: "".into(), origin: Origin::Src, + documentation: vec![], types: HashMap::new(), types_value_constructors: HashMap::new(), + type_aliases: HashMap::new(), values: HashMap::new(), accessors: HashMap::new(), is_internal: false, @@ -409,12 +411,14 @@ pub fn build_prelude(ids: &UniqueIdGenerator) -> ModuleInterface { TypeValueConstructor { name: "Ok".into(), parameters: vec![TypeValueConstructorField { + label: None, type_: result_value, }], }, TypeValueConstructor { name: "Error".into(), parameters: vec![TypeValueConstructorField { + label: None, type_: result_error, }], }, diff --git a/compiler-core/src/type_/tests.rs b/compiler-core/src/type_/tests.rs index 6b1d6c0e57a..465a1a5bba9 100644 --- a/compiler-core/src/type_/tests.rs +++ b/compiler-core/src/type_/tests.rs @@ -702,6 +702,7 @@ fn infer_module_type_retention_test() { warnings: vec![], origin: Origin::Src, package: "thepackage".into(), + documentation: vec![], name: "ok".into(), is_internal: false, // Core type constructors like String and Int are not included @@ -731,12 +732,14 @@ fn infer_module_type_retention_test() { TypeValueConstructor { name: "Ok".into(), parameters: vec![TypeValueConstructorField { + label: None, type_: generic_var(1), }] }, TypeValueConstructor { name: "Error".into(), parameters: vec![TypeValueConstructorField { + label: None, type_: generic_var(2), }] } @@ -754,6 +757,7 @@ fn infer_module_type_retention_test() { } ) ]), + type_aliases: HashMap::new(), values: HashMap::new(), accessors: HashMap::new(), line_numbers: LineNumbers::new(""), From 88b5aff38ef41305b45b52b217908b406319bdb9 Mon Sep 17 00:00:00 2001 From: Pedro H C Francisco <75535904+mine-tech-oficial@users.noreply.github.com> Date: Sun, 20 Oct 2024 12:54:10 -0300 Subject: [PATCH 07/12] Removed the need for capnp during build and reordered fields to maintain backwards compatibility --- compiler-core/build.rs | 10 +- compiler-core/generated/schema_capnp.rs | 200 ++++++++++++------------ compiler-core/schema.capnp | 26 +-- 3 files changed, 118 insertions(+), 118 deletions(-) diff --git a/compiler-core/build.rs b/compiler-core/build.rs index cb2bf0f2c21..6f3fb7ce04f 100644 --- a/compiler-core/build.rs +++ b/compiler-core/build.rs @@ -1,7 +1,7 @@ fn main() { - capnpc::CompilerCommand::new() - .file("schema.capnp") - .output_path("generated/") - .run() - .expect("compiling schema.capnp"); + // capnpc::CompilerCommand::new() + // .file("schema.capnp") + // .output_path("generated/") + // .run() + // .expect("compiling schema.capnp"); } diff --git a/compiler-core/generated/schema_capnp.rs b/compiler-core/generated/schema_capnp.rs index 033464b233b..c60e4e5b539 100644 --- a/compiler-core/generated/schema_capnp.rs +++ b/compiler-core/generated/schema_capnp.rs @@ -430,87 +430,87 @@ pub mod module { !self.reader.get_pointer_field(0).is_null() } #[inline] - pub fn get_documentation(self) -> ::capnp::Result<::capnp::text_list::Reader<'a>> { + pub fn get_types(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1), ::core::option::Option::None) } #[inline] - pub fn has_documentation(&self) -> bool { + pub fn has_types(&self) -> bool { !self.reader.get_pointer_field(1).is_null() } #[inline] - pub fn get_types(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { + pub fn get_values(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(2), ::core::option::Option::None) } #[inline] - pub fn has_types(&self) -> bool { + pub fn has_values(&self) -> bool { !self.reader.get_pointer_field(2).is_null() } #[inline] - pub fn get_type_aliases(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { + pub fn get_accessors(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(3), ::core::option::Option::None) } #[inline] - pub fn has_type_aliases(&self) -> bool { + pub fn has_accessors(&self) -> bool { !self.reader.get_pointer_field(3).is_null() } #[inline] - pub fn get_values(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { + pub fn get_package(self) -> ::capnp::Result<::capnp::text::Reader<'a>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(4), ::core::option::Option::None) } #[inline] - pub fn has_values(&self) -> bool { + pub fn has_package(&self) -> bool { !self.reader.get_pointer_field(4).is_null() } #[inline] - pub fn get_accessors(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { + pub fn get_types_constructors(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(5), ::core::option::Option::None) } #[inline] - pub fn has_accessors(&self) -> bool { + pub fn has_types_constructors(&self) -> bool { !self.reader.get_pointer_field(5).is_null() } #[inline] - pub fn get_package(self) -> ::capnp::Result<::capnp::text::Reader<'a>> { + pub fn get_line_numbers(self) -> ::capnp::Result> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(6), ::core::option::Option::None) } #[inline] - pub fn has_package(&self) -> bool { + pub fn has_line_numbers(&self) -> bool { !self.reader.get_pointer_field(6).is_null() } #[inline] - pub fn get_types_constructors(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { + pub fn get_src_path(self) -> ::capnp::Result<::capnp::text::Reader<'a>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(7), ::core::option::Option::None) } #[inline] - pub fn has_types_constructors(&self) -> bool { + pub fn has_src_path(&self) -> bool { !self.reader.get_pointer_field(7).is_null() } #[inline] - pub fn get_line_numbers(self) -> ::capnp::Result> { + pub fn get_is_internal(self) -> bool { + self.reader.get_bool_field(0) + } + #[inline] + pub fn get_required_version(self) -> ::capnp::Result> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(8), ::core::option::Option::None) } #[inline] - pub fn has_line_numbers(&self) -> bool { + pub fn has_required_version(&self) -> bool { !self.reader.get_pointer_field(8).is_null() } #[inline] - pub fn get_src_path(self) -> ::capnp::Result<::capnp::text::Reader<'a>> { + pub fn get_documentation(self) -> ::capnp::Result<::capnp::text_list::Reader<'a>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(9), ::core::option::Option::None) } #[inline] - pub fn has_src_path(&self) -> bool { + pub fn has_documentation(&self) -> bool { !self.reader.get_pointer_field(9).is_null() } #[inline] - pub fn get_is_internal(self) -> bool { - self.reader.get_bool_field(0) - } - #[inline] - pub fn get_required_version(self) -> ::capnp::Result> { + pub fn get_type_aliases(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(10), ::core::option::Option::None) } #[inline] - pub fn has_required_version(&self) -> bool { + pub fn has_type_aliases(&self) -> bool { !self.reader.get_pointer_field(10).is_null() } } @@ -580,171 +580,171 @@ pub mod module { !self.builder.get_pointer_field(0).is_null() } #[inline] - pub fn get_documentation(self) -> ::capnp::Result<::capnp::text_list::Builder<'a>> { + pub fn get_types(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1), ::core::option::Option::None) } #[inline] - pub fn set_documentation(&mut self, value: ::capnp::text_list::Reader<'a>) -> ::capnp::Result<()> { + pub fn set_types(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value, false) } #[inline] - pub fn init_documentation(self, size: u32) -> ::capnp::text_list::Builder<'a> { + pub fn init_types(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), size) } #[inline] - pub fn has_documentation(&self) -> bool { + pub fn has_types(&self) -> bool { !self.builder.get_pointer_field(1).is_null() } #[inline] - pub fn get_types(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { + pub fn get_values(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(2), ::core::option::Option::None) } #[inline] - pub fn set_types(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { + pub fn set_values(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(2), value, false) } #[inline] - pub fn init_types(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { + pub fn init_values(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(2), size) } #[inline] - pub fn has_types(&self) -> bool { + pub fn has_values(&self) -> bool { !self.builder.get_pointer_field(2).is_null() } #[inline] - pub fn get_type_aliases(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { + pub fn get_accessors(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(3), ::core::option::Option::None) } #[inline] - pub fn set_type_aliases(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { + pub fn set_accessors(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(3), value, false) } #[inline] - pub fn init_type_aliases(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { + pub fn init_accessors(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(3), size) } #[inline] - pub fn has_type_aliases(&self) -> bool { + pub fn has_accessors(&self) -> bool { !self.builder.get_pointer_field(3).is_null() } #[inline] - pub fn get_values(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { + pub fn get_package(self) -> ::capnp::Result<::capnp::text::Builder<'a>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(4), ::core::option::Option::None) } #[inline] - pub fn set_values(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { - ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(4), value, false) + pub fn set_package(&mut self, value: ::capnp::text::Reader<'_>) { + self.builder.get_pointer_field(4).set_text(value); } #[inline] - pub fn init_values(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { - ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(4), size) + pub fn init_package(self, size: u32) -> ::capnp::text::Builder<'a> { + self.builder.get_pointer_field(4).init_text(size) } #[inline] - pub fn has_values(&self) -> bool { + pub fn has_package(&self) -> bool { !self.builder.get_pointer_field(4).is_null() } #[inline] - pub fn get_accessors(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { + pub fn get_types_constructors(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(5), ::core::option::Option::None) } #[inline] - pub fn set_accessors(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { + pub fn set_types_constructors(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(5), value, false) } #[inline] - pub fn init_accessors(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { + pub fn init_types_constructors(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(5), size) } #[inline] - pub fn has_accessors(&self) -> bool { + pub fn has_types_constructors(&self) -> bool { !self.builder.get_pointer_field(5).is_null() } #[inline] - pub fn get_package(self) -> ::capnp::Result<::capnp::text::Builder<'a>> { + pub fn get_line_numbers(self) -> ::capnp::Result> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(6), ::core::option::Option::None) } #[inline] - pub fn set_package(&mut self, value: ::capnp::text::Reader<'_>) { - self.builder.get_pointer_field(6).set_text(value); + pub fn set_line_numbers(&mut self, value: crate::schema_capnp::line_numbers::Reader<'_>) -> ::capnp::Result<()> { + ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(6), value, false) } #[inline] - pub fn init_package(self, size: u32) -> ::capnp::text::Builder<'a> { - self.builder.get_pointer_field(6).init_text(size) + pub fn init_line_numbers(self, ) -> crate::schema_capnp::line_numbers::Builder<'a> { + ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(6), 0) } #[inline] - pub fn has_package(&self) -> bool { + pub fn has_line_numbers(&self) -> bool { !self.builder.get_pointer_field(6).is_null() } #[inline] - pub fn get_types_constructors(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { + pub fn get_src_path(self) -> ::capnp::Result<::capnp::text::Builder<'a>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(7), ::core::option::Option::None) } #[inline] - pub fn set_types_constructors(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { - ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(7), value, false) + pub fn set_src_path(&mut self, value: ::capnp::text::Reader<'_>) { + self.builder.get_pointer_field(7).set_text(value); } #[inline] - pub fn init_types_constructors(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { - ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(7), size) + pub fn init_src_path(self, size: u32) -> ::capnp::text::Builder<'a> { + self.builder.get_pointer_field(7).init_text(size) } #[inline] - pub fn has_types_constructors(&self) -> bool { + pub fn has_src_path(&self) -> bool { !self.builder.get_pointer_field(7).is_null() } #[inline] - pub fn get_line_numbers(self) -> ::capnp::Result> { + pub fn get_is_internal(self) -> bool { + self.builder.get_bool_field(0) + } + #[inline] + pub fn set_is_internal(&mut self, value: bool) { + self.builder.set_bool_field(0, value); + } + #[inline] + pub fn get_required_version(self) -> ::capnp::Result> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(8), ::core::option::Option::None) } #[inline] - pub fn set_line_numbers(&mut self, value: crate::schema_capnp::line_numbers::Reader<'_>) -> ::capnp::Result<()> { + pub fn set_required_version(&mut self, value: crate::schema_capnp::version::Reader<'_>) -> ::capnp::Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(8), value, false) } #[inline] - pub fn init_line_numbers(self, ) -> crate::schema_capnp::line_numbers::Builder<'a> { + pub fn init_required_version(self, ) -> crate::schema_capnp::version::Builder<'a> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(8), 0) } #[inline] - pub fn has_line_numbers(&self) -> bool { + pub fn has_required_version(&self) -> bool { !self.builder.get_pointer_field(8).is_null() } #[inline] - pub fn get_src_path(self) -> ::capnp::Result<::capnp::text::Builder<'a>> { + pub fn get_documentation(self) -> ::capnp::Result<::capnp::text_list::Builder<'a>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(9), ::core::option::Option::None) } #[inline] - pub fn set_src_path(&mut self, value: ::capnp::text::Reader<'_>) { - self.builder.get_pointer_field(9).set_text(value); + pub fn set_documentation(&mut self, value: ::capnp::text_list::Reader<'a>) -> ::capnp::Result<()> { + ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(9), value, false) } #[inline] - pub fn init_src_path(self, size: u32) -> ::capnp::text::Builder<'a> { - self.builder.get_pointer_field(9).init_text(size) + pub fn init_documentation(self, size: u32) -> ::capnp::text_list::Builder<'a> { + ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(9), size) } #[inline] - pub fn has_src_path(&self) -> bool { + pub fn has_documentation(&self) -> bool { !self.builder.get_pointer_field(9).is_null() } #[inline] - pub fn get_is_internal(self) -> bool { - self.builder.get_bool_field(0) - } - #[inline] - pub fn set_is_internal(&mut self, value: bool) { - self.builder.set_bool_field(0, value); - } - #[inline] - pub fn get_required_version(self) -> ::capnp::Result> { + pub fn get_type_aliases(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(10), ::core::option::Option::None) } #[inline] - pub fn set_required_version(&mut self, value: crate::schema_capnp::version::Reader<'_>) -> ::capnp::Result<()> { + pub fn set_type_aliases(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::property::Owned>) -> ::capnp::Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(10), value, false) } #[inline] - pub fn init_required_version(self, ) -> crate::schema_capnp::version::Builder<'a> { - ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(10), 0) + pub fn init_type_aliases(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::property::Owned> { + ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(10), size) } #[inline] - pub fn has_required_version(&self) -> bool { + pub fn has_type_aliases(&self) -> bool { !self.builder.get_pointer_field(10).is_null() } } @@ -757,10 +757,10 @@ pub mod module { } impl Pipeline { pub fn get_line_numbers(&self) -> crate::schema_capnp::line_numbers::Pipeline { - ::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(8)) + ::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(6)) } pub fn get_required_version(&self) -> crate::schema_capnp::version::Pipeline { - ::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(10)) + ::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(8)) } } mod _private { @@ -1288,19 +1288,19 @@ pub mod type_value_constructor_parameter { self.reader.total_size() } #[inline] - pub fn get_label(self) -> ::capnp::Result<::capnp::text::Reader<'a>> { + pub fn get_type(self) -> ::capnp::Result> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(0), ::core::option::Option::None) } #[inline] - pub fn has_label(&self) -> bool { + pub fn has_type(&self) -> bool { !self.reader.get_pointer_field(0).is_null() } #[inline] - pub fn get_type(self) -> ::capnp::Result> { + pub fn get_label(self) -> ::capnp::Result<::capnp::text::Reader<'a>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1), ::core::option::Option::None) } #[inline] - pub fn has_type(&self) -> bool { + pub fn has_label(&self) -> bool { !self.reader.get_pointer_field(1).is_null() } } @@ -1354,35 +1354,35 @@ pub mod type_value_constructor_parameter { self.builder.into_reader().total_size() } #[inline] - pub fn get_label(self) -> ::capnp::Result<::capnp::text::Builder<'a>> { + pub fn get_type(self) -> ::capnp::Result> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(0), ::core::option::Option::None) } #[inline] - pub fn set_label(&mut self, value: ::capnp::text::Reader<'_>) { - self.builder.get_pointer_field(0).set_text(value); + pub fn set_type(&mut self, value: crate::schema_capnp::type_::Reader<'_>) -> ::capnp::Result<()> { + ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(0), value, false) } #[inline] - pub fn init_label(self, size: u32) -> ::capnp::text::Builder<'a> { - self.builder.get_pointer_field(0).init_text(size) + pub fn init_type(self, ) -> crate::schema_capnp::type_::Builder<'a> { + ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(0), 0) } #[inline] - pub fn has_label(&self) -> bool { + pub fn has_type(&self) -> bool { !self.builder.get_pointer_field(0).is_null() } #[inline] - pub fn get_type(self) -> ::capnp::Result> { + pub fn get_label(self) -> ::capnp::Result<::capnp::text::Builder<'a>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1), ::core::option::Option::None) } #[inline] - pub fn set_type(&mut self, value: crate::schema_capnp::type_::Reader<'_>) -> ::capnp::Result<()> { - ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value, false) + pub fn set_label(&mut self, value: ::capnp::text::Reader<'_>) { + self.builder.get_pointer_field(1).set_text(value); } #[inline] - pub fn init_type(self, ) -> crate::schema_capnp::type_::Builder<'a> { - ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), 0) + pub fn init_label(self, size: u32) -> ::capnp::text::Builder<'a> { + self.builder.get_pointer_field(1).init_text(size) } #[inline] - pub fn has_type(&self) -> bool { + pub fn has_label(&self) -> bool { !self.builder.get_pointer_field(1).is_null() } } @@ -1395,7 +1395,7 @@ pub mod type_value_constructor_parameter { } impl Pipeline { pub fn get_type(&self) -> crate::schema_capnp::type_::Pipeline { - ::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(1)) + ::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(0)) } } mod _private { diff --git a/compiler-core/schema.capnp b/compiler-core/schema.capnp index 6d335a0c295..96bebc7dba2 100644 --- a/compiler-core/schema.capnp +++ b/compiler-core/schema.capnp @@ -21,17 +21,17 @@ struct Option(Value) { struct Module { name @0 :Text; - documentation @1 :List(Text); - types @2 :List(Property(TypeConstructor)); - typeAliases @3 :List(Property(TypeAliasConstructor)); - values @4 :List(Property(ValueConstructor)); - accessors @5 :List(Property(AccessorsMap)); - package @6 :Text; - typesConstructors @7 :List(Property(TypesVariantConstructors)); - lineNumbers @8 :LineNumbers; - srcPath @9 :Text; - isInternal @10 :Bool; - requiredVersion @11 :Version; + documentation @10 :List(Text); + types @1 :List(Property(TypeConstructor)); + typeAliases @11 :List(Property(TypeAliasConstructor)); + values @2 :List(Property(ValueConstructor)); + accessors @3 :List(Property(AccessorsMap)); + package @4 :Text; + typesConstructors @5 :List(Property(TypesVariantConstructors)); + lineNumbers @6 :LineNumbers; + srcPath @7 :Text; + isInternal @8 :Bool; + requiredVersion @9 :Version; } struct Version { @@ -51,8 +51,8 @@ struct TypeValueConstructor { } struct TypeValueConstructorParameter { - label @0 :Text; - type @1 :Type; + type @0 :Type; + label @1 :Text; } struct TypeConstructor { From cdb39b3f296859d9286baf34a0b3132f4d060b6d Mon Sep 17 00:00:00 2001 From: Pedro H C Francisco <75535904+mine-tech-oficial@users.noreply.github.com> Date: Mon, 21 Oct 2024 20:14:17 -0300 Subject: [PATCH 08/12] Fixed broken tests --- compiler-core/build.rs | 10 +- compiler-core/generated/schema_capnp.rs | 14 +- compiler-core/schema.capnp | 1 + compiler-core/src/analyse.rs | 22 +- compiler-core/src/build/package_compiler.rs | 40 +- compiler-core/src/build/project_compiler.rs | 39 +- compiler-core/src/docs/tests.rs | 7 +- compiler-core/src/language_server/compiler.rs | 4 +- .../src/language_server/completer.rs | 121 ++++- ...__hover_function_definition_with_docs.snap | 2 +- ...__tests__hover__hover_module_constant.snap | 2 +- compiler-core/src/metadata/module_decoder.rs | 1 + compiler-core/src/metadata/module_encoder.rs | 20 +- compiler-core/src/metadata/tests.rs | 9 + compiler-core/src/package_interface.rs | 433 +++++++++--------- ...age_interface__tests__type_definition.snap | 2 +- compiler-core/src/package_interface/tests.rs | 1 + compiler-core/src/type_.rs | 6 + compiler-core/src/type_/prelude.rs | 9 + 19 files changed, 462 insertions(+), 281 deletions(-) diff --git a/compiler-core/build.rs b/compiler-core/build.rs index 6f3fb7ce04f..cb2bf0f2c21 100644 --- a/compiler-core/build.rs +++ b/compiler-core/build.rs @@ -1,7 +1,7 @@ fn main() { - // capnpc::CompilerCommand::new() - // .file("schema.capnp") - // .output_path("generated/") - // .run() - // .expect("compiling schema.capnp"); + capnpc::CompilerCommand::new() + .file("schema.capnp") + .output_path("generated/") + .run() + .expect("compiling schema.capnp"); } diff --git a/compiler-core/generated/schema_capnp.rs b/compiler-core/generated/schema_capnp.rs index c60e4e5b539..245a1be0eca 100644 --- a/compiler-core/generated/schema_capnp.rs +++ b/compiler-core/generated/schema_capnp.rs @@ -1507,6 +1507,10 @@ pub mod type_constructor { pub fn has_documentation(&self) -> bool { !self.reader.get_pointer_field(6).is_null() } + #[inline] + pub fn get_opaque(self) -> bool { + self.reader.get_bool_field(0) + } } pub struct Builder<'a> { builder: ::capnp::private::layout::StructBuilder<'a> } @@ -1669,6 +1673,14 @@ pub mod type_constructor { pub fn has_documentation(&self) -> bool { !self.builder.get_pointer_field(6).is_null() } + #[inline] + pub fn get_opaque(self) -> bool { + self.builder.get_bool_field(0) + } + #[inline] + pub fn set_opaque(&mut self, value: bool) { + self.builder.set_bool_field(0, value); + } } pub struct Pipeline { _typeless: ::capnp::any_pointer::Pipeline } @@ -1690,7 +1702,7 @@ pub mod type_constructor { } mod _private { use capnp::private::layout; - pub const STRUCT_SIZE: layout::StructSize = layout::StructSize { data: 0, pointers: 7 }; + pub const STRUCT_SIZE: layout::StructSize = layout::StructSize { data: 1, pointers: 7 }; pub const TYPE_ID: u64 = 0xb1fb_6d62_e00b_6d7a; } } diff --git a/compiler-core/schema.capnp b/compiler-core/schema.capnp index 96bebc7dba2..49613a19035 100644 --- a/compiler-core/schema.capnp +++ b/compiler-core/schema.capnp @@ -63,6 +63,7 @@ struct TypeConstructor { parameters @1 :List(Type); module @2 :Text; publicity @3 :Publicity; + opaque @7 :Bool; deprecated @4 :Text; origin @5 :SrcSpan; documentation @6 :Text; diff --git a/compiler-core/src/analyse.rs b/compiler-core/src/analyse.rs index 29d418b389a..4256d358bbe 100644 --- a/compiler-core/src/analyse.rs +++ b/compiler-core/src/analyse.rs @@ -974,7 +974,9 @@ impl<'a, A> ModuleAnalyzer<'a, A> { }; fields.push(TypeValueConstructorField { - label: label.clone().map_or(None, |(_, label)| Some(label.clone())), + label: label + .as_ref() + .map_or(None, |(_, label)| Some(label.clone())), type_: t.clone(), }); @@ -1132,6 +1134,7 @@ impl<'a, A> ModuleAnalyzer<'a, A> { deprecation: deprecation.clone(), parameters, publicity, + opaque: *opaque, type_, documentation: documentation.as_ref().map(|(_, doc)| doc.clone()), }, @@ -1190,11 +1193,14 @@ impl<'a, A> ModuleAnalyzer<'a, A> { let parameters = self.make_type_vars(args, &mut hydrator, environment); let mut tryblock = || { hydrator.disallow_new_type_variables(); - let type_ = hydrator.type_from_ast(resolved_type, environment, &mut self.problems)?; + let type_ref = + hydrator.type_from_ast(resolved_type, environment, &mut self.problems)?; + let type_ = type_ref.as_ref().clone(); + let arity = parameters.len(); environment .names - .type_in_scope(name.clone(), type_.as_ref()); + .type_in_scope(name.clone(), type_ref.as_ref()); // Insert the alias so that it can be used by other code. environment.insert_type_constructor( @@ -1202,10 +1208,12 @@ impl<'a, A> ModuleAnalyzer<'a, A> { TypeConstructor { origin: *location, module: self.module_name.clone(), - parameters: parameters.clone(), - type_: type_.clone(), + parameters, + type_: type_ref, deprecation: deprecation.clone(), publicity: *publicity, + // TODO: Find if the type is opaque + opaque: false, documentation: documentation.as_ref().map(|(_, doc)| doc.clone()), }, )?; @@ -1215,8 +1223,8 @@ impl<'a, A> ModuleAnalyzer<'a, A> { TypeAliasConstructor { origin: *location, module: self.module_name.clone(), - type_: type_.as_ref().clone(), - arity: parameters.len(), + type_, + arity, publicity: *publicity, deprecation: deprecation.clone(), documentation: documentation.as_ref().map(|(_, doc)| doc.clone()), diff --git a/compiler-core/src/build/package_compiler.rs b/compiler-core/src/build/package_compiler.rs index 68704026d6c..8bacc408687 100644 --- a/compiler-core/src/build/package_compiler.rs +++ b/compiler-core/src/build/package_compiler.rs @@ -32,6 +32,11 @@ use camino::{Utf8Path, Utf8PathBuf}; use super::{ErlangAppCodegenConfiguration, TargetCodegenConfiguration, Telemetry}; +pub struct Compiled { + pub modules: Vec, + pub cached_modules: Vec, +} + #[derive(Debug)] pub struct PackageCompiler<'a, IO> { pub io: IO, @@ -106,7 +111,7 @@ where stale_modules: &mut StaleTracker, incomplete_modules: &mut HashSet, telemetry: &dyn Telemetry, - ) -> Outcome<(Vec, Vec), Error> { + ) -> Outcome { let span = tracing::info_span!("compile", package = %self.config.name.as_str()); let _enter = span.enter(); @@ -187,7 +192,13 @@ where let mut modules = match outcome { Outcome::Ok(modules) => modules, Outcome::PartialFailure(modules, err) => { - return Outcome::PartialFailure((modules, loaded.cached), err) + return Outcome::PartialFailure( + Compiled { + modules, + cached_modules: loaded.cached, + }, + err, + ) } Outcome::TotalFailure(err) => return Outcome::TotalFailure(err), }; @@ -198,10 +209,18 @@ where return error.into(); } + for mut module in modules.iter_mut() { + module.ast.type_info.remove_duplicated_type_aliases(); + module.attach_doc_and_module_comments(); + } + if let Err(error) = self.encode_and_write_metadata(&modules) { return error.into(); } - Outcome::Ok((modules, loaded.cached)) + Outcome::Ok(Compiled { + modules, + cached_modules: loaded.cached, + }) } fn compile_erlang_to_beam(&mut self, modules: &HashSet) -> Result<(), Error> { @@ -295,8 +314,7 @@ where let artefact_dir = self.out.join(paths::ARTEFACT_DIRECTORY_NAME); tracing::debug!("writing_module_caches"); - for mut module in modules.clone() { - module.attach_doc_and_module_comments(); + for module in modules { let module_name = module.name.replace("/", "@"); // Write metadata file @@ -518,12 +536,15 @@ fn analyse( .infer_module(ast, line_numbers, path.clone()); match analysis { - Outcome::Ok(ast) => { + Outcome::Ok(mut ast) => { // Module has compiled successfully. Make sure it isn't marked as incomplete. let _ = incomplete_modules.remove(&name.clone()); // Register the types from this module so they can be imported into // other modules. let _ = module_types.insert(name.clone(), ast.type_info.clone()); + + ast.type_info.remove_duplicated_type_aliases(); + // Register the successfully type checked module data so that it can be // used for code generation and in the language server. modules.push(Module { @@ -538,7 +559,7 @@ fn analyse( }); } - Outcome::PartialFailure(ast, errors) => { + Outcome::PartialFailure(mut ast, errors) => { let error = Error::Type { names: ast.names.clone(), path: path.clone(), @@ -547,6 +568,9 @@ fn analyse( }; // Mark as incomplete so that this module isn't reloaded from cache. let _ = incomplete_modules.insert(name.clone()); + + ast.type_info.remove_duplicated_type_aliases(); + // Register the partially type checked module data so that it can be // used in the language server. modules.push(Module { @@ -651,7 +675,7 @@ pub(crate) struct CachedModule { } #[derive(Debug, serde::Serialize, serde::Deserialize)] -pub struct CacheMetadata { +pub(crate) struct CacheMetadata { pub mtime: SystemTime, pub codegen_performed: bool, pub dependencies: Vec<(EcoString, SrcSpan)>, diff --git a/compiler-core/src/build/project_compiler.rs b/compiler-core/src/build/project_compiler.rs index 10cb2d60f13..92f1494d4c9 100644 --- a/compiler-core/src/build/project_compiler.rs +++ b/compiler-core/src/build/project_compiler.rs @@ -33,8 +33,9 @@ use std::{ }; use super::{ - elixir_libraries::ElixirLibraries, package_compiler::CachedWarnings, Codegen, Compile, - ErlangAppCodegenConfiguration, Outcome, + elixir_libraries::ElixirLibraries, + package_compiler::{CachedWarnings, Compiled}, + Codegen, Compile, ErlangAppCodegenConfiguration, Outcome, }; use camino::{Utf8Path, Utf8PathBuf}; @@ -208,11 +209,16 @@ where pub fn compile_root_package(&mut self) -> Outcome { let config = self.config.clone(); self.compile_gleam_package(&config, true, self.paths.root().to_path_buf()) - .map(|(modules, cachedModules)| Package { - config, - modules, - cached_modules: cachedModules, - }) + .map( + |Compiled { + modules, + cached_modules, + }| Package { + config, + modules, + cached_modules, + }, + ) } /// Checks that version file found in the build directory matches the @@ -252,7 +258,10 @@ where let mut modules = vec![]; for name in sequence { - let compiled = self.load_cache_or_compile_package(&name)?; + let mut compiled = self.load_cache_or_compile_package(&name)?; + compiled.iter_mut().for_each(|module| { + module.ast.type_info.remove_duplicated_type_aliases(); + }); modules.extend(compiled); } @@ -292,7 +301,12 @@ where // longer need to have the package borrowed from self.packages. let package = self.packages.get(name).expect("Missing package").clone(); let result = match usable_build_tools(&package)?.as_slice() { - &[BuildTool::Gleam] => self.compile_gleam_dep_package(&package).map(|_| vec![]), + &[BuildTool::Gleam] => self.compile_gleam_dep_package(&package).map( + |Compiled { + modules, + cached_modules: _, + }| modules, + ), &[BuildTool::Rebar3] => self.compile_rebar3_dep_package(&package).map(|_| vec![]), &[BuildTool::Mix] => self.compile_mix_dep_package(&package).map(|_| vec![]), &[BuildTool::Mix, BuildTool::Rebar3] => self @@ -490,10 +504,7 @@ where } } - fn compile_gleam_dep_package( - &mut self, - package: &ManifestPackage, - ) -> Result<(Vec, Vec), Error> { + fn compile_gleam_dep_package(&mut self, package: &ManifestPackage) -> Result { // TODO: Test let package_root = match &package.source { // If the path is relative it is relative to the root of the @@ -524,7 +535,7 @@ where config: &PackageConfig, is_root: bool, root_path: Utf8PathBuf, - ) -> Outcome<(Vec, Vec), Error> { + ) -> Outcome { let out_path = self.paths .build_directory_for_package(self.mode(), self.target(), &config.name); diff --git a/compiler-core/src/docs/tests.rs b/compiler-core/src/docs/tests.rs index e8f3922b955..20e8bc9837f 100644 --- a/compiler-core/src/docs/tests.rs +++ b/compiler-core/src/docs/tests.rs @@ -61,9 +61,10 @@ fn compile_with_markdown_pages( &mut HashSet::new(), &NullTelemetry, ) - .unwrap(); + .unwrap() + .modules; - for module in &mut modules.0 { + for module in &mut modules { module.attach_doc_and_module_comments(); } @@ -79,7 +80,7 @@ fn compile_with_markdown_pages( super::generate_html( &paths, &config, - &modules.0, + &modules, &docs_pages, pages_fs, SystemTime::UNIX_EPOCH, diff --git a/compiler-core/src/language_server/compiler.rs b/compiler-core/src/language_server/compiler.rs index ab5b6ea5696..517672fe8f8 100644 --- a/compiler-core/src/language_server/compiler.rs +++ b/compiler-core/src/language_server/compiler.rs @@ -166,7 +166,9 @@ where .collect_vec(); // Store the compiled module information - for module in modules { + for mut module in modules { + module.ast.type_info.remove_duplicated_type_aliases(); + let path = module.input_path.as_os_str().to_string_lossy().to_string(); let line_numbers = LineNumbers::new(&module.code); let source = ModuleSourceInformation { path, line_numbers }; diff --git a/compiler-core/src/language_server/completer.rs b/compiler-core/src/language_server/completer.rs index c2d535894b7..458df149f95 100644 --- a/compiler-core/src/language_server/completer.rs +++ b/compiler-core/src/language_server/completer.rs @@ -16,7 +16,8 @@ use crate::{ line_numbers::LineNumbers, type_::{ self, collapse_links, pretty::Printer, AccessorsMap, FieldMap, ModuleInterface, - PreludeType, Type, TypeConstructor, ValueConstructorVariant, PRELUDE_MODULE_NAME, + PreludeType, Type, TypeAliasConstructor, TypeConstructor, ValueConstructorVariant, + PRELUDE_MODULE_NAME, }, Result, }; @@ -397,11 +398,18 @@ where }); } - // Module types + // Module types and type aliases // Do not complete direct module types if the user has already started typing a module select. // e.x. when the user has typed mymodule.| we know local module types are no longer relevant if module_select.is_none() { - for (name, type_) in &self.module.ast.type_info.types { + for (name, type_) in self + .module + .ast + .type_info + .types + .iter() + .filter(|(name, _)| !self.module.ast.type_info.type_aliases.contains_key(*name)) + { completions.push(type_completion( None, name, @@ -411,6 +419,16 @@ where CompletionKind::LocallyDefined, )); } + for (name, type_) in &self.module.ast.type_info.type_aliases { + completions.push(type_alias_completion( + None, + name, + type_, + insert_range, + TypeCompletionForm::Default, + CompletionKind::LocallyDefined, + )); + } } // Imported modules @@ -422,7 +440,11 @@ where }; // Qualified types - for (name, type_) in &module.types { + for (name, type_) in module + .types + .iter() + .filter(|(name, _)| !module.type_aliases.contains_key(*name)) + { if !self.is_suggestable_import(&type_.publicity, module.package.as_str()) { continue; } @@ -446,7 +468,32 @@ where } } - // Unqualified types + // Qualified type aliases + for (name, type_) in &module.type_aliases { + if !self.is_suggestable_import(&type_.publicity, module.package.as_str()) { + continue; + } + + if let Some(module) = import.used_name() { + // If the user has already started a module select then don't show irrelevant modules. + // e.x. when the user has typed mymodule.| we should only show items from mymodule. + if let Some(input_mod_name) = &module_select { + if &module != input_mod_name { + continue; + } + } + completions.push(type_alias_completion( + Some(&module), + name, + type_, + insert_range, + TypeCompletionForm::Default, + CompletionKind::ImportedModule, + )); + } + } + + // Unqualified types and type aliases // Do not complete unqualified types if the user has already started typing a module select. // e.x. when the user has typed mymodule.| we know unqualified module types are no longer relevant. if module_select.is_none() { @@ -498,7 +545,11 @@ where } // Qualified types - for (name, type_) in &module.types { + for (name, type_) in module + .types + .iter() + .filter(|(name, _)| !module.type_aliases.contains_key(*name)) + { if !self.is_suggestable_import(&type_.publicity, module.package.as_str()) { continue; } @@ -519,6 +570,29 @@ where ); completions.push(completion); } + + // Qualified type aliases + for (name, type_) in &module.type_aliases { + if !self.is_suggestable_import(&type_.publicity, module.package.as_str()) { + continue; + } + + let mut completion = type_alias_completion( + Some(qualifier), + name, + type_, + insert_range, + TypeCompletionForm::Default, + CompletionKind::ImportableModule, + ); + add_import_to_completion( + &mut completion, + import_location, + module_full_name, + &after_import_newlines, + ); + completions.push(completion); + } } completions @@ -872,6 +946,41 @@ fn type_completion( } } +fn type_alias_completion( + module: Option<&str>, + name: &str, + type_: &TypeAliasConstructor, + insert_range: Range, + include_type_in_completion: TypeCompletionForm, + priority: CompletionKind, +) -> CompletionItem { + let label = match module { + Some(module) => format!("{module}.{name}"), + None => name.to_string(), + }; + + let kind = Some(if type_.type_.is_variable() { + CompletionItemKind::VARIABLE + } else { + CompletionItemKind::CLASS + }); + + CompletionItem { + label: label.clone(), + kind, + detail: Some("Type".into()), + sort_text: Some(sort_text(priority, &label)), + text_edit: Some(CompletionTextEdit::Edit(TextEdit { + range: insert_range, + new_text: match include_type_in_completion { + TypeCompletionForm::UnqualifiedImport => format!("type {label}"), + TypeCompletionForm::Default => label.clone(), + }, + })), + ..Default::default() + } +} + fn value_completion( module_qualifier: Option<&str>, module_name: &str, diff --git a/compiler-core/src/language_server/tests/snapshots/gleam_core__language_server__tests__hover__hover_function_definition_with_docs.snap b/compiler-core/src/language_server/tests/snapshots/gleam_core__language_server__tests__hover__hover_function_definition_with_docs.snap index 2cc8a9f13f6..8f699f6d13c 100644 --- a/compiler-core/src/language_server/tests/snapshots/gleam_core__language_server__tests__hover__hover_function_definition_with_docs.snap +++ b/compiler-core/src/language_server/tests/snapshots/gleam_core__language_server__tests__hover__hover_function_definition_with_docs.snap @@ -13,6 +13,6 @@ fn append(x, y) { ----- Hover content ----- Scalar( String( - "```gleam\nfn(String, String) -> String\n```\n Exciting documentation\n Maybe even multiple lines\n", + "```gleam\nfn(String, String) -> String\n```\n Exciting documentation\n Maybe even multiple lines", ), ) diff --git a/compiler-core/src/language_server/tests/snapshots/gleam_core__language_server__tests__hover__hover_module_constant.snap b/compiler-core/src/language_server/tests/snapshots/gleam_core__language_server__tests__hover__hover_module_constant.snap index be57c67f1c9..8c1170d7869 100644 --- a/compiler-core/src/language_server/tests/snapshots/gleam_core__language_server__tests__hover__hover_module_constant.snap +++ b/compiler-core/src/language_server/tests/snapshots/gleam_core__language_server__tests__hover__hover_module_constant.snap @@ -11,6 +11,6 @@ const one = 1 ----- Hover content ----- Scalar( String( - "```gleam\nInt\n```\n Exciting documentation\n Maybe even multiple lines\n", + "```gleam\nInt\n```\n Exciting documentation\n Maybe even multiple lines", ), ) diff --git a/compiler-core/src/metadata/module_decoder.rs b/compiler-core/src/metadata/module_decoder.rs index ad3b12bb3a4..320397896ac 100755 --- a/compiler-core/src/metadata/module_decoder.rs +++ b/compiler-core/src/metadata/module_decoder.rs @@ -104,6 +104,7 @@ impl ModuleDecoder { }; Ok(TypeConstructor { publicity: self.publicity(reader.get_publicity()?)?, + opaque: reader.get_opaque(), origin: self.src_span(&reader.get_origin()?)?, module: reader.get_module()?.into(), parameters: read_vec!(reader.get_parameters()?, self, type_), diff --git a/compiler-core/src/metadata/module_encoder.rs b/compiler-core/src/metadata/module_encoder.rs index da24c7fe60d..d4dd36f7b94 100644 --- a/compiler-core/src/metadata/module_encoder.rs +++ b/compiler-core/src/metadata/module_encoder.rs @@ -119,23 +119,8 @@ impl<'a> ModuleEncoder<'a> { fn set_module_types(&mut self, module: &mut module::Builder<'_>) { tracing::trace!("Writing module metadata types"); - let filtered_types: Vec<_> = self - .data - .types - .iter() - .filter(|(name, _)| !self.data.type_aliases.contains_key(*name)) - // .map(|(type_name, type_)| { - // println!( - // "Type {}/{} has documentation {}", - // self.data.name, - // type_name, - // type_.documentation.clone().unwrap_or_default().len(), - // ); - // (type_name, type_) - // }) - .collect(); - let mut types = module.reborrow().init_types(filtered_types.len() as u32); - for (i, (name, type_)) in filtered_types.iter().enumerate() { + let mut types = module.reborrow().init_types(self.data.types.len() as u32); + for (i, (name, type_)) in self.data.types.iter().enumerate() { let mut property = types.reborrow().get(i as u32); property.set_key(name); self.build_type_constructor(property.init_value(), type_) @@ -228,6 +213,7 @@ impl<'a> ModuleEncoder<'a> { Deprecation::Deprecated { message } => message, }); self.build_publicity(builder.reborrow().init_publicity(), constructor.publicity); + builder.set_opaque(constructor.opaque); let type_builder = builder.reborrow().init_type(); self.build_type(type_builder, &constructor.type_); self.build_types( diff --git a/compiler-core/src/metadata/tests.rs b/compiler-core/src/metadata/tests.rs index 30aafff4aa0..19f559f8b0f 100644 --- a/compiler-core/src/metadata/tests.rs +++ b/compiler-core/src/metadata/tests.rs @@ -144,6 +144,7 @@ fn module_with_private_type() { TypeConstructor { type_: type_::list(type_::int()), publicity: Publicity::Private, + opaque: false, origin: Default::default(), module: "the/module".into(), parameters: vec![], @@ -177,6 +178,7 @@ fn module_with_app_type() { TypeConstructor { type_: type_::list(type_::int()), publicity: Publicity::Public, + opaque: false, origin: Default::default(), module: "the/module".into(), parameters: vec![], @@ -210,6 +212,7 @@ fn module_with_fn_type() { TypeConstructor { type_: type_::fn_(vec![type_::nil(), type_::float()], type_::int()), publicity: Publicity::Public, + opaque: false, origin: Default::default(), module: "the/module".into(), parameters: vec![], @@ -243,6 +246,7 @@ fn module_with_tuple_type() { TypeConstructor { type_: type_::tuple(vec![type_::nil(), type_::float(), type_::int()]), publicity: Publicity::Public, + opaque: false, origin: Default::default(), module: "the/module".into(), parameters: vec![], @@ -282,6 +286,7 @@ fn module_with_generic_type() { TypeConstructor { type_: type_::tuple(vec![t1.clone(), t1.clone(), t2.clone()]), publicity: Publicity::Public, + opaque: false, origin: Default::default(), module: "the/module".into(), parameters: vec![t1, t2], @@ -321,6 +326,7 @@ fn module_with_type_links() { TypeConstructor { type_, publicity: Publicity::Public, + opaque: false, origin: Default::default(), module: "a".into(), parameters: vec![], @@ -360,6 +366,7 @@ fn module_with_type_constructor_documentation() { TypeConstructor { type_, publicity: Publicity::Public, + opaque: false, origin: Default::default(), module: "a".into(), parameters: vec![], @@ -399,6 +406,7 @@ fn module_with_type_constructor_origin() { TypeConstructor { type_, publicity: Publicity::Public, + opaque: false, origin: SrcSpan { start: 535, end: 543, @@ -1251,6 +1259,7 @@ fn deprecated_type() { TypeConstructor { type_: type_::list(type_::int()), publicity: Publicity::Public, + opaque: false, origin: Default::default(), module: "the/module".into(), parameters: vec![], diff --git a/compiler-core/src/package_interface.rs b/compiler-core/src/package_interface.rs index 093a5f40597..38415fa4f08 100644 --- a/compiler-core/src/package_interface.rs +++ b/compiler-core/src/package_interface.rs @@ -375,20 +375,15 @@ impl PackageInterface { modules: package .modules .iter() + .map(|module| &module.ast.type_info) + .chain(package.cached_modules.iter()) .filter(|module| !package.config.is_internal_module(module.name.as_str())) - .map(|module| (module.name.clone(), ModuleInterface::from_module(module))) - .chain( - package - .cached_modules - .iter() - .filter(|module| !package.config.is_internal_module(module.name.as_str())) - .map(|interface| { - ( - interface.name.clone(), - ModuleInterface::from_untyped_module(interface), - ) - }), - ) + .map(|interface| { + ( + interface.name.clone(), + ModuleInterface::from_module_interface(interface), + ) + }) // .map(|(name, info)| debug_module(name, info)) .collect(), } @@ -439,187 +434,187 @@ impl PackageInterface { // } impl ModuleInterface { - fn from_module(module: &Module) -> ModuleInterface { - let mut types = HashMap::new(); - let mut type_aliases = HashMap::new(); - let mut constants = HashMap::new(); - let mut functions = HashMap::new(); - for statement in &module.ast.definitions { - match statement { - // A public type definition. - Definition::CustomType(CustomType { - publicity: Publicity::Public, - name, - constructors, - documentation, - opaque, - deprecation, - typed_parameters, - parameters: _, - location: _, - name_location: _, - end_position: _, - }) => { - let mut id_map = IdMap::new(); - - // Let's first add all the types that appear in the type parameters so those are - // taken into account when assigning incremental numbers to the constructor's - // type variables. - for typed_parameter in typed_parameters { - id_map.add_type_variable_id(typed_parameter.as_ref()); - } - - let _ = types.insert( - name.clone(), - TypeDefinitionInterface { - documentation: documentation.as_ref().map(|(_, doc)| doc.clone()), - deprecation: DeprecationInterface::from_deprecation(deprecation), - parameters: typed_parameters.len(), - constructors: if *opaque { - vec![] - } else { - constructors - .iter() - .map(|constructor| TypeConstructorInterface { - documentation: constructor - .documentation - .as_ref() - .map(|(_, doc)| doc.clone()), - name: constructor.name.clone(), - parameters: constructor - .arguments - .iter() - .map(|arg| ParameterInterface { - label: arg - .label - .as_ref() - .map(|(_, label)| label.clone()), - // We share the same id_map between each step so that the - // incremental ids assigned are consisten with each other - type_: from_type_helper(&arg.type_, &mut id_map), - }) - .collect_vec(), - }) - .collect() - }, - }, - ); - } - - // A public type alias definition - Definition::TypeAlias(TypeAlias { - publicity: Publicity::Public, - alias, - parameters, - type_, - documentation, - deprecation, - location: _, - name_location: _, - type_ast: _, - }) => { - let _ = type_aliases.insert( - alias.clone(), - TypeAliasInterface { - documentation: documentation.as_ref().map(|(_, doc)| doc.clone()), - deprecation: DeprecationInterface::from_deprecation(deprecation), - parameters: parameters.len(), - alias: TypeInterface::from_type(type_.as_ref()), - }, - ); - } - - // A public module constant. - Definition::ModuleConstant(ModuleConstant { - publicity: Publicity::Public, - name, - type_, - documentation, - implementations, - deprecation, - location: _, - name_location: _, - annotation: _, - value: _, - }) => { - let _ = constants.insert( - name.clone(), - ConstantInterface { - implementations: ImplementationsInterface::from_implementations( - implementations, - ), - type_: TypeInterface::from_type(type_.as_ref()), - deprecation: DeprecationInterface::from_deprecation(deprecation), - documentation: documentation.as_ref().map(|(_, doc)| doc.clone()), - }, - ); - } - - // A public top-level function. - Definition::Function(Function { - publicity: Publicity::Public, - name, - arguments, - deprecation, - return_type, - documentation, - implementations, - location: _, - end_position: _, - body: _, - return_annotation: _, - external_erlang: _, - external_javascript: _, - }) => { - let mut id_map = IdMap::new(); - let (_, name) = name - .as_ref() - .expect("Function in a definition must be named"); - let _ = functions.insert( - name.clone(), - FunctionInterface { - implementations: ImplementationsInterface::from_implementations( - implementations, - ), - deprecation: DeprecationInterface::from_deprecation(deprecation), - documentation: documentation.as_ref().map(|(_, doc)| doc.clone()), - parameters: arguments - .iter() - .map(|arg| ParameterInterface { - label: arg.names.get_label().cloned(), - type_: from_type_helper(arg.type_.as_ref(), &mut id_map), - }) - .collect(), - return_: from_type_helper(return_type, &mut id_map), - }, - ); - } - - // Private or internal definitions are not included. - Definition::Function(_) => {} - Definition::CustomType(_) => {} - Definition::ModuleConstant(_) => {} - Definition::TypeAlias(_) => {} - - // Imports are ignored. - Definition::Import(_) => {} - } - } - - ModuleInterface { - documentation: module.ast.documentation.clone(), - types, - type_aliases, - constants, - functions, - } - } - - pub fn from_untyped_module(interface: &type_::ModuleInterface) -> ModuleInterface { - println!( - "Module {} has following types {:#?}, following type constructors {:#?} and following accessors {:#?}", - interface.name, interface.types, interface.types_value_constructors, interface.accessors - ); + // fn from_module(module: &Module) -> ModuleInterface { + // let mut types = HashMap::new(); + // let mut type_aliases = HashMap::new(); + // let mut constants = HashMap::new(); + // let mut functions = HashMap::new(); + // for statement in &module.ast.definitions { + // match statement { + // // A public type definition. + // Definition::CustomType(CustomType { + // publicity: Publicity::Public, + // name, + // constructors, + // documentation, + // opaque, + // deprecation, + // typed_parameters, + // parameters: _, + // location: _, + // name_location: _, + // end_position: _, + // }) => { + // let mut id_map = IdMap::new(); + + // // Let's first add all the types that appear in the type parameters so those are + // // taken into account when assigning incremental numbers to the constructor's + // // type variables. + // for typed_parameter in typed_parameters { + // id_map.add_type_variable_id(typed_parameter.as_ref()); + // } + + // let _ = types.insert( + // name.clone(), + // TypeDefinitionInterface { + // documentation: documentation.as_ref().map(|(_, doc)| doc.clone()), + // deprecation: DeprecationInterface::from_deprecation(deprecation), + // parameters: typed_parameters.len(), + // constructors: if *opaque { + // vec![] + // } else { + // constructors + // .iter() + // .map(|constructor| TypeConstructorInterface { + // documentation: constructor + // .documentation + // .as_ref() + // .map(|(_, doc)| doc.clone()), + // name: constructor.name.clone(), + // parameters: constructor + // .arguments + // .iter() + // .map(|arg| ParameterInterface { + // label: arg + // .label + // .as_ref() + // .map(|(_, label)| label.clone()), + // // We share the same id_map between each step so that the + // // incremental ids assigned are consisten with each other + // type_: from_type_helper(&arg.type_, &mut id_map), + // }) + // .collect_vec(), + // }) + // .collect() + // }, + // }, + // ); + // } + + // // A public type alias definition + // Definition::TypeAlias(TypeAlias { + // publicity: Publicity::Public, + // alias, + // parameters, + // type_, + // documentation, + // deprecation, + // location: _, + // name_location: _, + // type_ast: _, + // }) => { + // let _ = type_aliases.insert( + // alias.clone(), + // TypeAliasInterface { + // documentation: documentation.as_ref().map(|(_, doc)| doc.clone()), + // deprecation: DeprecationInterface::from_deprecation(deprecation), + // parameters: parameters.len(), + // alias: TypeInterface::from_type(type_.as_ref()), + // }, + // ); + // } + + // // A public module constant. + // Definition::ModuleConstant(ModuleConstant { + // publicity: Publicity::Public, + // name, + // type_, + // documentation, + // implementations, + // deprecation, + // location: _, + // name_location: _, + // annotation: _, + // value: _, + // }) => { + // let _ = constants.insert( + // name.clone(), + // ConstantInterface { + // implementations: ImplementationsInterface::from_implementations( + // implementations, + // ), + // type_: TypeInterface::from_type(type_.as_ref()), + // deprecation: DeprecationInterface::from_deprecation(deprecation), + // documentation: documentation.as_ref().map(|(_, doc)| doc.clone()), + // }, + // ); + // } + + // // A public top-level function. + // Definition::Function(Function { + // publicity: Publicity::Public, + // name, + // arguments, + // deprecation, + // return_type, + // documentation, + // implementations, + // location: _, + // end_position: _, + // body: _, + // return_annotation: _, + // external_erlang: _, + // external_javascript: _, + // }) => { + // let mut id_map = IdMap::new(); + // let (_, name) = name + // .as_ref() + // .expect("Function in a definition must be named"); + // let _ = functions.insert( + // name.clone(), + // FunctionInterface { + // implementations: ImplementationsInterface::from_implementations( + // implementations, + // ), + // deprecation: DeprecationInterface::from_deprecation(deprecation), + // documentation: documentation.as_ref().map(|(_, doc)| doc.clone()), + // parameters: arguments + // .iter() + // .map(|arg| ParameterInterface { + // label: arg.names.get_label().cloned(), + // type_: from_type_helper(arg.type_.as_ref(), &mut id_map), + // }) + // .collect(), + // return_: from_type_helper(return_type, &mut id_map), + // }, + // ); + // } + + // // Private or internal definitions are not included. + // Definition::Function(_) => {} + // Definition::CustomType(_) => {} + // Definition::ModuleConstant(_) => {} + // Definition::TypeAlias(_) => {} + + // // Imports are ignored. + // Definition::Import(_) => {} + // } + // } + + // ModuleInterface { + // documentation: module.ast.documentation.clone(), + // types, + // type_aliases, + // constants, + // functions, + // } + // } + + pub fn from_module_interface(interface: &type_::ModuleInterface) -> ModuleInterface { + // println!( + // "Module {} has following types {:#?}, following type constructors {:#?} and following accessors {:#?}", + // interface.name, interface.types, interface.types_value_constructors, interface.accessors + // ); let mut types = HashMap::new(); let mut type_aliases = HashMap::new(); let mut constants = HashMap::new(); @@ -651,28 +646,34 @@ impl ModuleInterface { .get(&name.clone()) .map_or(vec![], |t| t.parameters.clone()) .len(), - constructors: match interface.types_value_constructors.get(&name.clone()) { - Some(constructors) => constructors - .variants - .iter() - .map(|constructor| TypeConstructorInterface { - // TODO: Find documentation - documentation: None, - name: constructor.name.clone(), - parameters: constructor - .parameters - .iter() - .map(|arg| ParameterInterface { - label: arg.label.clone(), - // label: None, - // We share the same id_map between each step so that the - // incremental ids assigned are consisten with each other - type_: from_type_helper(arg.type_.as_ref(), &mut id_map), - }) - .collect(), - }) - .collect(), - None => vec![], + constructors: if constructor.opaque { + vec![] + } else { + match interface.types_value_constructors.get(&name.clone()) { + Some(constructors) => constructors + .variants + .iter() + .map(|constructor| TypeConstructorInterface { + // TODO: Find documentation + documentation: None, + name: constructor.name.clone(), + parameters: constructor + .parameters + .iter() + .map(|arg| ParameterInterface { + label: arg.label.clone(), + // We share the same id_map between each step so that the + // incremental ids assigned are consisten with each other + type_: from_type_helper( + arg.type_.as_ref(), + &mut id_map, + ), + }) + .collect(), + }) + .collect(), + None => vec![], + } }, }, ); diff --git a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_definition.snap b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_definition.snap index dc114d48457..cacf1cc9868 100644 --- a/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_definition.snap +++ b/compiler-core/src/package_interface/snapshots/gleam_core__package_interface__tests__type_definition.snap @@ -12,7 +12,7 @@ expression: "\n/// Wibble's documentation\npub type Wibble(a, b) {\n Wibble\n "type-aliases": {}, "types": { "Wibble": { - "documentation": " Wibble's documentation", + "documentation": " Wibble's documentation\n", "deprecation": null, "parameters": 2, "constructors": [ diff --git a/compiler-core/src/package_interface/tests.rs b/compiler-core/src/package_interface/tests.rs index 19d00315976..54e57d0868c 100644 --- a/compiler-core/src/package_interface/tests.rs +++ b/compiler-core/src/package_interface/tests.rs @@ -133,6 +133,7 @@ pub fn compile_package( extra: parsed.extra, dependencies: vec![], }; + module.ast.type_info.remove_duplicated_type_aliases(); module.attach_doc_and_module_comments(); let package: Package = package_from_module(module); serde_json::to_string_pretty(&PackageInterface::from_package(&package)).expect("to json") diff --git a/compiler-core/src/type_.rs b/compiler-core/src/type_.rs index e24329caa1f..9a626ea55d1 100644 --- a/compiler-core/src/type_.rs +++ b/compiler-core/src/type_.rs @@ -643,6 +643,11 @@ impl ModuleInterface { pub fn contains_todo(&self) -> bool { self.warnings.iter().any(|warning| warning.is_todo()) } + + pub fn remove_duplicated_type_aliases(&mut self) { + self.types + .retain(|name, _| !self.type_aliases.contains_key(name)); + } } /// Information on the constructors of a custom type. @@ -918,6 +923,7 @@ impl TypeVar { #[derive(Debug, Clone, PartialEq, Eq)] pub struct TypeConstructor { pub publicity: Publicity, + pub opaque: bool, pub origin: SrcSpan, pub module: EcoString, pub parameters: Vec>, diff --git a/compiler-core/src/type_/prelude.rs b/compiler-core/src/type_/prelude.rs index 50c04394724..d46e49ae565 100644 --- a/compiler-core/src/type_/prelude.rs +++ b/compiler-core/src/type_/prelude.rs @@ -230,6 +230,7 @@ pub fn build_prelude(ids: &UniqueIdGenerator) -> ModuleInterface { type_: bits(), module: PRELUDE_MODULE_NAME.into(), publicity: Publicity::Public, + opaque: false, deprecation: NotDeprecated, documentation: None, }; @@ -293,6 +294,7 @@ pub fn build_prelude(ids: &UniqueIdGenerator) -> ModuleInterface { type_: bool(), module: PRELUDE_MODULE_NAME.into(), publicity: Publicity::Public, + opaque: false, deprecation: NotDeprecated, documentation: None, }, @@ -308,6 +310,7 @@ pub fn build_prelude(ids: &UniqueIdGenerator) -> ModuleInterface { type_: float(), module: PRELUDE_MODULE_NAME.into(), publicity: Publicity::Public, + opaque: false, deprecation: NotDeprecated, documentation: None, }, @@ -323,6 +326,7 @@ pub fn build_prelude(ids: &UniqueIdGenerator) -> ModuleInterface { origin: Default::default(), module: PRELUDE_MODULE_NAME.into(), publicity: Publicity::Public, + opaque: false, deprecation: NotDeprecated, documentation: None, }, @@ -339,6 +343,7 @@ pub fn build_prelude(ids: &UniqueIdGenerator) -> ModuleInterface { type_: list(list_parameter), module: PRELUDE_MODULE_NAME.into(), publicity: Publicity::Public, + opaque: false, deprecation: NotDeprecated, documentation: None, }, @@ -370,6 +375,7 @@ pub fn build_prelude(ids: &UniqueIdGenerator) -> ModuleInterface { type_: nil(), module: PRELUDE_MODULE_NAME.into(), publicity: Publicity::Public, + opaque: false, deprecation: NotDeprecated, documentation: None, }, @@ -399,6 +405,7 @@ pub fn build_prelude(ids: &UniqueIdGenerator) -> ModuleInterface { type_: result(result_value.clone(), result_error.clone()), module: PRELUDE_MODULE_NAME.into(), publicity: Publicity::Public, + opaque: false, deprecation: NotDeprecated, documentation: None, }, @@ -472,6 +479,7 @@ pub fn build_prelude(ids: &UniqueIdGenerator) -> ModuleInterface { type_: string(), module: PRELUDE_MODULE_NAME.into(), publicity: Publicity::Public, + opaque: false, deprecation: NotDeprecated, documentation: None, }, @@ -487,6 +495,7 @@ pub fn build_prelude(ids: &UniqueIdGenerator) -> ModuleInterface { type_: utf_codepoint(), module: PRELUDE_MODULE_NAME.into(), publicity: Publicity::Public, + opaque: false, deprecation: NotDeprecated, documentation: None, }, From 652e9cbfad141f1acc87423a7b33ee4b77dbf180 Mon Sep 17 00:00:00 2001 From: Pedro H C Francisco <75535904+mine-tech-oficial@users.noreply.github.com> Date: Mon, 21 Oct 2024 20:15:50 -0300 Subject: [PATCH 09/12] Removed unnecessary build step (capnp) --- compiler-core/build.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/compiler-core/build.rs b/compiler-core/build.rs index cb2bf0f2c21..6f3fb7ce04f 100644 --- a/compiler-core/build.rs +++ b/compiler-core/build.rs @@ -1,7 +1,7 @@ fn main() { - capnpc::CompilerCommand::new() - .file("schema.capnp") - .output_path("generated/") - .run() - .expect("compiling schema.capnp"); + // capnpc::CompilerCommand::new() + // .file("schema.capnp") + // .output_path("generated/") + // .run() + // .expect("compiling schema.capnp"); } From ce4c6570c04107e9e56010c23cdda5a5bbd50700 Mon Sep 17 00:00:00 2001 From: Pedro H C Francisco <75535904+mine-tech-oficial@users.noreply.github.com> Date: Mon, 21 Oct 2024 20:23:55 -0300 Subject: [PATCH 10/12] Removed debug leftovers --- compiler-core/src/analyse.rs | 5 - compiler-core/src/build.rs | 5 - compiler-core/src/build/package_loader.rs | 6 - compiler-core/src/docs.rs | 1 - compiler-core/src/metadata/module_encoder.rs | 22 +- compiler-core/src/package_interface.rs | 228 +------------------ 6 files changed, 3 insertions(+), 264 deletions(-) diff --git a/compiler-core/src/analyse.rs b/compiler-core/src/analyse.rs index 4256d358bbe..1a31e46d014 100644 --- a/compiler-core/src/analyse.rs +++ b/compiler-core/src/analyse.rs @@ -318,11 +318,6 @@ impl<'a, A> ModuleAnalyzer<'a, A> { self.warnings.emit(warning.clone()); } - // println!( - // "Generated module {} has documentation size {}", - // self.module_name, - // documentation.len() - // ); let module = ast::Module { documentation: documentation.clone(), name: self.module_name.clone(), diff --git a/compiler-core/src/build.rs b/compiler-core/src/build.rs index 5e6225da4af..5136dcd88ff 100644 --- a/compiler-core/src/build.rs +++ b/compiler-core/src/build.rs @@ -264,11 +264,6 @@ impl Module { .collect(); self.ast.type_info.documentation = self.ast.documentation.clone(); - // println!( - // "Module {} has documentation of length {}", - // self.name, - // self.ast.documentation.len() - // ); // Order statements to avoid misassociating doc comments after the // order has changed during compilation. diff --git a/compiler-core/src/build/package_loader.rs b/compiler-core/src/build/package_loader.rs index 15063479fe2..77259cac29f 100644 --- a/compiler-core/src/build/package_loader.rs +++ b/compiler-core/src/build/package_loader.rs @@ -175,12 +175,6 @@ where let bytes = self.io.read_bytes(&path)?; let mut module = metadata::ModuleDecoder::new(self.ids.clone()).read(bytes.as_slice())?; - // println!( - // "Loaded cached module {} has {} types", - // module.name, - // module.types.len() - // ); - // Load warnings if self.cached_warnings.should_use() { let path = dir.join(name.as_ref()).with_extension("cache_warnings"); diff --git a/compiler-core/src/docs.rs b/compiler-core/src/docs.rs index b53e1f9921a..f689ea33eff 100644 --- a/compiler-core/src/docs.rs +++ b/compiler-core/src/docs.rs @@ -447,7 +447,6 @@ pub fn generate_html( } pub fn generate_json_package_interface(path: Utf8PathBuf, package: &Package) -> OutputFile { - // println!("Generating Package Interface"); OutputFile { path, content: Content::Text( diff --git a/compiler-core/src/metadata/module_encoder.rs b/compiler-core/src/metadata/module_encoder.rs index d4dd36f7b94..5e1283269cb 100644 --- a/compiler-core/src/metadata/module_encoder.rs +++ b/compiler-core/src/metadata/module_encoder.rs @@ -39,12 +39,6 @@ impl<'a> ModuleEncoder<'a> { let mut module = message.init_root::>(); - // println!("Encoding module {}", self.data.name); - // println!( - // "Module {} has documentation size {}", - // self.data.name, - // self.data.documentation.len() - // ); module.set_name(&self.data.name); module.set_package(&self.data.package); module.set_src_path(self.data.src_path.as_str()); @@ -144,21 +138,7 @@ impl<'a> ModuleEncoder<'a> { let mut type_aliases = module .reborrow() .init_type_aliases(self.data.type_aliases.len() as u32); - for (i, (name, data)) in self - .data - .type_aliases - .iter() - // .map(|(type_alias_name, type_alias)| { - // println!( - // "Type Alias {}/{} has documentation {}", - // self.data.name, - // type_alias_name, - // type_alias.documentation.clone().unwrap_or_default().len(), - // ); - // (type_alias_name, type_alias) - // }) - .enumerate() - { + for (i, (name, data)) in self.data.type_aliases.iter().enumerate() { let mut property = type_aliases.reborrow().get(i as u32); property.set_key(name); self.build_type_aliases(property.init_value(), data) diff --git a/compiler-core/src/package_interface.rs b/compiler-core/src/package_interface.rs index 38415fa4f08..a6980c10907 100644 --- a/compiler-core/src/package_interface.rs +++ b/compiler-core/src/package_interface.rs @@ -381,240 +381,16 @@ impl PackageInterface { .map(|interface| { ( interface.name.clone(), - ModuleInterface::from_module_interface(interface), + ModuleInterface::from_interface(interface), ) }) - // .map(|(name, info)| debug_module(name, info)) .collect(), } } } -// pub fn debug_module(name: EcoString, info: ModuleInterface) -> (EcoString, ModuleInterface) { -// println!( -// "Module {} has documentation size {}", -// name, -// info.documentation.iter().map(|s| s.len()).sum::() -// ); -// info.types.iter().for_each(|(type_name, type_)| { -// println!( -// "Type {}/{} has documentation {}", -// name, -// type_name, -// type_.documentation.clone().unwrap_or_default().len(), -// ) -// }); -// info.type_aliases -// .iter() -// .for_each(|(type_alias_name, type_alias)| { -// println!( -// "Type Alias {}/{} has documentation {}", -// name, -// type_alias_name, -// type_alias.documentation.clone().unwrap_or_default().len(), -// ) -// }); -// info.constants.iter().for_each(|(constant_name, constant)| { -// println!( -// "Constant {}/{} has documentation {}", -// name, -// constant_name, -// constant.documentation.clone().unwrap_or_default().len(), -// ) -// }); -// info.functions.iter().for_each(|(function_name, function)| { -// println!( -// "Function {}/{} has documentation {}", -// name, -// function_name, -// function.documentation.clone().unwrap_or_default().len(), -// ) -// }); -// (name, info) -// } - impl ModuleInterface { - // fn from_module(module: &Module) -> ModuleInterface { - // let mut types = HashMap::new(); - // let mut type_aliases = HashMap::new(); - // let mut constants = HashMap::new(); - // let mut functions = HashMap::new(); - // for statement in &module.ast.definitions { - // match statement { - // // A public type definition. - // Definition::CustomType(CustomType { - // publicity: Publicity::Public, - // name, - // constructors, - // documentation, - // opaque, - // deprecation, - // typed_parameters, - // parameters: _, - // location: _, - // name_location: _, - // end_position: _, - // }) => { - // let mut id_map = IdMap::new(); - - // // Let's first add all the types that appear in the type parameters so those are - // // taken into account when assigning incremental numbers to the constructor's - // // type variables. - // for typed_parameter in typed_parameters { - // id_map.add_type_variable_id(typed_parameter.as_ref()); - // } - - // let _ = types.insert( - // name.clone(), - // TypeDefinitionInterface { - // documentation: documentation.as_ref().map(|(_, doc)| doc.clone()), - // deprecation: DeprecationInterface::from_deprecation(deprecation), - // parameters: typed_parameters.len(), - // constructors: if *opaque { - // vec![] - // } else { - // constructors - // .iter() - // .map(|constructor| TypeConstructorInterface { - // documentation: constructor - // .documentation - // .as_ref() - // .map(|(_, doc)| doc.clone()), - // name: constructor.name.clone(), - // parameters: constructor - // .arguments - // .iter() - // .map(|arg| ParameterInterface { - // label: arg - // .label - // .as_ref() - // .map(|(_, label)| label.clone()), - // // We share the same id_map between each step so that the - // // incremental ids assigned are consisten with each other - // type_: from_type_helper(&arg.type_, &mut id_map), - // }) - // .collect_vec(), - // }) - // .collect() - // }, - // }, - // ); - // } - - // // A public type alias definition - // Definition::TypeAlias(TypeAlias { - // publicity: Publicity::Public, - // alias, - // parameters, - // type_, - // documentation, - // deprecation, - // location: _, - // name_location: _, - // type_ast: _, - // }) => { - // let _ = type_aliases.insert( - // alias.clone(), - // TypeAliasInterface { - // documentation: documentation.as_ref().map(|(_, doc)| doc.clone()), - // deprecation: DeprecationInterface::from_deprecation(deprecation), - // parameters: parameters.len(), - // alias: TypeInterface::from_type(type_.as_ref()), - // }, - // ); - // } - - // // A public module constant. - // Definition::ModuleConstant(ModuleConstant { - // publicity: Publicity::Public, - // name, - // type_, - // documentation, - // implementations, - // deprecation, - // location: _, - // name_location: _, - // annotation: _, - // value: _, - // }) => { - // let _ = constants.insert( - // name.clone(), - // ConstantInterface { - // implementations: ImplementationsInterface::from_implementations( - // implementations, - // ), - // type_: TypeInterface::from_type(type_.as_ref()), - // deprecation: DeprecationInterface::from_deprecation(deprecation), - // documentation: documentation.as_ref().map(|(_, doc)| doc.clone()), - // }, - // ); - // } - - // // A public top-level function. - // Definition::Function(Function { - // publicity: Publicity::Public, - // name, - // arguments, - // deprecation, - // return_type, - // documentation, - // implementations, - // location: _, - // end_position: _, - // body: _, - // return_annotation: _, - // external_erlang: _, - // external_javascript: _, - // }) => { - // let mut id_map = IdMap::new(); - // let (_, name) = name - // .as_ref() - // .expect("Function in a definition must be named"); - // let _ = functions.insert( - // name.clone(), - // FunctionInterface { - // implementations: ImplementationsInterface::from_implementations( - // implementations, - // ), - // deprecation: DeprecationInterface::from_deprecation(deprecation), - // documentation: documentation.as_ref().map(|(_, doc)| doc.clone()), - // parameters: arguments - // .iter() - // .map(|arg| ParameterInterface { - // label: arg.names.get_label().cloned(), - // type_: from_type_helper(arg.type_.as_ref(), &mut id_map), - // }) - // .collect(), - // return_: from_type_helper(return_type, &mut id_map), - // }, - // ); - // } - - // // Private or internal definitions are not included. - // Definition::Function(_) => {} - // Definition::CustomType(_) => {} - // Definition::ModuleConstant(_) => {} - // Definition::TypeAlias(_) => {} - - // // Imports are ignored. - // Definition::Import(_) => {} - // } - // } - - // ModuleInterface { - // documentation: module.ast.documentation.clone(), - // types, - // type_aliases, - // constants, - // functions, - // } - // } - - pub fn from_module_interface(interface: &type_::ModuleInterface) -> ModuleInterface { - // println!( - // "Module {} has following types {:#?}, following type constructors {:#?} and following accessors {:#?}", - // interface.name, interface.types, interface.types_value_constructors, interface.accessors - // ); + pub fn from_interface(interface: &type_::ModuleInterface) -> ModuleInterface { let mut types = HashMap::new(); let mut type_aliases = HashMap::new(); let mut constants = HashMap::new(); From 71f7037842ad76d9a390aeb9a78ba0dbc88a4441 Mon Sep 17 00:00:00 2001 From: Pedro H C Francisco <75535904+mine-tech-oficial@users.noreply.github.com> Date: Fri, 15 Nov 2024 13:43:20 -0300 Subject: [PATCH 11/12] Removed unnecessary trait and reverted a parameter type change --- compiler-core/src/build.rs | 2 +- compiler-core/src/build/package_compiler.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/compiler-core/src/build.rs b/compiler-core/src/build.rs index 5136dcd88ff..8d1df5d3f4c 100644 --- a/compiler-core/src/build.rs +++ b/compiler-core/src/build.rs @@ -227,7 +227,7 @@ impl Package { } } -#[derive(Debug, Clone)] +#[derive(Debug)] pub struct Module { pub name: EcoString, pub code: EcoString, diff --git a/compiler-core/src/build/package_compiler.rs b/compiler-core/src/build/package_compiler.rs index 8bacc408687..8c682177889 100644 --- a/compiler-core/src/build/package_compiler.rs +++ b/compiler-core/src/build/package_compiler.rs @@ -302,7 +302,7 @@ where Ok(()) } - fn encode_and_write_metadata(&mut self, modules: &Vec) -> Result<()> { + fn encode_and_write_metadata(&mut self, modules: &[Module]) -> Result<()> { if !self.write_metadata { tracing::debug!("package_metadata_writing_disabled"); return Ok(()); From 3923c17e146d703e400b821c8960f8eda7659017 Mon Sep 17 00:00:00 2001 From: Pedro H C Francisco <75535904+mine-tech-oficial@users.noreply.github.com> Date: Sun, 15 Dec 2024 09:57:32 -0300 Subject: [PATCH 12/12] Made a way to find the label of the argument in the package export --- compiler-core/generated/schema_capnp.rs | 172 ++++++++++++++++++- compiler-core/schema.capnp | 7 +- compiler-core/src/analyse.rs | 31 +++- compiler-core/src/ast/tests.rs | 18 +- compiler-core/src/erlang.rs | 10 +- compiler-core/src/exhaustiveness.rs | 12 +- compiler-core/src/javascript/typescript.rs | 20 ++- compiler-core/src/language_server/engine.rs | 9 +- compiler-core/src/metadata/module_decoder.rs | 11 +- compiler-core/src/metadata/module_encoder.rs | 31 +++- compiler-core/src/metadata/tests.rs | 20 ++- compiler-core/src/package_interface.rs | 17 +- compiler-core/src/type_.rs | 43 ++++- compiler-core/src/type_/environment.rs | 28 ++- compiler-core/src/type_/expression.rs | 14 +- compiler-core/src/type_/hydrator.rs | 7 +- compiler-core/src/type_/pattern.rs | 2 +- compiler-core/src/type_/pipe.rs | 10 +- compiler-core/src/type_/prelude.rs | 23 ++- compiler-core/src/type_/pretty.rs | 107 +++++++++--- compiler-core/src/type_/printer.rs | 55 ++++-- 21 files changed, 536 insertions(+), 111 deletions(-) diff --git a/compiler-core/generated/schema_capnp.rs b/compiler-core/generated/schema_capnp.rs index 245a1be0eca..898911d45b0 100644 --- a/compiler-core/generated/schema_capnp.rs +++ b/compiler-core/generated/schema_capnp.rs @@ -2325,6 +2325,170 @@ pub mod record_accessor { } } +pub mod function_argument { + #[derive(Copy, Clone)] + pub struct Owned(()); + impl <'a> ::capnp::traits::Owned<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } + impl <'a> ::capnp::traits::OwnedStruct<'a> for Owned { type Reader = Reader<'a>; type Builder = Builder<'a>; } + impl ::capnp::traits::Pipelined for Owned { type Pipeline = Pipeline; } + + #[derive(Clone, Copy)] + pub struct Reader<'a> { reader: ::capnp::private::layout::StructReader<'a> } + + impl <'a,> ::capnp::traits::HasTypeId for Reader<'a,> { + #[inline] + fn type_id() -> u64 { _private::TYPE_ID } + } + impl <'a,> ::capnp::traits::FromStructReader<'a> for Reader<'a,> { + fn new(reader: ::capnp::private::layout::StructReader<'a>) -> Reader<'a,> { + Reader { reader, } + } + } + + impl <'a,> ::capnp::traits::FromPointerReader<'a> for Reader<'a,> { + fn get_from_pointer(reader: &::capnp::private::layout::PointerReader<'a>, default: ::core::option::Option<&'a [capnp::Word]>) -> ::capnp::Result> { + ::core::result::Result::Ok(::capnp::traits::FromStructReader::new(reader.get_struct(default)?)) + } + } + + impl <'a,> ::capnp::traits::IntoInternalStructReader<'a> for Reader<'a,> { + fn into_internal_struct_reader(self) -> ::capnp::private::layout::StructReader<'a> { + self.reader + } + } + + impl <'a,> ::capnp::traits::Imbue<'a> for Reader<'a,> { + fn imbue(&mut self, cap_table: &'a ::capnp::private::layout::CapTable) { + self.reader.imbue(::capnp::private::layout::CapTableReader::Plain(cap_table)) + } + } + + impl <'a,> Reader<'a,> { + pub fn reborrow(&self) -> Reader<'_,> { + Reader { .. *self } + } + + pub fn total_size(&self) -> ::capnp::Result<::capnp::MessageSize> { + self.reader.total_size() + } + #[inline] + pub fn get_name(self) -> ::capnp::Result<::capnp::text::Reader<'a>> { + ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(0), ::core::option::Option::None) + } + #[inline] + pub fn has_name(&self) -> bool { + !self.reader.get_pointer_field(0).is_null() + } + #[inline] + pub fn get_type(self) -> ::capnp::Result> { + ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(1), ::core::option::Option::None) + } + #[inline] + pub fn has_type(&self) -> bool { + !self.reader.get_pointer_field(1).is_null() + } + } + + pub struct Builder<'a> { builder: ::capnp::private::layout::StructBuilder<'a> } + impl <'a,> ::capnp::traits::HasStructSize for Builder<'a,> { + #[inline] + fn struct_size() -> ::capnp::private::layout::StructSize { _private::STRUCT_SIZE } + } + impl <'a,> ::capnp::traits::HasTypeId for Builder<'a,> { + #[inline] + fn type_id() -> u64 { _private::TYPE_ID } + } + impl <'a,> ::capnp::traits::FromStructBuilder<'a> for Builder<'a,> { + fn new(builder: ::capnp::private::layout::StructBuilder<'a>) -> Builder<'a, > { + Builder { builder, } + } + } + + impl <'a,> ::capnp::traits::ImbueMut<'a> for Builder<'a,> { + fn imbue_mut(&mut self, cap_table: &'a mut ::capnp::private::layout::CapTable) { + self.builder.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table)) + } + } + + impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> { + fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size: u32) -> Builder<'a,> { + ::capnp::traits::FromStructBuilder::new(builder.init_struct(_private::STRUCT_SIZE)) + } + fn get_from_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, default: ::core::option::Option<&'a [capnp::Word]>) -> ::capnp::Result> { + ::core::result::Result::Ok(::capnp::traits::FromStructBuilder::new(builder.get_struct(_private::STRUCT_SIZE, default)?)) + } + } + + impl <'a,> ::capnp::traits::SetPointerBuilder for Reader<'a,> { + fn set_pointer_builder<'b>(pointer: ::capnp::private::layout::PointerBuilder<'b>, value: Reader<'a,>, canonicalize: bool) -> ::capnp::Result<()> { pointer.set_struct(&value.reader, canonicalize) } + } + + impl <'a,> Builder<'a,> { + pub fn into_reader(self) -> Reader<'a,> { + ::capnp::traits::FromStructReader::new(self.builder.into_reader()) + } + pub fn reborrow(&mut self) -> Builder<'_,> { + Builder { .. *self } + } + pub fn reborrow_as_reader(&self) -> Reader<'_,> { + ::capnp::traits::FromStructReader::new(self.builder.into_reader()) + } + + pub fn total_size(&self) -> ::capnp::Result<::capnp::MessageSize> { + self.builder.into_reader().total_size() + } + #[inline] + pub fn get_name(self) -> ::capnp::Result<::capnp::text::Builder<'a>> { + ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(0), ::core::option::Option::None) + } + #[inline] + pub fn set_name(&mut self, value: ::capnp::text::Reader<'_>) { + self.builder.get_pointer_field(0).set_text(value); + } + #[inline] + pub fn init_name(self, size: u32) -> ::capnp::text::Builder<'a> { + self.builder.get_pointer_field(0).init_text(size) + } + #[inline] + pub fn has_name(&self) -> bool { + !self.builder.get_pointer_field(0).is_null() + } + #[inline] + pub fn get_type(self) -> ::capnp::Result> { + ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(1), ::core::option::Option::None) + } + #[inline] + pub fn set_type(&mut self, value: crate::schema_capnp::type_::Reader<'_>) -> ::capnp::Result<()> { + ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(1), value, false) + } + #[inline] + pub fn init_type(self, ) -> crate::schema_capnp::type_::Builder<'a> { + ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(1), 0) + } + #[inline] + pub fn has_type(&self) -> bool { + !self.builder.get_pointer_field(1).is_null() + } + } + + pub struct Pipeline { _typeless: ::capnp::any_pointer::Pipeline } + impl ::capnp::capability::FromTypelessPipeline for Pipeline { + fn new(typeless: ::capnp::any_pointer::Pipeline) -> Pipeline { + Pipeline { _typeless: typeless, } + } + } + impl Pipeline { + pub fn get_type(&self) -> crate::schema_capnp::type_::Pipeline { + ::capnp::capability::FromTypelessPipeline::new(self._typeless.get_pointer_field(1)) + } + } + mod _private { + use capnp::private::layout; + pub const STRUCT_SIZE: layout::StructSize = layout::StructSize { data: 0, pointers: 2 }; + pub const TYPE_ID: u64 = 0x8186_fa95_8dce_799d; + } +} + pub mod type_ { pub use self::Which::{App,Fn,Var,Tuple}; @@ -2783,7 +2947,7 @@ pub mod type_ { self.reader.total_size() } #[inline] - pub fn get_arguments(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::type_::Owned>> { + pub fn get_arguments(self) -> ::capnp::Result<::capnp::struct_list::Reader<'a,crate::schema_capnp::function_argument::Owned>> { ::capnp::traits::FromPointerReader::get_from_pointer(&self.reader.get_pointer_field(0), ::core::option::Option::None) } #[inline] @@ -2849,15 +3013,15 @@ pub mod type_ { self.builder.into_reader().total_size() } #[inline] - pub fn get_arguments(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::type_::Owned>> { + pub fn get_arguments(self) -> ::capnp::Result<::capnp::struct_list::Builder<'a,crate::schema_capnp::function_argument::Owned>> { ::capnp::traits::FromPointerBuilder::get_from_pointer(self.builder.get_pointer_field(0), ::core::option::Option::None) } #[inline] - pub fn set_arguments(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::type_::Owned>) -> ::capnp::Result<()> { + pub fn set_arguments(&mut self, value: ::capnp::struct_list::Reader<'a,crate::schema_capnp::function_argument::Owned>) -> ::capnp::Result<()> { ::capnp::traits::SetPointerBuilder::set_pointer_builder(self.builder.get_pointer_field(0), value, false) } #[inline] - pub fn init_arguments(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::type_::Owned> { + pub fn init_arguments(self, size: u32) -> ::capnp::struct_list::Builder<'a,crate::schema_capnp::function_argument::Owned> { ::capnp::traits::FromPointerBuilder::init_pointer(self.builder.get_pointer_field(0), size) } #[inline] diff --git a/compiler-core/schema.capnp b/compiler-core/schema.capnp index 49613a19035..2a9733278b7 100644 --- a/compiler-core/schema.capnp +++ b/compiler-core/schema.capnp @@ -90,6 +90,11 @@ struct RecordAccessor { label @2 :Text; } +struct FunctionArgument { + name @0 :Text; + type @1 :Type; +} + struct Type { union { app :group { @@ -100,7 +105,7 @@ struct Type { } fn :group { - arguments @3 :List(Type); + arguments @3 :List(FunctionArgument); return @4 :Type; } diff --git a/compiler-core/src/analyse.rs b/compiler-core/src/analyse.rs index 1a31e46d014..b3284867381 100644 --- a/compiler-core/src/analyse.rs +++ b/compiler-core/src/analyse.rs @@ -27,9 +27,10 @@ use crate::{ fields::{FieldMap, FieldMapBuilder}, hydrator::Hydrator, prelude::*, - AccessorsMap, Deprecation, ModuleInterface, PatternConstructor, RecordAccessor, Type, - TypeAliasConstructor, TypeConstructor, TypeValueConstructor, TypeValueConstructorField, - TypeVariantConstructors, ValueConstructor, ValueConstructorVariant, Warning, + AccessorsMap, Deprecation, FunctionArgument, ModuleInterface, PatternConstructor, + RecordAccessor, Type, TypeAliasConstructor, TypeConstructor, TypeValueConstructor, + TypeValueConstructorField, TypeVariantConstructors, ValueConstructor, + ValueConstructorVariant, Warning, }, uid::UniqueIdGenerator, warning::TypeWarningEmitter, @@ -526,7 +527,13 @@ impl<'a, A> ModuleAnalyzer<'a, A> { body, Some(prereg_return_type.clone()), )?; - let args_types = args.iter().map(|a| a.type_.clone()).collect(); + let args_types = args + .iter() + .map(|a| FunctionArgument { + name: a.get_variable_name().cloned(), + type_: a.type_.clone(), + }) + .collect(); let type_ = fn_(args_types, body.last().type_()); Ok(( type_, @@ -976,7 +983,10 @@ impl<'a, A> ModuleAnalyzer<'a, A> { }); // Register the type for this parameter - args_types.push(t); + args_types.push(FunctionArgument { + name: None, + type_: t, + }); // Register the label for this parameter, if there is one if let Some((_, label)) = label { @@ -992,7 +1002,7 @@ impl<'a, A> ModuleAnalyzer<'a, A> { // Insert constructor function into module scope let type_ = match constructor.arguments.len() { 0 => type_.clone(), - _ => fn_(args_types.clone(), type_.clone()), + _ => fn_(args_types, type_.clone()), }; let constructor_info = ValueConstructorVariant::Record { documentation: constructor @@ -1321,7 +1331,14 @@ impl<'a, A> ModuleAnalyzer<'a, A> { let arg_types = args .iter() .map(|arg| { - hydrator.type_from_option_ast(&arg.annotation, environment, &mut self.problems) + Ok(FunctionArgument { + name: None, + type_: hydrator.type_from_option_ast( + &arg.annotation, + environment, + &mut self.problems, + )?, + }) }) .try_collect()?; let return_type = diff --git a/compiler-core/src/ast/tests.rs b/compiler-core/src/ast/tests.rs index 4aebb57720c..158abb59744 100644 --- a/compiler-core/src/ast/tests.rs +++ b/compiler-core/src/ast/tests.rs @@ -13,8 +13,8 @@ use crate::{ ast::{SrcSpan, TypedExpr}, build::Located, type_::{ - self, AccessorsMap, Environment, ExprTyper, FieldMap, ModuleValueConstructor, - RecordAccessor, Type, ValueConstructor, ValueConstructorVariant, + self, AccessorsMap, Environment, ExprTyper, FieldMap, FunctionArgument, + ModuleValueConstructor, RecordAccessor, Type, ValueConstructor, ValueConstructorVariant, }, uid::UniqueIdGenerator, warning::TypeWarningEmitter, @@ -108,7 +108,19 @@ fn compile_expression(src: &str) -> TypedStatement { environment.insert_variable( "Cat".into(), variant, - type_::fn_(vec![type_::string(), type_::int()], cat_type.clone()), + type_::fn_( + vec![ + FunctionArgument { + name: None, + type_: type_::string(), + }, + FunctionArgument { + name: None, + type_: type_::int(), + }, + ], + cat_type.clone(), + ), Publicity::Public, Deprecation::NotDeprecated, ); diff --git a/compiler-core/src/erlang.rs b/compiler-core/src/erlang.rs index 5301c1252fd..1dd257e50cb 100644 --- a/compiler-core/src/erlang.rs +++ b/compiler-core/src/erlang.rs @@ -15,8 +15,8 @@ use crate::{ line_numbers::LineNumbers, pretty::*, type_::{ - ModuleValueConstructor, PatternConstructor, Type, TypeVar, ValueConstructor, - ValueConstructorVariant, + FunctionArgument, ModuleValueConstructor, PatternConstructor, Type, TypeVar, + ValueConstructor, ValueConstructorVariant, }, Result, }; @@ -2140,7 +2140,7 @@ fn type_var_ids(type_: &Type, ids: &mut HashMap) { }, Type::Fn { args, retrn } => { for arg in args { - type_var_ids(arg, ids) + type_var_ids(&arg.type_, ids) } type_var_ids(retrn, ids); } @@ -2293,8 +2293,8 @@ impl<'a> TypePrinter<'a> { } } - fn print_fn(&self, args: &[Arc], retrn: &Type) -> Document<'static> { - let args = join(args.iter().map(|a| self.print(a)), ", ".to_doc()); + fn print_fn(&self, args: &[FunctionArgument], retrn: &Type) -> Document<'static> { + let args = join(args.iter().map(|a| self.print(&a.type_)), ", ".to_doc()); let retrn = self.print(retrn); "fun((" .to_doc() diff --git a/compiler-core/src/exhaustiveness.rs b/compiler-core/src/exhaustiveness.rs index 5283d9e1508..608cac78ce1 100644 --- a/compiler-core/src/exhaustiveness.rs +++ b/compiler-core/src/exhaustiveness.rs @@ -38,8 +38,8 @@ use self::pattern::{Constructor, Pattern, PatternId}; use crate::{ ast::AssignName, type_::{ - collapse_links, error::UnknownTypeConstructorError, is_prelude_module, Environment, Type, - TypeValueConstructor, TypeValueConstructorField, TypeVar, + collapse_links, error::UnknownTypeConstructorError, is_prelude_module, Environment, + FunctionArgument, Type, TypeValueConstructor, TypeValueConstructorField, TypeVar, }, }; use ecow::EcoString; @@ -905,7 +905,13 @@ impl ConstructorSpecialiser { }, Type::Fn { args, retrn } => Type::Fn { - args: args.iter().map(|a| self.specialise_type(a)).collect(), + args: args + .iter() + .map(|a| FunctionArgument { + name: a.name.clone(), + type_: self.specialise_type(&a.type_), + }) + .collect(), retrn: retrn.clone(), }, diff --git a/compiler-core/src/javascript/typescript.rs b/compiler-core/src/javascript/typescript.rs index 22e605caba3..8821c454284 100644 --- a/compiler-core/src/javascript/typescript.rs +++ b/compiler-core/src/javascript/typescript.rs @@ -106,7 +106,7 @@ fn generic_ids(type_: &Type, ids: &mut HashMap) { } Type::Fn { args, retrn } => { for arg in args { - generic_ids(arg, ids) + generic_ids(&arg.type_, ids) } generic_ids(retrn, ids); } @@ -561,7 +561,14 @@ impl<'a> TypeScriptGenerator<'a> { name, args, module, .. } => self.print_type_app(name, args, module, generic_usages), - Type::Fn { args, retrn } => self.print_fn(args, retrn, generic_usages), + Type::Fn { args, retrn } => self.print_fn( + args.iter() + .map(|a| a.type_.clone()) + .collect_vec() + .as_slice(), + retrn, + generic_usages, + ), Type::Tuple { elems } => tuple(elems.iter().map(|e| self.do_print(e, generic_usages))), } @@ -579,7 +586,14 @@ impl<'a> TypeScriptGenerator<'a> { name, args, module, .. } => self.print_type_app(name, args, module, None), - Type::Fn { args, retrn } => self.print_fn(args, retrn, None), + Type::Fn { args, retrn } => self.print_fn( + args.iter() + .map(|a| a.type_.clone()) + .collect_vec() + .as_slice(), + retrn, + None, + ), Type::Tuple { elems } => tuple(elems.iter().map(|e| self.do_print(e, None))), } diff --git a/compiler-core/src/language_server/engine.rs b/compiler-core/src/language_server/engine.rs index c3377e7d39b..164c71d42ae 100644 --- a/compiler-core/src/language_server/engine.rs +++ b/compiler-core/src/language_server/engine.rs @@ -790,7 +790,14 @@ fn hover_for_pattern(pattern: &TypedPattern, line_numbers: LineNumbers, module: fn get_function_type(fun: &TypedFunction) -> Type { Type::Fn { - args: fun.arguments.iter().map(|arg| arg.type_.clone()).collect(), + args: fun + .arguments + .iter() + .map(|arg| type_::FunctionArgument { + name: arg.names.get_variable_name().cloned(), + type_: arg.type_.clone(), + }) + .collect(), retrn: fun.return_type.clone(), } } diff --git a/compiler-core/src/metadata/module_decoder.rs b/compiler-core/src/metadata/module_decoder.rs index 320397896ac..665bca7c1d5 100755 --- a/compiler-core/src/metadata/module_decoder.rs +++ b/compiler-core/src/metadata/module_decoder.rs @@ -140,10 +140,19 @@ impl ModuleDecoder { fn type_fn(&mut self, reader: &schema::type_::fn_::Reader<'_>) -> Result> { let retrn = self.type_(&reader.get_return()?)?; - let args = read_vec!(&reader.get_arguments()?, self, type_); + let args = read_vec!(&reader.get_arguments()?, self, function_argument); Ok(Arc::new(Type::Fn { args, retrn })) } + fn function_argument( + &mut self, + reader: &function_argument::Reader<'_>, + ) -> Result { + let name = self.optional_string(reader.get_name()?); + let type_ = self.type_(&reader.get_type()?)?; + Ok(type_::FunctionArgument { name, type_ }) + } + fn type_tuple(&mut self, reader: &schema::type_::tuple::Reader<'_>) -> Result> { let elems = read_vec!(&reader.get_elements()?, self, type_); Ok(Arc::new(Type::Tuple { elems })) diff --git a/compiler-core/src/metadata/module_encoder.rs b/compiler-core/src/metadata/module_encoder.rs index 5e1283269cb..ae414a0f6e4 100644 --- a/compiler-core/src/metadata/module_encoder.rs +++ b/compiler-core/src/metadata/module_encoder.rs @@ -7,8 +7,8 @@ use crate::{ }, schema_capnp::{self as schema, *}, type_::{ - self, expression::Implementations, AccessorsMap, Deprecation, FieldMap, RecordAccessor, - Type, TypeAliasConstructor, TypeConstructor, TypeValueConstructor, TypeVar, + self, expression::Implementations, AccessorsMap, Deprecation, FieldMap, FunctionArgument, + RecordAccessor, Type, TypeAliasConstructor, TypeConstructor, TypeValueConstructor, TypeVar, TypeVariantConstructors, ValueConstructor, ValueConstructorVariant, }, }; @@ -545,11 +545,36 @@ impl<'a> ModuleEncoder<'a> { } } + fn build_function_argument( + &mut self, + mut builder: function_argument::Builder<'_>, + arg: &FunctionArgument, + ) { + match &arg.name { + Some(name) => builder.set_name(name), + None => builder.set_name(""), + } + self.build_type(builder.init_type(), arg.type_.as_ref()); + } + + fn build_function_arguments( + &mut self, + mut builder: capnp::struct_list::Builder<'_, function_argument::Owned>, + args: &[FunctionArgument], + ) { + for (i, arg) in args.iter().enumerate() { + self.build_function_argument(builder.reborrow().get(i as u32), arg); + } + } + fn build_type(&mut self, builder: schema::type_::Builder<'_>, type_: &Type) { match type_ { Type::Fn { args, retrn } => { let mut fun = builder.init_fn(); - self.build_types(fun.reborrow().init_arguments(args.len() as u32), args); + self.build_function_arguments( + fun.reborrow().init_arguments(args.len() as u32), + args, + ); self.build_type(fun.init_return(), retrn) } diff --git a/compiler-core/src/metadata/tests.rs b/compiler-core/src/metadata/tests.rs index 19f559f8b0f..533ad3999a6 100644 --- a/compiler-core/src/metadata/tests.rs +++ b/compiler-core/src/metadata/tests.rs @@ -11,9 +11,9 @@ use crate::{ build::Origin, line_numbers::LineNumbers, type_::{ - self, expression::Implementations, Deprecation, ModuleInterface, Type, TypeConstructor, - TypeValueConstructor, TypeValueConstructorField, TypeVariantConstructors, ValueConstructor, - ValueConstructorVariant, + self, expression::Implementations, Deprecation, FunctionArgument, ModuleInterface, Type, + TypeConstructor, TypeValueConstructor, TypeValueConstructorField, TypeVariantConstructors, + ValueConstructor, ValueConstructorVariant, }, uid::UniqueIdGenerator, }; @@ -210,7 +210,19 @@ fn module_with_fn_type() { types: [( "FnType".into(), TypeConstructor { - type_: type_::fn_(vec![type_::nil(), type_::float()], type_::int()), + type_: type_::fn_( + vec![ + FunctionArgument { + name: None, + type_: type_::nil(), + }, + FunctionArgument { + name: None, + type_: type_::float(), + }, + ], + type_::int(), + ), publicity: Publicity::Public, opaque: false, origin: Default::default(), diff --git a/compiler-core/src/package_interface.rs b/compiler-core/src/package_interface.rs index a6980c10907..3608232ff88 100644 --- a/compiler-core/src/package_interface.rs +++ b/compiler-core/src/package_interface.rs @@ -1,24 +1,20 @@ use std::{collections::HashMap, ops::Deref}; use ecow::EcoString; -use itertools::Itertools; use serde::Serialize; #[cfg(test)] mod tests; use crate::{ - ast::{CustomType, Definition, Function, ModuleConstant, Publicity, TypeAlias, UntypedModule}, - build::package_compiler::UncompiledModule, io::ordered_map, - schema_capnp::publicity, type_::{ - self, expression::Implementations, Deprecation, Type, TypeAliasConstructor, - TypeConstructor, TypeVar, ValueConstructorVariant, + self, expression::Implementations, Deprecation, Type, TypeConstructor, TypeVar, + ValueConstructorVariant, }, }; -use crate::build::{Module, Package}; +use crate::build::Package; /// The public interface of a package that gets serialised as a json object. #[derive(Serialize, Debug)] @@ -501,9 +497,8 @@ impl ModuleInterface { parameters: arguments .iter() .map(|arg| ParameterInterface { - //TODO: Find label - label: None, - type_: from_type_helper(arg.as_ref(), &mut id_map), + label: arg.name.clone(), + type_: from_type_helper(arg.type_.as_ref(), &mut id_map), }) .collect(), return_: from_type_helper(return_type, &mut id_map), @@ -561,7 +556,7 @@ fn from_type_helper(type_: &Type, id_map: &mut IdMap) -> TypeInterface { Type::Fn { args, retrn } => TypeInterface::Fn { parameters: args .iter() - .map(|arg| from_type_helper(arg.as_ref(), id_map)) + .map(|arg| from_type_helper(arg.type_.as_ref(), id_map)) .collect(), return_: Box::new(from_type_helper(retrn, id_map)), }, diff --git a/compiler-core/src/type_.rs b/compiler-core/src/type_.rs index 9a626ea55d1..ef5518c64b8 100644 --- a/compiler-core/src/type_.rs +++ b/compiler-core/src/type_.rs @@ -68,7 +68,7 @@ pub enum Type { /// The type of a function. It takes arguments and returns a value. /// Fn { - args: Vec>, + args: Vec, retrn: Arc, }, @@ -141,7 +141,10 @@ impl Type { pub fn fn_types(&self) -> Option<(Vec>, Arc)> { match self { - Self::Fn { args, retrn, .. } => Some((args.clone(), retrn.clone())), + Self::Fn { args, retrn, .. } => Some(( + args.iter().map(|a| a.type_.clone()).collect(), + retrn.clone(), + )), Self::Var { type_ } => type_.borrow().fn_types(), _ => None, } @@ -316,7 +319,7 @@ impl Type { Self::Fn { retrn, args, .. } => retrn .find_private_type() - .or_else(|| args.iter().find_map(|t| t.find_private_type())), + .or_else(|| args.iter().find_map(|t| t.type_.find_private_type())), Self::Var { type_, .. } => match type_.borrow().deref() { TypeVar::Unbound { .. } => None, @@ -338,7 +341,7 @@ impl Type { Self::Fn { retrn, args, .. } => retrn .find_internal_type() - .or_else(|| args.iter().find_map(|t| t.find_internal_type())), + .or_else(|| args.iter().find_map(|t| t.type_.find_internal_type())), Self::Var { type_, .. } => match type_.borrow().deref() { TypeVar::Unbound { .. } | TypeVar::Generic { .. } => None, @@ -364,6 +367,12 @@ pub fn collapse_links(t: Arc) -> Arc { t } +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct FunctionArgument { + pub name: Option, + pub type_: Arc, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct AccessorsMap { pub publicity: Publicity, @@ -1087,7 +1096,7 @@ fn unify_unbound_type(type_: Arc, own_id: u64) -> Result<(), UnifyError> { Type::Fn { args, retrn } => { for arg in args { - unify_unbound_type(arg.clone(), own_id)?; + unify_unbound_type(arg.type_.clone(), own_id)?; } unify_unbound_type(retrn.clone(), own_id) } @@ -1125,7 +1134,15 @@ fn match_fun_type( if let Some((args, retrn)) = new_value { *type_.borrow_mut() = TypeVar::Link { - type_: fn_(args.clone(), retrn.clone()), + type_: fn_( + args.iter() + .map(|t| FunctionArgument { + name: None, + type_: t.clone(), + }) + .collect(), + retrn.clone(), + ), }; return Ok((args, retrn)); } @@ -1136,11 +1153,14 @@ fn match_fun_type( Err(MatchFunTypeError::IncorrectArity { expected: args.len(), given: arity, - args: args.clone(), + args: args.iter().map(|a| a.type_.clone()).collect(), return_type: retrn.clone(), }) } else { - Ok((args.clone(), retrn.clone())) + Ok(( + args.iter().map(|a| a.type_.clone()).collect(), + retrn.clone(), + )) }; } @@ -1175,7 +1195,12 @@ pub fn generalise(t: Arc) -> Arc { } Type::Fn { args, retrn } => fn_( - args.iter().map(|t| generalise(t.clone())).collect(), + args.iter() + .map(|t| FunctionArgument { + name: t.name.clone(), + type_: generalise(t.type_.clone()), + }) + .collect(), generalise(retrn.clone()), ), diff --git a/compiler-core/src/type_/environment.rs b/compiler-core/src/type_/environment.rs index 830b7f58cc8..a99c2eb73da 100644 --- a/compiler-core/src/type_/environment.rs +++ b/compiler-core/src/type_/environment.rs @@ -379,6 +379,19 @@ impl<'a> Environment<'a> { None => self .module_types .get(name) + // .or_else(|| { + // self.module_type_aliases + // .get(name) + // .map(|t| &TypeConstructor { + // opaque: false, + // type_: Arc::new(t.type_.clone()), + // deprecation: t.deprecation, + // origin: t.origin, + // module: t.module.clone(), + // parameters: t.parameters.clone(), + // publicity: t.publicity, + // }) + // }) .ok_or_else(|| UnknownTypeConstructorError::Type { name: name.clone(), hint: self.unknown_type_hint(name), @@ -397,6 +410,12 @@ impl<'a> Environment<'a> { module .types .get(name) + // .map(|t| t.type_.clone()) + // .or_else(|| { + // self.module_type_aliases + // .get(name) + // .map(|t| Arc::new(t.type_.clone())) + // }) .ok_or_else(|| UnknownTypeConstructorError::ModuleType { name: name.clone(), module_name: module.name.clone(), @@ -558,7 +577,10 @@ impl<'a> Environment<'a> { Type::Fn { args, retrn, .. } => fn_( args.iter() - .map(|t| self.instantiate(t.clone(), ids, hydrator)) + .map(|t| FunctionArgument { + name: None, + type_: self.instantiate(t.type_.clone(), ids, hydrator), + }) .collect(), self.instantiate(retrn.clone(), ids, hydrator), ), @@ -873,8 +895,8 @@ pub fn unify(t1: Arc, t2: Arc) -> Result<(), UnifyError> { } for (i, (a, b)) in args1.iter().zip(args2).enumerate() { - unify(a.clone(), b.clone()) - .map_err(|_| unify_wrong_arguments(&t1, a, &t2, b, i))?; + unify(a.type_.clone(), b.type_.clone()) + .map_err(|_| unify_wrong_arguments(&t1, &a.type_, &t2, &b.type_, i))?; } unify(retrn1.clone(), retrn2.clone()) diff --git a/compiler-core/src/type_/expression.rs b/compiler-core/src/type_/expression.rs index 0785f72710e..9c4016c5db8 100644 --- a/compiler-core/src/type_/expression.rs +++ b/compiler-core/src/type_/expression.rs @@ -745,7 +745,13 @@ impl<'a, 'b> ExprTyper<'a, 'b> { self.previous_panics = false; let (args, body) = self.do_infer_fn(args, expected_args, body, &return_annotation)?; - let args_types = args.iter().map(|a| a.type_.clone()).collect(); + let args_types = args + .iter() + .map(|a| FunctionArgument { + name: None, + type_: a.type_.clone(), + }) + .collect(); let type_ = fn_(args_types, body.last().type_()); // Defining an anonymous function never panics. @@ -3245,7 +3251,11 @@ impl<'a, 'b> ExprTyper<'a, 'b> { }, ) if expected_arguments.len() == arguments.len() => self.infer_fn( arguments, - expected_arguments, + expected_arguments + .iter() + .map(|a| a.type_.clone()) + .collect_vec() + .as_slice(), body, false, return_annotation, diff --git a/compiler-core/src/type_/hydrator.rs b/compiler-core/src/type_/hydrator.rs index 772de1e16d3..b3561e86802 100644 --- a/compiler-core/src/type_/hydrator.rs +++ b/compiler-core/src/type_/hydrator.rs @@ -204,7 +204,12 @@ impl Hydrator { }) => { let args = args .iter() - .map(|t| self.type_from_ast(t, environment, problems)) + .map(|t| { + Ok(FunctionArgument { + name: None, + type_: self.type_from_ast(t, environment, problems)?, + }) + }) .try_collect()?; let retrn = self.type_from_ast(retrn, environment, problems)?; Ok(fn_(args, retrn)) diff --git a/compiler-core/src/type_/pattern.rs b/compiler-core/src/type_/pattern.rs index b6913e20ecc..09fb476159a 100644 --- a/compiler-core/src/type_/pattern.rs +++ b/compiler-core/src/type_/pattern.rs @@ -646,7 +646,7 @@ impl<'a, 'b> PatternTyper<'a, 'b> { implicit, label, } = arg; - let value = self.unify(value, type_.clone())?; + let value = self.unify(value, type_.type_.clone())?; Ok(CallArg { value, location, diff --git a/compiler-core/src/type_/pipe.rs b/compiler-core/src/type_/pipe.rs index 7f055e28974..3e0e94e256a 100644 --- a/compiler-core/src/type_/pipe.rs +++ b/compiler-core/src/type_/pipe.rs @@ -292,7 +292,13 @@ impl<'a, 'b, 'c> PipeTyper<'a, 'b, 'c> { // Ensure that the function accepts one argument of the correct type unify( function.type_(), - fn_(vec![self.argument_type.clone()], return_type.clone()), + fn_( + vec![FunctionArgument { + name: None, + type_: self.argument_type.clone(), + }], + return_type.clone(), + ), ) .map_err(|e| { if self.check_if_pipe_function_mismatch(&e) { @@ -326,7 +332,7 @@ impl<'a, 'b, 'c> PipeTyper<'a, 'b, 'c> { match types { (Type::Fn { args: a, .. }, Type::Fn { args: b, .. }) if a.len() == b.len() => { match (a.first(), b.first()) { - (Some(a), Some(b)) => unify(a.clone(), b.clone()).is_err(), + (Some(a), Some(b)) => unify(a.type_.clone(), b.type_.clone()).is_err(), _ => false, } } diff --git a/compiler-core/src/type_/prelude.rs b/compiler-core/src/type_/prelude.rs index d46e49ae565..40472c8cf4d 100644 --- a/compiler-core/src/type_/prelude.rs +++ b/compiler-core/src/type_/prelude.rs @@ -9,8 +9,9 @@ use crate::{ }; use super::{ - ModuleInterface, Type, TypeConstructor, TypeValueConstructor, TypeValueConstructorField, - TypeVar, TypeVariantConstructors, ValueConstructor, ValueConstructorVariant, + FunctionArgument, ModuleInterface, Type, TypeConstructor, TypeValueConstructor, + TypeValueConstructorField, TypeVar, TypeVariantConstructors, ValueConstructor, + ValueConstructorVariant, }; use crate::type_::Deprecation::NotDeprecated; use std::{cell::RefCell, collections::HashMap, sync::Arc}; @@ -135,7 +136,7 @@ pub fn tuple(elems: Vec>) -> Arc { Arc::new(Type::Tuple { elems }) } -pub fn fn_(args: Vec>, retrn: Arc) -> Arc { +pub fn fn_(args: Vec, retrn: Arc) -> Arc { Arc::new(Type::Fn { retrn, args }) } @@ -447,7 +448,13 @@ pub fn build_prelude(ids: &UniqueIdGenerator) -> ModuleInterface { constructors_count: 2, constructor_index: 0, }, - fn_(vec![ok.clone()], result(ok, error)), + fn_( + vec![FunctionArgument { + name: None, + type_: ok.clone(), + }], + result(ok, error), + ), ), ); let ok = generic_var(ids.next()); @@ -465,7 +472,13 @@ pub fn build_prelude(ids: &UniqueIdGenerator) -> ModuleInterface { constructors_count: 2, constructor_index: 1, }, - fn_(vec![error.clone()], result(ok, error)), + fn_( + vec![FunctionArgument { + name: None, + type_: error.clone(), + }], + result(ok, error), + ), ), ); } diff --git a/compiler-core/src/type_/pretty.rs b/compiler-core/src/type_/pretty.rs index 13a0e3985f8..a5709ad312d 100644 --- a/compiler-core/src/type_/pretty.rs +++ b/compiler-core/src/type_/pretty.rs @@ -1,4 +1,4 @@ -use super::{Type, TypeVar}; +use super::{FunctionArgument, Type, TypeVar}; use crate::{ docvec, pretty::{nil, *}, @@ -72,7 +72,7 @@ impl Printer { Type::Fn { args, retrn } => "fn(" .to_doc() - .append(self.args_to_gleam_doc(args)) + .append(self.function_args_to_gleam_doc(args)) .append(") ->") .append( break_("", " ") @@ -139,6 +139,22 @@ impl Printer { chars.into_iter().rev().collect() } + fn function_args_to_gleam_doc(&mut self, args: &[FunctionArgument]) -> Document<'static> { + if args.is_empty() { + return nil(); + } + + let args = join( + args.iter().map(|t| self.print(&t.type_).group()), + break_(",", ", "), + ); + break_("", "") + .append(args) + .nest(INDENT) + .append(break_(",", "")) + .group() + } + fn args_to_gleam_doc(&mut self, args: &[Arc]) -> Document<'static> { if args.is_empty() { return nil(); @@ -290,20 +306,26 @@ fn pretty_print_test() { assert_string!( Type::Fn { args: vec![ - Arc::new(Type::Named { - args: vec![], - module: "whatever".into(), - package: "whatever".into(), - name: "Int".into(), - publicity: Publicity::Public, - }), - Arc::new(Type::Named { - args: vec![], - module: "whatever".into(), - package: "whatever".into(), - name: "Bool".into(), - publicity: Publicity::Public, - }), + FunctionArgument { + name: None, + type_: Arc::new(Type::Named { + args: vec![], + module: "whatever".into(), + package: "whatever".into(), + name: "Int".into(), + publicity: Publicity::Public, + }) + }, + FunctionArgument { + name: None, + type_: Arc::new(Type::Named { + args: vec![], + module: "whatever".into(), + package: "whatever".into(), + name: "Bool".into(), + publicity: Publicity::Public, + }) + }, ], retrn: Arc::new(Type::Named { args: vec![], @@ -337,9 +359,12 @@ fn pretty_print_test() { ); assert_string!( fn_( - vec![Arc::new(Type::Var { - type_: Arc::new(RefCell::new(TypeVar::Unbound { id: 78 })), - })], + vec![FunctionArgument { + name: None, + type_: Arc::new(Type::Var { + type_: Arc::new(RefCell::new(TypeVar::Unbound { id: 78 })), + }) + }], Arc::new(Type::Var { type_: Arc::new(RefCell::new(TypeVar::Unbound { id: 2 })), }), @@ -348,9 +373,12 @@ fn pretty_print_test() { ); assert_string!( fn_( - vec![Arc::new(Type::Var { - type_: Arc::new(RefCell::new(TypeVar::Generic { id: 78 })), - })], + vec![FunctionArgument { + name: None, + type_: Arc::new(Type::Var { + type_: Arc::new(RefCell::new(TypeVar::Generic { id: 78 })), + }) + }], Arc::new(Type::Var { type_: Arc::new(RefCell::new(TypeVar::Generic { id: 2 })), }), @@ -364,7 +392,16 @@ fn function_test() { assert_eq!(pretty_print(fn_(vec![], int())), "fn() -> Int"); assert_eq!( - pretty_print(fn_(vec![int(), int(), int()], int())), + pretty_print(fn_( + vec![int(), int(), int()] + .into_iter() + .map(|t| FunctionArgument { + name: None, + type_: t, + }) + .collect(), + int() + )), "fn(Int, Int, Int) -> Int" ); @@ -384,7 +421,13 @@ fn function_test() { float(), float(), float() - ], + ] + .into_iter() + .map(|t| FunctionArgument { + name: None, + type_: t, + }) + .collect(), float() )), "fn( @@ -415,7 +458,13 @@ fn function_test() { float(), float(), float() - ], + ] + .into_iter() + .map(|t| FunctionArgument { + name: None, + type_: t, + }) + .collect(), float() )), "fn( @@ -439,7 +488,13 @@ fn function_test() { float(), float(), float() - ]),], + ]),] + .into_iter() + .map(|t| FunctionArgument { + name: None, + type_: t, + }) + .collect(), tuple(vec![ tuple(vec![float(), float(), float(), float(), float(), float()]), tuple(vec![float(), float(), float(), float(), float(), float()]), diff --git a/compiler-core/src/type_/printer.rs b/compiler-core/src/type_/printer.rs index 91b50d3d501..fb921314169 100644 --- a/compiler-core/src/type_/printer.rs +++ b/compiler-core/src/type_/printer.rs @@ -3,7 +3,10 @@ use ecow::EcoString; use im::HashMap; use std::{collections::HashSet, sync::Arc}; -use crate::type_::{Type, TypeVar}; +use crate::{ + analyse::name, + type_::{FunctionArgument, Type, TypeVar}, +}; /// This class keeps track of what names are used for modules in the current /// scope, so they can be printed in errors, etc. @@ -332,7 +335,7 @@ impl<'a> Printer<'a> { Type::Fn { args, retrn } => { buffer.push_str("fn("); - self.print_arguments(args, buffer, print_mode); + self.print_function_arguments(args, buffer, print_mode); buffer.push_str(") -> "); self.print(retrn, buffer, print_mode); } @@ -352,6 +355,20 @@ impl<'a> Printer<'a> { } } + fn print_function_arguments( + &mut self, + args: &[FunctionArgument], + typ_str: &mut EcoString, + print_mode: PrintMode, + ) { + for (i, arg) in args.iter().enumerate() { + self.print(&arg.type_, typ_str, print_mode); + if i < args.len() - 1 { + typ_str.push_str(", "); + } + } + } + fn print_arguments( &mut self, args: &[Arc], @@ -529,20 +546,26 @@ fn test_fn_type() { let type_ = Type::Fn { args: vec![ - Arc::new(Type::Named { - name: "Int".into(), - args: vec![], - module: "gleam".into(), - publicity: crate::ast::Publicity::Public, - package: "".into(), - }), - Arc::new(Type::Named { - name: "String".into(), - args: vec![], - module: "gleam".into(), - publicity: crate::ast::Publicity::Public, - package: "".into(), - }), + FunctionArgument { + name: None, + type_: Arc::new(Type::Named { + name: "Int".into(), + args: vec![], + module: "gleam".into(), + publicity: crate::ast::Publicity::Public, + package: "".into(), + }), + }, + FunctionArgument { + name: None, + type_: Arc::new(Type::Named { + name: "String".into(), + args: vec![], + module: "gleam".into(), + publicity: crate::ast::Publicity::Public, + package: "".into(), + }), + }, ], retrn: Arc::new(Type::Named { name: "Bool".into(),