Skip to content

Commit

Permalink
Rename Package -> CompilationUnitComponent in PMS
Browse files Browse the repository at this point in the history
  • Loading branch information
integraledelebesgue committed Mar 7, 2025
1 parent 938767d commit 5159327
Show file tree
Hide file tree
Showing 11 changed files with 60 additions and 55 deletions.
4 changes: 3 additions & 1 deletion scarb/src/compiler/compilation_unit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,9 @@ impl CompilationUnitComponent {
}
}

impl From<&CompilationUnitComponent> for scarb_proc_macro_server_types::scope::Package {
impl From<&CompilationUnitComponent>
for scarb_proc_macro_server_types::scope::CompilationUnitComponent
{
fn from(value: &CompilationUnitComponent) -> Self {
// `name` and `discriminator` used here must be identital to the scarb-metadata.
// This implementation detail is crucial for communication between PMS and LS.
Expand Down
30 changes: 11 additions & 19 deletions scarb/src/compiler/plugin/collection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{collections::HashMap, sync::Arc};
use anyhow::Result;
use cairo_lang_semantic::{inline_macros::get_default_plugin_suite, plugin::PluginSuite};
use itertools::Itertools;
use scarb_proc_macro_server_types::scope::Package;
use scarb_proc_macro_server_types::scope::CompilationUnitComponent;

use crate::{
compiler::{CairoCompilationUnit, CompilationUnitComponentId, CompilationUnitDependency},
Expand Down Expand Up @@ -49,17 +49,11 @@ impl PluginsForComponents {
// NOTE: Since this structure is used to handle JsonRPC requests, its keys have to be serialized to strings.
//
/// A container for Proc Macro Server to manage macros present in the analyzed workspace.
///
/// # Invariant
/// Correct usage of this struct during proc macro server <-> LS communication
/// relies on the implicit contract that keys of `macros_for_packages` are of form
/// `PackageId.to_serialized_string()` which is always equal to
/// `scarb_metadata::CompilationUnitComponentId.repr`.
pub struct WorkspaceProcMacros {
/// A mapping of the form: `package (as a serialized [`PackageId`]) -> plugin`.
/// Contains IDs of all packages from the workspace, each mapped to a [`ProcMacroHostPlugin`] which contains
/// A mapping of the form: `cu_component (as a [`CompilationUnitComponent`]) -> plugin`.
/// Contains IDs of all components of all from the workspace, each mapped to a [`ProcMacroHostPlugin`] which contains
/// **all proc macro dependencies of the package** collected from **all compilation units it appears in**.
pub macros_for_packages: HashMap<Package, Arc<ProcMacroHostPlugin>>,
pub macros_for_packages: HashMap<CompilationUnitComponent, Arc<ProcMacroHostPlugin>>,
}

impl WorkspaceProcMacros {
Expand All @@ -72,17 +66,15 @@ impl WorkspaceProcMacros {

for &unit in compilation_units {
for (component_id, mut macro_instances) in collect_proc_macros(workspace, unit)? {
// Here we assume that CompilationUnitComponentId.repr == PackageId.to_serialized_string().
let component = unit
let component: CompilationUnitComponent = unit
.components
.iter()
.find(|component| component.id == component_id)
.expect("component should always exist");

let package: Package = component.into();
.expect("component should always exist")
.into();

macros_for_components
.entry(package)
.entry(component)
.or_default()
.append(&mut macro_instances);
}
Expand All @@ -107,9 +99,9 @@ impl WorkspaceProcMacros {
})
}

/// Returns a [`ProcMacroHostPlugin`] assigned to the package with `package_id`.
pub fn get(&self, package: &Package) -> Option<Arc<ProcMacroHostPlugin>> {
self.macros_for_packages.get(package).cloned()
/// Returns a [`ProcMacroHostPlugin`] assigned to the [`CompilationUnitComponent`].
pub fn get(&self, component: &CompilationUnitComponent) -> Option<Arc<ProcMacroHostPlugin>> {
self.macros_for_packages.get(component).cloned()
}
}

Expand Down
12 changes: 6 additions & 6 deletions scarb/src/ops/proc_macro_server/methods/defined_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use anyhow::Result;
use cairo_lang_defs::plugin::MacroPlugin;
use convert_case::{Case, Casing};
use scarb_proc_macro_server_types::methods::defined_macros::{
DefinedMacros, DefinedMacrosResponse, PackageDefinedMacrosInfo,
CompilationUnitComponentMacros, DefinedMacros, DefinedMacrosResponse,
};

use super::Handler;
Expand All @@ -15,10 +15,10 @@ impl Handler for DefinedMacros {
workspace_macros: Arc<WorkspaceProcMacros>,
_params: Self::Params,
) -> Result<Self::Response> {
let macros_by_package_id = workspace_macros
let macros_for_cu_components = workspace_macros
.macros_for_packages
.iter()
.map(|(package, plugin)| {
.map(|(component, plugin)| {
let attributes = plugin.declared_attributes_without_executables();
let inline_macros = plugin.declared_inline_macros();
let derives = plugin
Expand All @@ -28,8 +28,8 @@ impl Handler for DefinedMacros {
.collect();
let executables = plugin.executable_attributes();

PackageDefinedMacrosInfo {
package: package.to_owned(),
CompilationUnitComponentMacros {
component: component.to_owned(),
attributes,
inline_macros,
derives,
Expand All @@ -39,7 +39,7 @@ impl Handler for DefinedMacros {
.collect();

Ok(DefinedMacrosResponse {
macros_for_packages: macros_by_package_id,
macros_for_cu_components,
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ impl Handler for ExpandAttribute {
} = params;

let plugin = workspace_macros
.get(&context.package)
.get(&context.cu_component)
.with_context(|| format!("No macros found in scope: {context:?}"))?;

let instance = plugin
Expand Down
2 changes: 1 addition & 1 deletion scarb/src/ops/proc_macro_server/methods/expand_derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ impl Handler for ExpandDerive {
let expansion = Expansion::new(derive.to_case(Case::Snake), ExpansionKind::Derive);

let plugin = workspace_macros
.get(&context.package)
.get(&context.cu_component)
.with_context(|| format!("No macros found in scope {context:?}"))?;

let instance = plugin
Expand Down
2 changes: 1 addition & 1 deletion scarb/src/ops/proc_macro_server/methods/expand_inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ impl Handler for ExpandInline {
} = params;

let plugin = workspace_macros
.get(&context.package)
.get(&context.cu_component)
.with_context(|| format!("No macros found in scope: {context:?}"))?;

let instance = plugin
Expand Down
6 changes: 4 additions & 2 deletions scarb/tests/proc_macro_prebuilt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,11 +220,13 @@ fn load_prebuilt_proc_macros() {

let package = proc_macro_client
.defined_macros_for_package("test_package")
.package;
.component;

let response = proc_macro_client
.request_and_wait::<ExpandInline>(ExpandInlineMacroParams {
context: ProcMacroScope { package },
context: ProcMacroScope {
cu_component: package,
},
name: "some".to_string(),
args: TokenStream::new("42".to_string()),
})
Expand Down
18 changes: 12 additions & 6 deletions scarb/tests/proc_macro_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,13 @@ fn expand_attribute() {

let package = proc_macro_client
.defined_macros_for_package("test_package")
.package;
.component;

let response = proc_macro_client
.request_and_wait::<ExpandAttribute>(ExpandAttributeParams {
context: ProcMacroScope { package },
context: ProcMacroScope {
cu_component: package,
},
attr: "rename_to_very_new_name".to_string(),
args: TokenStream::empty(),
item: TokenStream::new("fn some_test_fn(){}".to_string()),
Expand Down Expand Up @@ -120,13 +122,15 @@ fn expand_derive() {

let package = proc_macro_client
.defined_macros_for_package("test_package")
.package;
.component;

let item = TokenStream::new("fn some_test_fn(){}".to_string());

let response = proc_macro_client
.request_and_wait::<ExpandDerive>(ExpandDeriveParams {
context: ProcMacroScope { package },
context: ProcMacroScope {
cu_component: package,
},
derives: vec!["some_derive".to_string()],
item,
})
Expand Down Expand Up @@ -168,11 +172,13 @@ fn expand_inline() {

let package = proc_macro_client
.defined_macros_for_package("test_package")
.package;
.component;

let response = proc_macro_client
.request_and_wait::<ExpandInline>(ExpandInlineMacroParams {
context: ProcMacroScope { package },
context: ProcMacroScope {
cu_component: package,
},
name: "replace_all_15_with_25".to_string(),
args: TokenStream::new(
"struct A { field: 15 , other_field: macro_call!(12)}".to_string(),
Expand Down
20 changes: 10 additions & 10 deletions utils/scarb-proc-macro-server-types/src/methods/defined_macros.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::scope::Package;
use crate::scope::CompilationUnitComponent;

use super::Method;
use serde::{Deserialize, Serialize};
Expand All @@ -7,25 +7,25 @@ use serde::{Deserialize, Serialize};
/// about the macros used by packages from the workspace.
///
/// # Invariant
/// Each [`PackageDefinedMacrosInfo`] in `macros_for_packages` should have
/// Each [`CompilationUnitComponentMacros`] in `macros_for_packages` should have
/// an exclusive `package` field which identifies it in the response.
/// Effectively, it simulates a HashMap which cannot be used directly
/// because of the JSON serialization.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct DefinedMacrosResponse {
/// A list of [`PackageDefinedMacrosInfo`], describing macros
/// A list of [`CompilationUnitComponentMacros`], describing macros
/// available for each package from the workspace.
pub macros_for_packages: Vec<PackageDefinedMacrosInfo>,
pub macros_for_cu_components: Vec<CompilationUnitComponentMacros>,
}

/// Response structure containing lists of all defined macros available for one package.
/// Details the types of macros that can be expanded, such as attributes, inline macros, and derives.
/// Response structure containing lists of all defined macros available for one compilation unit component.
/// Provides the types of macros that can be expanded, such as attributes, inline macros, and derives.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct PackageDefinedMacrosInfo {
/// A package for which the macros are defined.
/// It should identify [`PackageDefinedMacrosInfo`]
pub struct CompilationUnitComponentMacros {
/// A component for which the macros are defined.
/// It should identify [`CompilationUnitComponentMacros`]
/// uniquely in the [`DefinedMacrosResponse`].
pub package: Package,
pub component: CompilationUnitComponent,
/// List of attribute macro names available.
pub attributes: Vec<String>,
/// List of inline macro names available.
Expand Down
8 changes: 4 additions & 4 deletions utils/scarb-proc-macro-server-types/src/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ use serde::{Deserialize, Serialize};
/// At the moment, they are obtained using `CompilationUnitComponent::cairo_package_name`
/// and `CompilationUnitComponentId::to_discriminator`, respectively.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub struct Package {
pub struct CompilationUnitComponent {
/// Name of the `CompilationUnitComponent` associated with the package.
pub name: String,
/// A `CompilationUnitComponent` discriminator.
/// `None` only for corelib.
pub discriminator: Option<String>,
}

impl Package {
impl CompilationUnitComponent {
/// Builds a new [`Package`] from `name` and `discriminator`
/// without checking them for consistency.
///
Expand All @@ -35,6 +35,6 @@ impl Package {
/// A description of the location in the workspace where particular macro is available.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub struct ProcMacroScope {
/// A package in which context the action occurs.
pub package: Package,
/// A [`CompilationUnitComponent`] in which context the action occurs.
pub cu_component: CompilationUnitComponent,
}
11 changes: 7 additions & 4 deletions utils/scarb-test-support/src/proc_macro_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ use scarb_proc_macro_server_types::jsonrpc::RequestId;
use scarb_proc_macro_server_types::jsonrpc::ResponseError;
use scarb_proc_macro_server_types::jsonrpc::RpcRequest;
use scarb_proc_macro_server_types::jsonrpc::RpcResponse;
use scarb_proc_macro_server_types::methods::defined_macros::CompilationUnitComponentMacros;
use scarb_proc_macro_server_types::methods::defined_macros::DefinedMacros;
use scarb_proc_macro_server_types::methods::defined_macros::DefinedMacrosParams;
use scarb_proc_macro_server_types::methods::defined_macros::PackageDefinedMacrosInfo;
use scarb_proc_macro_server_types::methods::Method;
use std::collections::HashMap;
use std::io::BufRead;
Expand Down Expand Up @@ -174,15 +174,18 @@ impl ProcMacroClient {

/// Returns the information about macros available for the package with name `package_name`.
/// Used as a helper in PMS tests, where communication requires package IDs assigned by Scarb.
pub fn defined_macros_for_package(&mut self, package_name: &str) -> PackageDefinedMacrosInfo {
pub fn defined_macros_for_package(
&mut self,
package_name: &str,
) -> CompilationUnitComponentMacros {
let response = self
.request_and_wait::<DefinedMacros>(DefinedMacrosParams {})
.unwrap();

response
.macros_for_packages
.macros_for_cu_components
.into_iter()
.find(|package_response| package_response.package.name == package_name)
.find(|cu_response| cu_response.component.name == package_name)
.expect("Response from Proc Macro Server should contain the tested package.")
}
}
Expand Down

0 comments on commit 5159327

Please sign in to comment.