Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adjust ProjectConfig to remove implicit assumption that discriminator == version #6503

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 3 additions & 6 deletions crates/cairo-lang-compiler/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use cairo_lang_defs::db::{DefsDatabase, DefsGroup, ext_as_virtual_impl};
use cairo_lang_defs::plugin::{InlineMacroExprPlugin, MacroPlugin};
use cairo_lang_filesystem::cfg::CfgSet;
use cairo_lang_filesystem::db::{
AsFilesGroupMut, CORELIB_CRATE_NAME, CORELIB_VERSION, ExternalFiles, FilesDatabase, FilesGroup,
FilesGroupEx, init_dev_corelib, init_files_group,
AsFilesGroupMut, CORELIB_VERSION, ExternalFiles, FilesDatabase, FilesGroup, FilesGroupEx,
init_dev_corelib, init_files_group,
};
use cairo_lang_filesystem::detect::detect_corelib;
use cairo_lang_filesystem::flag::Flag;
Expand All @@ -23,7 +23,7 @@ use cairo_lang_utils::Upcast;
use cairo_lang_utils::ordered_hash_map::OrderedHashMap;

use crate::InliningStrategy;
use crate::project::{update_crate_root, update_crate_roots_from_project_config};
use crate::project::update_crate_roots_from_project_config;

#[salsa::database(
DefsDatabase,
Expand Down Expand Up @@ -183,9 +183,6 @@ impl RootDatabaseBuilder {

if let Some(config) = &self.project_config {
update_crate_roots_from_project_config(&mut db, config.as_ref());
if let Some(corelib) = &config.corelib {
update_crate_root(&mut db, config, CORELIB_CRATE_NAME.into(), corelib.clone());
}
}
validate_corelib(&db)?;

Expand Down
28 changes: 14 additions & 14 deletions crates/cairo-lang-compiler/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@ use std::path::Path;

use cairo_lang_defs::ids::ModuleId;
use cairo_lang_filesystem::db::{
CORELIB_CRATE_NAME, CrateConfiguration, CrateSettings, FilesGroupEx,
CORELIB_CRATE_NAME, CrateConfiguration, CrateIdentifier, CrateSettings, FilesGroupEx,
};
use cairo_lang_filesystem::ids::{CrateId, CrateLongId, Directory};
pub use cairo_lang_project::*;
use cairo_lang_semantic::db::SemanticGroup;
use cairo_lang_utils::Intern;
use smol_str::{SmolStr, ToSmolStr};

#[derive(thiserror::Error, Debug)]
pub enum ProjectError {
Expand Down Expand Up @@ -68,9 +67,9 @@ pub fn setup_single_file_project(

/// Updates the crate roots from a ProjectConfig object.
pub fn update_crate_roots_from_project_config(db: &mut dyn SemanticGroup, config: &ProjectConfig) {
for (crate_name, directory_path) in config.content.crate_roots.iter() {
for (crate_identifier, directory_path) in config.content.crate_roots.iter() {
let root = Directory::Real(config.absolute_crate_root(directory_path));
update_crate_root(db, config, crate_name.clone(), root);
update_crate_root(db, config, crate_identifier, root);
}
}

Expand All @@ -80,10 +79,10 @@ pub fn update_crate_roots_from_project_config(db: &mut dyn SemanticGroup, config
pub fn update_crate_root(
db: &mut dyn SemanticGroup,
config: &ProjectConfig,
crate_name: SmolStr,
crate_identifier: &CrateIdentifier,
root: Directory,
) {
let (crate_id, crate_settings) = get_crate_id_and_settings(db, crate_name, config);
let (crate_id, crate_settings) = get_crate_id_and_settings(db, crate_identifier, config);
db.set_crate_config(
crate_id,
Some(CrateConfiguration { root, settings: crate_settings.clone() }),
Expand Down Expand Up @@ -135,21 +134,22 @@ pub fn get_main_crate_ids_from_project(
.content
.crate_roots
.keys()
.map(|name| get_crate_id_and_settings(db, name.clone(), config).0)
.map(|crate_identifier| get_crate_id_and_settings(db, crate_identifier, config).0)
.collect()
}

fn get_crate_id_and_settings<'a>(
db: &mut dyn SemanticGroup,
name: SmolStr,
crate_identifier: &CrateIdentifier,
config: &'a ProjectConfig,
) -> (CrateId, &'a CrateSettings) {
let crate_settings = config.content.crates_config.get(&name);
let discriminator = if name == CORELIB_CRATE_NAME {
None
} else {
crate_settings.version.as_ref().map(ToSmolStr::to_smolstr)
};
let crate_settings = config.content.crates_config.get(crate_identifier);
let name = crate_settings.name.clone().unwrap_or_else(|| crate_identifier.clone().into());
// It has to be done due to how `CrateId::core` works.
let discriminator =
if name == CORELIB_CRATE_NAME { None } else { Some(crate_identifier.clone().into()) };

let crate_id = CrateLongId::Real { name, discriminator }.intern(db);

(crate_id, crate_settings)
}
27 changes: 26 additions & 1 deletion crates/cairo-lang-filesystem/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
use cairo_lang_utils::{LookupIntern, Upcast};
use semver::Version;
use serde::{Deserialize, Serialize};
use smol_str::SmolStr;
use smol_str::{SmolStr, ToSmolStr};

use crate::cfg::CfgSet;
use crate::flag::Flag;
Expand All @@ -24,6 +24,25 @@ mod test;
pub const CORELIB_CRATE_NAME: &str = "core";
pub const CORELIB_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Unique identifier of a crate.
///
/// This directly translates to [`DependencySettings.discriminator`] expect the discriminator
/// **must** be `None` for the core crate.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub struct CrateIdentifier(SmolStr);

impl<T: ToSmolStr> From<T> for CrateIdentifier {
fn from(value: T) -> Self {
Self(value.to_smolstr())
}
}

impl From<CrateIdentifier> for SmolStr {
fn from(value: CrateIdentifier) -> Self {
value.0
}
}

/// A configuration per crate.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CrateConfiguration {
Expand All @@ -41,6 +60,9 @@ impl CrateConfiguration {
/// Same as `CrateConfiguration` but without the root directory.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CrateSettings {
/// The name reflecting how the crate is referred to in the Cairo code e.g. `use crate_name::`.
/// If set to [`None`] then [`CrateIdentifier`] key will be used as a name.
pub name: Option<SmolStr>,
/// The crate's Cairo edition.
pub edition: Edition,
/// The crate's version.
Expand Down Expand Up @@ -119,6 +141,8 @@ pub struct DependencySettings {
/// in the compilation unit.
///
/// Usually such copies differ by their versions or sources (or both).
/// It **must** be [`None`] for the core crate, for other crates it should be directly
/// translated from their [`CrateIdentifier`].
pub discriminator: Option<SmolStr>,
}

Expand Down Expand Up @@ -201,6 +225,7 @@ pub fn init_dev_corelib(db: &mut (dyn FilesGroup + 'static), core_lib_dir: PathB
Some(CrateConfiguration {
root: Directory::Real(core_lib_dir),
settings: CrateSettings {
name: None,
edition: Edition::V2024_07,
version: Version::parse(CORELIB_VERSION).ok(),
cfg_set: Default::default(),
Expand Down
10 changes: 8 additions & 2 deletions crates/cairo-lang-language-server/src/project/scarb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,14 @@ pub fn update_crate_roots(metadata: &Metadata, db: &mut AnalysisDatabase) {
.collect()
};

let settings =
CrateSettings { edition, version, dependencies, cfg_set, experimental_features };
let settings = CrateSettings {
name: Some(crate_name.into()),
edition,
version,
dependencies,
cfg_set,
experimental_features,
};

let custom_main_file_stems = (file_stem != "lib").then_some(vec![file_stem.into()]);

Expand Down
4 changes: 4 additions & 0 deletions crates/cairo-lang-language-server/tests/e2e/analysis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ fn cairo_projects() {
- `core`: `["[CAIRO_SOURCE]/corelib/src/lib.cairo"]`
```rust
CrateSettings {
name: None,
edition: V2024_07,
version: Some(
Version {
Expand All @@ -61,6 +62,7 @@ fn cairo_projects() {
- `project1`: `["[ROOT]/project1/src/lib.cairo"]`
```rust
CrateSettings {
name: None,
edition: V2023_01,
version: None,
cfg_set: None,
Expand All @@ -74,6 +76,7 @@ fn cairo_projects() {
- `project2`: `["[ROOT]/project2/src/lib.cairo"]`
```rust
CrateSettings {
name: None,
edition: V2023_01,
version: None,
cfg_set: None,
Expand All @@ -87,6 +90,7 @@ fn cairo_projects() {
- `subproject`: `["[ROOT]/project2/subproject/src/lib.cairo"]`
```rust
CrateSettings {
name: None,
edition: V2023_01,
version: None,
cfg_set: None,
Expand Down
1 change: 0 additions & 1 deletion crates/cairo-lang-project/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ description = "Cairo project specification. For example, crates and flags used f
cairo-lang-filesystem = { path = "../cairo-lang-filesystem", version = "~2.8.4" }
cairo-lang-utils = { path = "../cairo-lang-utils", version = "~2.8.4" }
serde = { workspace = true, default-features = true }
smol_str.workspace = true
thiserror.workspace = true
toml.workspace = true

Expand Down
16 changes: 7 additions & 9 deletions crates/cairo-lang-project/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@ mod test;

use std::path::{Path, PathBuf};

use cairo_lang_filesystem::db::CrateSettings;
use cairo_lang_filesystem::ids::Directory;
use cairo_lang_filesystem::db::{CrateIdentifier, CrateSettings};
use cairo_lang_utils::ordered_hash_map::OrderedHashMap;
use serde::{Deserialize, Serialize};
use smol_str::SmolStr;

#[derive(thiserror::Error, Debug)]
pub enum DeserializationError {
Expand All @@ -27,14 +25,13 @@ pub const PROJECT_FILE_NAME: &str = "cairo_project.toml";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ProjectConfig {
pub base_path: PathBuf,
pub corelib: Option<Directory>,
pub content: ProjectConfigContent,
}

/// Contents of a Cairo project config file.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectConfigContent {
pub crate_roots: OrderedHashMap<SmolStr, PathBuf>,
pub crate_roots: OrderedHashMap<CrateIdentifier, PathBuf>,
/// Additional configurations for the crates.
#[serde(default)]
#[serde(rename = "config")]
Expand All @@ -50,12 +47,13 @@ pub struct AllCratesConfig {
/// Configuration override per crate.
#[serde(default)]
#[serde(rename = "override")]
pub override_map: OrderedHashMap<SmolStr, CrateSettings>,
pub override_map: OrderedHashMap<CrateIdentifier, CrateSettings>,
}

impl AllCratesConfig {
/// Returns the configuration for the given crate.
pub fn get(&self, crate_name: &str) -> &CrateSettings {
self.override_map.get(crate_name).unwrap_or(&self.global)
pub fn get(&self, crate_identifier: &CrateIdentifier) -> &CrateSettings {
self.override_map.get(crate_identifier).unwrap_or(&self.global)
}
}

Expand All @@ -70,7 +68,7 @@ impl ProjectConfig {
.ok_or(DeserializationError::PathError)?
.into();
let content = toml::from_str(&std::fs::read_to_string(filename)?)?;
Ok(ProjectConfig { base_path, content, corelib: None })
Ok(ProjectConfig { base_path, content })
}

/// Returns the crate root's absolute path, according to the base path of this project.
Expand Down
3 changes: 3 additions & 0 deletions crates/cairo-lang-project/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ fn test_serde() {
.collect(),
crates_config: AllCratesConfig {
global: CrateSettings {
name: None,
edition: Default::default(),
version: Default::default(),
dependencies: Default::default(),
Expand All @@ -24,13 +25,15 @@ fn test_serde() {
},
override_map: [
("crate1".into(), CrateSettings {
name: None,
edition: Edition::V2023_10,
version: Default::default(),
dependencies: Default::default(),
experimental_features: ExperimentalFeaturesConfig::default(),
cfg_set: Default::default(),
}),
("crate3".into(), CrateSettings {
name: None,
edition: Default::default(),
version: Default::default(),
dependencies: Default::default(),
Expand Down
1 change: 1 addition & 0 deletions crates/cairo-lang-semantic/src/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ pub fn setup_test_crate_ex(
toml::from_str(crate_settings).expect("Invalid config.")
} else {
CrateSettings {
name: None,
edition: Edition::default(),
version: None,
dependencies: Default::default(),
Expand Down